title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Writing a For Loop to Evaluate a Factorial - JavaScript
We are required to write a simple JavaScript function that takes in a Number, say n and computes its factorial using a for loop and returns the factorial. For example − factorial(5) = 120, factorial(6) = 720 Maintain a count and a result variable, keep multiplying the count into result, simultaneously decreasing the count by 1, until it reaches 1 And then finally we return the result. Following is the code − const num = 14; const factorial = num => { let res = 1; for(let i = num; i > 1; i--){ res *= i; }; return res; }; console.log(factorial(num)); This will produce the following output in console − 87178291200
[ { "code": null, "e": 1217, "s": 1062, "text": "We are required to write a simple JavaScript function that takes in a Number, say n and computes its factorial using a for loop and returns the factorial." }, { "code": null, "e": 1231, "s": 1217, "text": "For example −" }, { "code": null, "e": 1270, "s": 1231, "text": "factorial(5) = 120,\nfactorial(6) = 720" }, { "code": null, "e": 1411, "s": 1270, "text": "Maintain a count and a result variable, keep multiplying the count into result, simultaneously decreasing the count by 1, until it reaches 1" }, { "code": null, "e": 1450, "s": 1411, "text": "And then finally we return the result." }, { "code": null, "e": 1474, "s": 1450, "text": "Following is the code −" }, { "code": null, "e": 1635, "s": 1474, "text": "const num = 14;\nconst factorial = num => {\n let res = 1;\n for(let i = num; i > 1; i--){\n res *= i;\n };\n return res;\n};\nconsole.log(factorial(num));" }, { "code": null, "e": 1687, "s": 1635, "text": "This will produce the following output in console −" }, { "code": null, "e": 1699, "s": 1687, "text": "87178291200" } ]
AWT Frame Class
The class Frame is a top level window with border and title. It uses BorderLayout as default layout manager. Following is the declaration for java.awt.Frame class: public class Frame extends Window implements MenuContainer Following are the fields for java.awt.Frame class: static float BOTTOM_ALIGNMENT -- Ease-of-use constant for getAlignmentY. static float BOTTOM_ALIGNMENT -- Ease-of-use constant for getAlignmentY. static int CROSSHAIR_CURSOR -- Deprecated. replaced by Cursor.CROSSHAIR_CURSOR. static int CROSSHAIR_CURSOR -- Deprecated. replaced by Cursor.CROSSHAIR_CURSOR. static int DEFAULT_CURSOR -- Deprecated. replaced by Cursor.DEFAULT_CURSOR. static int DEFAULT_CURSOR -- Deprecated. replaced by Cursor.DEFAULT_CURSOR. static int E_RESIZE_CURSOR -- Deprecated. replaced by Cursor.E_RESIZE_CURSOR. static int E_RESIZE_CURSOR -- Deprecated. replaced by Cursor.E_RESIZE_CURSOR. static int HAND_CURSOR -- Deprecated. replaced by Cursor.HAND_CURSOR. static int HAND_CURSOR -- Deprecated. replaced by Cursor.HAND_CURSOR. static int ICONIFIED -- This state bit indicates that frame is iconified. static int ICONIFIED -- This state bit indicates that frame is iconified. static int MAXIMIZED_BOTH -- This state bit mask indicates that frame is fully maximized (that is both horizontally and vertically). static int MAXIMIZED_BOTH -- This state bit mask indicates that frame is fully maximized (that is both horizontally and vertically). static int MAXIMIZED_HORIZ -- This state bit indicates that frame is maximized in the horizontal direction. static int MAXIMIZED_HORIZ -- This state bit indicates that frame is maximized in the horizontal direction. static int MAXIMIZED_VERT -- This state bit indicates that frame is maximized in the vertical direction. static int MAXIMIZED_VERT -- This state bit indicates that frame is maximized in the vertical direction. static int MOVE_CURSOR -- Deprecated. replaced by Cursor.MOVE_CURSOR. static int MOVE_CURSOR -- Deprecated. replaced by Cursor.MOVE_CURSOR. static int N_RESIZE_CURSOR -- Deprecated. replaced by Cursor.N_RESIZE_CURSOR. static int N_RESIZE_CURSOR -- Deprecated. replaced by Cursor.N_RESIZE_CURSOR. static int NE_RESIZE_CURSOR -- Deprecated. replaced by Cursor.NE_RESIZE_CURSOR. static int NE_RESIZE_CURSOR -- Deprecated. replaced by Cursor.NE_RESIZE_CURSOR. static int NORMAL -- Frame is in the "normal" state. static int NORMAL -- Frame is in the "normal" state. static int NW_RESIZE_CURSOR -- Deprecated. replaced by Cursor.NW_RESIZE_CURSOR. static int NW_RESIZE_CURSOR -- Deprecated. replaced by Cursor.NW_RESIZE_CURSOR. static int S_RESIZE_CURSOR -- Deprecated. replaced by Cursor.S_RESIZE_CURSOR. static int S_RESIZE_CURSOR -- Deprecated. replaced by Cursor.S_RESIZE_CURSOR. static int SE_RESIZE_CURSOR -- Deprecated. replaced by Cursor.SE_RESIZE_CURSOR. static int SE_RESIZE_CURSOR -- Deprecated. replaced by Cursor.SE_RESIZE_CURSOR. static int SW_RESIZE_CURSOR -- Deprecated. replaced by Cursor.SW_RESIZE_CURSOR. static int SW_RESIZE_CURSOR -- Deprecated. replaced by Cursor.SW_RESIZE_CURSOR. static int TEXT_CURSOR -- Deprecated. replaced by Cursor.TEXT_CURSOR. static int TEXT_CURSOR -- Deprecated. replaced by Cursor.TEXT_CURSOR. static int W_RESIZE_CURSOR -- Deprecated. replaced by Cursor.W_RESIZE_CURSOR. static int W_RESIZE_CURSOR -- Deprecated. replaced by Cursor.W_RESIZE_CURSOR. static int WAIT_CURSOR -- Deprecated. replaced by Cursor.WAIT_CURSOR. static int WAIT_CURSOR -- Deprecated. replaced by Cursor.WAIT_CURSOR. Frame() Constructs a new instance of Frame that is initially invisible. Frame(GraphicsConfiguration gc) Constructs a new, initially invisible Frame with the specified GraphicsConfiguration. Frame(String title) Constructs a new, initially invisible Frame object with the specified title. Frame(String title, GraphicsConfiguration gc) Constructs a new, initially invisible Frame object with the specified title and a GraphicsConfiguration. void addNotify() Makes this Frame displayable by connecting it to a native screen resource. AccessibleContext getAccessibleContext() Gets the AccessibleContext associated with this Frame. int getCursorType() Deprecated. As of JDK version 1.1, replaced by Component.getCursor(). int getExtendedState() Gets the state of this frame. static Frame[] getFrames() Returns an array of all Frames created by this application. Image getIconImage() Returns the image to be displayed as the icon for this frame. Rectangle getMaximizedBounds() Gets maximized bounds for this frame. MenuBar getMenuBar() Gets the menu bar for this frame. int getState() Gets the state of this frame (obsolete). String getTitle() Gets the title of the frame. boolean isResizable() Indicates whether this frame is resizable by the user. boolean isUndecorated() Indicates whether this frame is undecorated. protected String paramString() Returns a string representing the state of this Frame. void remove(MenuComponent m) Removes the specified menu bar from this frame. void removeNotify() Makes this Frame undisplayable by removing its connection to its native screen resource. void setCursor(int cursorType) Deprecated. As of JDK version 1.1, replaced by Component.setCursor(Cursor). void setExtendedState(int state) Sets the state of this frame. void setIconImage(Image image) Sets the image to be displayed as the icon for this window. void setMaximizedBounds(Rectangle bounds) Sets the maximized bounds for this frame. void setMenuBar(MenuBar mb) Sets the menu bar for this frame to the specified menu bar. void setResizable(boolean resizable) Sets whether this frame is resizable by the user. void setState(int state) Sets the state of this frame (obsolete). void setTitle(String title) Sets the title for this frame to the specified string. void setUndecorated(boolean undecorated) Disables or enables decorations for this frame. This class inherits methods from the following classes: java.awt.Window java.awt.Window java.awt.Container java.awt.Container 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 AwtContainerDemo { private Frame mainFrame; private Label headerLabel; private Label statusLabel; private Panel controlPanel; private Label msglabel; public AwtContainerDemo(){ prepareGUI(); } public static void main(String[] args){ AwtContainerDemo awtContainerDemo = new AwtContainerDemo(); awtContainerDemo.showFrameDemo(); } 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); msglabel = new Label(); msglabel.setAlignment(Label.CENTER); msglabel.setText("Welcome to TutorialsPoint AWT Tutorial."); controlPanel = new Panel(); controlPanel.setLayout(new FlowLayout()); mainFrame.add(headerLabel); mainFrame.add(controlPanel); mainFrame.add(statusLabel); mainFrame.setVisible(true); } private void showFrameDemo(){ headerLabel.setText("Container in action: Frame"); final Frame frame = new Frame(); frame.setSize(300, 300); frame.setLayout(new FlowLayout()); frame.add(msglabel); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent windowEvent){ frame.dispose(); } }); Button okButton = new Button("Open a Frame"); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { statusLabel.setText("A Frame shown to the user."); frame.setVisible(true); } }); controlPanel.add(okButton); mainFrame.setVisible(true); } } Compile the program using command prompt. Go to D:/ > AWT and type the following command. D:\AWT>javac com\tutorialspoint\gui\AwtContainerDemo.java If no error comes that means compilation is successful. Run the program using following command. D:\AWT>java com.tutorialspoint.gui.AwtContainerDemo Verify the following output 13 Lectures 2 hours EduOLC Print Add Notes Bookmark this page
[ { "code": null, "e": 1856, "s": 1747, "text": "The class Frame is a top level window with border and title. It uses BorderLayout as default layout manager." }, { "code": null, "e": 1911, "s": 1856, "text": "Following is the declaration for java.awt.Frame class:" }, { "code": null, "e": 1979, "s": 1911, "text": "public class Frame\n extends Window\n implements MenuContainer" }, { "code": null, "e": 2030, "s": 1979, "text": "Following are the fields for java.awt.Frame class:" }, { "code": null, "e": 2103, "s": 2030, "text": "static float BOTTOM_ALIGNMENT -- Ease-of-use constant for getAlignmentY." }, { "code": null, "e": 2176, "s": 2103, "text": "static float BOTTOM_ALIGNMENT -- Ease-of-use constant for getAlignmentY." }, { "code": null, "e": 2257, "s": 2176, "text": "static int CROSSHAIR_CURSOR -- Deprecated. replaced by Cursor.CROSSHAIR_CURSOR." }, { "code": null, "e": 2338, "s": 2257, "text": "static int CROSSHAIR_CURSOR -- Deprecated. replaced by Cursor.CROSSHAIR_CURSOR." }, { "code": null, "e": 2415, "s": 2338, "text": "static int DEFAULT_CURSOR -- Deprecated. replaced by Cursor.DEFAULT_CURSOR." }, { "code": null, "e": 2492, "s": 2415, "text": "static int DEFAULT_CURSOR -- Deprecated. replaced by Cursor.DEFAULT_CURSOR." }, { "code": null, "e": 2571, "s": 2492, "text": "static int E_RESIZE_CURSOR -- Deprecated. replaced by Cursor.E_RESIZE_CURSOR." }, { "code": null, "e": 2650, "s": 2571, "text": "static int E_RESIZE_CURSOR -- Deprecated. replaced by Cursor.E_RESIZE_CURSOR." }, { "code": null, "e": 2721, "s": 2650, "text": "static int HAND_CURSOR -- Deprecated. replaced by Cursor.HAND_CURSOR." }, { "code": null, "e": 2792, "s": 2721, "text": "static int HAND_CURSOR -- Deprecated. replaced by Cursor.HAND_CURSOR." }, { "code": null, "e": 2867, "s": 2792, "text": "static int ICONIFIED -- This state bit indicates that frame is iconified." }, { "code": null, "e": 2942, "s": 2867, "text": "static int ICONIFIED -- This state bit indicates that frame is iconified." }, { "code": null, "e": 3076, "s": 2942, "text": "static int MAXIMIZED_BOTH -- This state bit mask indicates that frame is fully maximized (that is both horizontally and vertically)." }, { "code": null, "e": 3210, "s": 3076, "text": "static int MAXIMIZED_BOTH -- This state bit mask indicates that frame is fully maximized (that is both horizontally and vertically)." }, { "code": null, "e": 3319, "s": 3210, "text": "static int MAXIMIZED_HORIZ -- This state bit indicates that frame is maximized in the horizontal direction." }, { "code": null, "e": 3428, "s": 3319, "text": "static int MAXIMIZED_HORIZ -- This state bit indicates that frame is maximized in the horizontal direction." }, { "code": null, "e": 3534, "s": 3428, "text": "static int MAXIMIZED_VERT -- This state bit indicates that frame is maximized in the vertical direction." }, { "code": null, "e": 3640, "s": 3534, "text": "static int MAXIMIZED_VERT -- This state bit indicates that frame is maximized in the vertical direction." }, { "code": null, "e": 3711, "s": 3640, "text": "static int MOVE_CURSOR -- Deprecated. replaced by Cursor.MOVE_CURSOR." }, { "code": null, "e": 3782, "s": 3711, "text": "static int MOVE_CURSOR -- Deprecated. replaced by Cursor.MOVE_CURSOR." }, { "code": null, "e": 3861, "s": 3782, "text": "static int N_RESIZE_CURSOR -- Deprecated. replaced by Cursor.N_RESIZE_CURSOR." }, { "code": null, "e": 3940, "s": 3861, "text": "static int N_RESIZE_CURSOR -- Deprecated. replaced by Cursor.N_RESIZE_CURSOR." }, { "code": null, "e": 4021, "s": 3940, "text": "static int NE_RESIZE_CURSOR -- Deprecated. replaced by Cursor.NE_RESIZE_CURSOR." }, { "code": null, "e": 4102, "s": 4021, "text": "static int NE_RESIZE_CURSOR -- Deprecated. replaced by Cursor.NE_RESIZE_CURSOR." }, { "code": null, "e": 4157, "s": 4102, "text": "static int NORMAL -- Frame is in the \"normal\" state.\n" }, { "code": null, "e": 4212, "s": 4157, "text": "static int NORMAL -- Frame is in the \"normal\" state.\n" }, { "code": null, "e": 4293, "s": 4212, "text": "static int NW_RESIZE_CURSOR -- Deprecated. replaced by Cursor.NW_RESIZE_CURSOR." }, { "code": null, "e": 4374, "s": 4293, "text": "static int NW_RESIZE_CURSOR -- Deprecated. replaced by Cursor.NW_RESIZE_CURSOR." }, { "code": null, "e": 4453, "s": 4374, "text": "static int S_RESIZE_CURSOR -- Deprecated. replaced by Cursor.S_RESIZE_CURSOR." }, { "code": null, "e": 4532, "s": 4453, "text": "static int S_RESIZE_CURSOR -- Deprecated. replaced by Cursor.S_RESIZE_CURSOR." }, { "code": null, "e": 4613, "s": 4532, "text": "static int SE_RESIZE_CURSOR -- Deprecated. replaced by Cursor.SE_RESIZE_CURSOR." }, { "code": null, "e": 4694, "s": 4613, "text": "static int SE_RESIZE_CURSOR -- Deprecated. replaced by Cursor.SE_RESIZE_CURSOR." }, { "code": null, "e": 4775, "s": 4694, "text": "static int SW_RESIZE_CURSOR -- Deprecated. replaced by Cursor.SW_RESIZE_CURSOR." }, { "code": null, "e": 4856, "s": 4775, "text": "static int SW_RESIZE_CURSOR -- Deprecated. replaced by Cursor.SW_RESIZE_CURSOR." }, { "code": null, "e": 4927, "s": 4856, "text": "static int TEXT_CURSOR -- Deprecated. replaced by Cursor.TEXT_CURSOR." }, { "code": null, "e": 4998, "s": 4927, "text": "static int TEXT_CURSOR -- Deprecated. replaced by Cursor.TEXT_CURSOR." }, { "code": null, "e": 5077, "s": 4998, "text": "static int W_RESIZE_CURSOR -- Deprecated. replaced by Cursor.W_RESIZE_CURSOR." }, { "code": null, "e": 5156, "s": 5077, "text": "static int W_RESIZE_CURSOR -- Deprecated. replaced by Cursor.W_RESIZE_CURSOR." }, { "code": null, "e": 5227, "s": 5156, "text": "static int WAIT_CURSOR -- Deprecated. replaced by Cursor.WAIT_CURSOR." }, { "code": null, "e": 5298, "s": 5227, "text": "static int WAIT_CURSOR -- Deprecated. replaced by Cursor.WAIT_CURSOR." }, { "code": null, "e": 5307, "s": 5298, "text": "Frame() " }, { "code": null, "e": 5371, "s": 5307, "text": "Constructs a new instance of Frame that is initially invisible." }, { "code": null, "e": 5404, "s": 5371, "text": "Frame(GraphicsConfiguration gc) " }, { "code": null, "e": 5490, "s": 5404, "text": "Constructs a new, initially invisible Frame with the specified GraphicsConfiguration." }, { "code": null, "e": 5511, "s": 5490, "text": "Frame(String title) " }, { "code": null, "e": 5588, "s": 5511, "text": "Constructs a new, initially invisible Frame object with the specified title." }, { "code": null, "e": 5635, "s": 5588, "text": "Frame(String title, GraphicsConfiguration gc) " }, { "code": null, "e": 5740, "s": 5635, "text": "Constructs a new, initially invisible Frame object with the specified title and a GraphicsConfiguration." }, { "code": null, "e": 5758, "s": 5740, "text": "void addNotify() " }, { "code": null, "e": 5833, "s": 5758, "text": "Makes this Frame displayable by connecting it to a native screen resource." }, { "code": null, "e": 5874, "s": 5833, "text": "AccessibleContext\tgetAccessibleContext()" }, { "code": null, "e": 5929, "s": 5874, "text": "Gets the AccessibleContext associated with this Frame." }, { "code": null, "e": 5950, "s": 5929, "text": "int getCursorType() " }, { "code": null, "e": 6020, "s": 5950, "text": "Deprecated. As of JDK version 1.1, replaced by Component.getCursor()." }, { "code": null, "e": 6044, "s": 6020, "text": "int getExtendedState() " }, { "code": null, "e": 6074, "s": 6044, "text": "Gets the state of this frame." }, { "code": null, "e": 6102, "s": 6074, "text": "static Frame[]\tgetFrames() " }, { "code": null, "e": 6162, "s": 6102, "text": "Returns an array of all Frames created by this application." }, { "code": null, "e": 6184, "s": 6162, "text": "Image getIconImage() " }, { "code": null, "e": 6246, "s": 6184, "text": "Returns the image to be displayed as the icon for this frame." }, { "code": null, "e": 6278, "s": 6246, "text": "Rectangle getMaximizedBounds() " }, { "code": null, "e": 6316, "s": 6278, "text": "Gets maximized bounds for this frame." }, { "code": null, "e": 6338, "s": 6316, "text": "MenuBar getMenuBar() " }, { "code": null, "e": 6372, "s": 6338, "text": "Gets the menu bar for this frame." }, { "code": null, "e": 6388, "s": 6372, "text": "int getState() " }, { "code": null, "e": 6429, "s": 6388, "text": "Gets the state of this frame (obsolete)." }, { "code": null, "e": 6447, "s": 6429, "text": "String\tgetTitle()" }, { "code": null, "e": 6476, "s": 6447, "text": "Gets the title of the frame." }, { "code": null, "e": 6499, "s": 6476, "text": "boolean isResizable() " }, { "code": null, "e": 6554, "s": 6499, "text": "Indicates whether this frame is resizable by the user." }, { "code": null, "e": 6579, "s": 6554, "text": "boolean isUndecorated() " }, { "code": null, "e": 6624, "s": 6579, "text": "Indicates whether this frame is undecorated." }, { "code": null, "e": 6656, "s": 6624, "text": "protected String paramString() " }, { "code": null, "e": 6711, "s": 6656, "text": "Returns a string representing the state of this Frame." }, { "code": null, "e": 6741, "s": 6711, "text": "void remove(MenuComponent m) " }, { "code": null, "e": 6789, "s": 6741, "text": "Removes the specified menu bar from this frame." }, { "code": null, "e": 6810, "s": 6789, "text": "void removeNotify() " }, { "code": null, "e": 6899, "s": 6810, "text": "Makes this Frame undisplayable by removing its connection to its native screen resource." }, { "code": null, "e": 6931, "s": 6899, "text": "void setCursor(int cursorType) " }, { "code": null, "e": 7007, "s": 6931, "text": "Deprecated. As of JDK version 1.1, replaced by Component.setCursor(Cursor)." }, { "code": null, "e": 7041, "s": 7007, "text": "void setExtendedState(int state) " }, { "code": null, "e": 7071, "s": 7041, "text": "Sets the state of this frame." }, { "code": null, "e": 7103, "s": 7071, "text": "void setIconImage(Image image) " }, { "code": null, "e": 7163, "s": 7103, "text": "Sets the image to be displayed as the icon for this window." }, { "code": null, "e": 7206, "s": 7163, "text": "void setMaximizedBounds(Rectangle bounds) " }, { "code": null, "e": 7248, "s": 7206, "text": "Sets the maximized bounds for this frame." }, { "code": null, "e": 7277, "s": 7248, "text": "void setMenuBar(MenuBar mb) " }, { "code": null, "e": 7337, "s": 7277, "text": "Sets the menu bar for this frame to the specified menu bar." }, { "code": null, "e": 7375, "s": 7337, "text": "void setResizable(boolean resizable) " }, { "code": null, "e": 7425, "s": 7375, "text": "Sets whether this frame is resizable by the user." }, { "code": null, "e": 7451, "s": 7425, "text": "void setState(int state) " }, { "code": null, "e": 7492, "s": 7451, "text": "Sets the state of this frame (obsolete)." }, { "code": null, "e": 7521, "s": 7492, "text": "void setTitle(String title) " }, { "code": null, "e": 7576, "s": 7521, "text": "Sets the title for this frame to the specified string." }, { "code": null, "e": 7618, "s": 7576, "text": "void setUndecorated(boolean undecorated) " }, { "code": null, "e": 7666, "s": 7618, "text": "Disables or enables decorations for this frame." }, { "code": null, "e": 7722, "s": 7666, "text": "This class inherits methods from the following classes:" }, { "code": null, "e": 7738, "s": 7722, "text": "java.awt.Window" }, { "code": null, "e": 7754, "s": 7738, "text": "java.awt.Window" }, { "code": null, "e": 7773, "s": 7754, "text": "java.awt.Container" }, { "code": null, "e": 7792, "s": 7773, "text": "java.awt.Container" }, { "code": null, "e": 7811, "s": 7792, "text": "java.awt.Component" }, { "code": null, "e": 7830, "s": 7811, "text": "java.awt.Component" }, { "code": null, "e": 7847, "s": 7830, "text": "java.lang.Object" }, { "code": null, "e": 7864, "s": 7847, "text": "java.lang.Object" }, { "code": null, "e": 7978, "s": 7864, "text": "Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >" }, { "code": null, "e": 10151, "s": 7978, "text": "package com.tutorialspoint.gui;\n\nimport java.awt.*;\nimport java.awt.event.*;\n\npublic class AwtContainerDemo {\n private Frame mainFrame;\n private Label headerLabel;\n private Label statusLabel;\n private Panel controlPanel;\n private Label msglabel;\n\n public AwtContainerDemo(){\n prepareGUI();\n }\n\n public static void main(String[] args){\n AwtContainerDemo awtContainerDemo = new AwtContainerDemo(); \n awtContainerDemo.showFrameDemo();\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 msglabel = new Label();\n msglabel.setAlignment(Label.CENTER);\n msglabel.setText(\"Welcome to TutorialsPoint AWT Tutorial.\");\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 showFrameDemo(){\n headerLabel.setText(\"Container in action: Frame\"); \n\n final Frame frame = new Frame();\n frame.setSize(300, 300);\n frame.setLayout(new FlowLayout()); \n frame.add(msglabel);\n frame.addWindowListener(new WindowAdapter() {\n public void windowClosing(WindowEvent windowEvent){\n frame.dispose();\n } \n }); \n Button okButton = new Button(\"Open a Frame\");\n\n okButton.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent e) {\n statusLabel.setText(\"A Frame shown to the user.\");\n frame.setVisible(true);\n }\n });\n controlPanel.add(okButton);\n\n mainFrame.setVisible(true); \n }\n}" }, { "code": null, "e": 10242, "s": 10151, "text": "Compile the program using command prompt. Go to D:/ > AWT and type the following command." }, { "code": null, "e": 10300, "s": 10242, "text": "D:\\AWT>javac com\\tutorialspoint\\gui\\AwtContainerDemo.java" }, { "code": null, "e": 10397, "s": 10300, "text": "If no error comes that means compilation is successful. Run the program using following command." }, { "code": null, "e": 10449, "s": 10397, "text": "D:\\AWT>java com.tutorialspoint.gui.AwtContainerDemo" }, { "code": null, "e": 10477, "s": 10449, "text": "Verify the following output" }, { "code": null, "e": 10510, "s": 10477, "text": "\n 13 Lectures \n 2 hours \n" }, { "code": null, "e": 10518, "s": 10510, "text": " EduOLC" }, { "code": null, "e": 10525, "s": 10518, "text": " Print" }, { "code": null, "e": 10536, "s": 10525, "text": " Add Notes" } ]
Aptitude - Averages Examples
Q 1 - The average of 20 numbers is zero. Of them, at the most, how many may be greater than zero? A - 19 B - 10 C - 0 D - 1 Answer - A Explanation Average of 20 numbers = 0. Therefore Sum of 20 numbers = (0 x 20) = 0 It is quite possible that 19 of these numbers may be positive and if their sum is a, then 20th number is (-a). Q 2 - Find the average of all the numbers between 6 and 34 which are divisible by 5? A - 30 B - 24 C - 20 D - 18 Answer - C Explanation Average = (10 + 15 + 20 + 25 + 30)⁄5 = 100⁄5 = 20. Q 3 - The average of first five multiples of 3 is? A - 15 B - 12 C - 3 D - 9 Answer - D Explanation Average = 3(1 + 2 + 3 + 4 + 5)⁄5 = 45⁄5 = 9 Q 4 - The average of first nine prime numbers is? A - 10 B - 111⁄9 C - 9 D - 112⁄9 Answer - B Explanation Average = (2 + 3 + 5 + 7 + 11 + 13 + 17 + 19 + 23)⁄9 = 100⁄9 = 111⁄9 Q 5 - A student was asked to find the arithmetic mean of the numbers 3, 11, 7, 9, 15, 13, 8, 19, 17, 21, 14, and z? A - 3 B - 7 C - 17 D - 31 Answer - B Explanation Clearly, we have (3 + 11 + 7 + 9 + 15 + 13 + 8 + 19 + 17 + 21 + 14 + z)⁄12 = 12 or 137 + z = 144 or z = 144 - 137 = 7. Q 6 - If the mean of 5 observation z, z + 2, z + 4, z + 6 and z + 8 is 11, then the mean of the last three observation is? A - 11 B - 13 C - 15 D - 17 Answer - B Explanation we have : (z + (z + 2) + (z + 4) + (z + 6) + (z + 8))⁄5 = 11 or 5z + 20 = 55 or z = 7. So the numbers are 7, 9, 11, 13, 15. therefore required mean = (11 + 13 + 15⁄3) = 39⁄3 = 13. Q 7 - The average of the two-digit numbers, which remain the same when the digits interchange their positions, is? A - 55 B - 33 C - 44 D - 66 Answer - A Explanation Average = (11 + 22 + 33 + 44 + 55 + 66 + 77 + 88 + 99⁄9) ((11 + 99) + (22 + 88) + (33 + 77) + (44 + 66) +55⁄9) (4 x 110 + 55⁄9) (495⁄9) = 55 Q 8 - The average of a non-zero number and its square is 5 times the number. The number is? A - 9 B - 17 C - 29 D - 295 Answer - A Explanation Let the number be z. then, z + z 2⁄2 = 5z = z 2 - 9z = 0 z (z - 9) = 0 z = 0 or z = 9 so the number is 9. Q 9 - The average of 7 consecutive number is 20. The largest of these numbers is? A - 20 B - 22 C - 23 D - 24 Answer - C Explanation Let the number be z, z + 1, z + 2, z + 3 ,z + 4, z + 5 ,z + 6. then, (z + (z + 1) + (z + 2) + (z + 3) + (z + 4) + (z + 5) + (z + 6))⁄7 = 20 7z + 21 = 140 or 7z = 119 or z = 17 Largest number = z + 6 = 17 + 6 = 23 Q 10 - The average of five consecutive odd numbers is 61. What is the difference between the highest and lowest numbers? A - 9 B - 8 C - 10 D - 11 Answer - B Explanation Let the number be z, z + 2, z + 4, z + 6 and z + 8. then, (z + (z + 2) + (z + 4) + (z + 6) + (z + 8))⁄5 = 61 5z + 20 = 305 or z = 57 so the required number is = (57 + 8) - 57 = 8 Q 11 - The sum of three consecutive odd numbers is 38 more than the average of these numbers. What is the first of these numbers? A - 17 B - 13 C - 19 D - none Answer - A Explanation Let the number be z, z + 2, and z + 4. then, (z + z + 2 + z + 4) - (z + z + 2 + z + 4)⁄3 = 38 2(3z + 6) = 114 or 6z = 102 or z = 17. Q 12 - The average age of the boys in a class is 16 years and that of the girls is 15 years. The average age for the whole class is A - 15 years B - 15.5 years C - 16 years D - Cannot be computed with the given information Answer - D Explanation Clearly to find the average we ought to know the number of boys, girls or students in the class neither of which is given. So, data is inadequate. Q 13 - The average annual income (in Rs.) of certain agricultural workers is S and that of other workers is T. The number of agriculture workers is 11 times that of other workers. Then the average monthly income (in Rs.) of all the workers is? A - S + T⁄2 B - 11S + T⁄12 C - 1 +⁄11ST D - S + 11T⁄2 Answer - B Explanation Let the number of other workers be z. then, number of agricultural workers = 11z Total number of workers = 12z Therefore Average monthly salary = S x 11z + T x z⁄12z = 11S + T⁄12 Q 14 - A family consists of grandparents, parents and three grandchildren. The average age of the grandparents is 67 years, that of the parent is 35 years and that of the grandchildren is 6 years. What is the average age of the family? A - 284⁄7 B - 315⁄7 C - 321⁄7 D - none Answer - B Explanation Required average = (67 x 2 + 35 x 2 + 6 x 3⁄2 + 2 + 3) = (134 + 70 + 18⁄7) = 222⁄7 = 315⁄7 Q 15 - A library has an average of 510 visitors on Sundays and 240 on other days. The average number of visiters per day in a month of 30 days begining with a Sunday is? A - 276 B - 280 C - 285 D - 250 Answer - C Explanation Since the month begins with a sunday, so there will be five sundays in the month Therefore Required average = (510 x 5 + 240 x 25⁄30) = 8550⁄30 = 285 Q 16 - If the average marks of three batches of 55, 60 and 45 students respectively is 50, 55 and 60, then the average marks of all the students is? A - 53.33 B - 54.68 C - 55 D - none Answer - B Explanation Required average = (55 x 50 + 60 x 55 + 45 x 60⁄55 + 60 + 45) (2750 + 3300 + 2700⁄160) = (8750⁄160) = 54.68 Q 17 - The average weight of 16 boys in a class is 50.25 kgs and that of the remaining 8 boys is 45.15 kgs. Find the average weight of all the boys in the class? A - 48.55 B - 49.25 C - 45 D - 47 Answer - A Explanation Required average = (50.25 x 16 + 45.15 x 8⁄16 + 8) (804 + 361.20⁄24) = (1165.20⁄24) = 48.55 Q 18 - A car owner buys petrol at Rs. 7.50, Rs. 8 and Rs. 8.50 per litre for three successive years. What approximately is the average cost per litre of petrol if he spends Rs. 4000 each year? A - 7.98 B - 8 C - 8.50 D - 9 Answer - A Explanation Total quantity of petrol consumed in 3 years. = (4000⁄7.50 + 4000⁄8 + 4000⁄8.50) litres = 4000 2⁄15 + 1⁄8 2⁄17 = 76700⁄51 litres Total amount spent = Rs. (3 x 4000) = Rs 12000 Therefore Average cost = Rs. (12000 x 51⁄76700) = Rs. 6120⁄767 = Rs. 7.98. Q 19 - The average of six numbers is z and the average of three of these is y. If the average of the remaining three is w, then? A - 2z = 2y + 2w B - z = 2y + 2w C - z = y + w D - 2z = y + w Answer - D Explanation Clearly, we have: z = 3y + 3w⁄6 or 2z = y + w. Q 20 - Out of 9 persons, 8 persons spent Rs. 30 each for their meals. The ninth one spent Rs. 20 more than the average expenditure of all the nine. The total money spent by all of them was? A - 290 B - 260 C - 292.50 D - 400.50 Answer - C Explanation Let the average expenditure be Rs z then, 9z = 8 x 30 + (z + 20) or 9z = z + 260 or 8z = 260 or z = 32.50. Therefore total money spent = 9z = Rs. (9 x 32.50) = Rs. 292.50. 87 Lectures 22.5 hours Programming Line Print Add Notes Bookmark this page
[ { "code": null, "e": 3990, "s": 3892, "text": "Q 1 - The average of 20 numbers is zero. Of them, at the most, how many may be greater than zero?" }, { "code": null, "e": 3997, "s": 3990, "text": "A - 19" }, { "code": null, "e": 4004, "s": 3997, "text": "B - 10" }, { "code": null, "e": 4010, "s": 4004, "text": "C - 0" }, { "code": null, "e": 4016, "s": 4010, "text": "D - 1" }, { "code": null, "e": 4027, "s": 4016, "text": "Answer - A" }, { "code": null, "e": 4039, "s": 4027, "text": "Explanation" }, { "code": null, "e": 4224, "s": 4039, "text": "Average of 20 numbers = 0. \n Therefore Sum of 20 numbers = (0 x 20) = 0 \nIt is quite possible that 19 of these numbers may be positive and if their sum is a, then 20th number is (-a).\n" }, { "code": null, "e": 4309, "s": 4224, "text": "Q 2 - Find the average of all the numbers between 6 and 34 which are divisible by 5?" }, { "code": null, "e": 4316, "s": 4309, "text": "A - 30" }, { "code": null, "e": 4323, "s": 4316, "text": "B - 24" }, { "code": null, "e": 4330, "s": 4323, "text": "C - 20" }, { "code": null, "e": 4337, "s": 4330, "text": "D - 18" }, { "code": null, "e": 4348, "s": 4337, "text": "Answer - C" }, { "code": null, "e": 4360, "s": 4348, "text": "Explanation" }, { "code": null, "e": 4412, "s": 4360, "text": "Average = (10 + 15 + 20 + 25 + 30)⁄5 = 100⁄5 = 20.\n" }, { "code": null, "e": 4463, "s": 4412, "text": "Q 3 - The average of first five multiples of 3 is?" }, { "code": null, "e": 4470, "s": 4463, "text": "A - 15" }, { "code": null, "e": 4477, "s": 4470, "text": "B - 12" }, { "code": null, "e": 4483, "s": 4477, "text": "C - 3" }, { "code": null, "e": 4489, "s": 4483, "text": "D - 9" }, { "code": null, "e": 4500, "s": 4489, "text": "Answer - D" }, { "code": null, "e": 4512, "s": 4500, "text": "Explanation" }, { "code": null, "e": 4557, "s": 4512, "text": "Average = 3(1 + 2 + 3 + 4 + 5)⁄5 = 45⁄5 = 9\n" }, { "code": null, "e": 4607, "s": 4557, "text": "Q 4 - The average of first nine prime numbers is?" }, { "code": null, "e": 4614, "s": 4607, "text": "A - 10" }, { "code": null, "e": 4624, "s": 4614, "text": "B - 111⁄9" }, { "code": null, "e": 4630, "s": 4624, "text": "C - 9" }, { "code": null, "e": 4640, "s": 4630, "text": "D - 112⁄9" }, { "code": null, "e": 4651, "s": 4640, "text": "Answer - B" }, { "code": null, "e": 4663, "s": 4651, "text": "Explanation" }, { "code": null, "e": 4733, "s": 4663, "text": "Average = (2 + 3 + 5 + 7 + 11 + 13 + 17 + 19 + 23)⁄9 = 100⁄9 = 111⁄9\n" }, { "code": null, "e": 4849, "s": 4733, "text": "Q 5 - A student was asked to find the arithmetic mean of the numbers 3, 11, 7, 9, 15, 13, 8, 19, 17, 21, 14, and z?" }, { "code": null, "e": 4855, "s": 4849, "text": "A - 3" }, { "code": null, "e": 4861, "s": 4855, "text": "B - 7" }, { "code": null, "e": 4868, "s": 4861, "text": "C - 17" }, { "code": null, "e": 4875, "s": 4868, "text": "D - 31" }, { "code": null, "e": 4886, "s": 4875, "text": "Answer - B" }, { "code": null, "e": 4898, "s": 4886, "text": "Explanation" }, { "code": null, "e": 5021, "s": 4898, "text": "Clearly, we have (3 + 11 + 7 + 9 + 15 + 13 + 8 + 19 + 17 + 21 + 14 + z)⁄12 = 12 \nor 137 + z = 144 \n\nor z = 144 - 137 = 7.\n" }, { "code": null, "e": 5144, "s": 5021, "text": "Q 6 - If the mean of 5 observation z, z + 2, z + 4, z + 6 and z + 8 is 11, then the mean of the last three observation is?" }, { "code": null, "e": 5151, "s": 5144, "text": "A - 11" }, { "code": null, "e": 5158, "s": 5151, "text": "B - 13" }, { "code": null, "e": 5165, "s": 5158, "text": "C - 15" }, { "code": null, "e": 5172, "s": 5165, "text": "D - 17" }, { "code": null, "e": 5183, "s": 5172, "text": "Answer - B" }, { "code": null, "e": 5195, "s": 5183, "text": "Explanation" }, { "code": null, "e": 5379, "s": 5195, "text": "we have : (z + (z + 2) + (z + 4) + (z + 6) + (z + 8))⁄5 = 11 or 5z + 20 = 55 or z = 7. \nSo the numbers are 7, 9, 11, 13, 15. \ntherefore required mean = (11 + 13 + 15⁄3) \n= 39⁄3 = 13.\n" }, { "code": null, "e": 5494, "s": 5379, "text": "Q 7 - The average of the two-digit numbers, which remain the same when the digits interchange their positions, is?" }, { "code": null, "e": 5501, "s": 5494, "text": "A - 55" }, { "code": null, "e": 5508, "s": 5501, "text": "B - 33" }, { "code": null, "e": 5515, "s": 5508, "text": "C - 44" }, { "code": null, "e": 5522, "s": 5515, "text": "D - 66" }, { "code": null, "e": 5533, "s": 5522, "text": "Answer - A" }, { "code": null, "e": 5545, "s": 5533, "text": "Explanation" }, { "code": null, "e": 5690, "s": 5545, "text": "Average = (11 + 22 + 33 + 44 + 55 + 66 + 77 + 88 + 99⁄9) \n((11 + 99) + (22 + 88) + (33 + 77) + (44 + 66) +55⁄9) \n(4 x 110 + 55⁄9) \n(495⁄9) = 55\n" }, { "code": null, "e": 5782, "s": 5690, "text": "Q 8 - The average of a non-zero number and its square is 5 times the number. The number is?" }, { "code": null, "e": 5788, "s": 5782, "text": "A - 9" }, { "code": null, "e": 5795, "s": 5788, "text": "B - 17" }, { "code": null, "e": 5802, "s": 5795, "text": "C - 29" }, { "code": null, "e": 5810, "s": 5802, "text": "D - 295" }, { "code": null, "e": 5821, "s": 5810, "text": "Answer - A" }, { "code": null, "e": 5833, "s": 5821, "text": "Explanation" }, { "code": null, "e": 5946, "s": 5833, "text": "Let the number be z. then, \nz + z 2⁄2 = 5z \n= z 2 - 9z = 0 \n\nz (z - 9) = 0 \nz = 0 or z = 9 \nso the number is 9.\n" }, { "code": null, "e": 6028, "s": 5946, "text": "Q 9 - The average of 7 consecutive number is 20. The largest of these numbers is?" }, { "code": null, "e": 6035, "s": 6028, "text": "A - 20" }, { "code": null, "e": 6042, "s": 6035, "text": "B - 22" }, { "code": null, "e": 6049, "s": 6042, "text": "C - 23" }, { "code": null, "e": 6056, "s": 6049, "text": "D - 24" }, { "code": null, "e": 6067, "s": 6056, "text": "Answer - C" }, { "code": null, "e": 6079, "s": 6067, "text": "Explanation" }, { "code": null, "e": 6294, "s": 6079, "text": "Let the number be z, z + 1, z + 2, z + 3 ,z + 4, z + 5 ,z + 6. then, (z + (z + 1) + (z + 2) + (z + 3) + (z + 4) + (z + 5) + (z + 6))⁄7 = 20\n7z + 21 = 140 or 7z = 119 or z = 17 \nLargest number = z + 6 = 17 + 6 = 23\n" }, { "code": null, "e": 6415, "s": 6294, "text": "Q 10 - The average of five consecutive odd numbers is 61. What is the difference between the highest and lowest numbers?" }, { "code": null, "e": 6421, "s": 6415, "text": "A - 9" }, { "code": null, "e": 6427, "s": 6421, "text": "B - 8" }, { "code": null, "e": 6434, "s": 6427, "text": "C - 10" }, { "code": null, "e": 6441, "s": 6434, "text": "D - 11" }, { "code": null, "e": 6452, "s": 6441, "text": "Answer - B" }, { "code": null, "e": 6464, "s": 6452, "text": "Explanation" }, { "code": null, "e": 6646, "s": 6464, "text": "Let the number be z, z + 2, z + 4, z + 6 and z + 8. then, (z + (z + 2) + (z + 4) + (z + 6) + (z + 8))⁄5 = 61\n5z + 20 = 305 or z = 57 \nso the required number is = (57 + 8) - 57 = 8\n" }, { "code": null, "e": 6776, "s": 6646, "text": "Q 11 - The sum of three consecutive odd numbers is 38 more than the average of these numbers. What is the first of these numbers?" }, { "code": null, "e": 6783, "s": 6776, "text": "A - 17" }, { "code": null, "e": 6790, "s": 6783, "text": "B - 13" }, { "code": null, "e": 6797, "s": 6790, "text": "C - 19" }, { "code": null, "e": 6806, "s": 6797, "text": "D - none" }, { "code": null, "e": 6817, "s": 6806, "text": "Answer - A" }, { "code": null, "e": 6829, "s": 6817, "text": "Explanation" }, { "code": null, "e": 6963, "s": 6829, "text": "Let the number be z, z + 2, and z + 4. then, (z + z + 2 + z + 4) - (z + z + 2 + z + 4)⁄3 = 38\n2(3z + 6) = 114 or 6z = 102 or z = 17.\n" }, { "code": null, "e": 7095, "s": 6963, "text": "Q 12 - The average age of the boys in a class is 16 years and that of the girls is 15 years. The average age for the whole class is" }, { "code": null, "e": 7108, "s": 7095, "text": "A - 15 years" }, { "code": null, "e": 7123, "s": 7108, "text": "B - 15.5 years" }, { "code": null, "e": 7136, "s": 7123, "text": "C - 16 years" }, { "code": null, "e": 7186, "s": 7136, "text": "D - Cannot be computed with the given information" }, { "code": null, "e": 7197, "s": 7186, "text": "Answer - D" }, { "code": null, "e": 7209, "s": 7197, "text": "Explanation" }, { "code": null, "e": 7358, "s": 7209, "text": "Clearly to find the average we ought to know the number of boys, girls or students in the class neither of which is given. So, data is inadequate. \n" }, { "code": null, "e": 7602, "s": 7358, "text": "Q 13 - The average annual income (in Rs.) of certain agricultural workers is S and that of other workers is T. The number of agriculture workers is 11 times that of other workers. Then the average monthly income (in Rs.) of all the workers is?" }, { "code": null, "e": 7614, "s": 7602, "text": "A - S + T⁄2" }, { "code": null, "e": 7629, "s": 7614, "text": "B - 11S + T⁄12" }, { "code": null, "e": 7642, "s": 7629, "text": "C - 1 +⁄11ST" }, { "code": null, "e": 7656, "s": 7642, "text": "D - S + 11T⁄2" }, { "code": null, "e": 7667, "s": 7656, "text": "Answer - B" }, { "code": null, "e": 7679, "s": 7667, "text": "Explanation" }, { "code": null, "e": 7863, "s": 7679, "text": "Let the number of other workers be z. \nthen, number of agricultural workers = 11z \nTotal number of workers = 12z \n\nTherefore Average monthly salary = S x 11z + T x z⁄12z = 11S + T⁄12\n" }, { "code": null, "e": 8099, "s": 7863, "text": "Q 14 - A family consists of grandparents, parents and three grandchildren. The average age of the grandparents is 67 years, that of the parent is 35 years and that of the grandchildren is 6 years. What is the average age of the family?" }, { "code": null, "e": 8109, "s": 8099, "text": "A - 284⁄7" }, { "code": null, "e": 8119, "s": 8109, "text": "B - 315⁄7" }, { "code": null, "e": 8129, "s": 8119, "text": "C - 321⁄7" }, { "code": null, "e": 8138, "s": 8129, "text": "D - none" }, { "code": null, "e": 8149, "s": 8138, "text": "Answer - B" }, { "code": null, "e": 8161, "s": 8149, "text": "Explanation" }, { "code": null, "e": 8254, "s": 8161, "text": "Required average = (67 x 2 + 35 x 2 + 6 x 3⁄2 + 2 + 3) = (134 + 70 + 18⁄7) \n= 222⁄7 = 315⁄7\n" }, { "code": null, "e": 8424, "s": 8254, "text": "Q 15 - A library has an average of 510 visitors on Sundays and 240 on other days. The average number of visiters per day in a month of 30 days begining with a Sunday is?" }, { "code": null, "e": 8432, "s": 8424, "text": "A - 276" }, { "code": null, "e": 8440, "s": 8432, "text": "B - 280" }, { "code": null, "e": 8448, "s": 8440, "text": "C - 285" }, { "code": null, "e": 8456, "s": 8448, "text": "D - 250" }, { "code": null, "e": 8467, "s": 8456, "text": "Answer - C" }, { "code": null, "e": 8479, "s": 8467, "text": "Explanation" }, { "code": null, "e": 8632, "s": 8479, "text": "Since the month begins with a sunday, so there will be five sundays in the month \nTherefore Required average = (510 x 5 + 240 x 25⁄30) \n= 8550⁄30 = 285\n" }, { "code": null, "e": 8781, "s": 8632, "text": "Q 16 - If the average marks of three batches of 55, 60 and 45 students respectively is 50, 55 and 60, then the average marks of all the students is?" }, { "code": null, "e": 8791, "s": 8781, "text": "A - 53.33" }, { "code": null, "e": 8801, "s": 8791, "text": "B - 54.68" }, { "code": null, "e": 8808, "s": 8801, "text": "C - 55" }, { "code": null, "e": 8817, "s": 8808, "text": "D - none" }, { "code": null, "e": 8828, "s": 8817, "text": "Answer - B" }, { "code": null, "e": 8840, "s": 8828, "text": "Explanation" }, { "code": null, "e": 8950, "s": 8840, "text": "Required average = (55 x 50 + 60 x 55 + 45 x 60⁄55 + 60 + 45) \n(2750 + 3300 + 2700⁄160) = (8750⁄160) = 54.68\n" }, { "code": null, "e": 9112, "s": 8950, "text": "Q 17 - The average weight of 16 boys in a class is 50.25 kgs and that of the remaining 8 boys is 45.15 kgs. Find the average weight of all the boys in the class?" }, { "code": null, "e": 9122, "s": 9112, "text": "A - 48.55" }, { "code": null, "e": 9132, "s": 9122, "text": "B - 49.25" }, { "code": null, "e": 9139, "s": 9132, "text": "C - 45" }, { "code": null, "e": 9146, "s": 9139, "text": "D - 47" }, { "code": null, "e": 9157, "s": 9146, "text": "Answer - A" }, { "code": null, "e": 9169, "s": 9157, "text": "Explanation" }, { "code": null, "e": 9263, "s": 9169, "text": "Required average = (50.25 x 16 + 45.15 x 8⁄16 + 8) \n(804 + 361.20⁄24) = (1165.20⁄24) = 48.55\n" }, { "code": null, "e": 9456, "s": 9263, "text": "Q 18 - A car owner buys petrol at Rs. 7.50, Rs. 8 and Rs. 8.50 per litre for three successive years. What approximately is the average cost per litre of petrol if he spends Rs. 4000 each year?" }, { "code": null, "e": 9465, "s": 9456, "text": "A - 7.98" }, { "code": null, "e": 9471, "s": 9465, "text": "B - 8" }, { "code": null, "e": 9480, "s": 9471, "text": "C - 8.50" }, { "code": null, "e": 9486, "s": 9480, "text": "D - 9" }, { "code": null, "e": 9497, "s": 9486, "text": "Answer - A" }, { "code": null, "e": 9509, "s": 9497, "text": "Explanation" }, { "code": null, "e": 9765, "s": 9509, "text": "Total quantity of petrol consumed in 3 years. = (4000⁄7.50 + 4000⁄8 + 4000⁄8.50) litres \n= 4000 2⁄15 + 1⁄8 2⁄17 = 76700⁄51 litres \nTotal amount spent = Rs. (3 x 4000) = Rs 12000 \nTherefore Average cost = Rs. (12000 x 51⁄76700) = Rs. 6120⁄767 \n= Rs. 7.98.\n" }, { "code": null, "e": 9894, "s": 9765, "text": "Q 19 - The average of six numbers is z and the average of three of these is y. If the average of the remaining three is w, then?" }, { "code": null, "e": 9911, "s": 9894, "text": "A - 2z = 2y + 2w" }, { "code": null, "e": 9927, "s": 9911, "text": "B - z = 2y + 2w" }, { "code": null, "e": 9941, "s": 9927, "text": "C - z = y + w" }, { "code": null, "e": 9956, "s": 9941, "text": "D - 2z = y + w" }, { "code": null, "e": 9967, "s": 9956, "text": "Answer - D" }, { "code": null, "e": 9979, "s": 9967, "text": "Explanation" }, { "code": null, "e": 10028, "s": 9979, "text": "Clearly, we have: z = 3y + 3w⁄6 \nor 2z = y + w.\n" }, { "code": null, "e": 10218, "s": 10028, "text": "Q 20 - Out of 9 persons, 8 persons spent Rs. 30 each for their meals. The ninth one spent Rs. 20 more than the average expenditure of all the nine. The total money spent by all of them was?" }, { "code": null, "e": 10226, "s": 10218, "text": "A - 290" }, { "code": null, "e": 10234, "s": 10226, "text": "B - 260" }, { "code": null, "e": 10245, "s": 10234, "text": "C - 292.50" }, { "code": null, "e": 10256, "s": 10245, "text": "D - 400.50" }, { "code": null, "e": 10267, "s": 10256, "text": "Answer - C" }, { "code": null, "e": 10279, "s": 10267, "text": "Explanation" }, { "code": null, "e": 10454, "s": 10279, "text": "Let the average expenditure be Rs z then, \n9z = 8 x 30 + (z + 20) or 9z = z + 260 or 8z = 260 or z = 32.50. \nTherefore total money spent = 9z = Rs. (9 x 32.50) = Rs. 292.50.\n" }, { "code": null, "e": 10490, "s": 10454, "text": "\n 87 Lectures \n 22.5 hours \n" }, { "code": null, "e": 10508, "s": 10490, "text": " Programming Line" }, { "code": null, "e": 10515, "s": 10508, "text": " Print" }, { "code": null, "e": 10526, "s": 10515, "text": " Add Notes" } ]
array_sum() function in PHP
The array_sum() function returns the sum of the values in an array. The returned value can be integer or float. It returns 0 if the array is empty. array_sum(arr) arr − the specified array The array_sum() function returns the sum of values. The returned value can be integer or float. It returns 0 if the array is empty. The following is an example − Live Demo <?php $arr = array(50, 100, 150, 300); echo array_sum($arr); ?> The following is the output − 600 Let us see another example − Live Demo <?php $arr = array("a"=>29.8,"b"=>66.4); echo array_sum($arr); ?> The following is the output − 96.2
[ { "code": null, "e": 1210, "s": 1062, "text": "The array_sum() function returns the sum of the values in an array. The returned value can be integer or float. It returns 0 if the array is empty." }, { "code": null, "e": 1225, "s": 1210, "text": "array_sum(arr)" }, { "code": null, "e": 1251, "s": 1225, "text": "arr − the specified array" }, { "code": null, "e": 1383, "s": 1251, "text": "The array_sum() function returns the sum of values. The returned value can be integer or float. It returns 0 if the array is empty." }, { "code": null, "e": 1413, "s": 1383, "text": "The following is an example −" }, { "code": null, "e": 1424, "s": 1413, "text": " Live Demo" }, { "code": null, "e": 1488, "s": 1424, "text": "<?php\n$arr = array(50, 100, 150, 300);\necho array_sum($arr);\n?>" }, { "code": null, "e": 1518, "s": 1488, "text": "The following is the output −" }, { "code": null, "e": 1522, "s": 1518, "text": "600" }, { "code": null, "e": 1551, "s": 1522, "text": "Let us see another example −" }, { "code": null, "e": 1562, "s": 1551, "text": " Live Demo" }, { "code": null, "e": 1628, "s": 1562, "text": "<?php\n$arr = array(\"a\"=>29.8,\"b\"=>66.4);\necho array_sum($arr);\n?>" }, { "code": null, "e": 1658, "s": 1628, "text": "The following is the output −" }, { "code": null, "e": 1663, "s": 1658, "text": "96.2" } ]
What is the difference between = and == operators in Python?
In Python = symbol is defined as assignment operator. It requires one variable on its left and an expression on its right. Value of the expression on right is assigned to variable on left. Expression and name of variable are not interchangeable. >>> a=10 >>> b=20 >>> c=a+b >>> a,b,c (10, 20, 30) >>> a+b=c SyntaxError: can't assign to operator The == symbol is a comparison operator and called equal to operator. It returns true if operands on either side are equal, otherwise it returns false >>> 10+2 == 10 False >>> (10+2) == 12 True >>> 'computer' == 'Computer' False >>> 'computer' == "computer" True
[ { "code": null, "e": 1308, "s": 1062, "text": "In Python = symbol is defined as assignment operator. It requires one variable on its left and an expression on its right. Value of the expression on right is assigned to variable on left. Expression and name of variable are not interchangeable." }, { "code": null, "e": 1407, "s": 1308, "text": ">>> a=10\n>>> b=20\n>>> c=a+b\n>>> a,b,c\n(10, 20, 30)\n>>> a+b=c\nSyntaxError: can't assign to operator" }, { "code": null, "e": 1557, "s": 1407, "text": "The == symbol is a comparison operator and called equal to operator. It returns true if operands on either side are equal, otherwise it returns false" }, { "code": null, "e": 1669, "s": 1557, "text": ">>> 10+2 == 10\nFalse\n>>> (10+2) == 12\nTrue\n>>> 'computer' == 'Computer'\nFalse\n>>> 'computer' == \"computer\"\nTrue" } ]
Float parseFloat() method in Java with examples - GeeksforGeeks
26 Oct, 2018 The parseFloat() method in Float Class is a built in method in Java that returns a new float initialized to the value represented by the specified String, as done by the valueOf method of class Float. Syntax: public static float parseFloat(String s) Parameters: It accepts a single mandatory parameter s which specifies the string to be parsed. Return type: It returns e float value represented by the string argument. Exception: The function throws two exceptions which are described below: NullPointerException– when the string parsed is null NumberFormatException– when the string parsed does not contain a parsable float Below is the implementation of the above method. Program 1: // Java Code to implement// parseFloat() method of Float class class GFG { // Driver method public static void main(String[] args) { String str = "100"; // returns the float value // represented by the string argument float val = Float.parseFloat(str); // prints the float value System.out.println("Value = " + val); }} Value = 100.0 Program 2: To show NumberFormatException // Java Code to implement// parseFloat() method of Float class class GFG { // Driver method public static void main(String[] args) { try { String str = ""; // returns the float value // represented by the string argument float val = Float.parseFloat(str); // prints the float value System.out.println("Value = " + val); } catch (Exception e) { System.out.println("Exception: " + e); } }} Exception: java.lang.NumberFormatException: empty String Program 3: To show NullPointerException // Java Code to implement// parseFloat() method of Float class class GFG { // Driver method public static void main(String[] args) { try { String str = null; // returns the float value // represented by the string argument float val = Float.parseFloat(str); // prints the float value System.out.println("Value = " + val); } catch (Exception e) { System.out.println("Exception: " + e); } }} Exception: java.lang.NullPointerException Reference: https://docs.oracle.com/javase/7/docs/api/java/lang/Float.html#parseFloat(java.lang.String) java-basics Java-Float Java-Functions Java-lang package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples How to iterate any Map in Java Interfaces in Java Initialize an ArrayList in Java ArrayList in Java Stack Class in Java Multidimensional Arrays in Java Singleton Class in Java LinkedList in Java
[ { "code": null, "e": 24142, "s": 24114, "text": "\n26 Oct, 2018" }, { "code": null, "e": 24343, "s": 24142, "text": "The parseFloat() method in Float Class is a built in method in Java that returns a new float initialized to the value represented by the specified String, as done by the valueOf method of class Float." }, { "code": null, "e": 24351, "s": 24343, "text": "Syntax:" }, { "code": null, "e": 24392, "s": 24351, "text": "public static float parseFloat(String s)" }, { "code": null, "e": 24487, "s": 24392, "text": "Parameters: It accepts a single mandatory parameter s which specifies the string to be parsed." }, { "code": null, "e": 24561, "s": 24487, "text": "Return type: It returns e float value represented by the string argument." }, { "code": null, "e": 24634, "s": 24561, "text": "Exception: The function throws two exceptions which are described below:" }, { "code": null, "e": 24687, "s": 24634, "text": "NullPointerException– when the string parsed is null" }, { "code": null, "e": 24767, "s": 24687, "text": "NumberFormatException– when the string parsed does not contain a parsable float" }, { "code": null, "e": 24816, "s": 24767, "text": "Below is the implementation of the above method." }, { "code": null, "e": 24827, "s": 24816, "text": "Program 1:" }, { "code": "// Java Code to implement// parseFloat() method of Float class class GFG { // Driver method public static void main(String[] args) { String str = \"100\"; // returns the float value // represented by the string argument float val = Float.parseFloat(str); // prints the float value System.out.println(\"Value = \" + val); }}", "e": 25208, "s": 24827, "text": null }, { "code": null, "e": 25223, "s": 25208, "text": "Value = 100.0\n" }, { "code": null, "e": 25264, "s": 25223, "text": "Program 2: To show NumberFormatException" }, { "code": "// Java Code to implement// parseFloat() method of Float class class GFG { // Driver method public static void main(String[] args) { try { String str = \"\"; // returns the float value // represented by the string argument float val = Float.parseFloat(str); // prints the float value System.out.println(\"Value = \" + val); } catch (Exception e) { System.out.println(\"Exception: \" + e); } }}", "e": 25780, "s": 25264, "text": null }, { "code": null, "e": 25838, "s": 25780, "text": "Exception: java.lang.NumberFormatException: empty String\n" }, { "code": null, "e": 25878, "s": 25838, "text": "Program 3: To show NullPointerException" }, { "code": "// Java Code to implement// parseFloat() method of Float class class GFG { // Driver method public static void main(String[] args) { try { String str = null; // returns the float value // represented by the string argument float val = Float.parseFloat(str); // prints the float value System.out.println(\"Value = \" + val); } catch (Exception e) { System.out.println(\"Exception: \" + e); } }}", "e": 26398, "s": 25878, "text": null }, { "code": null, "e": 26441, "s": 26398, "text": "Exception: java.lang.NullPointerException\n" }, { "code": null, "e": 26544, "s": 26441, "text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/lang/Float.html#parseFloat(java.lang.String)" }, { "code": null, "e": 26556, "s": 26544, "text": "java-basics" }, { "code": null, "e": 26567, "s": 26556, "text": "Java-Float" }, { "code": null, "e": 26582, "s": 26567, "text": "Java-Functions" }, { "code": null, "e": 26600, "s": 26582, "text": "Java-lang package" }, { "code": null, "e": 26605, "s": 26600, "text": "Java" }, { "code": null, "e": 26610, "s": 26605, "text": "Java" }, { "code": null, "e": 26708, "s": 26610, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26717, "s": 26708, "text": "Comments" }, { "code": null, "e": 26730, "s": 26717, "text": "Old Comments" }, { "code": null, "e": 26781, "s": 26730, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 26811, "s": 26781, "text": "HashMap in Java with Examples" }, { "code": null, "e": 26842, "s": 26811, "text": "How to iterate any Map in Java" }, { "code": null, "e": 26861, "s": 26842, "text": "Interfaces in Java" }, { "code": null, "e": 26893, "s": 26861, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 26911, "s": 26893, "text": "ArrayList in Java" }, { "code": null, "e": 26931, "s": 26911, "text": "Stack Class in Java" }, { "code": null, "e": 26963, "s": 26931, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 26987, "s": 26963, "text": "Singleton Class in Java" } ]
How to copy from clipboard using tkinter without displaying a window
Let us suppose that in a particular application, we have to copy the content residing in the clipboard. We can access the clipboard using clipboard_get(). After copying the text from the clipboard, it will reside in the cache memory through which we can debug the program and display the text in the frame, then we can see the copied text from the clipboard. First, we will create a window which will store the copied characters or text from the source using the get method. Once the execution is done, then we can hide the window by using the “withdraw” method in tkinter. It helps to get rid of the window. #Import the tkinter library from tkinter import * #Create an instance of tkinter canvas by executing it win = Tk() win.geometry("600x200") #Get the data from the clipboard cliptext = win.clipboard_get() #Create the label for the clipboard lab=Label(win, text = cliptext) lab.pack() #Keep Running the window win.mainloop() Running the above code snippet will copy the content from the clipboard and display it in a window. To avoid the window, we can use “withdraw” method, from tkinter import * win = Tk() win.withdraw() number = win.clipboard_get()
[ { "code": null, "e": 1217, "s": 1062, "text": "Let us suppose that in a particular application, we have to copy the content residing in the clipboard. We can access the clipboard using clipboard_get()." }, { "code": null, "e": 1421, "s": 1217, "text": "After copying the text from the clipboard, it will reside in the cache memory through\nwhich we can debug the program and display the text in the frame, then we can\nsee the copied text from the clipboard." }, { "code": null, "e": 1671, "s": 1421, "text": "First, we will create a window which will store the copied characters or text from the source using the get method. Once the execution is done, then we can hide the window by using the “withdraw” method in tkinter. It helps to get rid of the window." }, { "code": null, "e": 1997, "s": 1671, "text": "#Import the tkinter library\nfrom tkinter import *\n\n#Create an instance of tkinter canvas by executing it\nwin = Tk()\nwin.geometry(\"600x200\")\n\n#Get the data from the clipboard\ncliptext = win.clipboard_get()\n\n#Create the label for the clipboard\nlab=Label(win, text = cliptext)\nlab.pack()\n\n#Keep Running the window\nwin.mainloop()" }, { "code": null, "e": 2097, "s": 1997, "text": "Running the above code snippet will copy the content from the clipboard and display it in a window." }, { "code": null, "e": 2148, "s": 2097, "text": "To avoid the window, we can use “withdraw” method," }, { "code": null, "e": 2225, "s": 2148, "text": "from tkinter import *\nwin = Tk()\nwin.withdraw()\nnumber = win.clipboard_get()" } ]
Extract unique values from an array - JavaScript
Suppose we have an array that contains duplicate elements like this − const arr = [1,1,2,2,3,4,4,5]; We are required to write a JavaScript function that takes in one such array and returns a new array. The array should only contain the elements that only appear once in the original array. Following is the code − const arr = [1,1,2,2,3,4,4,5]; const extractUnique = arr => { const res = []; for(let i = 0; i < arr.length; i++){ if(arr.lastIndexOf(arr[i]) !== arr.indexOf(arr[i])){ continue; }; res.push(arr[i]); }; return res; }; console.log(extractUnique(arr)); This will produce the following output in console − [ 3, 5 ]
[ { "code": null, "e": 1132, "s": 1062, "text": "Suppose we have an array that contains duplicate elements like this −" }, { "code": null, "e": 1163, "s": 1132, "text": "const arr = [1,1,2,2,3,4,4,5];" }, { "code": null, "e": 1352, "s": 1163, "text": "We are required to write a JavaScript function that takes in one such array and returns a new array. The array should only contain the elements that only appear once in the original array." }, { "code": null, "e": 1376, "s": 1352, "text": "Following is the code −" }, { "code": null, "e": 1665, "s": 1376, "text": "const arr = [1,1,2,2,3,4,4,5];\nconst extractUnique = arr => {\n const res = [];\n for(let i = 0; i < arr.length; i++){\n if(arr.lastIndexOf(arr[i]) !== arr.indexOf(arr[i])){\n continue;\n };\n res.push(arr[i]);\n };\n return res;\n};\nconsole.log(extractUnique(arr));" }, { "code": null, "e": 1717, "s": 1665, "text": "This will produce the following output in console −" }, { "code": null, "e": 1726, "s": 1717, "text": "[ 3, 5 ]" } ]
How to do a sum of previous row value with the current row and display the result in another row with MySQL cross join?
Let us first create a table − mysql> create table DemoTable(Value int); Query OK, 0 rows affected (1.79 sec) Insert some records in the table using insert command − mysql> insert into DemoTable values(50); Query OK, 1 row affected (0.24 sec) mysql> insert into DemoTable values(20); Query OK, 1 row affected (0.68 sec) mysql> insert into DemoTable values(30); Query OK, 1 row affected (0.18 sec) Display all records from the table using select statement − mysql> select *from DemoTable; This will produce the following output − +-------+ | Value | +-------+ | 50 | | 20 | | 30 | +-------+ 3 rows in set (0.00 sec) Here is the query to do a sum of previous rows in MySQL a sum of previous rows − mysql> select t.Value, (@s := @s + t.Value) as Number from DemoTable t cross join (select @s := 0) p order by t.Value; This will produce the following output − +-------+--------+ | Value | Number | +-------+--------+ | 20 | 20 | | 30 | 50 | | 50 | 100 | +-------+--------+ 3 rows in set (0.07 sec)
[ { "code": null, "e": 1092, "s": 1062, "text": "Let us first create a table −" }, { "code": null, "e": 1171, "s": 1092, "text": "mysql> create table DemoTable(Value int);\nQuery OK, 0 rows affected (1.79 sec)" }, { "code": null, "e": 1227, "s": 1171, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1458, "s": 1227, "text": "mysql> insert into DemoTable values(50);\nQuery OK, 1 row affected (0.24 sec)\nmysql> insert into DemoTable values(20);\nQuery OK, 1 row affected (0.68 sec)\nmysql> insert into DemoTable values(30);\nQuery OK, 1 row affected (0.18 sec)" }, { "code": null, "e": 1518, "s": 1458, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1549, "s": 1518, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 1590, "s": 1549, "text": "This will produce the following output −" }, { "code": null, "e": 1685, "s": 1590, "text": "+-------+\n| Value |\n+-------+\n| 50 |\n| 20 |\n| 30 |\n+-------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 1766, "s": 1685, "text": "Here is the query to do a sum of previous rows in MySQL a sum of previous rows −" }, { "code": null, "e": 1900, "s": 1766, "text": "mysql> select t.Value,\n (@s := @s + t.Value) as Number\n from DemoTable t cross join\n (select @s := 0) p\n order by t.Value;" }, { "code": null, "e": 1941, "s": 1900, "text": "This will produce the following output −" }, { "code": null, "e": 2099, "s": 1941, "text": "+-------+--------+\n| Value | Number |\n+-------+--------+\n| 20 | 20 |\n| 30 | 50 |\n| 50 | 100 |\n+-------+--------+\n3 rows in set (0.07 sec)" } ]
How to write an image file in internal storage in android?
This example demonstrates How to write an image file in internal storage in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:layout_height = "match_parent" tools:context = ".MainActivity" android:orientation = "vertical"> <Button android:id = "@+id/save" android:text = "save" android:layout_width = "wrap_content" android:layout_height = "wrap_content" /> </LinearLayout> In the above code, we have taken a button. When user click on button, It will store data in internal storage. Step 3 − Add the following code to src/MainActivity.java package com.example.andy.myapplication; import android.content.Context; import android.content.ContextWrapper; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import java.io.File; import java.io.FileOutputStream; public class MainActivity extends AppCompatActivity { Button save; Bitmap bitmap; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Drawable drawable = getResources().getDrawable(R.drawable.mario); bitmap = ((BitmapDrawable) drawable).getBitmap(); save = findViewById(R.id.save); save.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ContextWrapper cw = new ContextWrapper(getApplicationContext()); File directory = cw.getDir("imageDir", Context.MODE_PRIVATE); File file = new File(directory, "UniqueFileName" + ".jpg"); if (!file.exists()) { Log.d("path", file.toString()); FileOutputStream fos = null; try { fos = new FileOutputStream(file); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos); fos.flush(); fos.close(); } catch (java.io.IOException e) { e.printStackTrace(); } } } }); } } Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen - In the above result, click on save button to store image in internal storage as shown below – Click here to download the project code
[ { "code": null, "e": 1147, "s": 1062, "text": "This example demonstrates How to write an image file in internal storage in android." }, { "code": null, "e": 1276, "s": 1147, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1341, "s": 1276, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1802, "s": 1341, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\nxmlns:tools = \"http://schemas.android.com/tools\"\nandroid:layout_width = \"match_parent\"\nandroid:layout_height = \"match_parent\"\ntools:context = \".MainActivity\"\nandroid:orientation = \"vertical\">\n<Button\nandroid:id = \"@+id/save\"\nandroid:text = \"save\"\nandroid:layout_width = \"wrap_content\"\nandroid:layout_height = \"wrap_content\" />\n</LinearLayout>" }, { "code": null, "e": 1912, "s": 1802, "text": "In the above code, we have taken a button. When user click on button, It will store data in internal storage." }, { "code": null, "e": 1969, "s": 1912, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3645, "s": 1969, "text": "package com.example.andy.myapplication;\nimport android.content.Context;\nimport android.content.ContextWrapper;\nimport android.graphics.Bitmap;\nimport android.graphics.drawable.BitmapDrawable;\nimport android.graphics.drawable.Drawable;\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.util.Log;\nimport android.view.View;\nimport android.widget.Button;\nimport java.io.File;\nimport java.io.FileOutputStream;\npublic class MainActivity extends AppCompatActivity {\n Button save;\n Bitmap bitmap;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n Drawable drawable = getResources().getDrawable(R.drawable.mario);\n bitmap = ((BitmapDrawable) drawable).getBitmap();\n save = findViewById(R.id.save);\n save.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n ContextWrapper cw = new ContextWrapper(getApplicationContext());\n File directory = cw.getDir(\"imageDir\", Context.MODE_PRIVATE);\n File file = new File(directory, \"UniqueFileName\" + \".jpg\");\n if (!file.exists()) {\n Log.d(\"path\", file.toString());\n FileOutputStream fos = null;\n try {\n fos = new FileOutputStream(file);\n bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);\n fos.flush();\n fos.close();\n } catch (java.io.IOException e) {\n e.printStackTrace();\n }\n }\n }\n });\n }\n}" }, { "code": null, "e": 3992, "s": 3645, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen -" }, { "code": null, "e": 4086, "s": 3992, "text": "In the above result, click on save button to store image in internal storage as shown below –" }, { "code": null, "e": 4126, "s": 4086, "text": "Click here to download the project code" } ]
remove null value from a String array in Java
Following program creates an array with null values. Convert it a list with not-null values only and then get the array of that list. import java.util.ArrayList; import java.util.List; public class Tester { public static void main(String[] args) { String[] array = {"I", null, "love", null, "Java" }; List<String> values = new ArrayList<String>(); for(String data: array) { if(data != null) { values.add(data); } } String[] target = values.toArray(new String[values.size()]); for(String data: target) { System.out.println(data + " "); } } } I love Java
[ { "code": null, "e": 1196, "s": 1062, "text": "Following program creates an array with null values. Convert it a list with not-null values only and then get the array of that list." }, { "code": null, "e": 1691, "s": 1196, "text": "import java.util.ArrayList;\nimport java.util.List;\npublic class Tester {\n public static void main(String[] args) {\n String[] array = {\"I\", null, \"love\", null, \"Java\" };\n List<String> values = new ArrayList<String>();\n for(String data: array) {\n if(data != null) { \n values.add(data);\n }\n }\n String[] target = values.toArray(new String[values.size()]);\n for(String data: target) {\n System.out.println(data + \" \");\n }\n }\n}" }, { "code": null, "e": 1703, "s": 1691, "text": "I\nlove\nJava" } ]
Foundation - Switch
It is used to switch between on and off state. The following example demonstrates the use of switch in Foundation − <!doctype html> <head> <meta charset = "utf-8" /> <meta http-equiv = "x-ua-compatible" content = "ie = edge" /> <meta name = "viewport" content = "width = device-width, initial-scale = 1.0" /> <title>Switch</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/foundation.min.css" integrity="sha256-1mcRjtAxlSjp6XJBgrBeeCORfBp/ppyX4tsvpQVCcpA= sha384-b5S5X654rX3Wo6z5/hnQ4GBmKuIJKMPwrJXn52ypjztlnDK2w9+9hSMBz/asy9Gw sha512-M1VveR2JGzpgWHb0elGqPTltHK3xbvu3Brgjfg4cg5ZNtyyApxw/45yHYsZ/rCVbfoO5MSZxB241wWq642jLtA==" crossorigin="anonymous"> <!-- Compressed JavaScript --> <script src="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.0.1/js/vendor/jquery.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/foundation.min.js" integrity="sha256-WUKHnLrIrx8dew//IpSEmPN/NT3DGAEmIePQYIEJLLs= sha384-53StQWuVbn6figscdDC3xV00aYCPEz3srBdV/QGSXw3f19og3Tq2wTRe0vJqRTEO sha512-X9O+2f1ty1rzBJOC8AXBnuNUdyJg0m8xMKmbt9I3Vu/UOWmSg5zG+dtnje4wAZrKtkopz/PEDClHZ1LXx5IeOw==" crossorigin="anonymous"></script> </head> <body> <h2>Switch Example</h2> <div class = "switch tiny"> <input class = "switch-input" id = "switch_tiny" type = "checkbox"> <label class = "switch-paddle" for = "switch_tiny"></label> </div> <div class = "switch small"> <input class = "switch-input" id = "switch_small" type = "checkbox"> <label class = "switch-paddle" for = "switch_small"></label> </div> <div class = "switch large"> <input class = "switch-input" id = "switch_large" type = "checkbox"> <label class = "switch-paddle" for = "switch_large"></label> </div> <script> $(document).ready(function() { $(document).foundation(); }) </script> </body> </html> Let us carry out the following steps to see how the above given code works − Save the above given html code switch.html file. Save the above given html code switch.html file. Open this HTML file in a browser, an output is displayed as shown below. Open this HTML file in a browser, an output is displayed as shown below. 117 Lectures 5.5 hours Shakthi Swaroop 61 Lectures 1.5 hours Hans Weemaes 17 Lectures 4 hours Stephen Kahuria 8 Lectures 50 mins Zenva 28 Lectures 2 hours Sandra L 16 Lectures 2.5 hours GreyCampus Inc. Print Add Notes Bookmark this page
[ { "code": null, "e": 2285, "s": 2238, "text": "It is used to switch between on and off state." }, { "code": null, "e": 2354, "s": 2285, "text": "The following example demonstrates the use of switch in Foundation −" }, { "code": null, "e": 4259, "s": 2354, "text": "<!doctype html>\n <head>\n <meta charset = \"utf-8\" />\n <meta http-equiv = \"x-ua-compatible\" content = \"ie = edge\" />\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1.0\" />\n\n <title>Switch</title>\n\n <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/css/foundation.min.css\" integrity=\"sha256-1mcRjtAxlSjp6XJBgrBeeCORfBp/ppyX4tsvpQVCcpA= sha384-b5S5X654rX3Wo6z5/hnQ4GBmKuIJKMPwrJXn52ypjztlnDK2w9+9hSMBz/asy9Gw sha512-M1VveR2JGzpgWHb0elGqPTltHK3xbvu3Brgjfg4cg5ZNtyyApxw/45yHYsZ/rCVbfoO5MSZxB241wWq642jLtA==\" crossorigin=\"anonymous\">\n\n <!-- Compressed JavaScript -->\n <script src=\"https://cdnjs.cloudflare.com/ajax/libs/foundation/6.0.1/js/vendor/jquery.min.js\"></script>\n <script src=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/js/foundation.min.js\" integrity=\"sha256-WUKHnLrIrx8dew//IpSEmPN/NT3DGAEmIePQYIEJLLs= sha384-53StQWuVbn6figscdDC3xV00aYCPEz3srBdV/QGSXw3f19og3Tq2wTRe0vJqRTEO sha512-X9O+2f1ty1rzBJOC8AXBnuNUdyJg0m8xMKmbt9I3Vu/UOWmSg5zG+dtnje4wAZrKtkopz/PEDClHZ1LXx5IeOw==\" crossorigin=\"anonymous\"></script>\n\n </head>\n\n <body>\n <h2>Switch Example</h2>\n\n <div class = \"switch tiny\">\n <input class = \"switch-input\" id = \"switch_tiny\" type = \"checkbox\">\n <label class = \"switch-paddle\" for = \"switch_tiny\"></label>\n </div>\n\n <div class = \"switch small\">\n <input class = \"switch-input\" id = \"switch_small\" type = \"checkbox\">\n <label class = \"switch-paddle\" for = \"switch_small\"></label>\n </div>\n\n <div class = \"switch large\">\n <input class = \"switch-input\" id = \"switch_large\" type = \"checkbox\">\n <label class = \"switch-paddle\" for = \"switch_large\"></label>\n </div>\n\n <script>\n $(document).ready(function() {\n $(document).foundation();\n })\n </script>\n </body>\n</html>" }, { "code": null, "e": 4336, "s": 4259, "text": "Let us carry out the following steps to see how the above given code works −" }, { "code": null, "e": 4385, "s": 4336, "text": "Save the above given html code switch.html file." }, { "code": null, "e": 4434, "s": 4385, "text": "Save the above given html code switch.html file." }, { "code": null, "e": 4507, "s": 4434, "text": "Open this HTML file in a browser, an output is displayed as shown below." }, { "code": null, "e": 4580, "s": 4507, "text": "Open this HTML file in a browser, an output is displayed as shown below." }, { "code": null, "e": 4616, "s": 4580, "text": "\n 117 Lectures \n 5.5 hours \n" }, { "code": null, "e": 4633, "s": 4616, "text": " Shakthi Swaroop" }, { "code": null, "e": 4668, "s": 4633, "text": "\n 61 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4682, "s": 4668, "text": " Hans Weemaes" }, { "code": null, "e": 4715, "s": 4682, "text": "\n 17 Lectures \n 4 hours \n" }, { "code": null, "e": 4732, "s": 4715, "text": " Stephen Kahuria" }, { "code": null, "e": 4763, "s": 4732, "text": "\n 8 Lectures \n 50 mins\n" }, { "code": null, "e": 4770, "s": 4763, "text": " Zenva" }, { "code": null, "e": 4803, "s": 4770, "text": "\n 28 Lectures \n 2 hours \n" }, { "code": null, "e": 4813, "s": 4803, "text": " Sandra L" }, { "code": null, "e": 4848, "s": 4813, "text": "\n 16 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4865, "s": 4848, "text": " GreyCampus Inc." }, { "code": null, "e": 4872, "s": 4865, "text": " Print" }, { "code": null, "e": 4883, "s": 4872, "text": " Add Notes" } ]
GATE | GATE-CS-2007 | Question 58 - GeeksforGeeks
28 Jun, 2021 Two processes, P1 and P2, need to access a critical section of code. Consider the following synchronization construct used by the processes:Here, wants1 and wants2 are shared variables, which are initialized to false. Which one of the following statements is TRUE about the above construct?v /* P1 */ while (true) { wants1 = true; while (wants2 == true); /* Critical Section */ wants1=false; } /* Remainder section */ /* P2 */ while (true) { wants2 = true; while (wants1==true); /* Critical Section */ wants2 = false; } /* Remainder section */ (A) It does not ensure mutual exclusion.(B) It does not ensure bounded waiting.(C) It requires that processes enter the critical section in strict alternation.(D) It does not prevent deadlocks, but ensures mutual exclusion.Answer: (D)Explanation:Bounded waiting :There exists a bound, or limit, on the number of times other processes are allowed to enter their critical sections after a process has made request to enter its critical section and before that request is granted. mutual exclusion prevents simultaneous access to a shared resource. This concept is used in concurrent programming with a critical section, a piece of code in which processes or threads access a shared resource. Solution: Two processes, P1 and P2, need to access a critical section of code. Here, wants1 and wants2 are shared variables, which are initialized to false.Now, when both wants1 and wants2 become true, both process p1 and p2 enter in while loop and waiting for each other to finish. This while loop run indefinitely which leads to deadlock.Now, Assume P1 is in critical section (it means wants1=true, wants2 can be anything, true or false). So this ensures that p2 won’t enter in critical section and vice versa. This satisfies the property of mutual exclusion.Here bounded waiting condition is also satisfied as there is a bound on the number of process which gets access to critical section after a process request access to it. See question 3 of https://www.geeksforgeeks.org/operating-systems-set-13/ This solution is contributed by Nitika BansalQuiz of this Question GATE-CS-2007 GATE-GATE-CS-2007 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments GATE | GATE-IT-2004 | Question 71 GATE | GATE CS 2011 | Question 7 GATE | GATE-CS-2015 (Set 3) | Question 65 GATE | GATE-CS-2016 (Set 2) | Question 48 GATE | GATE-CS-2014-(Set-3) | Question 38 GATE | GATE CS 2018 | Question 37 GATE | GATE-CS-2016 (Set 1) | Question 65 GATE | GATE-IT-2004 | Question 83 GATE | GATE-CS-2016 (Set 1) | Question 63 GATE | GATE-CS-2014-(Set-2) | Question 65
[ { "code": null, "e": 24588, "s": 24560, "text": "\n28 Jun, 2021" }, { "code": null, "e": 24880, "s": 24588, "text": "Two processes, P1 and P2, need to access a critical section of code. Consider the following synchronization construct used by the processes:Here, wants1 and wants2 are shared variables, which are initialized to false. Which one of the following statements is TRUE about the above construct?v" }, { "code": null, "e": 25167, "s": 24880, "text": " /* P1 */\nwhile (true) {\n wants1 = true;\n while (wants2 == true);\n /* Critical\n Section */\n wants1=false;\n}\n/* Remainder section */ \n\n\n/* P2 */\nwhile (true) {\n wants2 = true;\n while (wants1==true);\n /* Critical\n Section */\n wants2 = false;\n}\n/* Remainder section */" }, { "code": null, "e": 25645, "s": 25167, "text": "(A) It does not ensure mutual exclusion.(B) It does not ensure bounded waiting.(C) It requires that processes enter the critical section in strict alternation.(D) It does not prevent deadlocks, but ensures mutual exclusion.Answer: (D)Explanation:Bounded waiting :There exists a bound, or limit, on the number of times other processes are allowed to enter their critical sections after a process has made request to enter its critical section and before that request is granted." }, { "code": null, "e": 25857, "s": 25645, "text": "mutual exclusion prevents simultaneous access to a shared resource. This concept is used in concurrent programming with a critical section, a piece of code in which processes or threads access a shared resource." }, { "code": null, "e": 25867, "s": 25857, "text": "Solution:" }, { "code": null, "e": 26588, "s": 25867, "text": "Two processes, P1 and P2, need to access a critical section of code. Here, wants1 and wants2 are shared variables, which are initialized to false.Now, when both wants1 and wants2 become true, both process p1 and p2 enter in while loop and waiting for each other to finish. This while loop run indefinitely which leads to deadlock.Now, Assume P1 is in critical section (it means wants1=true, wants2 can be anything, true or false). So this ensures that p2 won’t enter in critical section and vice versa. This satisfies the property of mutual exclusion.Here bounded waiting condition is also satisfied as there is a bound on the number of process which gets access to critical section after a process request access to it." }, { "code": null, "e": 26662, "s": 26588, "text": "See question 3 of https://www.geeksforgeeks.org/operating-systems-set-13/" }, { "code": null, "e": 26729, "s": 26662, "text": "This solution is contributed by Nitika BansalQuiz of this Question" }, { "code": null, "e": 26742, "s": 26729, "text": "GATE-CS-2007" }, { "code": null, "e": 26760, "s": 26742, "text": "GATE-GATE-CS-2007" }, { "code": null, "e": 26765, "s": 26760, "text": "GATE" }, { "code": null, "e": 26863, "s": 26765, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26872, "s": 26863, "text": "Comments" }, { "code": null, "e": 26885, "s": 26872, "text": "Old Comments" }, { "code": null, "e": 26919, "s": 26885, "text": "GATE | GATE-IT-2004 | Question 71" }, { "code": null, "e": 26952, "s": 26919, "text": "GATE | GATE CS 2011 | Question 7" }, { "code": null, "e": 26994, "s": 26952, "text": "GATE | GATE-CS-2015 (Set 3) | Question 65" }, { "code": null, "e": 27036, "s": 26994, "text": "GATE | GATE-CS-2016 (Set 2) | Question 48" }, { "code": null, "e": 27078, "s": 27036, "text": "GATE | GATE-CS-2014-(Set-3) | Question 38" }, { "code": null, "e": 27112, "s": 27078, "text": "GATE | GATE CS 2018 | Question 37" }, { "code": null, "e": 27154, "s": 27112, "text": "GATE | GATE-CS-2016 (Set 1) | Question 65" }, { "code": null, "e": 27188, "s": 27154, "text": "GATE | GATE-IT-2004 | Question 83" }, { "code": null, "e": 27230, "s": 27188, "text": "GATE | GATE-CS-2016 (Set 1) | Question 63" } ]
Can namespaces be nested in C++? - GeeksforGeeks
29 May, 2017 In C++, namespaces can be nested, and resolution of namespace variables is hierarchical. For example, in the following code, namespace inner is created inside namespace outer, which is inside the global namespace. In the line “int z = x”, x refers to outer::x. If x would not have been in outer then this x would have referred to x in global namespace. #include <iostream> int x = 20;namespace outer { int x = 10; namespace inner { int z = x; // this x refers to outer::x }} int main(){ std::cout<<outer::inner::z; //prints 10 getchar(); return 0;} Output of the above program is 10. On a side node, unlike C++ namespaces, Java packages are not hierarchical. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. namespaces C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Inheritance in C++ Map in C++ Standard Template Library (STL) C++ Classes and Objects Socket Programming in C/C++ Operator Overloading in C++ Bitwise Operators in C/C++ Virtual Function in C++ Constructors in C++ Templates in C++ with Examples Object Oriented Programming in C++
[ { "code": null, "e": 24758, "s": 24730, "text": "\n29 May, 2017" }, { "code": null, "e": 25111, "s": 24758, "text": "In C++, namespaces can be nested, and resolution of namespace variables is hierarchical. For example, in the following code, namespace inner is created inside namespace outer, which is inside the global namespace. In the line “int z = x”, x refers to outer::x. If x would not have been in outer then this x would have referred to x in global namespace." }, { "code": "#include <iostream> int x = 20;namespace outer { int x = 10; namespace inner { int z = x; // this x refers to outer::x }} int main(){ std::cout<<outer::inner::z; //prints 10 getchar(); return 0;}", "e": 25327, "s": 25111, "text": null }, { "code": null, "e": 25362, "s": 25327, "text": "Output of the above program is 10." }, { "code": null, "e": 25437, "s": 25362, "text": "On a side node, unlike C++ namespaces, Java packages are not hierarchical." }, { "code": null, "e": 25562, "s": 25437, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 25573, "s": 25562, "text": "namespaces" }, { "code": null, "e": 25577, "s": 25573, "text": "C++" }, { "code": null, "e": 25581, "s": 25577, "text": "CPP" }, { "code": null, "e": 25679, "s": 25581, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25688, "s": 25679, "text": "Comments" }, { "code": null, "e": 25701, "s": 25688, "text": "Old Comments" }, { "code": null, "e": 25720, "s": 25701, "text": "Inheritance in C++" }, { "code": null, "e": 25763, "s": 25720, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 25787, "s": 25763, "text": "C++ Classes and Objects" }, { "code": null, "e": 25815, "s": 25787, "text": "Socket Programming in C/C++" }, { "code": null, "e": 25843, "s": 25815, "text": "Operator Overloading in C++" }, { "code": null, "e": 25870, "s": 25843, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 25894, "s": 25870, "text": "Virtual Function in C++" }, { "code": null, "e": 25914, "s": 25894, "text": "Constructors in C++" }, { "code": null, "e": 25945, "s": 25914, "text": "Templates in C++ with Examples" } ]
Sum of the multiples of two numbers below N in C++
In this problem, we have given three integers M1, M2, and N. Our task is to create a program to find the sum of multiples of two numbers below N. Here, we will add all the elements below N which are multiples of either M1 or M2 Let’s take an example to understand the problem, Input N = 13, M1 = 4, M2 = 6 Output 20 Explanation − Number that are multiples of 4 and 6 that are less than 13 are 4, 6, 8, 12. A simple solution to the problem is to be looping from 1 to N and adding all values that can be divided by M1 or M2. Step 1 − sum = 0 , i = 0. Loop from i = 1 to N. Step 1.1 − if (i%M1 == 0) or (i%M2 == 0), sum + = i Step 2 − Return sum. Program to illustrate the working of our solution, Live Demo #include <iostream< using namespace std; int calcMulSum(int N, int M1, int M2){ int sum = 0; for (int i = 0; i < N; i++) if (i%M1 == 0 || i%M2 == 0) sum += i; return sum; } int main(){ int N = 24, M1 = 4, M2 = 7; cout<<"The sum of multiples of "<<M1<<" and "<<M2<<" below "<<N<<" is "<<calcMulSum(N, M1, M2); return 0; } The sum of multiples of 4 and 7 below 24 is 102 This is not the best solution to our problem as it takes O(n) time complexity. A better solution will be using mathematical formulas for the sum of series. Here, we will use the formula for the sum of the series. The final sum will be the (multiples of M1 + multiples of M2 - multiples of M1*M2) Sum of multiple of x upto n terms is given by, Sum(X) = (n * (1+n) * X)/2 Let’s formulate the sum, sum = ( ( ((n/M1)*(1+(n/M1))*M1)/2) + ((n/M2)*(1+(n/M2))*M2)/2 ) - ((n/M1*M2)*(1+(n/M1*M2))*M1*M2)/2 ) ) Program to illustrate the solution, Live Demo #include <iostream> using namespace std; int calcMulSum(int N, int M1, int M2){ N--; return (((N/M1) * (1 + (N/M1)) * M1 / 2) + ((N/M2) * (1 + (N/M2)) * M2 / 2) - ((N/(M1*M2)) * (1 + (N/(M1*M2))) * (M1*M2) / 2)); } int main(){ int N = 24, M1 = 4, M2 = 7; cout<<"The sum of multiples of "<<M1<<" and "<<M2<<" below "<<N<<" is "<<calcMulSum(N, M1, M2); return 0; } The sum of multiples of 4 and 7 below 24 is 102
[ { "code": null, "e": 1208, "s": 1062, "text": "In this problem, we have given three integers M1, M2, and N. Our task is to create a program to find the sum of multiples of two numbers below N." }, { "code": null, "e": 1290, "s": 1208, "text": "Here, we will add all the elements below N which are multiples of either M1 or M2" }, { "code": null, "e": 1339, "s": 1290, "text": "Let’s take an example to understand the problem," }, { "code": null, "e": 1346, "s": 1339, "text": "Input " }, { "code": null, "e": 1369, "s": 1346, "text": "N = 13, M1 = 4, M2 = 6" }, { "code": null, "e": 1378, "s": 1369, "text": "Output " }, { "code": null, "e": 1381, "s": 1378, "text": "20" }, { "code": null, "e": 1471, "s": 1381, "text": "Explanation − Number that are multiples of 4 and 6 that are less than 13 are 4, 6, 8, 12." }, { "code": null, "e": 1588, "s": 1471, "text": "A simple solution to the problem is to be looping from 1 to N and adding all values that can be divided by M1 or M2." }, { "code": null, "e": 1636, "s": 1588, "text": "Step 1 − sum = 0 , i = 0. Loop from i = 1 to N." }, { "code": null, "e": 1688, "s": 1636, "text": "Step 1.1 − if (i%M1 == 0) or (i%M2 == 0), sum + = i" }, { "code": null, "e": 1709, "s": 1688, "text": "Step 2 − Return sum." }, { "code": null, "e": 1760, "s": 1709, "text": "Program to illustrate the working of our solution," }, { "code": null, "e": 1771, "s": 1760, "text": " Live Demo" }, { "code": null, "e": 2119, "s": 1771, "text": "#include <iostream<\nusing namespace std;\nint calcMulSum(int N, int M1, int M2){\n int sum = 0;\n for (int i = 0; i < N; i++)\n if (i%M1 == 0 || i%M2 == 0)\n sum += i;\n return sum;\n}\nint main(){\n int N = 24, M1 = 4, M2 = 7;\n cout<<\"The sum of multiples of \"<<M1<<\" and \"<<M2<<\" below \"<<N<<\" is \"<<calcMulSum(N, M1, M2);\n return 0;\n}" }, { "code": null, "e": 2167, "s": 2119, "text": "The sum of multiples of 4 and 7 below 24 is 102" }, { "code": null, "e": 2246, "s": 2167, "text": "This is not the best solution to our problem as it takes O(n) time complexity." }, { "code": null, "e": 2323, "s": 2246, "text": "A better solution will be using mathematical formulas for the sum of series." }, { "code": null, "e": 2463, "s": 2323, "text": "Here, we will use the formula for the sum of the series. The final sum will be the (multiples of M1 + multiples of M2 - multiples of M1*M2)" }, { "code": null, "e": 2510, "s": 2463, "text": "Sum of multiple of x upto n terms is given by," }, { "code": null, "e": 2537, "s": 2510, "text": "Sum(X) = (n * (1+n) * X)/2" }, { "code": null, "e": 2562, "s": 2537, "text": "Let’s formulate the sum," }, { "code": null, "e": 2667, "s": 2562, "text": "sum = ( ( ((n/M1)*(1+(n/M1))*M1)/2) + ((n/M2)*(1+(n/M2))*M2)/2 ) - ((n/M1*M2)*(1+(n/M1*M2))*M1*M2)/2 ) )" }, { "code": null, "e": 2703, "s": 2667, "text": "Program to illustrate the solution," }, { "code": null, "e": 2714, "s": 2703, "text": " Live Demo" }, { "code": null, "e": 3092, "s": 2714, "text": "#include <iostream>\nusing namespace std;\nint calcMulSum(int N, int M1, int M2){\n N--;\n return (((N/M1) * (1 + (N/M1)) * M1 / 2) + ((N/M2) * (1 + (N/M2)) * M2 / 2) - ((N/(M1*M2)) * (1 + (N/(M1*M2))) * (M1*M2) / 2));\n}\nint main(){\n int N = 24, M1 = 4, M2 = 7;\n cout<<\"The sum of multiples of \"<<M1<<\" and \"<<M2<<\" below \"<<N<<\" is \"<<calcMulSum(N, M1, M2);\n return 0;\n}" }, { "code": null, "e": 3140, "s": 3092, "text": "The sum of multiples of 4 and 7 below 24 is 102" } ]
Get Month Name from Month number in MySQL?
You can use MONTHNAME() function from MySQL to display Month name from number. The syntax is as follows. SELECT MONTHNAME(STR_TO_DATE(yourColumnName,’%m’)) as anyVariableName from yourTableName; To understand the above concept, let us first create a table. The query to create a table is as follows. mysql> create table MonthDemo -> ( -> MonthNum int -> ); Query OK, 0 rows affected (0.87 sec) Insert some records in the table using insert command. The query is as follows − mysql> insert into MonthDemo values(1); Query OK, 1 row affected (0.14 sec) mysql> insert into MonthDemo values(2); Query OK, 1 row affected (0.15 sec) mysql> insert into MonthDemo values(3); Query OK, 1 row affected (0.12 sec) mysql> insert into MonthDemo values(4); Query OK, 1 row affected (0.12 sec) mysql> insert into MonthDemo values(5); Query OK, 1 row affected (0.13 sec) mysql> insert into MonthDemo values(6); Query OK, 1 row affected (0.18 sec) mysql> insert into MonthDemo values(7); Query OK, 1 row affected (0.13 sec) mysql> insert into MonthDemo values(8); Query OK, 1 row affected (0.13 sec) mysql> insert into MonthDemo values(9); Query OK, 1 row affected (0.15 sec) mysql> insert into MonthDemo values(10); Query OK, 1 row affected (0.13 sec) mysql> insert into MonthDemo values(11); Query OK, 1 row affected (0.14 sec) mysql> insert into MonthDemo values(12); Query OK, 1 row affected (0.15 sec) Display all records from the table using select command. The query is as follows. mysql> select *from MonthDemo; The following is the output. +------------+ | MonthNum | +------------+ | 1 | | 2 | | 3 | | 4 | | 5 | | 6 | | 7 | | 8 | | 9 | | 10 | | 11 | | 12 | +------------+ 12 rows in set (0.00 sec) Here is the query to display month name. mysql> select monthname(str_to_date(MonthNum,'%m')) as MonthName from MonthDemo; The following is the output. +-----------+ | MonthName | +-----------+ | January | | February | | March | | April | | May | | June | | July | | August | | September | | October | | November | | December | +-----------+ 12 rows in set (0.00 sec)
[ { "code": null, "e": 1167, "s": 1062, "text": "You can use MONTHNAME() function from MySQL to display Month name from number. The syntax is as follows." }, { "code": null, "e": 1257, "s": 1167, "text": "SELECT MONTHNAME(STR_TO_DATE(yourColumnName,’%m’)) as anyVariableName from yourTableName;" }, { "code": null, "e": 1362, "s": 1257, "text": "To understand the above concept, let us first create a table. The query to create a table is as follows." }, { "code": null, "e": 1456, "s": 1362, "text": "mysql> create table MonthDemo\n-> (\n-> MonthNum int\n-> );\nQuery OK, 0 rows affected (0.87 sec)" }, { "code": null, "e": 1537, "s": 1456, "text": "Insert some records in the table using insert command. The query is as follows −" }, { "code": null, "e": 2463, "s": 1537, "text": "mysql> insert into MonthDemo values(1);\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into MonthDemo values(2);\nQuery OK, 1 row affected (0.15 sec)\n\nmysql> insert into MonthDemo values(3);\nQuery OK, 1 row affected (0.12 sec)\n\nmysql> insert into MonthDemo values(4);\nQuery OK, 1 row affected (0.12 sec)\n\nmysql> insert into MonthDemo values(5);\nQuery OK, 1 row affected (0.13 sec)\n\nmysql> insert into MonthDemo values(6);\nQuery OK, 1 row affected (0.18 sec)\n\nmysql> insert into MonthDemo values(7);\nQuery OK, 1 row affected (0.13 sec)\n\nmysql> insert into MonthDemo values(8);\nQuery OK, 1 row affected (0.13 sec)\n\nmysql> insert into MonthDemo values(9);\nQuery OK, 1 row affected (0.15 sec)\n\nmysql> insert into MonthDemo values(10);\nQuery OK, 1 row affected (0.13 sec)\n\nmysql> insert into MonthDemo values(11);\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into MonthDemo values(12);\nQuery OK, 1 row affected (0.15 sec)" }, { "code": null, "e": 2545, "s": 2463, "text": "Display all records from the table using select command. The query is as follows." }, { "code": null, "e": 2576, "s": 2545, "text": "mysql> select *from MonthDemo;" }, { "code": null, "e": 2605, "s": 2576, "text": "The following is the output." }, { "code": null, "e": 2871, "s": 2605, "text": "+------------+\n| MonthNum |\n+------------+\n| 1 |\n| 2 |\n| 3 |\n| 4 |\n| 5 |\n| 6 |\n| 7 |\n| 8 |\n| 9 |\n| 10 |\n| 11 |\n| 12 |\n+------------+\n12 rows in set (0.00 sec)" }, { "code": null, "e": 2912, "s": 2871, "text": "Here is the query to display month name." }, { "code": null, "e": 2993, "s": 2912, "text": "mysql> select monthname(str_to_date(MonthNum,'%m')) as MonthName from MonthDemo;" }, { "code": null, "e": 3022, "s": 2993, "text": "The following is the output." }, { "code": null, "e": 3272, "s": 3022, "text": "+-----------+\n| MonthName |\n+-----------+\n| January |\n| February |\n| March |\n| April |\n| May |\n| June |\n| July |\n| August |\n| September |\n| October |\n| November |\n| December |\n+-----------+\n12 rows in set (0.00 sec)" } ]
Draw a circle using Turtlesim in ROS-Python - GeeksforGeeks
27 Dec, 2021 In this article, we are going to see how to draw a circle using Turtlesim in ROS-Python. ROS stands for Robot Operating System. ROS is a set of libraries and tools that help build robot applications. It’s extensively used in robotics projects. ROS is an open-source, meta-operating system for robots. The software in the ROS ecosystem has both language-dependent and language-independent tools. ROS supports Python, C++, Lisp and other languages. rospy is a pure Python client library ROS. We shall make use of this library to implement our code. Turtlesim is a common tool specifically made to teach ROS and ROS packages. The idea is to import Twist from geometry_msgs.msg library and assign appropriate values for velocity components. Twist expresses the velocity of turtle in 3D space broken into 3 linear components and 3 angular components. Turtle here is 2D and is governed by 1 linear component (x-component) and 1 angular component (z-component). This is because the turtle cannot move in y or z directions. Hence. all other components are equated to 0. Step 1: First, import all the packages used in the program. rospy is a ROS-python library that contains different functions like creating a node, getting time, creating a publisher, etc. The geometry_msgs library contains a useful variable type Twist which is used to describe velocity in 3D. Python3 import rospyfrom geometry_msgs.msg import Twistimport sys Step 2: Next, we define our turtle_circle function, inside which we initiate our turtlesim node and our publisher. We also specify a rate equal to 10Hz, that is, the program goes through the loop 10 times per second. A Twist variable ‘vel’ is also created. Python3 def turtle_circle(radius): rospy.init_node('turtlesim', anonymous=True) pub = rospy.Publisher('/turtle1/cmd_vel', Twist, queue_size=10) rate = rospy.Rate(10) vel = Twist() Step 3: We now create a while loop that allows the turtle to run in a circle indefinitely. Inside the while loop, we provide the velocity components of the turtle appropriately as discussed above in the approach, and then publish them to the turtle. We also print the radius for each loop using rospy.loginfo() function. rate.sleep() is added at the end. rate object keeps track of the time since the last rate.sleep() was executed and sleeps for the correct amount of time to maintain a 10Hz frequency. Python3 rospy.loginfo("Radius = %f", radius)pub.publish(vel)rate.sleep() Step 4: Finally, we have the main loop which calls the function and handles exceptions if any exist: Python3 if __name__ == '__main__': try: turtle_circle(float(sys.argv[1])) except rospy.ROSInterruptException: pass Start ROS in the terminal using the command: $ roscore Start the turtlesim node on a new terminal using the command: $ rosrun turtlesim turtlesim_node Execute the program using the following command: $ rosrun my_package turtlesim.py 2.0 Below is the implementation: Python3 #!/usr/bin/env python# author : Sumanth Nethiimport rospyfrom geometry_msgs.msg import Twistimport sys def turtle_circle(radius): rospy.init_node('turtlesim', anonymous=True) pub = rospy.Publisher('/turtle1/cmd_vel', Twist, queue_size=10) rate = rospy.Rate(10) vel = Twist() while not rospy.is_shutdown(): vel.linear.x = radius vel.linear.y = 0 vel.linear.z = 0 vel.angular.x = 0 vel.angular.y = 0 vel.angular.z = 1 rospy.loginfo("Radius = %f", radius) pub.publish(vel) rate.sleep() if __name__ == '__main__': try: turtle_circle(float(sys.argv[1])) except rospy.ROSInterruptException: pass Output: kk773572498 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 ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Selecting rows in pandas DataFrame based on conditions Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Split string into list of characters
[ { "code": null, "e": 24317, "s": 24289, "text": "\n27 Dec, 2021" }, { "code": null, "e": 24407, "s": 24317, "text": "In this article, we are going to see how to draw a circle using Turtlesim in ROS-Python. " }, { "code": null, "e": 24765, "s": 24407, "text": "ROS stands for Robot Operating System. ROS is a set of libraries and tools that help build robot applications. It’s extensively used in robotics projects. ROS is an open-source, meta-operating system for robots. The software in the ROS ecosystem has both language-dependent and language-independent tools. ROS supports Python, C++, Lisp and other languages." }, { "code": null, "e": 24941, "s": 24765, "text": "rospy is a pure Python client library ROS. We shall make use of this library to implement our code. Turtlesim is a common tool specifically made to teach ROS and ROS packages." }, { "code": null, "e": 25381, "s": 24941, "text": "The idea is to import Twist from geometry_msgs.msg library and assign appropriate values for velocity components. Twist expresses the velocity of turtle in 3D space broken into 3 linear components and 3 angular components. Turtle here is 2D and is governed by 1 linear component (x-component) and 1 angular component (z-component). This is because the turtle cannot move in y or z directions. Hence. all other components are equated to 0. " }, { "code": null, "e": 25675, "s": 25381, "text": "Step 1: First, import all the packages used in the program. rospy is a ROS-python library that contains different functions like creating a node, getting time, creating a publisher, etc. The geometry_msgs library contains a useful variable type Twist which is used to describe velocity in 3D." }, { "code": null, "e": 25683, "s": 25675, "text": "Python3" }, { "code": "import rospyfrom geometry_msgs.msg import Twistimport sys", "e": 25741, "s": 25683, "text": null }, { "code": null, "e": 25999, "s": 25741, "text": " Step 2: Next, we define our turtle_circle function, inside which we initiate our turtlesim node and our publisher. We also specify a rate equal to 10Hz, that is, the program goes through the loop 10 times per second. A Twist variable ‘vel’ is also created." }, { "code": null, "e": 26007, "s": 25999, "text": "Python3" }, { "code": "def turtle_circle(radius): rospy.init_node('turtlesim', anonymous=True) pub = rospy.Publisher('/turtle1/cmd_vel', Twist, queue_size=10) rate = rospy.Rate(10) vel = Twist()", "e": 26216, "s": 26007, "text": null }, { "code": null, "e": 26720, "s": 26216, "text": "Step 3: We now create a while loop that allows the turtle to run in a circle indefinitely. Inside the while loop, we provide the velocity components of the turtle appropriately as discussed above in the approach, and then publish them to the turtle. We also print the radius for each loop using rospy.loginfo() function. rate.sleep() is added at the end. rate object keeps track of the time since the last rate.sleep() was executed and sleeps for the correct amount of time to maintain a 10Hz frequency." }, { "code": null, "e": 26728, "s": 26720, "text": "Python3" }, { "code": "rospy.loginfo(\"Radius = %f\", radius)pub.publish(vel)rate.sleep()", "e": 26793, "s": 26728, "text": null }, { "code": null, "e": 26894, "s": 26793, "text": "Step 4: Finally, we have the main loop which calls the function and handles exceptions if any exist:" }, { "code": null, "e": 26902, "s": 26894, "text": "Python3" }, { "code": "if __name__ == '__main__': try: turtle_circle(float(sys.argv[1])) except rospy.ROSInterruptException: pass", "e": 27029, "s": 26902, "text": null }, { "code": null, "e": 27074, "s": 27029, "text": "Start ROS in the terminal using the command:" }, { "code": null, "e": 27084, "s": 27074, "text": "$ roscore" }, { "code": null, "e": 27146, "s": 27084, "text": "Start the turtlesim node on a new terminal using the command:" }, { "code": null, "e": 27180, "s": 27146, "text": "$ rosrun turtlesim turtlesim_node" }, { "code": null, "e": 27229, "s": 27180, "text": "Execute the program using the following command:" }, { "code": null, "e": 27266, "s": 27229, "text": "$ rosrun my_package turtlesim.py 2.0" }, { "code": null, "e": 27295, "s": 27266, "text": "Below is the implementation:" }, { "code": null, "e": 27303, "s": 27295, "text": "Python3" }, { "code": "#!/usr/bin/env python# author : Sumanth Nethiimport rospyfrom geometry_msgs.msg import Twistimport sys def turtle_circle(radius): rospy.init_node('turtlesim', anonymous=True) pub = rospy.Publisher('/turtle1/cmd_vel', Twist, queue_size=10) rate = rospy.Rate(10) vel = Twist() while not rospy.is_shutdown(): vel.linear.x = radius vel.linear.y = 0 vel.linear.z = 0 vel.angular.x = 0 vel.angular.y = 0 vel.angular.z = 1 rospy.loginfo(\"Radius = %f\", radius) pub.publish(vel) rate.sleep() if __name__ == '__main__': try: turtle_circle(float(sys.argv[1])) except rospy.ROSInterruptException: pass", "e": 28039, "s": 27303, "text": null }, { "code": null, "e": 28047, "s": 28039, "text": "Output:" }, { "code": null, "e": 28059, "s": 28047, "text": "kk773572498" }, { "code": null, "e": 28074, "s": 28059, "text": "python-modules" }, { "code": null, "e": 28081, "s": 28074, "text": "Python" }, { "code": null, "e": 28179, "s": 28081, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28211, "s": 28179, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28267, "s": 28211, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28309, "s": 28267, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28351, "s": 28309, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28406, "s": 28351, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 28428, "s": 28406, "text": "Defaultdict in Python" }, { "code": null, "e": 28467, "s": 28428, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28498, "s": 28467, "text": "Python | os.path.join() method" }, { "code": null, "e": 28527, "s": 28498, "text": "Create a directory in Python" } ]
Run Pandas as Fast as Spark. Why the Pandas API on Spark is a total... | by Adrián González Carpintero | Towards Data Science
That’s it. It’s out. Spark now has a Pandas API. It seems that, every time you want to work with Dataframes, you have to open a messy drawer where you keep all the tools, and carefully look for the right one. If you work with structured data, you need SQL. Pandas is always there too. Spark is indispensable for Big Data. There is a tool for every need in the toolbox. But you don’t need the toolbox anymore, because Spark has become the ultimate Swiss Army Knife. It all started at the 2019 Spark + AI Summit. Koalas, an open source project that enables the use of Pandas on top of Spark, was launched. At the beginning, it only covered a small part of the Pandas functions, but it gradually grew. Two years have passed, and now, in the new Spark 3.2 release, Koalas has been merged into PySpark. And the result is wonderful. Spark now integrates a Pandas API so you can run Pandas on top of Spark. You just have to change one line of your code: import pyspark.pandas as ps Isn’t it great? Thanks to this, we can obtain a wide range of benefits: If you use Pandas but you are not familiar with Spark, you can work with Spark right away, with no learning curve. You can have a single codebase for everything: small data and big data. A single machine and distributed machines. You can run your Pandas code faster. This last point is especially remarkable. On the one hand, you can apply distributed computing to your code in Pandas. But the benefits don’t end there. Thanks to the Spark engine, your code will be faster even in a single machine! And in case you are wondering, yes, it looks like Pandas-on-Spark is also faster than Dask. I’m really excited about this breakthrough so, why don’t we get down to business? Let’s do some code with the Pandas API on Spark! The first thing we need to know is what exactly we are working with. When working with Pandas, we use the class pandas.core.frame.DataFrame. When working with the pandas API in Spark, we use the class pyspark.pandas.frame.DataFrame . Both are similar, but not the same. The main difference is that the former is in a single machine, whereas the latter is distributed. We can create a Dataframe with Pandas-on-Spark and convert it to Pandas, and vice-versa: # import Pandas-on-Sparkimport pyspark.pandas as ps# Create a DataFrame with Pandas-on-Sparkps_df = ps.DataFrame(range(10))# Convert a Pandas-on-Spark Dataframe into a Pandas Dataframepd_df = ps_df.to_pandas()# Convert a Pandas Dataframe into a Pandas-on-Spark Dataframeps_df = ps.from_pandas(pd_df) Note that if you are using multiple machines, when converting a Pandas-on-Spark Dataframe into a Pandas Dataframe, data is transferred from multiple machines to a single one, and vice-versa (see PySpark guide). We can also convert a Pandas-on-Spark Dataframe into a Spark DataFrame, and vice-versa: # Create a DataFrame with Pandas-on-Sparkps_df = ps.DataFrame(range(10))# Convert a Pandas-on-Spark Dataframe into a Spark Dataframespark_df = ps_df.to_spark()# Convert a Spark Dataframe into a Pandas-on-Spark Dataframeps_df_new = spark_df.to_pandas_on_spark() When working with Pandas-on-Spark and Pandas, the data types are basically the same. When converting a Pandas-on-Spark DataFrame to a Spark DataFrame, data types are casted to the appropriate type automatically (see PySpark guide) The aim of this section is to provide a cheatsheet with the most used functions for managing DataFrames in Spark and their analogues in Pandas-on-Spark. Note that the only difference in syntax between Pandas-on-Spark and Pandas is just the import pyspark.pandas as ps line. You will see how, even if you are not familiar with Spark, working with it is straightforward thanks to the Pandas API. # For running Sparkfrom pyspark.sql import SparkSessionspark = SparkSession.builder.appName("Spark").getOrCreate()# For running Pandas on top of Sparkimport pyspark.pandas as ps Let’s use the old dog iris dataset as example. # SPARKsdf = spark.read.options(inferSchema='True', header='True').csv('iris.csv')# PANDAS-ON-SPARKpdf = ps.read_csv('iris.csv') # SPARKsdf.select("sepal_length","sepal_width").show()# PANDAS-ON-SPARKpdf[["sepal_length","sepal_width"]].head() # SPARKsdf.drop('sepal_length').show()# PANDAS-ON-SPARKpdf.drop('sepal_length').head() # SPARKsdf.dropDuplicates(["sepal_length","sepal_width"]).show()# PANDAS-ON-SPARKpdf[["sepal_length", "sepal_width"]].drop_duplicates() # SPARKsdf.filter( (sdf.flower_type == "Iris-setosa") & (sdf.petal_length > 1.5) ).show()# PANDAS-ON-SPARKpdf.loc[ (pdf.flower_type == "Iris-setosa") & (pdf.petal_length > 1.5) ].head() # SPARKsdf.filter(sdf.flower_type == "Iris-virginica").count()# PANDAS-ON-SPARKpdf.loc[pdf.flower_type == "Iris-virginica"].count() # SPARKsdf.select("flower_type").distinct().show()# PANDAS-ON-SPARKpdf["flower_type"].unique() # SPARKsdf.sort("sepal_length", "sepal_width").show()# PANDAS-ON-SPARKpdf.sort_values(["sepal_length", "sepal_width"]).head() # SPARKsdf.groupBy("flower_type").count().show()# PANDAS-ON-SPARKpdf.groupby("flower_type").count() # SPARKsdf.replace("Iris-setosa", "setosa").show()# PANDAS-ON-SPARKpdf.replace("Iris-setosa", "setosa").head() # SPARKsdf.union(sdf)# PANDAS-ON-SPARKpdf.append(pdf) From now on, you will be able to use Pandas in top of Spark. This leads to an increase in Pandas speed, a decrease in the learning curve when emigrating to Spark, and the merging of single machine computing and distributed computing in the same codebase. I would like to leave a couple of questions to the reader: Do you think Spark is going to be the ultimate Swiss Army Knife for managing Dataframes? Will Pandas kill off other libraries like Dask or Vaex? Will Pandas users gradually migrate to Spark? Are we going to seeimport pandas as pdin the future? Spark User Guide: Pandas API on Spark Pandas API on Upcoming Apache Spark 3.2
[ { "code": null, "e": 221, "s": 172, "text": "That’s it. It’s out. Spark now has a Pandas API." }, { "code": null, "e": 381, "s": 221, "text": "It seems that, every time you want to work with Dataframes, you have to open a messy drawer where you keep all the tools, and carefully look for the right one." }, { "code": null, "e": 637, "s": 381, "text": "If you work with structured data, you need SQL. Pandas is always there too. Spark is indispensable for Big Data. There is a tool for every need in the toolbox. But you don’t need the toolbox anymore, because Spark has become the ultimate Swiss Army Knife." }, { "code": null, "e": 999, "s": 637, "text": "It all started at the 2019 Spark + AI Summit. Koalas, an open source project that enables the use of Pandas on top of Spark, was launched. At the beginning, it only covered a small part of the Pandas functions, but it gradually grew. Two years have passed, and now, in the new Spark 3.2 release, Koalas has been merged into PySpark. And the result is wonderful." }, { "code": null, "e": 1119, "s": 999, "text": "Spark now integrates a Pandas API so you can run Pandas on top of Spark. You just have to change one line of your code:" }, { "code": null, "e": 1147, "s": 1119, "text": "import pyspark.pandas as ps" }, { "code": null, "e": 1163, "s": 1147, "text": "Isn’t it great?" }, { "code": null, "e": 1219, "s": 1163, "text": "Thanks to this, we can obtain a wide range of benefits:" }, { "code": null, "e": 1334, "s": 1219, "text": "If you use Pandas but you are not familiar with Spark, you can work with Spark right away, with no learning curve." }, { "code": null, "e": 1449, "s": 1334, "text": "You can have a single codebase for everything: small data and big data. A single machine and distributed machines." }, { "code": null, "e": 1486, "s": 1449, "text": "You can run your Pandas code faster." }, { "code": null, "e": 1528, "s": 1486, "text": "This last point is especially remarkable." }, { "code": null, "e": 1718, "s": 1528, "text": "On the one hand, you can apply distributed computing to your code in Pandas. But the benefits don’t end there. Thanks to the Spark engine, your code will be faster even in a single machine!" }, { "code": null, "e": 1810, "s": 1718, "text": "And in case you are wondering, yes, it looks like Pandas-on-Spark is also faster than Dask." }, { "code": null, "e": 1941, "s": 1810, "text": "I’m really excited about this breakthrough so, why don’t we get down to business? Let’s do some code with the Pandas API on Spark!" }, { "code": null, "e": 2309, "s": 1941, "text": "The first thing we need to know is what exactly we are working with. When working with Pandas, we use the class pandas.core.frame.DataFrame. When working with the pandas API in Spark, we use the class pyspark.pandas.frame.DataFrame . Both are similar, but not the same. The main difference is that the former is in a single machine, whereas the latter is distributed." }, { "code": null, "e": 2398, "s": 2309, "text": "We can create a Dataframe with Pandas-on-Spark and convert it to Pandas, and vice-versa:" }, { "code": null, "e": 2698, "s": 2398, "text": "# import Pandas-on-Sparkimport pyspark.pandas as ps# Create a DataFrame with Pandas-on-Sparkps_df = ps.DataFrame(range(10))# Convert a Pandas-on-Spark Dataframe into a Pandas Dataframepd_df = ps_df.to_pandas()# Convert a Pandas Dataframe into a Pandas-on-Spark Dataframeps_df = ps.from_pandas(pd_df)" }, { "code": null, "e": 2909, "s": 2698, "text": "Note that if you are using multiple machines, when converting a Pandas-on-Spark Dataframe into a Pandas Dataframe, data is transferred from multiple machines to a single one, and vice-versa (see PySpark guide)." }, { "code": null, "e": 2997, "s": 2909, "text": "We can also convert a Pandas-on-Spark Dataframe into a Spark DataFrame, and vice-versa:" }, { "code": null, "e": 3258, "s": 2997, "text": "# Create a DataFrame with Pandas-on-Sparkps_df = ps.DataFrame(range(10))# Convert a Pandas-on-Spark Dataframe into a Spark Dataframespark_df = ps_df.to_spark()# Convert a Spark Dataframe into a Pandas-on-Spark Dataframeps_df_new = spark_df.to_pandas_on_spark()" }, { "code": null, "e": 3489, "s": 3258, "text": "When working with Pandas-on-Spark and Pandas, the data types are basically the same. When converting a Pandas-on-Spark DataFrame to a Spark DataFrame, data types are casted to the appropriate type automatically (see PySpark guide)" }, { "code": null, "e": 3763, "s": 3489, "text": "The aim of this section is to provide a cheatsheet with the most used functions for managing DataFrames in Spark and their analogues in Pandas-on-Spark. Note that the only difference in syntax between Pandas-on-Spark and Pandas is just the import pyspark.pandas as ps line." }, { "code": null, "e": 3883, "s": 3763, "text": "You will see how, even if you are not familiar with Spark, working with it is straightforward thanks to the Pandas API." }, { "code": null, "e": 4061, "s": 3883, "text": "# For running Sparkfrom pyspark.sql import SparkSessionspark = SparkSession.builder.appName(\"Spark\").getOrCreate()# For running Pandas on top of Sparkimport pyspark.pandas as ps" }, { "code": null, "e": 4108, "s": 4061, "text": "Let’s use the old dog iris dataset as example." }, { "code": null, "e": 4250, "s": 4108, "text": "# SPARKsdf = spark.read.options(inferSchema='True', header='True').csv('iris.csv')# PANDAS-ON-SPARKpdf = ps.read_csv('iris.csv')" }, { "code": null, "e": 4364, "s": 4250, "text": "# SPARKsdf.select(\"sepal_length\",\"sepal_width\").show()# PANDAS-ON-SPARKpdf[[\"sepal_length\",\"sepal_width\"]].head()" }, { "code": null, "e": 4451, "s": 4364, "text": "# SPARKsdf.drop('sepal_length').show()# PANDAS-ON-SPARKpdf.drop('sepal_length').head()" }, { "code": null, "e": 4587, "s": 4451, "text": "# SPARKsdf.dropDuplicates([\"sepal_length\",\"sepal_width\"]).show()# PANDAS-ON-SPARKpdf[[\"sepal_length\", \"sepal_width\"]].drop_duplicates()" }, { "code": null, "e": 4773, "s": 4587, "text": "# SPARKsdf.filter( (sdf.flower_type == \"Iris-setosa\") & (sdf.petal_length > 1.5) ).show()# PANDAS-ON-SPARKpdf.loc[ (pdf.flower_type == \"Iris-setosa\") & (pdf.petal_length > 1.5) ].head()" }, { "code": null, "e": 4905, "s": 4773, "text": "# SPARKsdf.filter(sdf.flower_type == \"Iris-virginica\").count()# PANDAS-ON-SPARKpdf.loc[pdf.flower_type == \"Iris-virginica\"].count()" }, { "code": null, "e": 5000, "s": 4905, "text": "# SPARKsdf.select(\"flower_type\").distinct().show()# PANDAS-ON-SPARKpdf[\"flower_type\"].unique()" }, { "code": null, "e": 5126, "s": 5000, "text": "# SPARKsdf.sort(\"sepal_length\", \"sepal_width\").show()# PANDAS-ON-SPARKpdf.sort_values([\"sepal_length\", \"sepal_width\"]).head()" }, { "code": null, "e": 5226, "s": 5126, "text": "# SPARKsdf.groupBy(\"flower_type\").count().show()# PANDAS-ON-SPARKpdf.groupby(\"flower_type\").count()" }, { "code": null, "e": 5337, "s": 5226, "text": "# SPARKsdf.replace(\"Iris-setosa\", \"setosa\").show()# PANDAS-ON-SPARKpdf.replace(\"Iris-setosa\", \"setosa\").head()" }, { "code": null, "e": 5391, "s": 5337, "text": "# SPARKsdf.union(sdf)# PANDAS-ON-SPARKpdf.append(pdf)" }, { "code": null, "e": 5646, "s": 5391, "text": "From now on, you will be able to use Pandas in top of Spark. This leads to an increase in Pandas speed, a decrease in the learning curve when emigrating to Spark, and the merging of single machine computing and distributed computing in the same codebase." }, { "code": null, "e": 5705, "s": 5646, "text": "I would like to leave a couple of questions to the reader:" }, { "code": null, "e": 5794, "s": 5705, "text": "Do you think Spark is going to be the ultimate Swiss Army Knife for managing Dataframes?" }, { "code": null, "e": 5850, "s": 5794, "text": "Will Pandas kill off other libraries like Dask or Vaex?" }, { "code": null, "e": 5896, "s": 5850, "text": "Will Pandas users gradually migrate to Spark?" }, { "code": null, "e": 5949, "s": 5896, "text": "Are we going to seeimport pandas as pdin the future?" }, { "code": null, "e": 5987, "s": 5949, "text": "Spark User Guide: Pandas API on Spark" } ]
How to create scrollable TextView on Android using Kotlin?
This example demonstrates how to create scrollable TextView on Android using Kotlin. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="5dp" tools:context=".MainActivity"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="match_parent" android:scrollbars="vertical" android:textColor="@android:color/background_dark" android:textSize="48sp" android:textStyle="italic" /> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.kt import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.text.method.ScrollingMovementMethod import android.widget.TextView class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) title = "KotlinApp" val textView: TextView = findViewById(R.id.textView) val text: String = "Your time is limited, so don’t waste it living someone else’s life. Don’t be trapped by dogma – which is living with the results of other people’s thinking. " + "If life were predictable it would cease to be life, and be without flavor. The big lesson in life, baby, is never be scared of anyone or anything." textView.text = text textView.movementMethod = ScrollingMovementMethod() } } Step 4 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.q11"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen. Click here to download the project code.
[ { "code": null, "e": 1147, "s": 1062, "text": "This example demonstrates how to create scrollable TextView on Android using Kotlin." }, { "code": null, "e": 1276, "s": 1147, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1341, "s": 1276, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1987, "s": 1341, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:id=\"@+id/activity_main\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:padding=\"5dp\"\n tools:context=\".MainActivity\">\n <TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"match_parent\"\n android:scrollbars=\"vertical\"\n android:textColor=\"@android:color/background_dark\"\n android:textSize=\"48sp\"\n android:textStyle=\"italic\" />\n</RelativeLayout>\n" }, { "code": null, "e": 2042, "s": 1987, "text": "Step 3 − Add the following code to src/MainActivity.kt" }, { "code": null, "e": 2895, "s": 2042, "text": "import androidx.appcompat.app.AppCompatActivity\nimport android.os.Bundle\nimport android.text.method.ScrollingMovementMethod\nimport android.widget.TextView\nclass MainActivity : AppCompatActivity() {\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n val textView: TextView = findViewById(R.id.textView)\n val text: String = \"Your time is limited, so don’t waste it living someone else’s life. Don’t be trapped by dogma – which is living with the results of other people’s thinking. \" + \"If life were predictable it would cease to be life, and be without flavor. The big lesson in life, baby, is never be scared of anyone or anything.\"\n textView.text = text\n textView.movementMethod = ScrollingMovementMethod()\n }\n}" }, { "code": null, "e": 2950, "s": 2895, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 3621, "s": 2950, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.example.q11\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 3971, "s": 3621, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen." }, { "code": null, "e": 4012, "s": 3971, "text": "Click here to download the project code." } ]
Here’s how you can speedup Pandas with cuDF and GPUs | by George Seif | Towards Data Science
Want to be inspired? Come join my Super Quotes newsletter. 😎 Pandas is the go-to data storage library for Data Scientists and Machine Learning practitioners. It allows for easy management, exploration, and manipulation of many different types of data, including both numbers and text. Even on its own, Pandas is already a significant step up from Python in terms of speed. Whenever you find your Python code running slow, especially if you see a lot of for-loops, it’s always a good idea to change the code which performs data exploration and filtering into Pandas functions. Pandas functions are specifically developed with vectorized operations that run at top speed! Still, even with that speedup, Pandas is only running on the CPU. With consumer CPUs typically having 8 cores or less, the amount of parallel processing, and therefore the amount of speedup that can be achieved, is limited. Modern datasets can have as much as millions, billions, or even trillions of data points that need processing — 8 cores just isn’t going to cut it. Luckily, following the popular success of GPU acceleration in Machine Learning, there’s been a strong push towards getting Data Analysis libraries onto GPUs. The cuDF library is a step in that direction. cuDF is a Python-based GPU DataFrame library for working with data including loading, joining, aggregating, and filtering data. The move to GPU allows for massive acceleration due to the many more cores GPUs have over CPUs. cuDF’s API is a mirror of Pandas’s and in most cases can be used as a direct replacement. This makes it very easy for Data Scientists, Analysts, and Engineers to integrate it into their workflow. All that needs to be done is to convert your Pandas DataFrame into a cuDF one and voila you have GPU speedup! cuDF will support most of the common DataFrame operations that Pandas does, so much of the regular Pandas code can be accelerated without much effort. To get started with an example of using cuDF, we can install the library via conda: conda install -c nvidia -c rapidsai -c numba -c conda-forge -c defaults cudf Keep in mind that for the following experiments, the machine we’re testing on has the following specs: i7–8700k CPU 1080 Ti GPU 32 GB of DDR4 3000MHz RAM CUDA 9.2 We’re going to load a big dataset of randomized numbers and compare the speed of various Pandas operations vs doing the same thing on GPU with cuDF. We can do this all in a Python Jupyter Notebook. Let’s start by initializing our DataFrames: one for Pandas and one for cuDF. The DataFrame has over 100 Million points! For our first test, let’s measure how long it takes to calculate the mean value of the ‘a’ variable in our data in Pandas vs. cuDF. The %timeit command allows us to measure the speed of Python commands in a Jupyter Notebook. Average run-time is shown in the code comments above. We got a 16X speedup just like that! Now, what about something a bit more complicated like doing a huge merge?! Let’s merge our DataFrame on itself on the DataFrame’s ‘b’ column. Merging here is a very large operation since Pandas will have to look for and match the common values — a time-consuming operation for a dataset with 100 Million rows! GPU acceleration will make this easier since we have many more parallel processes that can work together. Here’s the code and results: Even with a fairly powerful i7–8700k CPU, Pandas took 39.2 seconds on average to complete the merge. On the other hand, our friend cuDF on the GPU took only 2.76 seconds, a much more manageable time! That’s a total of over 14X speedup. So there you have it! That’s how you can speedup Pandas on GPU using cuDF. If you’re hungry for more, not to worry! There’s much more speed to be had with cuDF and the rest of the RAPIDS API. The best place to start is the official GitHub page! Follow me on twitter, where I post all about the latest and greatest AI, Technology, and Science! Connect with me on LinkedIn too!
[ { "code": null, "e": 233, "s": 172, "text": "Want to be inspired? Come join my Super Quotes newsletter. 😎" }, { "code": null, "e": 457, "s": 233, "text": "Pandas is the go-to data storage library for Data Scientists and Machine Learning practitioners. It allows for easy management, exploration, and manipulation of many different types of data, including both numbers and text." }, { "code": null, "e": 842, "s": 457, "text": "Even on its own, Pandas is already a significant step up from Python in terms of speed. Whenever you find your Python code running slow, especially if you see a lot of for-loops, it’s always a good idea to change the code which performs data exploration and filtering into Pandas functions. Pandas functions are specifically developed with vectorized operations that run at top speed!" }, { "code": null, "e": 1214, "s": 842, "text": "Still, even with that speedup, Pandas is only running on the CPU. With consumer CPUs typically having 8 cores or less, the amount of parallel processing, and therefore the amount of speedup that can be achieved, is limited. Modern datasets can have as much as millions, billions, or even trillions of data points that need processing — 8 cores just isn’t going to cut it." }, { "code": null, "e": 1418, "s": 1214, "text": "Luckily, following the popular success of GPU acceleration in Machine Learning, there’s been a strong push towards getting Data Analysis libraries onto GPUs. The cuDF library is a step in that direction." }, { "code": null, "e": 1642, "s": 1418, "text": "cuDF is a Python-based GPU DataFrame library for working with data including loading, joining, aggregating, and filtering data. The move to GPU allows for massive acceleration due to the many more cores GPUs have over CPUs." }, { "code": null, "e": 1838, "s": 1642, "text": "cuDF’s API is a mirror of Pandas’s and in most cases can be used as a direct replacement. This makes it very easy for Data Scientists, Analysts, and Engineers to integrate it into their workflow." }, { "code": null, "e": 2099, "s": 1838, "text": "All that needs to be done is to convert your Pandas DataFrame into a cuDF one and voila you have GPU speedup! cuDF will support most of the common DataFrame operations that Pandas does, so much of the regular Pandas code can be accelerated without much effort." }, { "code": null, "e": 2183, "s": 2099, "text": "To get started with an example of using cuDF, we can install the library via conda:" }, { "code": null, "e": 2260, "s": 2183, "text": "conda install -c nvidia -c rapidsai -c numba -c conda-forge -c defaults cudf" }, { "code": null, "e": 2363, "s": 2260, "text": "Keep in mind that for the following experiments, the machine we’re testing on has the following specs:" }, { "code": null, "e": 2376, "s": 2363, "text": "i7–8700k CPU" }, { "code": null, "e": 2388, "s": 2376, "text": "1080 Ti GPU" }, { "code": null, "e": 2414, "s": 2388, "text": "32 GB of DDR4 3000MHz RAM" }, { "code": null, "e": 2423, "s": 2414, "text": "CUDA 9.2" }, { "code": null, "e": 2572, "s": 2423, "text": "We’re going to load a big dataset of randomized numbers and compare the speed of various Pandas operations vs doing the same thing on GPU with cuDF." }, { "code": null, "e": 2741, "s": 2572, "text": "We can do this all in a Python Jupyter Notebook. Let’s start by initializing our DataFrames: one for Pandas and one for cuDF. The DataFrame has over 100 Million points!" }, { "code": null, "e": 2966, "s": 2741, "text": "For our first test, let’s measure how long it takes to calculate the mean value of the ‘a’ variable in our data in Pandas vs. cuDF. The %timeit command allows us to measure the speed of Python commands in a Jupyter Notebook." }, { "code": null, "e": 3057, "s": 2966, "text": "Average run-time is shown in the code comments above. We got a 16X speedup just like that!" }, { "code": null, "e": 3199, "s": 3057, "text": "Now, what about something a bit more complicated like doing a huge merge?! Let’s merge our DataFrame on itself on the DataFrame’s ‘b’ column." }, { "code": null, "e": 3473, "s": 3199, "text": "Merging here is a very large operation since Pandas will have to look for and match the common values — a time-consuming operation for a dataset with 100 Million rows! GPU acceleration will make this easier since we have many more parallel processes that can work together." }, { "code": null, "e": 3502, "s": 3473, "text": "Here’s the code and results:" }, { "code": null, "e": 3738, "s": 3502, "text": "Even with a fairly powerful i7–8700k CPU, Pandas took 39.2 seconds on average to complete the merge. On the other hand, our friend cuDF on the GPU took only 2.76 seconds, a much more manageable time! That’s a total of over 14X speedup." }, { "code": null, "e": 3813, "s": 3738, "text": "So there you have it! That’s how you can speedup Pandas on GPU using cuDF." }, { "code": null, "e": 3983, "s": 3813, "text": "If you’re hungry for more, not to worry! There’s much more speed to be had with cuDF and the rest of the RAPIDS API. The best place to start is the official GitHub page!" } ]
Compare Strings in Arduino
Arduino has an inbuilt compareTo() function that helps compare which string comes before another. Very crudely, you can think of it as this: if you are given two strings, which one will come first in a dictionary. String1.compareTo(String2) Where String1 and String2 are the two strings to be compared. This function returns an integer. Here’s the interpretation of the value of the integer − Negative − String1 comes before String2 Negative − String1 comes before String2 0 − String1 and String2 are equal 0 − String1 and String2 are equal Positive − String2 comes before String1 Positive − String2 comes before String1 Please note that this function is case sensitive. So ‘A’ comes before ‘a’ and ‘B’ comes before ‘a’. But ‘a’ comes before ‘b’. Also, numbers come before letters. Basically, if a character’s ASCII value is higher than another, then the higher character comes later in the dictionary. And compareTo() function compares the strings character by character. void setup() { // put your setup code here, to run once: Serial.begin(9600); Serial.println(); String s1 = "Book"; String s2 = "books"; String s3 = "library"; if(s1.compareTo(s2) < 0){ Serial.println("s1 before s2"); } if(s2.compareTo(s3) < 0){ Serial.println("s2 before s3"); } if(s3.compareTo(s1) < 0){ Serial.println("s3 before s1"); } } void loop() { // put your main code here, to run repeatedly: } The Serial Monitor output is shown below − As you can see, the function works exactly as described.
[ { "code": null, "e": 1276, "s": 1062, "text": "Arduino has an inbuilt compareTo() function that helps compare which string comes before another. Very crudely, you can think of it as this: if you are given two strings, which one will come first in a dictionary." }, { "code": null, "e": 1303, "s": 1276, "text": "String1.compareTo(String2)" }, { "code": null, "e": 1455, "s": 1303, "text": "Where String1 and String2 are the two strings to be compared. This function returns an integer. Here’s the interpretation of the value of the integer −" }, { "code": null, "e": 1495, "s": 1455, "text": "Negative − String1 comes before String2" }, { "code": null, "e": 1535, "s": 1495, "text": "Negative − String1 comes before String2" }, { "code": null, "e": 1569, "s": 1535, "text": "0 − String1 and String2 are equal" }, { "code": null, "e": 1603, "s": 1569, "text": "0 − String1 and String2 are equal" }, { "code": null, "e": 1643, "s": 1603, "text": "Positive − String2 comes before String1" }, { "code": null, "e": 1683, "s": 1643, "text": "Positive − String2 comes before String1" }, { "code": null, "e": 2035, "s": 1683, "text": "Please note that this function is case sensitive. So ‘A’ comes before ‘a’ and ‘B’ comes before ‘a’. But ‘a’ comes before ‘b’. Also, numbers come before letters. Basically, if a character’s ASCII value is higher than another, then the higher character comes later in the dictionary. And compareTo() function compares the strings character by character." }, { "code": null, "e": 2501, "s": 2035, "text": "void setup() {\n // put your setup code here, to run once:\n Serial.begin(9600);\n Serial.println();\n\n String s1 = \"Book\";\n String s2 = \"books\";\n String s3 = \"library\";\n\n if(s1.compareTo(s2) < 0){\n Serial.println(\"s1 before s2\");\n }\n\n if(s2.compareTo(s3) < 0){\n Serial.println(\"s2 before s3\");\n }\n\n if(s3.compareTo(s1) < 0){\n Serial.println(\"s3 before s1\");\n }\n}\n\nvoid loop() {\n // put your main code here, to run repeatedly:\n}" }, { "code": null, "e": 2544, "s": 2501, "text": "The Serial Monitor output is shown below −" }, { "code": null, "e": 2601, "s": 2544, "text": "As you can see, the function works exactly as described." } ]
Sentiment Analysis with Python (Part 2) | by Aaron Kub | Towards Data Science
In part one of this series we built a barebones movie review sentiment classifier. The goal of this next post is to provide an overview of several techniques that can be used to enhance an NLP model. That being said, we won’t go too far in depth on any particular topic. If you haven’t yet, you can read my first post here: towardsdatascience.com All of the code used in this series along with supplemental materials can be found in this GitHub Repository. For our first iteration we did very basic text processing like removing punctuation and HTML tags and making everything lower-case. We can clean things up further by removing stop words and normalizing the text. To make these transformations we’ll use libraries from the Natural Language Toolkit (NLTK). This is a very popular NLP library for Python. Stop words are the very common words like ‘if’, ‘but’, ‘we’, ‘he’, ‘she’, and ‘they’. We can usually remove these words without changing the semantics of a text and doing so often (but not always) improves the performance of a model. Removing these stop words becomes a lot more useful when we start using longer word sequences as model features (see n-grams below). Before "bromwell high is a cartoon comedy it ran at the same time as some other programs about school life such as teachers my years in the teaching profession lead me to believe that bromwell high’s satire is much closer to reality than is teachers the scramble to survive financially the insightful students who can see right through their pathetic teachers’ pomp the pettiness of the whole situation all remind me of the schools i knew and their students when i saw the episode in which a student repeatedly tried to burn down the school i immediately recalled at high a classic line inspector i’m here to sack one of your teachers student welcome to bromwell high i expect that many adults of my age think that bromwell high is far fetched what a pity that it isn’t" After "bromwell high cartoon comedy ran time programs school life teachers years teaching profession lead believe bromwell high's satire much closer reality teachers scramble survive financially insightful students see right pathetic teachers' pomp pettiness whole situation remind schools knew students saw episode student repeatedly tried burn school immediately recalled high classic line inspector i'm sack one teachers student welcome bromwell high expect many adults age think bromwell high far fetched pity" Note: In practice, an easier way to remove stop words is to just use the stop_words argument with any of scikit-learn’s ‘Vectorizer’ classes. If you want to use NLTK’s full list of stop words you can do stop_words='english’. In practice I’ve found that using NLTK’s list actually decreases my performance because its too expansive, so I usually supply my own list of words. For example, stop_words=['in','of','at','a','the'] . A common next step in text preprocessing is to normalize the words in your corpus by trying to convert all of the different forms of a given word into one. Two methods that exist for this are Stemming and Lemmatization. Stemming Stemming is considered to be the more crude/brute-force approach to normalization (although this doesn’t necessarily mean that it will perform worse). There’s several algorithms, but in general they all use basic rules to chop off the ends of words. NLTK has several stemming algorithm implementations. We’ll use the Porter stemmer here but you can explore all of the options with examples here: NLTK Stemmers Lemmatization Lemmatization works by identifying the part-of-speech of a given word and then applying more complex rules to transform the word into its true root. No Normalization "this is not the typical mel brooks film it was much less slapstick than most of his movies and actually had a plot that was followable leslie ann warren made the movie she is such a fantastic under rated actress there were some moments that could have been fleshed out a bit more and some scenes that could probably have been cut to make the room to do so but all in all this is worth the price to rent and see it the acting was good overall brooks himself did a good job without his characteristic speaking to directly to the audience again warren was the best actor in the movie but fume and sailor both played their parts well" Stemmed "thi is not the typic mel brook film it wa much less slapstick than most of hi movi and actual had a plot that wa follow lesli ann warren made the movi she is such a fantast under rate actress there were some moment that could have been flesh out a bit more and some scene that could probabl have been cut to make the room to do so but all in all thi is worth the price to rent and see it the act wa good overal brook himself did a good job without hi characterist speak to directli to the audienc again warren wa the best actor in the movi but fume and sailor both play their part well" Lemmatized "this is not the typical mel brook film it wa much le slapstick than most of his movie and actually had a plot that wa followable leslie ann warren made the movie she is such a fantastic under rated actress there were some moment that could have been fleshed out a bit more and some scene that could probably have been cut to make the room to do so but all in all this is worth the price to rent and see it the acting wa good overall brook himself did a good job without his characteristic speaking to directly to the audience again warren wa the best actor in the movie but fume and sailor both played their part well" Last time we used only single word features in our model, which we call 1-grams or unigrams. We can potentially add more predictive power to our model by adding two or three word sequences (bigrams or trigrams) as well. For example, if a review had the three word sequence “didn’t love movie” we would only consider these words individually with a unigram-only model and probably not capture that this is actually a negative sentiment because the word ‘love’ by itself is going to be highly correlated with a positive review. The scikit-learn library makes this really easy to play around with. Just use the ngram_range argument with any of the ‘Vectorizer’ classes. Getting pretty close to 90%! So, simply considering 2-word sequences in addition to single words increased our accuracy by more than 1.6 percentage points. Note: There’s technically no limit on the size that n can be for your model, but there are several things to consider. First, increasing the number of grams will not necessarily give you better performance. Second, the size of your matrix grows exponentially as you increment n, so if you have a large corpus that is comprised of large documents your model may take a very long time to train. In part 1 we represented each review as a binary vector (1s and 0s) with a slot/column for every unique word in our corpus, where 1 represents that a given word was in the review. While this simple approach can work very well, there are ways that we can encode more information into the vector. Instead of simply noting whether a word appears in the review or not, we can include the number of times a given word appears. This can give our sentiment classifier a lot more predictive power. For example, if a movie reviewer says ‘amazing’ or ‘terrible’ multiple times in a review it is considerably more probable that the review is positive or negative, respectively. Another common way to represent each document in a corpus is to use the tf-idf statistic (term frequency-inverse document frequency) for each word, which is a weighting factor that we can use in place of binary or word count representations. There are several ways to do tf-idf transformation but in a nutshell, tf-idf aims to represent the number of times a given word appears in a document (a movie review in our case) relative to the number of documents in the corpus that the word appears in — where words that appear in many documents have a value closer to zero and words that appear in less documents have values closer to 1. Note: Now that we’ve gone over n-grams, when I refer to ‘words’ I really mean any n-gram (sequence of words) if the model is using an n greater than one. So far we’ve chosen to represent each review as a very sparse vector (lots of zeros!) with a slot for every unique n-gram in the corpus (minus n-grams that appear too often or not often enough). Linear classifiers typically perform better than other algorithms on data that is represented in this way. Recall that linear classifiers tend to work well on very sparse datasets (like the one we have). Another algorithm that can produce great results with a quick training time are Support Vector Machines with a linear kernel. Here’s an example with an n-gram range from 1 to 2: There are many great explanations of Support Vector Machines that do a much better job than I could. If you’re interested in learning more, this is a great tutorial: blog.statsbot.co The goal of this post was to give you a toolbox of things to try and mix together when trying to find the right model + data transformation for your project. I found that removing a small set of stop words along with an n-gram range from 1 to 3 and a linear support vector classifier gave me the best results. We broke the 90% mark! We’ve gone over several options for transforming text that can improve the accuracy of an NLP model. Which combination of these techniques will yield the best results will depend on the task, data representation, and algorithms you choose. It’s always a good idea to try out many different combinations to see what works. I’m very confidant a higher accuracy on this data can be attained with a different combination of the things outlined in this post. I’ll leave that for a more ambitious reader. :) Please comment with your results and method! The next parts of this series will explore deep learning approaches to building a sentiment classifier.
[ { "code": null, "e": 443, "s": 172, "text": "In part one of this series we built a barebones movie review sentiment classifier. The goal of this next post is to provide an overview of several techniques that can be used to enhance an NLP model. That being said, we won’t go too far in depth on any particular topic." }, { "code": null, "e": 496, "s": 443, "text": "If you haven’t yet, you can read my first post here:" }, { "code": null, "e": 519, "s": 496, "text": "towardsdatascience.com" }, { "code": null, "e": 629, "s": 519, "text": "All of the code used in this series along with supplemental materials can be found in this GitHub Repository." }, { "code": null, "e": 841, "s": 629, "text": "For our first iteration we did very basic text processing like removing punctuation and HTML tags and making everything lower-case. We can clean things up further by removing stop words and normalizing the text." }, { "code": null, "e": 980, "s": 841, "text": "To make these transformations we’ll use libraries from the Natural Language Toolkit (NLTK). This is a very popular NLP library for Python." }, { "code": null, "e": 1347, "s": 980, "text": "Stop words are the very common words like ‘if’, ‘but’, ‘we’, ‘he’, ‘she’, and ‘they’. We can usually remove these words without changing the semantics of a text and doing so often (but not always) improves the performance of a model. Removing these stop words becomes a lot more useful when we start using longer word sequences as model features (see n-grams below)." }, { "code": null, "e": 1354, "s": 1347, "text": "Before" }, { "code": null, "e": 2118, "s": 1354, "text": "\"bromwell high is a cartoon comedy it ran at the same time as some other programs about school life such as teachers my years in the teaching profession lead me to believe that bromwell high’s satire is much closer to reality than is teachers the scramble to survive financially the insightful students who can see right through their pathetic teachers’ pomp the pettiness of the whole situation all remind me of the schools i knew and their students when i saw the episode in which a student repeatedly tried to burn down the school i immediately recalled at high a classic line inspector i’m here to sack one of your teachers student welcome to bromwell high i expect that many adults of my age think that bromwell high is far fetched what a pity that it isn’t\"" }, { "code": null, "e": 2124, "s": 2118, "text": "After" }, { "code": null, "e": 2633, "s": 2124, "text": "\"bromwell high cartoon comedy ran time programs school life teachers years teaching profession lead believe bromwell high's satire much closer reality teachers scramble survive financially insightful students see right pathetic teachers' pomp pettiness whole situation remind schools knew students saw episode student repeatedly tried burn school immediately recalled high classic line inspector i'm sack one teachers student welcome bromwell high expect many adults age think bromwell high far fetched pity\"" }, { "code": null, "e": 3060, "s": 2633, "text": "Note: In practice, an easier way to remove stop words is to just use the stop_words argument with any of scikit-learn’s ‘Vectorizer’ classes. If you want to use NLTK’s full list of stop words you can do stop_words='english’. In practice I’ve found that using NLTK’s list actually decreases my performance because its too expansive, so I usually supply my own list of words. For example, stop_words=['in','of','at','a','the'] ." }, { "code": null, "e": 3280, "s": 3060, "text": "A common next step in text preprocessing is to normalize the words in your corpus by trying to convert all of the different forms of a given word into one. Two methods that exist for this are Stemming and Lemmatization." }, { "code": null, "e": 3289, "s": 3280, "text": "Stemming" }, { "code": null, "e": 3539, "s": 3289, "text": "Stemming is considered to be the more crude/brute-force approach to normalization (although this doesn’t necessarily mean that it will perform worse). There’s several algorithms, but in general they all use basic rules to chop off the ends of words." }, { "code": null, "e": 3699, "s": 3539, "text": "NLTK has several stemming algorithm implementations. We’ll use the Porter stemmer here but you can explore all of the options with examples here: NLTK Stemmers" }, { "code": null, "e": 3713, "s": 3699, "text": "Lemmatization" }, { "code": null, "e": 3862, "s": 3713, "text": "Lemmatization works by identifying the part-of-speech of a given word and then applying more complex rules to transform the word into its true root." }, { "code": null, "e": 3879, "s": 3862, "text": "No Normalization" }, { "code": null, "e": 4511, "s": 3879, "text": "\"this is not the typical mel brooks film it was much less slapstick than most of his movies and actually had a plot that was followable leslie ann warren made the movie she is such a fantastic under rated actress there were some moments that could have been fleshed out a bit more and some scenes that could probably have been cut to make the room to do so but all in all this is worth the price to rent and see it the acting was good overall brooks himself did a good job without his characteristic speaking to directly to the audience again warren was the best actor in the movie but fume and sailor both played their parts well\"" }, { "code": null, "e": 4519, "s": 4511, "text": "Stemmed" }, { "code": null, "e": 5107, "s": 4519, "text": "\"thi is not the typic mel brook film it wa much less slapstick than most of hi movi and actual had a plot that wa follow lesli ann warren made the movi she is such a fantast under rate actress there were some moment that could have been flesh out a bit more and some scene that could probabl have been cut to make the room to do so but all in all thi is worth the price to rent and see it the act wa good overal brook himself did a good job without hi characterist speak to directli to the audienc again warren wa the best actor in the movi but fume and sailor both play their part well\"" }, { "code": null, "e": 5118, "s": 5107, "text": "Lemmatized" }, { "code": null, "e": 5738, "s": 5118, "text": "\"this is not the typical mel brook film it wa much le slapstick than most of his movie and actually had a plot that wa followable leslie ann warren made the movie she is such a fantastic under rated actress there were some moment that could have been fleshed out a bit more and some scene that could probably have been cut to make the room to do so but all in all this is worth the price to rent and see it the acting wa good overall brook himself did a good job without his characteristic speaking to directly to the audience again warren wa the best actor in the movie but fume and sailor both played their part well\"" }, { "code": null, "e": 6264, "s": 5738, "text": "Last time we used only single word features in our model, which we call 1-grams or unigrams. We can potentially add more predictive power to our model by adding two or three word sequences (bigrams or trigrams) as well. For example, if a review had the three word sequence “didn’t love movie” we would only consider these words individually with a unigram-only model and probably not capture that this is actually a negative sentiment because the word ‘love’ by itself is going to be highly correlated with a positive review." }, { "code": null, "e": 6405, "s": 6264, "text": "The scikit-learn library makes this really easy to play around with. Just use the ngram_range argument with any of the ‘Vectorizer’ classes." }, { "code": null, "e": 6561, "s": 6405, "text": "Getting pretty close to 90%! So, simply considering 2-word sequences in addition to single words increased our accuracy by more than 1.6 percentage points." }, { "code": null, "e": 6954, "s": 6561, "text": "Note: There’s technically no limit on the size that n can be for your model, but there are several things to consider. First, increasing the number of grams will not necessarily give you better performance. Second, the size of your matrix grows exponentially as you increment n, so if you have a large corpus that is comprised of large documents your model may take a very long time to train." }, { "code": null, "e": 7134, "s": 6954, "text": "In part 1 we represented each review as a binary vector (1s and 0s) with a slot/column for every unique word in our corpus, where 1 represents that a given word was in the review." }, { "code": null, "e": 7249, "s": 7134, "text": "While this simple approach can work very well, there are ways that we can encode more information into the vector." }, { "code": null, "e": 7621, "s": 7249, "text": "Instead of simply noting whether a word appears in the review or not, we can include the number of times a given word appears. This can give our sentiment classifier a lot more predictive power. For example, if a movie reviewer says ‘amazing’ or ‘terrible’ multiple times in a review it is considerably more probable that the review is positive or negative, respectively." }, { "code": null, "e": 7863, "s": 7621, "text": "Another common way to represent each document in a corpus is to use the tf-idf statistic (term frequency-inverse document frequency) for each word, which is a weighting factor that we can use in place of binary or word count representations." }, { "code": null, "e": 8254, "s": 7863, "text": "There are several ways to do tf-idf transformation but in a nutshell, tf-idf aims to represent the number of times a given word appears in a document (a movie review in our case) relative to the number of documents in the corpus that the word appears in — where words that appear in many documents have a value closer to zero and words that appear in less documents have values closer to 1." }, { "code": null, "e": 8408, "s": 8254, "text": "Note: Now that we’ve gone over n-grams, when I refer to ‘words’ I really mean any n-gram (sequence of words) if the model is using an n greater than one." }, { "code": null, "e": 8710, "s": 8408, "text": "So far we’ve chosen to represent each review as a very sparse vector (lots of zeros!) with a slot for every unique n-gram in the corpus (minus n-grams that appear too often or not often enough). Linear classifiers typically perform better than other algorithms on data that is represented in this way." }, { "code": null, "e": 8933, "s": 8710, "text": "Recall that linear classifiers tend to work well on very sparse datasets (like the one we have). Another algorithm that can produce great results with a quick training time are Support Vector Machines with a linear kernel." }, { "code": null, "e": 8985, "s": 8933, "text": "Here’s an example with an n-gram range from 1 to 2:" }, { "code": null, "e": 9151, "s": 8985, "text": "There are many great explanations of Support Vector Machines that do a much better job than I could. If you’re interested in learning more, this is a great tutorial:" }, { "code": null, "e": 9168, "s": 9151, "text": "blog.statsbot.co" }, { "code": null, "e": 9478, "s": 9168, "text": "The goal of this post was to give you a toolbox of things to try and mix together when trying to find the right model + data transformation for your project. I found that removing a small set of stop words along with an n-gram range from 1 to 3 and a linear support vector classifier gave me the best results." }, { "code": null, "e": 9501, "s": 9478, "text": "We broke the 90% mark!" }, { "code": null, "e": 9823, "s": 9501, "text": "We’ve gone over several options for transforming text that can improve the accuracy of an NLP model. Which combination of these techniques will yield the best results will depend on the task, data representation, and algorithms you choose. It’s always a good idea to try out many different combinations to see what works." }, { "code": null, "e": 10048, "s": 9823, "text": "I’m very confidant a higher accuracy on this data can be attained with a different combination of the things outlined in this post. I’ll leave that for a more ambitious reader. :) Please comment with your results and method!" } ]
mat-slide-toggle in Angular material - GeeksforGeeks
27 Jan, 2021 Angular Material is a UI component library that is developed by the Angular team to build design components for desktop and mobile web applications. In order to install it, we need to have angular installed in our project, once you have it you can enter the below command and can download it. mat-slide-toggle is a kind of switch or button that is used to toggle between states like one and off or true or false. Installation syntax: ng add @angular/material Approach: First, install the angular material using the above-mentioned command. After completing the installation, Import ‘MatSlideToggleModule’ from ‘@angular/material/slide-toggle’ in the app.module.ts file. Then use the mat-slide-toggle tag to display a toggle button. And in order to write the significance of that button then we need to mention it between the opening and closing tags. If we want to change the theme then we can change it by using the color property. In angular we have 3 themes, they are primary, accent, and warn. Once done with the above steps then serve or start the project. Code Implementation: app.module.ts: Javascript import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; import { MatSlideToggleModule } from '@angular/material/slide-toggle'; @NgModule({ imports: [ BrowserModule, FormsModule, MatSlideToggleModule], declarations: [ AppComponent ], bootstrap: [ AppComponent ] }) export class AppModule { } app.component.html: HTML <mat-slide-toggle color="primary"> Slide me to get the primary theme!</mat-slide-toggle> <br /><br /><mat-slide-toggle color="accent"> Slide me to get the accent theme!</mat-slide-toggle><br /><br /><mat-slide-toggle color="warn"> Slide me to get the warn theme!</mat-slide-toggle> Output: AngularJS-Misc Picked AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Angular PrimeNG Dropdown Component Angular PrimeNG Calendar Component Angular PrimeNG Messages Component Angular 10 (blur) Event How to make a Bootstrap Modal Popup in Angular 9/8 ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26464, "s": 26436, "text": "\n27 Jan, 2021" }, { "code": null, "e": 26758, "s": 26464, "text": "Angular Material is a UI component library that is developed by the Angular team to build design components for desktop and mobile web applications. In order to install it, we need to have angular installed in our project, once you have it you can enter the below command and can download it. " }, { "code": null, "e": 26878, "s": 26758, "text": "mat-slide-toggle is a kind of switch or button that is used to toggle between states like one and off or true or false." }, { "code": null, "e": 26899, "s": 26878, "text": "Installation syntax:" }, { "code": null, "e": 26924, "s": 26899, "text": "ng add @angular/material" }, { "code": null, "e": 26934, "s": 26924, "text": "Approach:" }, { "code": null, "e": 27005, "s": 26934, "text": "First, install the angular material using the above-mentioned command." }, { "code": null, "e": 27135, "s": 27005, "text": "After completing the installation, Import ‘MatSlideToggleModule’ from ‘@angular/material/slide-toggle’ in the app.module.ts file." }, { "code": null, "e": 27197, "s": 27135, "text": "Then use the mat-slide-toggle tag to display a toggle button." }, { "code": null, "e": 27316, "s": 27197, "text": "And in order to write the significance of that button then we need to mention it between the opening and closing tags." }, { "code": null, "e": 27463, "s": 27316, "text": "If we want to change the theme then we can change it by using the color property. In angular we have 3 themes, they are primary, accent, and warn." }, { "code": null, "e": 27527, "s": 27463, "text": "Once done with the above steps then serve or start the project." }, { "code": null, "e": 27548, "s": 27527, "text": "Code Implementation:" }, { "code": null, "e": 27563, "s": 27548, "text": "app.module.ts:" }, { "code": null, "e": 27574, "s": 27563, "text": "Javascript" }, { "code": "import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; import { MatSlideToggleModule } from '@angular/material/slide-toggle'; @NgModule({ imports: [ BrowserModule, FormsModule, MatSlideToggleModule], declarations: [ AppComponent ], bootstrap: [ AppComponent ] }) export class AppModule { }", "e": 28023, "s": 27574, "text": null }, { "code": null, "e": 28043, "s": 28023, "text": "app.component.html:" }, { "code": null, "e": 28048, "s": 28043, "text": "HTML" }, { "code": "<mat-slide-toggle color=\"primary\"> Slide me to get the primary theme!</mat-slide-toggle> <br /><br /><mat-slide-toggle color=\"accent\"> Slide me to get the accent theme!</mat-slide-toggle><br /><br /><mat-slide-toggle color=\"warn\"> Slide me to get the warn theme!</mat-slide-toggle>", "e": 28333, "s": 28048, "text": null }, { "code": null, "e": 28341, "s": 28333, "text": "Output:" }, { "code": null, "e": 28356, "s": 28341, "text": "AngularJS-Misc" }, { "code": null, "e": 28363, "s": 28356, "text": "Picked" }, { "code": null, "e": 28373, "s": 28363, "text": "AngularJS" }, { "code": null, "e": 28390, "s": 28373, "text": "Web Technologies" }, { "code": null, "e": 28488, "s": 28390, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28523, "s": 28488, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 28558, "s": 28523, "text": "Angular PrimeNG Calendar Component" }, { "code": null, "e": 28593, "s": 28558, "text": "Angular PrimeNG Messages Component" }, { "code": null, "e": 28617, "s": 28593, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 28670, "s": 28617, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 28710, "s": 28670, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28743, "s": 28710, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28788, "s": 28743, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28831, "s": 28788, "text": "How to fetch data from an API in ReactJS ?" } ]
Excel Delete Cells
Cells can be deleted by selecting them, and pressing the delete button. Note: The delete function will not delete the formatting of the cell, just the value inside of it. Let's have a look at three examples. Pressing the delete button: Pressing the delete button: With formatting: Pressing the delete button: Note that it only deletes the value in the cells, and not the formatting (the color). Note: You will learn more about formatting, and how to style cells in a later chapter. Complete the name of the command for removing columns: Columns Start the Exercise 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: [email protected] Your message has been sent to W3Schools.
[ { "code": null, "e": 72, "s": 0, "text": "Cells can be deleted by selecting them, and pressing the delete button." }, { "code": null, "e": 171, "s": 72, "text": "Note: The delete function will not delete the formatting of the cell, just the value inside of it." }, { "code": null, "e": 208, "s": 171, "text": "Let's have a look at three examples." }, { "code": null, "e": 236, "s": 208, "text": "Pressing the delete button:" }, { "code": null, "e": 264, "s": 236, "text": "Pressing the delete button:" }, { "code": null, "e": 281, "s": 264, "text": "With formatting:" }, { "code": null, "e": 309, "s": 281, "text": "Pressing the delete button:" }, { "code": null, "e": 395, "s": 309, "text": "Note that it only deletes the value in the cells, and not the formatting (the color)." }, { "code": null, "e": 482, "s": 395, "text": "Note: You will learn more about formatting, and how to style cells in a later chapter." }, { "code": null, "e": 537, "s": 482, "text": "Complete the name of the command for removing columns:" }, { "code": null, "e": 547, "s": 537, "text": " Columns\n" }, { "code": null, "e": 566, "s": 547, "text": "Start the Exercise" }, { "code": null, "e": 599, "s": 566, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 641, "s": 599, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 748, "s": 641, "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": 767, "s": 748, "text": "[email protected]" } ]
Git Ignore and .gitignore
When sharing your code with others, there are often files or parts of your project, you do not want to share. Examples log files temporary files hidden files personal files etc. Git can specify which files or parts of your project should be ignored by Git using a .gitignore file. Git will not track files and folders specified in .gitignore. However, the .gitignore file itself IS tracked by Git. To create a .gitignore file, go to the root of your local Git, and create it: touch .gitignore Now open the file using a text editor. We are just going to add two simple rules: Ignore any files with the .log extension Ignore everything in any directory named temp Now all .log files and anything in temp folders will be ignored by Git. Note: In this case, we use a single .gitignore which applies to the entire repository. It is also possible to have additional .gitignore files in subdirectories. These only apply to files or folders within that directory. Here are the general rules for matching patterns in .gitignore files: It is also possible to ignore files or folders but not show it in the distubuted .gitignore file. These kinds of ignores are specified in the .git/info/exclude file. It works the same way as .gitignore but are not shown to anyone else. In .gitignore add a line to ignore all .temp files: Start the Exercise 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: [email protected] Your message has been sent to W3Schools.
[ { "code": null, "e": 110, "s": 0, "text": "When sharing your code with others, there are often files or parts of your project, you do not want to share." }, { "code": null, "e": 119, "s": 110, "text": "Examples" }, { "code": null, "e": 129, "s": 119, "text": "log files" }, { "code": null, "e": 145, "s": 129, "text": "temporary files" }, { "code": null, "e": 158, "s": 145, "text": "hidden files" }, { "code": null, "e": 173, "s": 158, "text": "personal files" }, { "code": null, "e": 178, "s": 173, "text": "etc." }, { "code": null, "e": 282, "s": 178, "text": "Git can specify which files or parts of your project should be \nignored by Git using a .gitignore file." }, { "code": null, "e": 400, "s": 282, "text": "Git will not track files and folders specified in .gitignore. However, the .gitignore \nfile itself IS tracked by Git." }, { "code": null, "e": 478, "s": 400, "text": "To create a .gitignore file, go to the root of your local Git, and create it:" }, { "code": null, "e": 495, "s": 478, "text": "touch .gitignore" }, { "code": null, "e": 534, "s": 495, "text": "Now open the file using a text editor." }, { "code": null, "e": 577, "s": 534, "text": "We are just going to add two simple rules:" }, { "code": null, "e": 618, "s": 577, "text": "Ignore any files with the .log extension" }, { "code": null, "e": 664, "s": 618, "text": "Ignore everything in any directory named temp" }, { "code": null, "e": 737, "s": 664, "text": "Now all .log files and anything in \ntemp folders will be ignored by Git." }, { "code": null, "e": 824, "s": 737, "text": "Note: In this case, we use a single .gitignore which applies to the entire repository." }, { "code": null, "e": 960, "s": 824, "text": " It is also possible to have additional .gitignore files in subdirectories. These only apply to files or folders within that directory." }, { "code": null, "e": 1032, "s": 960, "text": "Here are the general rules for matching patterns in .gitignore \nfiles: " }, { "code": null, "e": 1131, "s": 1032, "text": "It is also possible to ignore files or folders but not show it in the \ndistubuted .gitignore file." }, { "code": null, "e": 1270, "s": 1131, "text": "These kinds of ignores are specified in the \n.git/info/exclude file. It works the same way as\n.gitignore but are not shown to anyone else." }, { "code": null, "e": 1322, "s": 1270, "text": "In .gitignore add a line to ignore all .temp files:" }, { "code": null, "e": 1344, "s": 1324, "text": "\nStart the Exercise" }, { "code": null, "e": 1377, "s": 1344, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 1419, "s": 1377, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1526, "s": 1419, "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": 1545, "s": 1526, "text": "[email protected]" } ]
How to find all uppercase strings in a MySQL table?
To find all upper case strings in a MySQL table, you need to use BINARY UPPER() function. The syntax is as follows: SELECT *FROM yourTableName WHERE yourColumnName=BINARY UPPER(yourColumnName); To understand the above syntax, let us create a table. The query to create a table is as follows: mysql> create table FindUpperCaseDemo -> ( -> Id int, -> FirstName varchar(20), -> Age int -> ); Query OK, 0 rows affected (1.04 sec) Insert some records in the table using insert command. The query is as follows: mysql> insert into FindUpperCaseDemo values(1,'John',23); Query OK, 1 row affected (0.17 sec) mysql> insert into FindUpperCaseDemo values(2,'CAROL',21); Query OK, 1 row affected (0.29 sec) mysql> insert into FindUpperCaseDemo values(3,'JoHN',23); Query OK, 1 row affected (0.11 sec) mysql> insert into FindUpperCaseDemo values(4,'JOHN',26); Query OK, 1 row affected (0.22 sec) mysql> insert into FindUpperCaseDemo values(5,'sAM',26); Query OK, 1 row affected (0.18 sec) mysql> insert into FindUpperCaseDemo values(6,'SAM',28); Query OK, 1 row affected (0.18 sec) mysql> insert into FindUpperCaseDemo values(7,'MIKE',29); Query OK, 1 row affected (0.17 sec) mysql> insert into FindUpperCaseDemo values(8,'BOB',20); Query OK, 1 row affected (0.45 sec) mysql> insert into FindUpperCaseDemo values(9,'LARRY',22); Query OK, 1 row affected (0.39 sec) mysql> insert into FindUpperCaseDemo values(10,'LARRy',22); Query OK, 1 row affected (0.14 sec) Display all records from the table using select statement. The query is as follows: mysql> select *from FindUpperCaseDemo; The following is the output: +------+-----------+------+ | Id | FirstName | Age | +------+-----------+------+ | 1 | John | 23 | | 2 | CAROL | 21 | | 3 | JoHN | 23 | | 4 | JOHN | 26 | | 5 | sAM | 26 | | 6 | SAM | 28 | | 7 | MIKE | 29 | | 8 | BOB | 20 | | 9 | LARRY | 22 | | 10 | LARRy | 22 | +------+-----------+------+ 10 rows in set (0.00 sec) Here is the query to find all uppercase strings in a MySQL table: mysql> select *from FindUpperCaseDemo where FirstName=BINARY UPPER(FirstName); The following is the output: +------+-----------+------+ | Id | FirstName | Age | +------+-----------+------+ | 2 | CAROL | 21 | | 4 | JOHN | 26 | | 6 | SAM | 28 | | 7 | MIKE | 29 | | 8 | BOB | 20 | | 9 | LARRY | 22 | +------+-----------+------+ 6 rows in set (0.09 sec)
[ { "code": null, "e": 1178, "s": 1062, "text": "To find all upper case strings in a MySQL table, you need to use BINARY UPPER() function. The syntax is as follows:" }, { "code": null, "e": 1256, "s": 1178, "text": "SELECT *FROM yourTableName WHERE yourColumnName=BINARY UPPER(yourColumnName);" }, { "code": null, "e": 1354, "s": 1256, "text": "To understand the above syntax, let us create a table. The query to create a table is as follows:" }, { "code": null, "e": 1503, "s": 1354, "text": "mysql> create table FindUpperCaseDemo\n -> (\n -> Id int,\n -> FirstName varchar(20),\n -> Age int\n -> );\nQuery OK, 0 rows affected (1.04 sec)" }, { "code": null, "e": 1583, "s": 1503, "text": "Insert some records in the table using insert command. The query is as follows:" }, { "code": null, "e": 2524, "s": 1583, "text": "mysql> insert into FindUpperCaseDemo values(1,'John',23);\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into FindUpperCaseDemo values(2,'CAROL',21);\nQuery OK, 1 row affected (0.29 sec)\nmysql> insert into FindUpperCaseDemo values(3,'JoHN',23);\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into FindUpperCaseDemo values(4,'JOHN',26);\nQuery OK, 1 row affected (0.22 sec)\nmysql> insert into FindUpperCaseDemo values(5,'sAM',26);\nQuery OK, 1 row affected (0.18 sec)\nmysql> insert into FindUpperCaseDemo values(6,'SAM',28);\nQuery OK, 1 row affected (0.18 sec)\nmysql> insert into FindUpperCaseDemo values(7,'MIKE',29);\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into FindUpperCaseDemo values(8,'BOB',20);\nQuery OK, 1 row affected (0.45 sec)\nmysql> insert into FindUpperCaseDemo values(9,'LARRY',22);\nQuery OK, 1 row affected (0.39 sec)\nmysql> insert into FindUpperCaseDemo values(10,'LARRy',22);\nQuery OK, 1 row affected (0.14 sec)" }, { "code": null, "e": 2608, "s": 2524, "text": "Display all records from the table using select statement. The query is as follows:" }, { "code": null, "e": 2647, "s": 2608, "text": "mysql> select *from FindUpperCaseDemo;" }, { "code": null, "e": 2676, "s": 2647, "text": "The following is the output:" }, { "code": null, "e": 3094, "s": 2676, "text": "+------+-----------+------+\n| Id | FirstName | Age |\n+------+-----------+------+\n| 1 | John | 23 |\n| 2 | CAROL | 21 |\n| 3 | JoHN | 23 |\n| 4 | JOHN | 26 |\n| 5 | sAM | 26 |\n| 6 | SAM | 28 |\n| 7 | MIKE | 29 |\n| 8 | BOB | 20 |\n| 9 | LARRY | 22 |\n| 10 | LARRy | 22 |\n+------+-----------+------+\n10 rows in set (0.00 sec)" }, { "code": null, "e": 3160, "s": 3094, "text": "Here is the query to find all uppercase strings in a MySQL table:" }, { "code": null, "e": 3239, "s": 3160, "text": "mysql> select *from FindUpperCaseDemo where FirstName=BINARY UPPER(FirstName);" }, { "code": null, "e": 3268, "s": 3239, "text": "The following is the output:" }, { "code": null, "e": 3573, "s": 3268, "text": "+------+-----------+------+\n| Id | FirstName | Age |\n+------+-----------+------+\n| 2 | CAROL | 21 |\n| 4 | JOHN | 26 |\n| 6 | SAM | 28 |\n| 7 | MIKE | 29 |\n| 8 | BOB | 20 |\n| 9 | LARRY | 22 |\n+------+-----------+------+\n6 rows in set (0.09 sec)" } ]
MFC - Messages & Events
An application is made of various objects. Most of the time, more than one application is running on the computer and the operating system is constantly asked to perform some assignments. Because there can be so many requests presented unpredictably, the operating system leaves it up to the objects to specify what they want, when they want it, and what behavior or result they expect. The Microsoft Windows operating system cannot predict what kinds of requests one object would need to be taken care of and what type of assignment another object would need. The Microsoft Windows operating system cannot predict what kinds of requests one object would need to be taken care of and what type of assignment another object would need. To manage all these assignments and requests, the objects send messages. To manage all these assignments and requests, the objects send messages. Each object has the responsibility to decided what message to send and when. Each object has the responsibility to decided what message to send and when. In order to send a message, a control must create an event. In order to send a message, a control must create an event. To make a distinction between the two, a message's name usually starts with WM_ which stands for Window Message. To make a distinction between the two, a message's name usually starts with WM_ which stands for Window Message. The name of an event usually starts with On which indicates an action. The name of an event usually starts with On which indicates an action. The event is the action of sending the message. The event is the action of sending the message. Since Windows is a message-oriented operating system, a large portion of programming for the Windows environment involves message handling. Each time an event such as a keystroke or mouse click occurs, a message is sent to the application, which must then handle the event. For the compiler to manage messages, they should be included in the class definition. For the compiler to manage messages, they should be included in the class definition. The DECLARE_MESSAGE_MAP macro should be provided at the end of the class definition as shown in the following code. The DECLARE_MESSAGE_MAP macro should be provided at the end of the class definition as shown in the following code. class CMainFrame : public CFrameWnd { public: CMainFrame(); protected: DECLARE_MESSAGE_MAP() }; The actual messages should be listed just above the DECLARE_MESSAGE_MAP line. The actual messages should be listed just above the DECLARE_MESSAGE_MAP line. To implement the messages, you need to create a table of messages that your program is using. To implement the messages, you need to create a table of messages that your program is using. This table uses two delimiting macros; This table uses two delimiting macros; Its starts with a BEGIN_MESSAGE_MAP and ends with an END_MESSAGE_MAP macros. Its starts with a BEGIN_MESSAGE_MAP and ends with an END_MESSAGE_MAP macros. The BEGIN_MESSAGE_MAP macro takes two arguments, the name of your class and the MFC class you derived your class from as shown in the following code. The BEGIN_MESSAGE_MAP macro takes two arguments, the name of your class and the MFC class you derived your class from as shown in the following code. #include <afxwin.h> class CMainFrame : public CFrameWnd { public: CMainFrame(); protected: DECLARE_MESSAGE_MAP() }; CMainFrame::CMainFrame() { // Create the window's frame Create(NULL, L"MFC Messages Demo", WS_OVERLAPPEDWINDOW, CRect(120, 100, 700, 480), NULL); } class CMessagesApp : public CWinApp { public: BOOL InitInstance(); }; BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd) END_MESSAGE_MAP() BOOL CMessagesApp::InitInstance(){ m_pMainWnd = new CMainFrame; m_pMainWnd->ShowWindow(SW_SHOW); m_pMainWnd->UpdateWindow(); return TRUE; } CMessagesApp theApp; Let us look into a simple example by creating a new Win32 project. Step 1 − To create an MFC project, right-click on the project and select Properties. Step 2 − In the left section, click Configuration Properties → General. Step 3 − Select the ‘Use MFC in Shared DLL’ option in Project Defaults section and click OK. Step 4 − We need to add a new source file. Step 5 − Right-click on your Project and select Add → New Item. Step 6 − In the Templates section, click C++ File (.cpp). Step 7 − Click Add to Continue. Step 8 − Now, add the following code in the *.cpp file. #include <afxwin.h> class CMainFrame : public CFrameWnd { public: CMainFrame(); protected: DECLARE_MESSAGE_MAP() }; CMainFrame::CMainFrame() { // Create the window's frame Create(NULL, L"MFC Messages Demo", WS_OVERLAPPEDWINDOW, CRect(120, 100, 700, 480), NULL); } class CMessagesApp : public CWinApp { public: BOOL InitInstance(); }; BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd) END_MESSAGE_MAP() BOOL CMessagesApp::InitInstance() { m_pMainWnd = new CMainFrame; m_pMainWnd->ShowWindow(SW_SHOW); m_pMainWnd->UpdateWindow(); return TRUE; } CMessagesApp theApp; There are different types of Windows messages like creating a window, showing a window etc. Here are some of the commonly used windows messages. Let us look into a simple example of window creation. WM_CREATE − When an object, called a window, is created, the frame that creates the objects sends a message identified as ON_WM_CREATE. Step 1 − To create ON_WM_CREATE, add afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); before the DECLARE_MESSAGE_MAP() as shown below. class CMainFrame : public CFrameWnd { public: CMainFrame(); protected: afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); DECLARE_MESSAGE_MAP() }; Step 2 − Add the ON_WM_CREATE() after the BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd) and before END_MESSAGE_MAP() BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd) ON_WM_CREATE() END_MESSAGE_MAP() Step 3 − Here is the Implementation of OnCreate() int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct) { // Call the base class to create the window if (CFrameWnd::OnCreate(lpCreateStruct) == 0) { // If the window was successfully created, let the user know MessageBox(L"The window has been created!!!"); // Since the window was successfully created, return 0 return 0; } // Otherwise, return -1 return -1; } Step 4 − Now your *.cpp file will look like as shown in the following code. #include <afxwin.h> class CMainFrame : public CFrameWnd { public: CMainFrame(); protected: afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); DECLARE_MESSAGE_MAP() }; CMainFrame::CMainFrame() { // Create the window's frame Create(NULL, L"MFC Messages Demo", WS_OVERLAPPEDWINDOW, CRect(120, 100, 700, 480), NULL); } class CMessagesApp : public CWinApp { public: BOOL InitInstance(); }; BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd) ON_WM_CREATE() END_MESSAGE_MAP() int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct) { // Call the base class to create the window if (CFrameWnd::OnCreate(lpCreateStruct) == 0) { // If the window was successfully created, let the user know MessageBox(L"The window has been created!!!"); // Since the window was successfully created, return 0 return 0; } // Otherwise, return -1 return -1; } BOOL CMessagesApp::InitInstance() { m_pMainWnd = new CMainFrame; m_pMainWnd -> ShowWindow(SW_SHOW); m_pMainWnd -> UpdateWindow(); return TRUE; } CMessagesApp theApp; Step 5 − When the above code is compiled and executed, you will see the following output. Step 6 − When you click OK, it will display the main window. One of the main features of a graphical application is to present Windows controls and resources that allow the user to interact with the machine. Examples of controls that we will learn are buttons, list boxes, combo boxes, etc. One type of resource we introduced in the previous lesson is the menu. Such controls and resources can initiate their own messages when the user clicks them. A message that emanates from a Windows control or a resource is called a command message. Let us look into a simple example of Command messages. To provide your application the ability to create a new document, the CWinApp class provides the OnFileNew() method. afx_msg void OnFileNew(); BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd) ON_COMMAND(ID_FILE_NEW, CMainFrame::OnFileNew) END_MESSAGE_MAP() Here is the method definition − void CMainFrame::OnFileNew() { // Create New file } A keyboard is a hardware object attached to the computer. By default, it is used to enter recognizable symbols, letters, and other characters on a control. Each key on the keyboard displays a symbol, a letter, or a combination of those, to give an indication of what the key could be used for. The user typically presses a key, which sends a signal to a program. Each key has a code that the operating system can recognize. This code is known as the virtual key code. VK_LBUTTON Left mouse button VK_RBUTTON Right mouse button VK_CANCEL Control-break processing VK_MBUTTON Middle mouse button (three-button mouse) VK_BACK BACKSPACE key VK_RETURN ENTER key VK_TAB TAB key VK_CLEAR CLEAR key VK_SHIFT SHIFT key VK_CONTROL CTRL key VK_MENU ALT key VK_PAUSE PAUSE key VK_CAPITAL CAPS LOCK key VK_ESCAPE ESC key VK_SPACE SPACEBAR VK_PRIOR PAGE UP key VK_NEXT PAGE DOWN key VK_END END key VK_HOME HOME key VK_LEFT LEFT ARROW key VK_UP UP ARROW key VK_RIGHT RIGHT ARROW key VK_DOWN DOWN ARROW key VK_SELECT SELECT key VK_PRINT PRINT key VK_EXECUTE EXECUTE key VK_SNAPSHOT PRINT SCREEN key VK_INSERT INS key VK_DELETE DEL key VK_NUMPAD0 Numeric keypad 0 key VK_NUMPAD1 Numeric keypad 1 key VK_NUMPAD2 Numeric keypad 2 key VK_NUMPAD3 Numeric keypad 3 key VK_NUMPAD4 Numeric keypad 4 key VK_NUMPAD5 Numeric keypad 5 key VK_NUMPAD6 Numeric keypad 6 key VK_NUMPAD7 Numeric keypad 7 key VK_NUMPAD8 Numeric keypad 8 key VK_NUMPAD9 Numeric keypad 9 key VK_MULTIPLY Multiply key VK_ADD Add key VK_SEPARATOR Separator key VK_SUBTRACT Subtract key VK_DECIMAL Decimal key VK_DIVIDE Divide key VK_F1 F1 key VK_F2 F2 key VK_F3 F3 key VK_F4 F4 key VK_F5 F5 key VK_F6 F6 key VK_F7 F7 key VK_F8 F8 key VK_F9 F9 key VK_F10 F10 key VK_F11 F11 key VK_F12 F12 key VK_NUMLOCK NUM LOCK key VK_SCROLL SCROLL LOCK key VK_LSHIFT Left SHIFT key VK_RSHIFT Right SHIFT key VK_LCONTROL Left CONTROL key VK_RCONTROL Right CONTROL key Pressing a key causes a WM_KEYDOWN or WM_SYSKEYDOWN message to be placed in the thread message. This can be defined as follows − afx_msg void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags); Let us look into a simple example. Step 1 − Here is the message. BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd) ON_WM_CREATE() ON_WM_KEYDOWN() END_MESSAGE_MAP() Step 2 − Here is the implementation of OnKeyDown(). void CMainFrame::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags) { switch (nChar) { case VK_RETURN: MessageBox(L"You pressed Enter"); break; case VK_F1: MessageBox(L"Help is not available at the moment"); break; case VK_DELETE: MessageBox(L"Can't Delete This"); break; default: MessageBox(L"Whatever"); } } Step 3 − When the above code is compiled and executed, you will see the following output. Step 4 − When you press Enter, it will display the following message. The mouse is another object that is attached to the computer allowing the user to interact with the machine. If the left mouse button was pressed, an ON_WM_LBUTTONDOWN message is sent. The syntax of this message is − afx_msg void OnLButtonDown(UINT nFlags, CPoint point) If the left mouse button was pressed, an ON_WM_LBUTTONDOWN message is sent. The syntax of this message is − afx_msg void OnLButtonDown(UINT nFlags, CPoint point) afx_msg void OnLButtonDown(UINT nFlags, CPoint point) If the right mouse button was pressed, an ON_WM_RBUTTONDOWN message is sent. Its syntax is − afx_msg void OnRButtonDown(UINT nFlags, CPoint point) If the right mouse button was pressed, an ON_WM_RBUTTONDOWN message is sent. Its syntax is − afx_msg void OnRButtonDown(UINT nFlags, CPoint point) afx_msg void OnRButtonDown(UINT nFlags, CPoint point) Similarly If the left mouse is being released, the ON_WM_LBUTTONUP message is sent. Its syntax is − afx_msg void OnLButtonUp(UINT nFlags, CPoint point) Similarly If the left mouse is being released, the ON_WM_LBUTTONUP message is sent. Its syntax is − afx_msg void OnLButtonUp(UINT nFlags, CPoint point) afx_msg void OnLButtonUp(UINT nFlags, CPoint point) If the right mouse is being released, the ON_WM_TBUTTONUP message is sent. Its syntax is − afx_msg void OnRButtonUp(UINT nFlags, CPoint point) If the right mouse is being released, the ON_WM_TBUTTONUP message is sent. Its syntax is − afx_msg void OnRButtonUp(UINT nFlags, CPoint point) afx_msg void OnRButtonUp(UINT nFlags, CPoint point) Let us look into a simple example. Step 1 − Add the following two functions in CMainFrame class definition as shown in the following code. class CMainFrame : public CFrameWnd { public: CMainFrame(); protected: afx_msg void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags); afx_msg void OnLButtonDown(UINT nFlags, CPoint point); afx_msg void OnRButtonUp(UINT nFlags, CPoint point); DECLARE_MESSAGE_MAP() }; Step 2 − Add the following two Message Maps. BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd) ON_WM_KEYDOWN() ON_WM_LBUTTONDOWN() ON_WM_RBUTTONUP() END_MESSAGE_MAP() Step 3 − Here is the functions definition. void CMainFrame::OnLButtonDown(UINT nFlags, CPoint point) { CString MsgCoord; MsgCoord.Format(L"Left Button at P(%d, %d)", point.x, point.y); MessageBox(MsgCoord); } void CMainFrame::OnRButtonUp(UINT nFlags, CPoint point) { MessageBox(L"Right Mouse Button Up"); } Step 4 − When you run this application, you will see the following output. Step 5 − When you click OK, you will see the following message. Step 6 − Right-click on this window. Now, when you release the right button of the mouse, it will display the following message. Print Add Notes Bookmark this page
[ { "code": null, "e": 2454, "s": 2067, "text": "An application is made of various objects. Most of the time, more than one application is running on the computer and the operating system is constantly asked to perform some assignments. Because there can be so many requests presented unpredictably, the operating system leaves it up to the objects to specify what they want, when they want it, and what behavior or result they expect." }, { "code": null, "e": 2628, "s": 2454, "text": "The Microsoft Windows operating system cannot predict what kinds of requests one object would need to be taken care of and what type of assignment another object would need." }, { "code": null, "e": 2802, "s": 2628, "text": "The Microsoft Windows operating system cannot predict what kinds of requests one object would need to be taken care of and what type of assignment another object would need." }, { "code": null, "e": 2875, "s": 2802, "text": "To manage all these assignments and requests, the objects send messages." }, { "code": null, "e": 2948, "s": 2875, "text": "To manage all these assignments and requests, the objects send messages." }, { "code": null, "e": 3025, "s": 2948, "text": "Each object has the responsibility to decided what message to send and when." }, { "code": null, "e": 3102, "s": 3025, "text": "Each object has the responsibility to decided what message to send and when." }, { "code": null, "e": 3162, "s": 3102, "text": "In order to send a message, a control must create an event." }, { "code": null, "e": 3222, "s": 3162, "text": "In order to send a message, a control must create an event." }, { "code": null, "e": 3335, "s": 3222, "text": "To make a distinction between the two, a message's name usually starts with WM_ which stands for Window Message." }, { "code": null, "e": 3448, "s": 3335, "text": "To make a distinction between the two, a message's name usually starts with WM_ which stands for Window Message." }, { "code": null, "e": 3519, "s": 3448, "text": "The name of an event usually starts with On which indicates an action." }, { "code": null, "e": 3590, "s": 3519, "text": "The name of an event usually starts with On which indicates an action." }, { "code": null, "e": 3638, "s": 3590, "text": "The event is the action of sending the message." }, { "code": null, "e": 3686, "s": 3638, "text": "The event is the action of sending the message." }, { "code": null, "e": 3960, "s": 3686, "text": "Since Windows is a message-oriented operating system, a large portion of programming for the Windows environment involves message handling. Each time an event such as a keystroke or mouse click occurs, a message is sent to the application, which must then handle the event." }, { "code": null, "e": 4046, "s": 3960, "text": "For the compiler to manage messages, they should be included in the class definition." }, { "code": null, "e": 4132, "s": 4046, "text": "For the compiler to manage messages, they should be included in the class definition." }, { "code": null, "e": 4248, "s": 4132, "text": "The DECLARE_MESSAGE_MAP macro should be provided at the end of the class definition as shown in the following code." }, { "code": null, "e": 4364, "s": 4248, "text": "The DECLARE_MESSAGE_MAP macro should be provided at the end of the class definition as shown in the following code." }, { "code": null, "e": 4478, "s": 4364, "text": "class CMainFrame : public CFrameWnd {\n public:\n CMainFrame();\n protected:\n DECLARE_MESSAGE_MAP()\n};" }, { "code": null, "e": 4556, "s": 4478, "text": "The actual messages should be listed just above the DECLARE_MESSAGE_MAP line." }, { "code": null, "e": 4634, "s": 4556, "text": "The actual messages should be listed just above the DECLARE_MESSAGE_MAP line." }, { "code": null, "e": 4728, "s": 4634, "text": "To implement the messages, you need to create a table of messages that your program is using." }, { "code": null, "e": 4822, "s": 4728, "text": "To implement the messages, you need to create a table of messages that your program is using." }, { "code": null, "e": 4861, "s": 4822, "text": "This table uses two delimiting macros;" }, { "code": null, "e": 4900, "s": 4861, "text": "This table uses two delimiting macros;" }, { "code": null, "e": 4977, "s": 4900, "text": "Its starts with a BEGIN_MESSAGE_MAP and ends with an END_MESSAGE_MAP macros." }, { "code": null, "e": 5054, "s": 4977, "text": "Its starts with a BEGIN_MESSAGE_MAP and ends with an END_MESSAGE_MAP macros." }, { "code": null, "e": 5204, "s": 5054, "text": "The BEGIN_MESSAGE_MAP macro takes two arguments, the name of your class and the MFC class you derived your class from as shown in the following code." }, { "code": null, "e": 5354, "s": 5204, "text": "The BEGIN_MESSAGE_MAP macro takes two arguments, the name of your class and the MFC class you derived your class from as shown in the following code." }, { "code": null, "e": 5992, "s": 5354, "text": "#include <afxwin.h>\nclass CMainFrame : public CFrameWnd {\n public:\n CMainFrame();\n protected:\n DECLARE_MESSAGE_MAP()\n};\nCMainFrame::CMainFrame() {\n\n // Create the window's frame\n Create(NULL, L\"MFC Messages Demo\", WS_OVERLAPPEDWINDOW,\n CRect(120, 100, 700, 480), NULL);\n}\nclass CMessagesApp : public CWinApp {\n public:\n BOOL InitInstance();\n};\nBEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)\nEND_MESSAGE_MAP()\nBOOL CMessagesApp::InitInstance(){\n m_pMainWnd = new CMainFrame;\n m_pMainWnd->ShowWindow(SW_SHOW);\n m_pMainWnd->UpdateWindow();\n return TRUE;\n}\nCMessagesApp theApp;" }, { "code": null, "e": 6059, "s": 5992, "text": "Let us look into a simple example by creating a new Win32 project." }, { "code": null, "e": 6144, "s": 6059, "text": "Step 1 − To create an MFC project, right-click on the project and select Properties." }, { "code": null, "e": 6216, "s": 6144, "text": "Step 2 − In the left section, click Configuration Properties → General." }, { "code": null, "e": 6309, "s": 6216, "text": "Step 3 − Select the ‘Use MFC in Shared DLL’ option in Project Defaults section and click OK." }, { "code": null, "e": 6352, "s": 6309, "text": "Step 4 − We need to add a new source file." }, { "code": null, "e": 6416, "s": 6352, "text": "Step 5 − Right-click on your Project and select Add → New Item." }, { "code": null, "e": 6474, "s": 6416, "text": "Step 6 − In the Templates section, click C++ File (.cpp)." }, { "code": null, "e": 6506, "s": 6474, "text": "Step 7 − Click Add to Continue." }, { "code": null, "e": 6562, "s": 6506, "text": "Step 8 − Now, add the following code in the *.cpp file." }, { "code": null, "e": 7171, "s": 6562, "text": "#include <afxwin.h>\nclass CMainFrame : public CFrameWnd {\n public:\n CMainFrame();\n protected:\n DECLARE_MESSAGE_MAP()\n};\n\nCMainFrame::CMainFrame() {\n // Create the window's frame\n Create(NULL, L\"MFC Messages Demo\", WS_OVERLAPPEDWINDOW,\n CRect(120, 100, 700, 480), NULL);\n}\n\nclass CMessagesApp : public CWinApp {\n public:\n BOOL InitInstance();\n};\n\nBEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)\nEND_MESSAGE_MAP()\nBOOL CMessagesApp::InitInstance() {\n m_pMainWnd = new CMainFrame;\n m_pMainWnd->ShowWindow(SW_SHOW);\n m_pMainWnd->UpdateWindow();\n return TRUE;\n}\nCMessagesApp theApp;" }, { "code": null, "e": 7316, "s": 7171, "text": "There are different types of Windows messages like creating a window, showing a window etc. Here are some of the commonly used windows messages." }, { "code": null, "e": 7370, "s": 7316, "text": "Let us look into a simple example of window creation." }, { "code": null, "e": 7506, "s": 7370, "text": "WM_CREATE − When an object, called a window, is created, the frame that creates the objects sends a message identified as ON_WM_CREATE." }, { "code": null, "e": 7645, "s": 7506, "text": "Step 1 − To create ON_WM_CREATE, add afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); before the DECLARE_MESSAGE_MAP() as shown below." }, { "code": null, "e": 7818, "s": 7645, "text": "class CMainFrame : public CFrameWnd {\n public:\n CMainFrame();\n protected:\n afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);\n DECLARE_MESSAGE_MAP()\n};" }, { "code": null, "e": 7930, "s": 7818, "text": "Step 2 − Add the ON_WM_CREATE() after the BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd) and before END_MESSAGE_MAP()" }, { "code": null, "e": 8007, "s": 7930, "text": "BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)\n ON_WM_CREATE()\nEND_MESSAGE_MAP()" }, { "code": null, "e": 8057, "s": 8007, "text": "Step 3 − Here is the Implementation of OnCreate()" }, { "code": null, "e": 8459, "s": 8057, "text": "int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct) {\n // Call the base class to create the window\n if (CFrameWnd::OnCreate(lpCreateStruct) == 0) {\n\n // If the window was successfully created, let the user know\n MessageBox(L\"The window has been created!!!\");\n // Since the window was successfully created, return 0\n return 0;\n }\n // Otherwise, return -1\n return -1;\n}" }, { "code": null, "e": 8535, "s": 8459, "text": "Step 4 − Now your *.cpp file will look like as shown in the following code." }, { "code": null, "e": 9625, "s": 8535, "text": "#include <afxwin.h>\nclass CMainFrame : public CFrameWnd {\n public:\n CMainFrame();\n protected:\n afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);\n DECLARE_MESSAGE_MAP()\n};\nCMainFrame::CMainFrame() {\n\n // Create the window's frame\n Create(NULL, L\"MFC Messages Demo\", WS_OVERLAPPEDWINDOW,\n CRect(120, 100, 700, 480), NULL);\n}\nclass CMessagesApp : public CWinApp {\n public:\n BOOL InitInstance();\n};\nBEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)\n ON_WM_CREATE()\nEND_MESSAGE_MAP()\nint CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct) {\n // Call the base class to create the window\n if (CFrameWnd::OnCreate(lpCreateStruct) == 0) {\n // If the window was successfully created, let the user know\n MessageBox(L\"The window has been created!!!\");\n // Since the window was successfully created, return 0\n return 0;\n }\n // Otherwise, return -1\n return -1;\n}\nBOOL CMessagesApp::InitInstance() { \n m_pMainWnd = new CMainFrame;\n m_pMainWnd -> ShowWindow(SW_SHOW);\n m_pMainWnd -> UpdateWindow();\n return TRUE;\n}\nCMessagesApp theApp;" }, { "code": null, "e": 9715, "s": 9625, "text": "Step 5 − When the above code is compiled and executed, you will see the following output." }, { "code": null, "e": 9776, "s": 9715, "text": "Step 6 − When you click OK, it will display the main window." }, { "code": null, "e": 10006, "s": 9776, "text": "One of the main features of a graphical application is to present Windows controls and resources that allow the user to interact with the machine. Examples of controls that we will learn are buttons, list boxes, combo boxes, etc." }, { "code": null, "e": 10254, "s": 10006, "text": "One type of resource we introduced in the previous lesson is the menu. Such controls and resources can initiate their own messages when the user clicks them. A message that emanates from a Windows control or a resource is called a command message." }, { "code": null, "e": 10309, "s": 10254, "text": "Let us look into a simple example of Command messages." }, { "code": null, "e": 10426, "s": 10309, "text": "To provide your application the ability to create a new document, the CWinApp class provides the OnFileNew() method." }, { "code": null, "e": 10562, "s": 10426, "text": "afx_msg void OnFileNew();\n\nBEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)\n ON_COMMAND(ID_FILE_NEW, CMainFrame::OnFileNew)\nEND_MESSAGE_MAP()" }, { "code": null, "e": 10594, "s": 10562, "text": "Here is the method definition −" }, { "code": null, "e": 10649, "s": 10594, "text": "void CMainFrame::OnFileNew() {\n // Create New file\n}" }, { "code": null, "e": 11012, "s": 10649, "text": "A keyboard is a hardware object attached to the computer. By default, it is used to enter recognizable symbols, letters, and other characters on a control. Each key on the keyboard displays a symbol, a letter, or a combination of those, to give an indication of what the key could be used for. The user typically presses a key, which sends a signal to a program." }, { "code": null, "e": 11117, "s": 11012, "text": "Each key has a code that the operating system can recognize. This code is known as the virtual key code." }, { "code": null, "e": 11128, "s": 11117, "text": "VK_LBUTTON" }, { "code": null, "e": 11146, "s": 11128, "text": "Left mouse button" }, { "code": null, "e": 11157, "s": 11146, "text": "VK_RBUTTON" }, { "code": null, "e": 11176, "s": 11157, "text": "Right mouse button" }, { "code": null, "e": 11186, "s": 11176, "text": "VK_CANCEL" }, { "code": null, "e": 11211, "s": 11186, "text": "Control-break processing" }, { "code": null, "e": 11222, "s": 11211, "text": "VK_MBUTTON" }, { "code": null, "e": 11263, "s": 11222, "text": "Middle mouse button (three-button mouse)" }, { "code": null, "e": 11271, "s": 11263, "text": "VK_BACK" }, { "code": null, "e": 11285, "s": 11271, "text": "BACKSPACE key" }, { "code": null, "e": 11295, "s": 11285, "text": "VK_RETURN" }, { "code": null, "e": 11305, "s": 11295, "text": "ENTER key" }, { "code": null, "e": 11312, "s": 11305, "text": "VK_TAB" }, { "code": null, "e": 11320, "s": 11312, "text": "TAB key" }, { "code": null, "e": 11329, "s": 11320, "text": "VK_CLEAR" }, { "code": null, "e": 11339, "s": 11329, "text": "CLEAR key" }, { "code": null, "e": 11348, "s": 11339, "text": "VK_SHIFT" }, { "code": null, "e": 11358, "s": 11348, "text": "SHIFT key" }, { "code": null, "e": 11369, "s": 11358, "text": "VK_CONTROL" }, { "code": null, "e": 11378, "s": 11369, "text": "CTRL key" }, { "code": null, "e": 11386, "s": 11378, "text": "VK_MENU" }, { "code": null, "e": 11394, "s": 11386, "text": "ALT key" }, { "code": null, "e": 11403, "s": 11394, "text": "VK_PAUSE" }, { "code": null, "e": 11413, "s": 11403, "text": "PAUSE key" }, { "code": null, "e": 11424, "s": 11413, "text": "VK_CAPITAL" }, { "code": null, "e": 11438, "s": 11424, "text": "CAPS LOCK key" }, { "code": null, "e": 11448, "s": 11438, "text": "VK_ESCAPE" }, { "code": null, "e": 11456, "s": 11448, "text": "ESC key" }, { "code": null, "e": 11465, "s": 11456, "text": "VK_SPACE" }, { "code": null, "e": 11474, "s": 11465, "text": "SPACEBAR" }, { "code": null, "e": 11483, "s": 11474, "text": "VK_PRIOR" }, { "code": null, "e": 11495, "s": 11483, "text": "PAGE UP key" }, { "code": null, "e": 11503, "s": 11495, "text": "VK_NEXT" }, { "code": null, "e": 11517, "s": 11503, "text": "PAGE DOWN key" }, { "code": null, "e": 11524, "s": 11517, "text": "VK_END" }, { "code": null, "e": 11532, "s": 11524, "text": "END key" }, { "code": null, "e": 11540, "s": 11532, "text": "VK_HOME" }, { "code": null, "e": 11549, "s": 11540, "text": "HOME key" }, { "code": null, "e": 11557, "s": 11549, "text": "VK_LEFT" }, { "code": null, "e": 11572, "s": 11557, "text": "LEFT ARROW key" }, { "code": null, "e": 11578, "s": 11572, "text": "VK_UP" }, { "code": null, "e": 11591, "s": 11578, "text": "UP ARROW key" }, { "code": null, "e": 11600, "s": 11591, "text": "VK_RIGHT" }, { "code": null, "e": 11616, "s": 11600, "text": "RIGHT ARROW key" }, { "code": null, "e": 11624, "s": 11616, "text": "VK_DOWN" }, { "code": null, "e": 11639, "s": 11624, "text": "DOWN ARROW key" }, { "code": null, "e": 11649, "s": 11639, "text": "VK_SELECT" }, { "code": null, "e": 11660, "s": 11649, "text": "SELECT key" }, { "code": null, "e": 11669, "s": 11660, "text": "VK_PRINT" }, { "code": null, "e": 11679, "s": 11669, "text": "PRINT key" }, { "code": null, "e": 11690, "s": 11679, "text": "VK_EXECUTE" }, { "code": null, "e": 11702, "s": 11690, "text": "EXECUTE key" }, { "code": null, "e": 11714, "s": 11702, "text": "VK_SNAPSHOT" }, { "code": null, "e": 11731, "s": 11714, "text": "PRINT SCREEN key" }, { "code": null, "e": 11741, "s": 11731, "text": "VK_INSERT" }, { "code": null, "e": 11749, "s": 11741, "text": "INS key" }, { "code": null, "e": 11759, "s": 11749, "text": "VK_DELETE" }, { "code": null, "e": 11767, "s": 11759, "text": "DEL key" }, { "code": null, "e": 11778, "s": 11767, "text": "VK_NUMPAD0" }, { "code": null, "e": 11799, "s": 11778, "text": "Numeric keypad 0 key" }, { "code": null, "e": 11810, "s": 11799, "text": "VK_NUMPAD1" }, { "code": null, "e": 11831, "s": 11810, "text": "Numeric keypad 1 key" }, { "code": null, "e": 11842, "s": 11831, "text": "VK_NUMPAD2" }, { "code": null, "e": 11863, "s": 11842, "text": "Numeric keypad 2 key" }, { "code": null, "e": 11874, "s": 11863, "text": "VK_NUMPAD3" }, { "code": null, "e": 11895, "s": 11874, "text": "Numeric keypad 3 key" }, { "code": null, "e": 11906, "s": 11895, "text": "VK_NUMPAD4" }, { "code": null, "e": 11927, "s": 11906, "text": "Numeric keypad 4 key" }, { "code": null, "e": 11938, "s": 11927, "text": "VK_NUMPAD5" }, { "code": null, "e": 11959, "s": 11938, "text": "Numeric keypad 5 key" }, { "code": null, "e": 11970, "s": 11959, "text": "VK_NUMPAD6" }, { "code": null, "e": 11991, "s": 11970, "text": "Numeric keypad 6 key" }, { "code": null, "e": 12002, "s": 11991, "text": "VK_NUMPAD7" }, { "code": null, "e": 12023, "s": 12002, "text": "Numeric keypad 7 key" }, { "code": null, "e": 12034, "s": 12023, "text": "VK_NUMPAD8" }, { "code": null, "e": 12055, "s": 12034, "text": "Numeric keypad 8 key" }, { "code": null, "e": 12066, "s": 12055, "text": "VK_NUMPAD9" }, { "code": null, "e": 12087, "s": 12066, "text": "Numeric keypad 9 key" }, { "code": null, "e": 12099, "s": 12087, "text": "VK_MULTIPLY" }, { "code": null, "e": 12112, "s": 12099, "text": "Multiply key" }, { "code": null, "e": 12119, "s": 12112, "text": "VK_ADD" }, { "code": null, "e": 12127, "s": 12119, "text": "Add key" }, { "code": null, "e": 12140, "s": 12127, "text": "VK_SEPARATOR" }, { "code": null, "e": 12154, "s": 12140, "text": "Separator key" }, { "code": null, "e": 12166, "s": 12154, "text": "VK_SUBTRACT" }, { "code": null, "e": 12179, "s": 12166, "text": "Subtract key" }, { "code": null, "e": 12190, "s": 12179, "text": "VK_DECIMAL" }, { "code": null, "e": 12202, "s": 12190, "text": "Decimal key" }, { "code": null, "e": 12212, "s": 12202, "text": "VK_DIVIDE" }, { "code": null, "e": 12223, "s": 12212, "text": "Divide key" }, { "code": null, "e": 12229, "s": 12223, "text": "VK_F1" }, { "code": null, "e": 12236, "s": 12229, "text": "F1 key" }, { "code": null, "e": 12242, "s": 12236, "text": "VK_F2" }, { "code": null, "e": 12249, "s": 12242, "text": "F2 key" }, { "code": null, "e": 12255, "s": 12249, "text": "VK_F3" }, { "code": null, "e": 12262, "s": 12255, "text": "F3 key" }, { "code": null, "e": 12268, "s": 12262, "text": "VK_F4" }, { "code": null, "e": 12275, "s": 12268, "text": "F4 key" }, { "code": null, "e": 12281, "s": 12275, "text": "VK_F5" }, { "code": null, "e": 12288, "s": 12281, "text": "F5 key" }, { "code": null, "e": 12294, "s": 12288, "text": "VK_F6" }, { "code": null, "e": 12301, "s": 12294, "text": "F6 key" }, { "code": null, "e": 12307, "s": 12301, "text": "VK_F7" }, { "code": null, "e": 12314, "s": 12307, "text": "F7 key" }, { "code": null, "e": 12320, "s": 12314, "text": "VK_F8" }, { "code": null, "e": 12327, "s": 12320, "text": "F8 key" }, { "code": null, "e": 12333, "s": 12327, "text": "VK_F9" }, { "code": null, "e": 12340, "s": 12333, "text": "F9 key" }, { "code": null, "e": 12347, "s": 12340, "text": "VK_F10" }, { "code": null, "e": 12355, "s": 12347, "text": "F10 key" }, { "code": null, "e": 12362, "s": 12355, "text": "VK_F11" }, { "code": null, "e": 12370, "s": 12362, "text": "F11 key" }, { "code": null, "e": 12377, "s": 12370, "text": "VK_F12" }, { "code": null, "e": 12385, "s": 12377, "text": "F12 key" }, { "code": null, "e": 12396, "s": 12385, "text": "VK_NUMLOCK" }, { "code": null, "e": 12409, "s": 12396, "text": "NUM LOCK key" }, { "code": null, "e": 12419, "s": 12409, "text": "VK_SCROLL" }, { "code": null, "e": 12435, "s": 12419, "text": "SCROLL LOCK key" }, { "code": null, "e": 12445, "s": 12435, "text": "VK_LSHIFT" }, { "code": null, "e": 12460, "s": 12445, "text": "Left SHIFT key" }, { "code": null, "e": 12470, "s": 12460, "text": "VK_RSHIFT" }, { "code": null, "e": 12486, "s": 12470, "text": "Right SHIFT key" }, { "code": null, "e": 12498, "s": 12486, "text": "VK_LCONTROL" }, { "code": null, "e": 12515, "s": 12498, "text": "Left CONTROL key" }, { "code": null, "e": 12527, "s": 12515, "text": "VK_RCONTROL" }, { "code": null, "e": 12545, "s": 12527, "text": "Right CONTROL key" }, { "code": null, "e": 12674, "s": 12545, "text": "Pressing a key causes a WM_KEYDOWN or WM_SYSKEYDOWN message to be placed in the thread message. This can be defined as follows −" }, { "code": null, "e": 12737, "s": 12674, "text": "afx_msg void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags);" }, { "code": null, "e": 12772, "s": 12737, "text": "Let us look into a simple example." }, { "code": null, "e": 12802, "s": 12772, "text": "Step 1 − Here is the message." }, { "code": null, "e": 12898, "s": 12802, "text": "BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)\n ON_WM_CREATE()\n ON_WM_KEYDOWN()\nEND_MESSAGE_MAP()" }, { "code": null, "e": 12950, "s": 12898, "text": "Step 2 − Here is the implementation of OnKeyDown()." }, { "code": null, "e": 13352, "s": 12950, "text": "void CMainFrame::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags) {\n switch (nChar) {\n\n case VK_RETURN:\n MessageBox(L\"You pressed Enter\");\n break;\n case VK_F1:\n MessageBox(L\"Help is not available at the moment\");\n break;\n case VK_DELETE:\n MessageBox(L\"Can't Delete This\");\n break;\n default:\n MessageBox(L\"Whatever\");\n }\n}" }, { "code": null, "e": 13442, "s": 13352, "text": "Step 3 − When the above code is compiled and executed, you will see the following output." }, { "code": null, "e": 13512, "s": 13442, "text": "Step 4 − When you press Enter, it will display the following message." }, { "code": null, "e": 13621, "s": 13512, "text": "The mouse is another object that is attached to the computer allowing the user to interact with the machine." }, { "code": null, "e": 13787, "s": 13621, "text": "If the left mouse button was pressed, an ON_WM_LBUTTONDOWN message is sent. The syntax of this message is − \n\nafx_msg void OnLButtonDown(UINT nFlags, CPoint point)\n\n" }, { "code": null, "e": 13896, "s": 13787, "text": "If the left mouse button was pressed, an ON_WM_LBUTTONDOWN message is sent. The syntax of this message is − " }, { "code": null, "e": 13950, "s": 13896, "text": "afx_msg void OnLButtonDown(UINT nFlags, CPoint point)" }, { "code": null, "e": 14004, "s": 13950, "text": "afx_msg void OnLButtonDown(UINT nFlags, CPoint point)" }, { "code": null, "e": 14154, "s": 14004, "text": "If the right mouse button was pressed, an ON_WM_RBUTTONDOWN message is sent. Its syntax is −\n\nafx_msg void OnRButtonDown(UINT nFlags, CPoint point)\n\n" }, { "code": null, "e": 14247, "s": 14154, "text": "If the right mouse button was pressed, an ON_WM_RBUTTONDOWN message is sent. Its syntax is −" }, { "code": null, "e": 14301, "s": 14247, "text": "afx_msg void OnRButtonDown(UINT nFlags, CPoint point)" }, { "code": null, "e": 14355, "s": 14301, "text": "afx_msg void OnRButtonDown(UINT nFlags, CPoint point)" }, { "code": null, "e": 14510, "s": 14355, "text": "Similarly If the left mouse is being released, the ON_WM_LBUTTONUP message is sent. Its syntax is −\n\nafx_msg void OnLButtonUp(UINT nFlags, CPoint point)\n\n" }, { "code": null, "e": 14610, "s": 14510, "text": "Similarly If the left mouse is being released, the ON_WM_LBUTTONUP message is sent. Its syntax is −" }, { "code": null, "e": 14662, "s": 14610, "text": "afx_msg void OnLButtonUp(UINT nFlags, CPoint point)" }, { "code": null, "e": 14714, "s": 14662, "text": "afx_msg void OnLButtonUp(UINT nFlags, CPoint point)" }, { "code": null, "e": 14860, "s": 14714, "text": "If the right mouse is being released, the ON_WM_TBUTTONUP message is sent. Its syntax is −\n\nafx_msg void OnRButtonUp(UINT nFlags, CPoint point)\n\n" }, { "code": null, "e": 14951, "s": 14860, "text": "If the right mouse is being released, the ON_WM_TBUTTONUP message is sent. Its syntax is −" }, { "code": null, "e": 15003, "s": 14951, "text": "afx_msg void OnRButtonUp(UINT nFlags, CPoint point)" }, { "code": null, "e": 15055, "s": 15003, "text": "afx_msg void OnRButtonUp(UINT nFlags, CPoint point)" }, { "code": null, "e": 15090, "s": 15055, "text": "Let us look into a simple example." }, { "code": null, "e": 15194, "s": 15090, "text": "Step 1 − Add the following two functions in CMainFrame class definition as shown in the following code." }, { "code": null, "e": 15497, "s": 15194, "text": "class CMainFrame : public CFrameWnd {\n public:\n CMainFrame();\n protected:\n afx_msg void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags);\n afx_msg void OnLButtonDown(UINT nFlags, CPoint point);\n afx_msg void OnRButtonUp(UINT nFlags, CPoint point);\n DECLARE_MESSAGE_MAP()\n};" }, { "code": null, "e": 15542, "s": 15497, "text": "Step 2 − Add the following two Message Maps." }, { "code": null, "e": 15664, "s": 15542, "text": "BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)\n ON_WM_KEYDOWN()\n ON_WM_LBUTTONDOWN()\n ON_WM_RBUTTONUP()\nEND_MESSAGE_MAP()" }, { "code": null, "e": 15707, "s": 15664, "text": "Step 3 − Here is the functions definition." }, { "code": null, "e": 15985, "s": 15707, "text": "void CMainFrame::OnLButtonDown(UINT nFlags, CPoint point) { \n CString MsgCoord;\n MsgCoord.Format(L\"Left Button at P(%d, %d)\", point.x, point.y);\n MessageBox(MsgCoord);\n}\nvoid CMainFrame::OnRButtonUp(UINT nFlags, CPoint point) { \n MessageBox(L\"Right Mouse Button Up\");\n}" }, { "code": null, "e": 16060, "s": 15985, "text": "Step 4 − When you run this application, you will see the following output." }, { "code": null, "e": 16124, "s": 16060, "text": "Step 5 − When you click OK, you will see the following message." }, { "code": null, "e": 16253, "s": 16124, "text": "Step 6 − Right-click on this window. Now, when you release the right button of the mouse, it will display the following message." }, { "code": null, "e": 16260, "s": 16253, "text": " Print" }, { "code": null, "e": 16271, "s": 16260, "text": " Add Notes" } ]
How to detect click on HTML button through javascript in Android WebView?
This example demonstrate about How to lock the Android device programmatically. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml <? xml version= "1.0" encoding= "utf-8" ?> <RelativeLayout xmlns: android = "http://schemas.android.com/apk/res/android" xmlns: tools = "http://schemas.android.com/tools" android :layout_width= "match_parent" android :layout_height= "match_parent" android :layout_margin= "16dp" tools :context= ".MainActivity" > <Button android :onClick= "loadPage" android :layout_width= "match_parent" android :layout_height= "wrap_content" android :text= "Load web Page" /> </RelativeLayout> Step 3 − Add the following code to assets/page.html <html> <body> First name: <input type= "text" name= "fname" id= "txtfname" ><br> Last name: <input type= "text" name= "lname" id= "txtlname" ><br> <script> function getValues() { document.getElementById("btnOK").value = document.getElementById("txtfname").value+" "+document.getElementById("txtlname").value; } </script> <button type= "button" value= "" id= "btnOK" onclick= " getValues();ok.performClick(this.value); " > OK </button> </body> </html> Step 4 − Add the following code to src/MainActivity package app.tutorialspoint.com.sample ; import android.os.Bundle ; import android.support.v7.app.AppCompatActivity ; import android.view.View ; import android.webkit. JavascriptInterface ; import android.webkit.WebSettings ; import android.webkit.WebView ; import android.widget.Toast ; public class MainActivity extends AppCompatActivity { @Override protected void onCreate (Bundle savedInstanceState) { super .onCreate(savedInstanceState) ; setContentView(R.layout. activity_main ) ; } public void loadPage (View view) { WebView browser = new WebView( this ) ; browser.getSettings().setJavaScriptEnabled( true ) ; browser.loadUrl( "file:///android_asset/page.html" ) ; setContentView(browser) ; WebSettings ws = browser.getSettings() ; ws.setJavaScriptEnabled( true ) ; browser.addJavascriptInterface( new Object() { @JavascriptInterface // For API 17+ public void performClick (String strl) { Toast. makeText (MainActivity. this, strl , Toast. LENGTH_SHORT ).show() ; } } , "ok" ) ; } } Step 5 − Add the following code to androidManifest.xml <? xml version= "1.0" encoding= "utf-8" ?> <manifest xmlns: android = "http://schemas.android.com/apk/res/android" package= "app.tutorialspoint.com.sample" > <uses-permission android :name= "android.permission.CALL_PHONE" /> <application android :allowBackup= "true" android :icon= "@mipmap/ic_launcher" android :label= "@string/app_name" android :roundIcon= "@mipmap/ic_launcher_round" android :supportsRtl= "true" android :theme= "@style/AppTheme" > <activity android :name= ".MainActivity" > <intent-filter> <action android :name= "android.intent.action.MAIN" /> <category android :name= "android.intent.category.LAUNCHER" /> </intent-filter> </activity> <receiver android :name= ".DeviceAdmin" android :description= "@string/app_description" android :label= "@string/app_name" android :permission= "android.permission.BIND_DEVICE_ADMIN" > <meta-data android :name= "android.app.device_admin" android :resource= "@xml/policies" /> <intent-filter> <action android :name= "android.app.action.DEVICE_ADMIN_ENABLED" /> </intent-filter> </receiver> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
[ { "code": null, "e": 1142, "s": 1062, "text": "This example demonstrate about How to lock the Android device programmatically." }, { "code": null, "e": 1271, "s": 1142, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1335, "s": 1271, "text": "Step 2 − Add the following code to res/layout/activity_main.xml" }, { "code": null, "e": 1856, "s": 1335, "text": "<? xml version= \"1.0\" encoding= \"utf-8\" ?>\n<RelativeLayout xmlns: android = \"http://schemas.android.com/apk/res/android\"\n xmlns: tools = \"http://schemas.android.com/tools\"\n android :layout_width= \"match_parent\"\n android :layout_height= \"match_parent\"\n android :layout_margin= \"16dp\"\n tools :context= \".MainActivity\" >\n <Button\n android :onClick= \"loadPage\"\n android :layout_width= \"match_parent\"\n android :layout_height= \"wrap_content\"\n android :text= \"Load web Page\" />\n</RelativeLayout>" }, { "code": null, "e": 1908, "s": 1856, "text": "Step 3 − Add the following code to assets/page.html" }, { "code": null, "e": 2449, "s": 1908, "text": "<html>\n <body>\n First name: <input type= \"text\" name= \"fname\" id= \"txtfname\" ><br>\n Last name: <input type= \"text\" name= \"lname\" id= \"txtlname\" ><br>\n <script>\n function getValues() {\n document.getElementById(\"btnOK\").value =\n document.getElementById(\"txtfname\").value+\"\n \"+document.getElementById(\"txtlname\").value;\n }\n </script>\n <button type= \"button\" value= \"\" id= \"btnOK\" onclick= \" getValues();ok.performClick(this.value); \" > OK </button>\n </body>\n</html>" }, { "code": null, "e": 2501, "s": 2449, "text": "Step 4 − Add the following code to src/MainActivity" }, { "code": null, "e": 3605, "s": 2501, "text": "package app.tutorialspoint.com.sample ;\nimport android.os.Bundle ;\nimport android.support.v7.app.AppCompatActivity ;\nimport android.view.View ;\nimport android.webkit. JavascriptInterface ;\nimport android.webkit.WebSettings ;\nimport android.webkit.WebView ;\nimport android.widget.Toast ;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate (Bundle savedInstanceState) {\n super .onCreate(savedInstanceState) ;\n setContentView(R.layout. activity_main ) ;\n }\n public void loadPage (View view) {\n WebView browser = new WebView( this ) ;\n browser.getSettings().setJavaScriptEnabled( true ) ;\n browser.loadUrl( \"file:///android_asset/page.html\" ) ;\n setContentView(browser) ;\n WebSettings ws = browser.getSettings() ;\n ws.setJavaScriptEnabled( true ) ;\n browser.addJavascriptInterface( new Object() {\n @JavascriptInterface // For API 17+\n public void performClick (String strl) {\n Toast. makeText (MainActivity. this, strl , Toast. LENGTH_SHORT ).show() ;\n }\n } , \"ok\" ) ;\n }\n}" }, { "code": null, "e": 3660, "s": 3605, "text": "Step 5 − Add the following code to androidManifest.xml" }, { "code": null, "e": 4947, "s": 3660, "text": "<? xml version= \"1.0\" encoding= \"utf-8\" ?>\n<manifest xmlns: android = \"http://schemas.android.com/apk/res/android\"\n package= \"app.tutorialspoint.com.sample\" >\n <uses-permission android :name= \"android.permission.CALL_PHONE\" />\n <application\n android :allowBackup= \"true\"\n android :icon= \"@mipmap/ic_launcher\"\n android :label= \"@string/app_name\"\n android :roundIcon= \"@mipmap/ic_launcher_round\"\n android :supportsRtl= \"true\"\n android :theme= \"@style/AppTheme\" >\n <activity android :name= \".MainActivity\" >\n <intent-filter>\n <action android :name= \"android.intent.action.MAIN\" />\n <category android :name= \"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n <receiver\n android :name= \".DeviceAdmin\"\n android :description= \"@string/app_description\"\n android :label= \"@string/app_name\"\n android :permission= \"android.permission.BIND_DEVICE_ADMIN\" >\n <meta-data\n android :name= \"android.app.device_admin\"\n android :resource= \"@xml/policies\" />\n <intent-filter>\n <action android :name= \"android.app.action.DEVICE_ADMIN_ENABLED\" />\n </intent-filter>\n </receiver>\n </application>\n</manifest>" }, { "code": null, "e": 5294, "s": 4947, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –" } ]
Using the new keyword in C#
Use the new keyword to create an instance of the array. The new operator is used to create an object or instantiate an object. Here in the example an object is created for the class using the new. The following is an example. Calculate c = new Calculate(); You can also use the new keyword to create an instance of the array. double[] points = new double[10]; The new keyword is also used to create object of a collection. SortedList sl = new SortedList(); // SortedList List<string> myList = new List<string>() // List Let us see an example. Live Demo using System; class Program { static void Main() { int[] arrSource = new int[4]; arrSource[0] = 5; arrSource[1] = 9; arrSource[2] = 1; arrSource[3] = 3; int[] arrTarget = new int[4]; // CopyTo() method arrSource.CopyTo(arrTarget,0 ); Console.WriteLine("Destination Array ..."); foreach (int value in arrTarget) { Console.WriteLine(value); } } } Destination Array ... 5 9 1 3
[ { "code": null, "e": 1259, "s": 1062, "text": "Use the new keyword to create an instance of the array. The new operator is used to create an object or instantiate an object. Here in the example an object is created for the class using the new." }, { "code": null, "e": 1288, "s": 1259, "text": "The following is an example." }, { "code": null, "e": 1319, "s": 1288, "text": "Calculate c = new Calculate();" }, { "code": null, "e": 1388, "s": 1319, "text": "You can also use the new keyword to create an instance of the array." }, { "code": null, "e": 1422, "s": 1388, "text": "double[] points = new double[10];" }, { "code": null, "e": 1485, "s": 1422, "text": "The new keyword is also used to create object of a collection." }, { "code": null, "e": 1582, "s": 1485, "text": "SortedList sl = new SortedList(); // SortedList\nList<string> myList = new List<string>() // List" }, { "code": null, "e": 1605, "s": 1582, "text": "Let us see an example." }, { "code": null, "e": 1616, "s": 1605, "text": " Live Demo" }, { "code": null, "e": 2046, "s": 1616, "text": "using System;\nclass Program {\n static void Main() {\n\n int[] arrSource = new int[4];\n arrSource[0] = 5;\n arrSource[1] = 9;\n arrSource[2] = 1;\n arrSource[3] = 3;\n\n int[] arrTarget = new int[4];\n\n // CopyTo() method\n arrSource.CopyTo(arrTarget,0 );\n\n Console.WriteLine(\"Destination Array ...\");\n foreach (int value in arrTarget) {\n Console.WriteLine(value);\n }\n }\n}" }, { "code": null, "e": 2076, "s": 2046, "text": "Destination Array ...\n5\n9\n1\n3" } ]
Calculate Hyperbolic sine of a value in R Programming - sinh() Function - GeeksforGeeks
01 Jun, 2020 sinh() function in R Language is used to calculate the hyperbolic sine value of the numeric value passed to it as argument. Syntax: sinh(x) Parameter:x: Numeric value Example 1: # R code to calculate hyperbolic sine of a value # Assigning values to variablesx1 <- -90x2 <- -30 # Using sinh() Functionsinh(x1)sinh(x2) Output: [1] -6.102016e+38 [1] -5.343237e+12 Example 2: # R code to calculate hyperbolic sine of a value # Assigning values to variablesx1 <- pix2 <- pi / 3 # Using sinh() Functionsinh(x1)sinh(x2) Output: [1] 11.54874 [1] 1.249367 R Math-Function R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? How to filter R dataframe by multiple conditions? R - if statement Replace Specific Characters in String in R How to import an Excel File into R ? Filter multiple values on a string column in R using Dplyr
[ { "code": null, "e": 25242, "s": 25214, "text": "\n01 Jun, 2020" }, { "code": null, "e": 25366, "s": 25242, "text": "sinh() function in R Language is used to calculate the hyperbolic sine value of the numeric value passed to it as argument." }, { "code": null, "e": 25382, "s": 25366, "text": "Syntax: sinh(x)" }, { "code": null, "e": 25409, "s": 25382, "text": "Parameter:x: Numeric value" }, { "code": null, "e": 25420, "s": 25409, "text": "Example 1:" }, { "code": "# R code to calculate hyperbolic sine of a value # Assigning values to variablesx1 <- -90x2 <- -30 # Using sinh() Functionsinh(x1)sinh(x2)", "e": 25561, "s": 25420, "text": null }, { "code": null, "e": 25569, "s": 25561, "text": "Output:" }, { "code": null, "e": 25605, "s": 25569, "text": "[1] -6.102016e+38\n[1] -5.343237e+12" }, { "code": null, "e": 25616, "s": 25605, "text": "Example 2:" }, { "code": "# R code to calculate hyperbolic sine of a value # Assigning values to variablesx1 <- pix2 <- pi / 3 # Using sinh() Functionsinh(x1)sinh(x2)", "e": 25759, "s": 25616, "text": null }, { "code": null, "e": 25767, "s": 25759, "text": "Output:" }, { "code": null, "e": 25793, "s": 25767, "text": "[1] 11.54874\n[1] 1.249367" }, { "code": null, "e": 25809, "s": 25793, "text": "R Math-Function" }, { "code": null, "e": 25820, "s": 25809, "text": "R Language" }, { "code": null, "e": 25918, "s": 25820, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25927, "s": 25918, "text": "Comments" }, { "code": null, "e": 25940, "s": 25927, "text": "Old Comments" }, { "code": null, "e": 25992, "s": 25940, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 26030, "s": 25992, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 26065, "s": 26030, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 26123, "s": 26065, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 26172, "s": 26123, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 26222, "s": 26172, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 26239, "s": 26222, "text": "R - if statement" }, { "code": null, "e": 26282, "s": 26239, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 26319, "s": 26282, "text": "How to import an Excel File into R ?" } ]
C program to sort an array of ten elements in an ascending order
An array is a group of related data items that are stored with single name. For example, int student[30]; Here, student is an array name which holds 30 collection of data items, with a single variable name. The operations of an array are explained below − Searching − It is used to find whether a particular element is present or not. Searching − It is used to find whether a particular element is present or not. Sorting − Helps in arranging the elements in an array either in ascending or descending order. Sorting − Helps in arranging the elements in an array either in ascending or descending order. Traversing − Processing every element in an array, sequentially. Traversing − Processing every element in an array, sequentially. Inserting − Helps in inserting the elements in an array. Inserting − Helps in inserting the elements in an array. Deleting − Helps in deleting an element in an array. Deleting − Helps in deleting an element in an array. In this program, we are using the swapping technique to sort the elements in an ascending order. The logic that we applied to sort an array in ascending order is as follows − for(i=0;i<10-1;i++){ for(j=i+1;j<10;j++){ if(element[i]>element[j]){ temp=element[i]; //swapping element[i] with element[j] element[i]=element[j]; element[j]=temp; } } } Given below is the C program to sort an array of ten elements in an ascending order − Live Demo #include<stdio.h> int main(){ int element[10],i,j,temp; printf("enter 10 integer numbers:"); for(i=0;i<10;i++){ scanf("%d",&element[i]); } for(i=0;i<10-1;i++){ for(j=i+1;j<10;j++){ if(element[i]>element[j]){ temp=element[i]; //swapping element[i] with element[j] element[i]=element[j]; element[j]=temp; } } } printf("Elements are now in ascending order:"); for(i=0;i<10;i++) printf("%d\n",element[i]); return 0; } The output is given below − enter 10 integer numbers: 12 23 34 1 22 34 56 45 33 78 Elements are now in ascending order:1 12 22 23 33 34 34 45 56 78
[ { "code": null, "e": 1138, "s": 1062, "text": "An array is a group of related data items that are stored with single name." }, { "code": null, "e": 1168, "s": 1138, "text": "For example, int student[30];" }, { "code": null, "e": 1269, "s": 1168, "text": "Here, student is an array name which holds 30 collection of data items, with a single variable name." }, { "code": null, "e": 1318, "s": 1269, "text": "The operations of an array are explained below −" }, { "code": null, "e": 1397, "s": 1318, "text": "Searching − It is used to find whether a particular element is present or not." }, { "code": null, "e": 1476, "s": 1397, "text": "Searching − It is used to find whether a particular element is present or not." }, { "code": null, "e": 1571, "s": 1476, "text": "Sorting − Helps in arranging the elements in an array either in ascending or descending order." }, { "code": null, "e": 1666, "s": 1571, "text": "Sorting − Helps in arranging the elements in an array either in ascending or descending order." }, { "code": null, "e": 1731, "s": 1666, "text": "Traversing − Processing every element in an array, sequentially." }, { "code": null, "e": 1796, "s": 1731, "text": "Traversing − Processing every element in an array, sequentially." }, { "code": null, "e": 1853, "s": 1796, "text": "Inserting − Helps in inserting the elements in an array." }, { "code": null, "e": 1910, "s": 1853, "text": "Inserting − Helps in inserting the elements in an array." }, { "code": null, "e": 1963, "s": 1910, "text": "Deleting − Helps in deleting an element in an array." }, { "code": null, "e": 2016, "s": 1963, "text": "Deleting − Helps in deleting an element in an array." }, { "code": null, "e": 2113, "s": 2016, "text": "In this program, we are using the swapping technique to sort the elements in an ascending order." }, { "code": null, "e": 2191, "s": 2113, "text": "The logic that we applied to sort an array in ascending order is as follows −" }, { "code": null, "e": 2406, "s": 2191, "text": "for(i=0;i<10-1;i++){\n for(j=i+1;j<10;j++){\n if(element[i]>element[j]){\n temp=element[i]; //swapping element[i] with element[j]\n element[i]=element[j];\n element[j]=temp;\n }\n }\n}" }, { "code": null, "e": 2492, "s": 2406, "text": "Given below is the C program to sort an array of ten elements in an ascending order −" }, { "code": null, "e": 2503, "s": 2492, "text": " Live Demo" }, { "code": null, "e": 3022, "s": 2503, "text": "#include<stdio.h>\nint main(){\n int element[10],i,j,temp;\n printf(\"enter 10 integer numbers:\");\n for(i=0;i<10;i++){\n scanf(\"%d\",&element[i]);\n }\n for(i=0;i<10-1;i++){\n for(j=i+1;j<10;j++){\n if(element[i]>element[j]){\n temp=element[i]; //swapping element[i] with element[j]\n element[i]=element[j];\n element[j]=temp;\n }\n }\n }\n printf(\"Elements are now in ascending order:\");\n for(i=0;i<10;i++)\n printf(\"%d\\n\",element[i]);\n return 0;\n}" }, { "code": null, "e": 3050, "s": 3022, "text": "The output is given below −" }, { "code": null, "e": 3170, "s": 3050, "text": "enter 10 integer numbers:\n12\n23\n34\n1\n22\n34\n56\n45\n33\n78\nElements are now in ascending order:1\n12\n22\n23\n33\n34\n34\n45\n56\n78" } ]
C library function - isspace()
The C library function int isspace(char c) checks whether the passed character is white-space. Standard white-space characters are − ' ' (0x20) space (SPC) '\t' (0x09) horizontal tab (TAB) '\n' (0x0a) newline (LF) '\v' (0x0b) vertical tab (VT) '\f' (0x0c) feed (FF) '\r' (0x0d) carriage return (CR) Following is the declaration for isspace() function. int isspace(char c); c − This is the character to be checked. c − This is the character to be checked. This function returns a non-zero value(true) if c is a white-space character else, zero (false). The following example shows the usage of isspace() function. #include <stdio.h> #include <ctype.h> int main () { int var1 = 't'; int var2 = '1'; int var3 = ' '; if( isspace(var1) ) { printf("var1 = |%c| is a white-space character\n", var1 ); } else { printf("var1 = |%c| is not a white-space character\n", var1 ); } if( isspace(var2) ) { printf("var2 = |%c| is a white-space character\n", var2 ); } else { printf("var2 = |%c| is not a white-space character\n", var2 ); } if( isspace(var3) ) { printf("var3 = |%c| is a white-space character\n", var3 ); } else { printf("var3 = |%c| is not a white-space character\n", var3 ); } return(0); } Let us compile and run the above program that will produce the following result − var1 = |t| is not a white-space character var2 = |1| is not a white-space character var3 = | | is a white-space character 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": 2102, "s": 2007, "text": "The C library function int isspace(char c) checks whether the passed character is white-space." }, { "code": null, "e": 2140, "s": 2102, "text": "Standard white-space characters are −" }, { "code": null, "e": 2308, "s": 2140, "text": "' ' (0x20)\tspace (SPC)\n'\\t'\t(0x09)\thorizontal tab (TAB)\n'\\n'\t(0x0a)\tnewline (LF)\n'\\v'\t(0x0b)\tvertical tab (VT)\n'\\f'\t(0x0c)\tfeed (FF)\n'\\r'\t(0x0d)\tcarriage return (CR)" }, { "code": null, "e": 2361, "s": 2308, "text": "Following is the declaration for isspace() function." }, { "code": null, "e": 2382, "s": 2361, "text": "int isspace(char c);" }, { "code": null, "e": 2423, "s": 2382, "text": "c − This is the character to be checked." }, { "code": null, "e": 2464, "s": 2423, "text": "c − This is the character to be checked." }, { "code": null, "e": 2561, "s": 2464, "text": "This function returns a non-zero value(true) if c is a white-space character else, zero (false)." }, { "code": null, "e": 2622, "s": 2561, "text": "The following example shows the usage of isspace() function." }, { "code": null, "e": 3289, "s": 2622, "text": "#include <stdio.h>\n#include <ctype.h>\n\nint main () {\n int var1 = 't';\n int var2 = '1';\n int var3 = ' ';\n\n if( isspace(var1) ) {\n printf(\"var1 = |%c| is a white-space character\\n\", var1 );\n } else {\n printf(\"var1 = |%c| is not a white-space character\\n\", var1 );\n }\n \n if( isspace(var2) ) {\n printf(\"var2 = |%c| is a white-space character\\n\", var2 );\n } else {\n printf(\"var2 = |%c| is not a white-space character\\n\", var2 );\n }\n \n if( isspace(var3) ) {\n printf(\"var3 = |%c| is a white-space character\\n\", var3 );\n } else {\n printf(\"var3 = |%c| is not a white-space character\\n\", var3 );\n }\n \n return(0);\n}" }, { "code": null, "e": 3371, "s": 3289, "text": "Let us compile and run the above program that will produce the following result −" }, { "code": null, "e": 3494, "s": 3371, "text": "var1 = |t| is not a white-space character\nvar2 = |1| is not a white-space character\nvar3 = | | is a white-space character\n" }, { "code": null, "e": 3527, "s": 3494, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 3542, "s": 3527, "text": " Nishant Malik" }, { "code": null, "e": 3577, "s": 3542, "text": "\n 12 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3592, "s": 3577, "text": " Nishant Malik" }, { "code": null, "e": 3627, "s": 3592, "text": "\n 48 Lectures \n 6.5 hours \n" }, { "code": null, "e": 3641, "s": 3627, "text": " Asif Hussain" }, { "code": null, "e": 3674, "s": 3641, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 3692, "s": 3674, "text": " Richa Maheshwari" }, { "code": null, "e": 3727, "s": 3692, "text": "\n 20 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3746, "s": 3727, "text": " Vandana Annavaram" }, { "code": null, "e": 3779, "s": 3746, "text": "\n 44 Lectures \n 1 hours \n" }, { "code": null, "e": 3791, "s": 3779, "text": " Amit Diwan" }, { "code": null, "e": 3798, "s": 3791, "text": " Print" }, { "code": null, "e": 3809, "s": 3798, "text": " Add Notes" } ]
Count of occurrences of each prefix in a string using modified KMP algorithm - GeeksforGeeks
13 Dec, 2021 Given a string S of size N, the task is to count the occurrences of all the prefixes of the given string S. Examples: Input: S = “AAAA” Output: A occurs 4 times AA occurs 3 times. AAA occurs 2 times. AAAA occurs 1 times. Explanation: Below is the illustration of all the prefix: Input: S = “ABACABA” Output: A occurs 4 times AB occurs 2 times ABA occurs 2 times ABAC occurs 1 times ABACA occurs 1 times ABACAB occurs 1 times ABACABA occurs 1 times Naive Approach: Traverse over all the prefixes in set P. Let the x be the prefix.Do a sliding window approach of size |x|.Check if the current sliding window on S is equal to x. If yes then increase the count[x] by 1. Traverse over all the prefixes in set P. Let the x be the prefix. Do a sliding window approach of size |x|. Check if the current sliding window on S is equal to x. If yes then increase the count[x] by 1. Time complexity: O(N3) Auxiliary Space: O(N) Efficient Approach: Use the LPS array (also called prefix_function) from the KMP algorithm. The prefix function for this string is defined as an array LPS of length N, where LPS[i] is the length of the longest proper prefix of the substring S[0...i] which is also a suffix of this substring. Let occ[i] denote the number of occurrences of the prefix of length i. Below are the steps to implement this approach: Compute the LPS array or prefix_function.For each value of the prefix function, first, count how many times it occurs in the LPS array.The length prefix i appears exactly ans[i] times, then this number must be added to the number of occurrences of its longest suffix that is also a prefix.In the end, add 1 to all the values of occ array, because of the original prefix that should be counted as well. Compute the LPS array or prefix_function. For each value of the prefix function, first, count how many times it occurs in the LPS array. The length prefix i appears exactly ans[i] times, then this number must be added to the number of occurrences of its longest suffix that is also a prefix. In the end, add 1 to all the values of occ array, because of the original prefix that should be counted as well. For example: LPS[i] denotes that in position i, a prefix of length = LPS[i] appears. And this is the longest prefix possible. But shorter prefixes can occur. For String S = “AAAA”, following are the prefixes: S[0..0] = A S[0..1] = AA S[0..2] = AAA S[0..3] = AAAA Initially: occ[A] = 0 occ[AA] = 0 occ[AAA] = 0 occ[AAAA] = 0 Step1: LPS Array of the following string denotes the length of the longest prefix which is also a suffix: LPS[1] denotes in string AA, A is a suffix and also a prefix as LPS[1] = 1 LPS[2] denotes in string AAA, AA is a suffix and also a prefix as LPS[2] = 2 LPS[3] denotes in string AAAA, AAA is a suffix and also a prefix as LPS[3] = 3 Step 2:Add these occurrences of prefixes as suffixes to the answer in the occ[] array: Values : Counted substrings occ[A] = 1 : S[1] occ[AA] = 1 : S[1..2] occ[AAA] = 1 : S[1..3] occ[AAAA] = 0 : NULL(as there is not a prefix “AAAA” which is also a suffix. Step 3: Now traverse the string in reverse order starting from “AAA” (as the last value will always be 0 since the complete string is not a proper prefix). Since, string “AAA” S[1..3] contains “AA” S[2..3] as well, which was not counted yet, therefore increment the occurrence of string “AA” in occ[“AA”] as occ[“AA”] += occ[“AAA”]. Below is the count for the same: Values : Counted substrings occ[A] = 1 : S[1] occ[AA] = 2 : S[1..2], S[2..3] occ[AAA] = 1 : S[1..3] occ[AAAA] = 0 : NULL Now string “AA” contains “A” as well, which was not counted yet, therefore increment the occurrence of string “A” in occ[“A”] as occ[“A”] += occ[“AA”]. Below is the count for the same: Values : Counted substrings occ[A] = 3 : S[1], S[2], S[3] occ[AA] = 2 : S[1..2], S[2..3] occ[AAA] = 1 : S[1..3] occ[AAAA] = 0 : NULL Step 4: At last add one to all occurrences for the original prefixes, which are not counted yet. Values : Counted substrings occ[A] = 4 : S[1], S[2], S[3], S[0] occ[AA] = 3 : S[1..2], S[2..3], S[0..1] occ[AAA] = 2 : S[1..3], S[0..2] occ[AAAA] = 1 : S[0..3] Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to print the count of all// prefix in the given stringvoid print(vector<int>& occ, string& s){ // Iterate over string s for (int i = 1; i <= int(s.size()); i++) { // Print the prefix and their // frequency cout << s.substr(0, i) << " occurs " << occ[i] << " times." << endl; }} // Function to implement the LPS// array to store the longest prefix// which is also a suffix for every// substring of the string Svector<int> prefix_function(string& s){ // Array to store LPS values vector<int> LPS(s.size()); // Value of lps[0] is 0 // by definition LPS[0] = 0; // Find the values of LPS[i] for // the rest of the string using // two pointers and DP for (int i = 1; i < int(s.size()); i++) { // Initially set the value // of j as the longest // prefix that is also a // suffix for i as LPS[i-1] int j = LPS[i - 1]; // Check if the suffix of // length j+1 is also a prefix while (j > 0 && s[i] != s[j]) { j = LPS[j - 1]; } // If s[i] = s[j] then, assign // LPS[i] as j+1 if (s[i] == s[j]) { LPS[i] = j + 1; } // If we reached j = 0, assign // LPS[i] as 0 as there was no // prefix equal to suffix else { LPS[i] = 0; } } // Return the calculated // LPS array return LPS;} // Function to count the occurrence// of all the prefix in the string Svoid count_occurrence(string& s){ int n = s.size(); // Call the prefix_function // to get LPS vector<int> LPS = prefix_function(s); // To store the occurrence of // all the prefix vector<int> occ(n + 1); // Count all the suffixes that // are also prefix for (int i = 0; i < n; i++) { occ[LPS[i]]++; } // Add the occurrences of // i to smaller prefixes for (int i = n - 1; i > 0; i--) { occ[LPS[i - 1]] += occ[i]; } // Adding 1 to all occ[i] for all // the original prefix for (int i = 0; i <= n; i++) occ[i]++; // Function Call to print the // occurrence of all the prefix print(occ, s);} // Driver Codeint main(){ // Given String string A = "ABACABA"; // Function Call count_occurrence(A); return 0;} // Java program for// the above approachimport java.util.*;class GFG{ // Function to print the count// of all prefix in the// given Stringstatic void print(int[] occ, String s){ // Iterate over String s for (int i = 1; i <= s.length() - 1; i++) { // Print the prefix and their // frequency System.out.print(s.substring(0, i) + " occurs " + occ[i] + " times." + "\n"); }} // Function to implement the LPS// array to store the longest prefix// which is also a suffix for every// subString of the String Sstatic int[] prefix_function(String s){ // Array to store LPS values int []LPS = new int[s.length()]; // Value of lps[0] is 0 // by definition LPS[0] = 0; // Find the values of LPS[i] for // the rest of the String using // two pointers and DP for (int i = 1; i < s.length(); i++) { // Initially set the value // of j as the longest // prefix that is also a // suffix for i as LPS[i-1] int j = LPS[i - 1]; // Check if the suffix of // length j+1 is also a prefix while (j > 0 && s.charAt(i) != s.charAt(j)) { j = LPS[j - 1]; } // If s[i] = s[j] then, assign // LPS[i] as j+1 if (s.charAt(i) == s.charAt(j)) { LPS[i] = j + 1; } // If we reached j = 0, assign // LPS[i] as 0 as there was no // prefix equal to suffix else { LPS[i] = 0; } } // Return the calculated // LPS array return LPS;} // Function to count the occurrence// of all the prefix in the String Sstatic void count_occurrence(String s){ int n = s.length(); // Call the prefix_function // to get LPS int[] LPS = prefix_function(s); // To store the occurrence of // all the prefix int []occ = new int[n + 1]; // Count all the suffixes that // are also prefix for (int i = 0; i < n; i++) { occ[LPS[i]]++; } // Add the occurrences of // i to smaller prefixes for (int i = n - 1; i > 0; i--) { occ[LPS[i - 1]] += occ[i]; } // Adding 1 to all occ[i] for all // the original prefix for (int i = 0; i <= n; i++) occ[i]++; // Function Call to print the // occurrence of all the prefix print(occ, s);} // Driver Codepublic static void main(String[] args){ // Given String String A = "ABACABA"; // Function Call count_occurrence(A);}} // This code is contributed by Princi Singh # Python3 program for the above approach # Function to print the count of all# prefix in the given stringdef Print(occ, s): # Iterate over string s for i in range(1, len(s) + 1): # Print the prefix and their # frequency print(s[0 : i], "occur", occ[i], "times.") # Function to implement the LPS# array to store the longest prefix# which is also a suffix for every# substring of the string Sdef prefix_function(s): # Array to store LPS values # Value of lps[0] is 0 # by definition LPS = [0 for i in range(len(s))] # Find the values of LPS[i] for # the rest of the string using # two pointers and DP for i in range(1, len(s)): # Initially set the value # of j as the longest # prefix that is also a # suffix for i as LPS[i-1] j = LPS[i - 1] # Check if the suffix of # length j+1 is also a prefix while (j > 0 and s[i] != s[j]): j = LPS[j - 1] # If s[i] = s[j] then, assign # LPS[i] as j+1 if (s[i] == s[j]): LPS[i] = j + 1 # If we reached j = 0, assign # LPS[i] as 0 as there was no # prefix equal to suffix else: LPS[i] = 0 # Return the calculated # LPS array return LPS # Function to count the occurrence# of all the prefix in the string Sdef count_occurrence(s): n = len(s) # Call the prefix_function # to get LPS LPS = prefix_function(s) # To store the occurrence of # all the prefix occ = [0 for i in range(n + 1)] # Count all the suffixes that # are also prefix for i in range(n): occ[LPS[i]] += 1 # Add the occurrences of # i to smaller prefixes for i in range(n - 1, 0, -1): occ[LPS[i - 1]] += occ[i] # Adding 1 to all occ[i] for all # the original prefix for i in range(n + 1): occ[i] += 1 # Function Call to print the # occurrence of all the prefix Print(occ, s) # Driver Code # Given StringA = "ABACABA" # Function Callcount_occurrence(A) # This code is contributed by avanitrachhadiya2155 // C# program for// the above approachusing System;class GFG{ // Function to print the// count of all prefix// in the given Stringstatic void print(int[] occ, String s){ // Iterate over String s for (int i = 1; i <= s.Length - 1; i++) { // Print the prefix and their // frequency Console.Write(s.Substring(0, i) + " occurs " + occ[i] + " times." + "\n"); }} // Function to implement the LPS// array to store the longest prefix// which is also a suffix for every// subString of the String Sstatic int[] prefix_function(String s){ // Array to store LPS values int []LPS = new int[s.Length]; // Value of lps[0] is 0 // by definition LPS[0] = 0; // Find the values of LPS[i] for // the rest of the String using // two pointers and DP for (int i = 1; i < s.Length; i++) { // Initially set the value // of j as the longest // prefix that is also a // suffix for i as LPS[i-1] int j = LPS[i - 1]; // Check if the suffix of // length j+1 is also a prefix while (j > 0 && s[i] != s[j]) { j = LPS[j - 1]; } // If s[i] = s[j] then, // assign LPS[i] as j+1 if (s[i] == s[j]) { LPS[i] = j + 1; } // If we reached j = 0, assign // LPS[i] as 0 as there was no // prefix equal to suffix else { LPS[i] = 0; } } // Return the calculated // LPS array return LPS;} // Function to count the occurrence// of all the prefix in the String Sstatic void count_occurrence(String s){ int n = s.Length; // Call the prefix_function // to get LPS int[] LPS = prefix_function(s); // To store the occurrence of // all the prefix int []occ = new int[n + 1]; // Count all the suffixes that // are also prefix for (int i = 0; i < n; i++) { occ[LPS[i]]++; } // Add the occurrences of // i to smaller prefixes for (int i = n - 1; i > 0; i--) { occ[LPS[i - 1]] += occ[i]; } // Adding 1 to all occ[i] for all // the original prefix for (int i = 0; i <= n; i++) occ[i]++; // Function Call to print the // occurrence of all the prefix print(occ, s);} // Driver Codepublic static void Main(String[] args){ // Given String String A = "ABACABA"; // Function Call count_occurrence(A);}} // This code is contributed by Amit Katiyar <script> // JavaScript program for the above approach // Function to print the count of all // prefix in the given string const print = (occ, s) => { // Iterate over string s for (let i = 1; i <= s.length; i++) { // Print the prefix and their // frequency document.write(`${s.substr(0, i)} occurs ${occ[i]} times.<br/>`); } } // Function to implement the LPS // array to store the longest prefix // which is also a suffix for every // substring of the string S const prefix_function = (s) => { // Array to store LPS values let LPS = new Array(s.length).fill(0); // Value of lps[0] is 0 // by definition LPS[0] = 0; // Find the values of LPS[i] for // the rest of the string using // two pointers and DP for (let i = 1; i < s.length; i++) { // Initially set the value // of j as the longest // prefix that is also a // suffix for i as LPS[i-1] let j = LPS[i - 1]; // Check if the suffix of // length j+1 is also a prefix while (j > 0 && s[i] != s[j]) { j = LPS[j - 1]; } // If s[i] = s[j] then, assign // LPS[i] as j+1 if (s[i] == s[j]) { LPS[i] = j + 1; } // If we reached j = 0, assign // LPS[i] as 0 as there was no // prefix equal to suffix else { LPS[i] = 0; } } // Return the calculated // LPS array return LPS; } // Function to count the occurrence // of all the prefix in the string S const count_occurrence = (s) => { let n = s.length; // Call the prefix_function // to get LPS let LPS = prefix_function(s); // To store the occurrence of // all the prefix let occ = new Array(n + 1).fill(0); // Count all the suffixes that // are also prefix for (let i = 0; i < n; i++) { occ[LPS[i]]++; } // Add the occurrences of // i to smaller prefixes for (let i = n - 1; i > 0; i--) { occ[LPS[i - 1]] += occ[i]; } // Adding 1 to all occ[i] for all // the original prefix for (let i = 0; i <= n; i++) occ[i]++; // Function Call to print the // occurrence of all the prefix print(occ, s); } // Driver Code // Given String let A = "ABACABA"; // Function Call count_occurrence(A); // This code is contributed by rakeshsahni </script> A occurs 4 times. AB occurs 2 times. ABA occurs 2 times. ABAC occurs 1 times. ABACA occurs 1 times. ABACAB occurs 1 times. ABACABA occurs 1 times. Time Complexity: O(N2) Auxiliary Space: O(N) princi singh amit143katiyar avanitrachhadiya2155 simranarora5sos germanshephered48 rakeshsahni Longest Common Prefix prefix strings Suffix Dynamic Programming Pattern Searching Strings Strings Dynamic Programming Pattern Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16 Matrix Chain Multiplication | DP-8 Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Edit Distance | DP-5 Pattern Searching using Suffix Tree How to check if string contains only digits in Java Wildcard Pattern Matching Applications of String Matching Algorithms Search a Word in a 2D Grid of characters
[ { "code": null, "e": 24713, "s": 24685, "text": "\n13 Dec, 2021" }, { "code": null, "e": 24821, "s": 24713, "text": "Given a string S of size N, the task is to count the occurrences of all the prefixes of the given string S." }, { "code": null, "e": 24833, "s": 24821, "text": "Examples: " }, { "code": null, "e": 24996, "s": 24833, "text": "Input: S = “AAAA” Output: A occurs 4 times AA occurs 3 times. AAA occurs 2 times. AAAA occurs 1 times. Explanation: Below is the illustration of all the prefix: " }, { "code": null, "e": 25167, "s": 24996, "text": "Input: S = “ABACABA” Output: A occurs 4 times AB occurs 2 times ABA occurs 2 times ABAC occurs 1 times ABACA occurs 1 times ABACAB occurs 1 times ABACABA occurs 1 times " }, { "code": null, "e": 25185, "s": 25167, "text": "Naive Approach: " }, { "code": null, "e": 25387, "s": 25185, "text": "Traverse over all the prefixes in set P. Let the x be the prefix.Do a sliding window approach of size |x|.Check if the current sliding window on S is equal to x. If yes then increase the count[x] by 1." }, { "code": null, "e": 25453, "s": 25387, "text": "Traverse over all the prefixes in set P. Let the x be the prefix." }, { "code": null, "e": 25495, "s": 25453, "text": "Do a sliding window approach of size |x|." }, { "code": null, "e": 25591, "s": 25495, "text": "Check if the current sliding window on S is equal to x. If yes then increase the count[x] by 1." }, { "code": null, "e": 25636, "s": 25591, "text": "Time complexity: O(N3) Auxiliary Space: O(N)" }, { "code": null, "e": 25999, "s": 25636, "text": "Efficient Approach: Use the LPS array (also called prefix_function) from the KMP algorithm. The prefix function for this string is defined as an array LPS of length N, where LPS[i] is the length of the longest proper prefix of the substring S[0...i] which is also a suffix of this substring. Let occ[i] denote the number of occurrences of the prefix of length i." }, { "code": null, "e": 26049, "s": 25999, "text": "Below are the steps to implement this approach: " }, { "code": null, "e": 26451, "s": 26049, "text": "Compute the LPS array or prefix_function.For each value of the prefix function, first, count how many times it occurs in the LPS array.The length prefix i appears exactly ans[i] times, then this number must be added to the number of occurrences of its longest suffix that is also a prefix.In the end, add 1 to all the values of occ array, because of the original prefix that should be counted as well." }, { "code": null, "e": 26493, "s": 26451, "text": "Compute the LPS array or prefix_function." }, { "code": null, "e": 26588, "s": 26493, "text": "For each value of the prefix function, first, count how many times it occurs in the LPS array." }, { "code": null, "e": 26743, "s": 26588, "text": "The length prefix i appears exactly ans[i] times, then this number must be added to the number of occurrences of its longest suffix that is also a prefix." }, { "code": null, "e": 26856, "s": 26743, "text": "In the end, add 1 to all the values of occ array, because of the original prefix that should be counted as well." }, { "code": null, "e": 27067, "s": 26856, "text": "For example: LPS[i] denotes that in position i, a prefix of length = LPS[i] appears. And this is the longest prefix possible. But shorter prefixes can occur. For String S = “AAAA”, following are the prefixes: " }, { "code": null, "e": 27122, "s": 27067, "text": "S[0..0] = A S[0..1] = AA S[0..2] = AAA S[0..3] = AAAA " }, { "code": null, "e": 27135, "s": 27122, "text": "Initially: " }, { "code": null, "e": 27186, "s": 27135, "text": "occ[A] = 0 occ[AA] = 0 occ[AAA] = 0 occ[AAAA] = 0 " }, { "code": null, "e": 27293, "s": 27186, "text": "Step1: LPS Array of the following string denotes the length of the longest prefix which is also a suffix: " }, { "code": null, "e": 27524, "s": 27293, "text": "LPS[1] denotes in string AA, A is a suffix and also a prefix as LPS[1] = 1 LPS[2] denotes in string AAA, AA is a suffix and also a prefix as LPS[2] = 2 LPS[3] denotes in string AAAA, AAA is a suffix and also a prefix as LPS[3] = 3" }, { "code": null, "e": 27613, "s": 27524, "text": "Step 2:Add these occurrences of prefixes as suffixes to the answer in the occ[] array: " }, { "code": null, "e": 27783, "s": 27613, "text": "Values : Counted substrings occ[A] = 1 : S[1] occ[AA] = 1 : S[1..2] occ[AAA] = 1 : S[1..3] occ[AAAA] = 0 : NULL(as there is not a prefix “AAAA” which is also a suffix. " }, { "code": null, "e": 27940, "s": 27783, "text": "Step 3: Now traverse the string in reverse order starting from “AAA” (as the last value will always be 0 since the complete string is not a proper prefix). " }, { "code": null, "e": 28272, "s": 27940, "text": "Since, string “AAA” S[1..3] contains “AA” S[2..3] as well, which was not counted yet, therefore increment the occurrence of string “AA” in occ[“AA”] as occ[“AA”] += occ[“AAA”]. Below is the count for the same: Values : Counted substrings occ[A] = 1 : S[1] occ[AA] = 2 : S[1..2], S[2..3] occ[AAA] = 1 : S[1..3] occ[AAAA] = 0 : NULL " }, { "code": null, "e": 28459, "s": 28272, "text": "Now string “AA” contains “A” as well, which was not counted yet, therefore increment the occurrence of string “A” in occ[“A”] as occ[“A”] += occ[“AA”]. Below is the count for the same: " }, { "code": null, "e": 28593, "s": 28459, "text": "Values : Counted substrings occ[A] = 3 : S[1], S[2], S[3] occ[AA] = 2 : S[1..2], S[2..3] occ[AAA] = 1 : S[1..3] occ[AAAA] = 0 : NULL " }, { "code": null, "e": 28692, "s": 28593, "text": "Step 4: At last add one to all occurrences for the original prefixes, which are not counted yet. " }, { "code": null, "e": 28854, "s": 28692, "text": "Values : Counted substrings occ[A] = 4 : S[1], S[2], S[3], S[0] occ[AA] = 3 : S[1..2], S[2..3], S[0..1] occ[AAA] = 2 : S[1..3], S[0..2] occ[AAAA] = 1 : S[0..3] " }, { "code": null, "e": 28905, "s": 28854, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 28909, "s": 28905, "text": "C++" }, { "code": null, "e": 28914, "s": 28909, "text": "Java" }, { "code": null, "e": 28922, "s": 28914, "text": "Python3" }, { "code": null, "e": 28925, "s": 28922, "text": "C#" }, { "code": null, "e": 28936, "s": 28925, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to print the count of all// prefix in the given stringvoid print(vector<int>& occ, string& s){ // Iterate over string s for (int i = 1; i <= int(s.size()); i++) { // Print the prefix and their // frequency cout << s.substr(0, i) << \" occurs \" << occ[i] << \" times.\" << endl; }} // Function to implement the LPS// array to store the longest prefix// which is also a suffix for every// substring of the string Svector<int> prefix_function(string& s){ // Array to store LPS values vector<int> LPS(s.size()); // Value of lps[0] is 0 // by definition LPS[0] = 0; // Find the values of LPS[i] for // the rest of the string using // two pointers and DP for (int i = 1; i < int(s.size()); i++) { // Initially set the value // of j as the longest // prefix that is also a // suffix for i as LPS[i-1] int j = LPS[i - 1]; // Check if the suffix of // length j+1 is also a prefix while (j > 0 && s[i] != s[j]) { j = LPS[j - 1]; } // If s[i] = s[j] then, assign // LPS[i] as j+1 if (s[i] == s[j]) { LPS[i] = j + 1; } // If we reached j = 0, assign // LPS[i] as 0 as there was no // prefix equal to suffix else { LPS[i] = 0; } } // Return the calculated // LPS array return LPS;} // Function to count the occurrence// of all the prefix in the string Svoid count_occurrence(string& s){ int n = s.size(); // Call the prefix_function // to get LPS vector<int> LPS = prefix_function(s); // To store the occurrence of // all the prefix vector<int> occ(n + 1); // Count all the suffixes that // are also prefix for (int i = 0; i < n; i++) { occ[LPS[i]]++; } // Add the occurrences of // i to smaller prefixes for (int i = n - 1; i > 0; i--) { occ[LPS[i - 1]] += occ[i]; } // Adding 1 to all occ[i] for all // the original prefix for (int i = 0; i <= n; i++) occ[i]++; // Function Call to print the // occurrence of all the prefix print(occ, s);} // Driver Codeint main(){ // Given String string A = \"ABACABA\"; // Function Call count_occurrence(A); return 0;}", "e": 31398, "s": 28936, "text": null }, { "code": "// Java program for// the above approachimport java.util.*;class GFG{ // Function to print the count// of all prefix in the// given Stringstatic void print(int[] occ, String s){ // Iterate over String s for (int i = 1; i <= s.length() - 1; i++) { // Print the prefix and their // frequency System.out.print(s.substring(0, i) + \" occurs \" + occ[i] + \" times.\" + \"\\n\"); }} // Function to implement the LPS// array to store the longest prefix// which is also a suffix for every// subString of the String Sstatic int[] prefix_function(String s){ // Array to store LPS values int []LPS = new int[s.length()]; // Value of lps[0] is 0 // by definition LPS[0] = 0; // Find the values of LPS[i] for // the rest of the String using // two pointers and DP for (int i = 1; i < s.length(); i++) { // Initially set the value // of j as the longest // prefix that is also a // suffix for i as LPS[i-1] int j = LPS[i - 1]; // Check if the suffix of // length j+1 is also a prefix while (j > 0 && s.charAt(i) != s.charAt(j)) { j = LPS[j - 1]; } // If s[i] = s[j] then, assign // LPS[i] as j+1 if (s.charAt(i) == s.charAt(j)) { LPS[i] = j + 1; } // If we reached j = 0, assign // LPS[i] as 0 as there was no // prefix equal to suffix else { LPS[i] = 0; } } // Return the calculated // LPS array return LPS;} // Function to count the occurrence// of all the prefix in the String Sstatic void count_occurrence(String s){ int n = s.length(); // Call the prefix_function // to get LPS int[] LPS = prefix_function(s); // To store the occurrence of // all the prefix int []occ = new int[n + 1]; // Count all the suffixes that // are also prefix for (int i = 0; i < n; i++) { occ[LPS[i]]++; } // Add the occurrences of // i to smaller prefixes for (int i = n - 1; i > 0; i--) { occ[LPS[i - 1]] += occ[i]; } // Adding 1 to all occ[i] for all // the original prefix for (int i = 0; i <= n; i++) occ[i]++; // Function Call to print the // occurrence of all the prefix print(occ, s);} // Driver Codepublic static void main(String[] args){ // Given String String A = \"ABACABA\"; // Function Call count_occurrence(A);}} // This code is contributed by Princi Singh", "e": 33777, "s": 31398, "text": null }, { "code": "# Python3 program for the above approach # Function to print the count of all# prefix in the given stringdef Print(occ, s): # Iterate over string s for i in range(1, len(s) + 1): # Print the prefix and their # frequency print(s[0 : i], \"occur\", occ[i], \"times.\") # Function to implement the LPS# array to store the longest prefix# which is also a suffix for every# substring of the string Sdef prefix_function(s): # Array to store LPS values # Value of lps[0] is 0 # by definition LPS = [0 for i in range(len(s))] # Find the values of LPS[i] for # the rest of the string using # two pointers and DP for i in range(1, len(s)): # Initially set the value # of j as the longest # prefix that is also a # suffix for i as LPS[i-1] j = LPS[i - 1] # Check if the suffix of # length j+1 is also a prefix while (j > 0 and s[i] != s[j]): j = LPS[j - 1] # If s[i] = s[j] then, assign # LPS[i] as j+1 if (s[i] == s[j]): LPS[i] = j + 1 # If we reached j = 0, assign # LPS[i] as 0 as there was no # prefix equal to suffix else: LPS[i] = 0 # Return the calculated # LPS array return LPS # Function to count the occurrence# of all the prefix in the string Sdef count_occurrence(s): n = len(s) # Call the prefix_function # to get LPS LPS = prefix_function(s) # To store the occurrence of # all the prefix occ = [0 for i in range(n + 1)] # Count all the suffixes that # are also prefix for i in range(n): occ[LPS[i]] += 1 # Add the occurrences of # i to smaller prefixes for i in range(n - 1, 0, -1): occ[LPS[i - 1]] += occ[i] # Adding 1 to all occ[i] for all # the original prefix for i in range(n + 1): occ[i] += 1 # Function Call to print the # occurrence of all the prefix Print(occ, s) # Driver Code # Given StringA = \"ABACABA\" # Function Callcount_occurrence(A) # This code is contributed by avanitrachhadiya2155", "e": 35905, "s": 33777, "text": null }, { "code": "// C# program for// the above approachusing System;class GFG{ // Function to print the// count of all prefix// in the given Stringstatic void print(int[] occ, String s){ // Iterate over String s for (int i = 1; i <= s.Length - 1; i++) { // Print the prefix and their // frequency Console.Write(s.Substring(0, i) + \" occurs \" + occ[i] + \" times.\" + \"\\n\"); }} // Function to implement the LPS// array to store the longest prefix// which is also a suffix for every// subString of the String Sstatic int[] prefix_function(String s){ // Array to store LPS values int []LPS = new int[s.Length]; // Value of lps[0] is 0 // by definition LPS[0] = 0; // Find the values of LPS[i] for // the rest of the String using // two pointers and DP for (int i = 1; i < s.Length; i++) { // Initially set the value // of j as the longest // prefix that is also a // suffix for i as LPS[i-1] int j = LPS[i - 1]; // Check if the suffix of // length j+1 is also a prefix while (j > 0 && s[i] != s[j]) { j = LPS[j - 1]; } // If s[i] = s[j] then, // assign LPS[i] as j+1 if (s[i] == s[j]) { LPS[i] = j + 1; } // If we reached j = 0, assign // LPS[i] as 0 as there was no // prefix equal to suffix else { LPS[i] = 0; } } // Return the calculated // LPS array return LPS;} // Function to count the occurrence// of all the prefix in the String Sstatic void count_occurrence(String s){ int n = s.Length; // Call the prefix_function // to get LPS int[] LPS = prefix_function(s); // To store the occurrence of // all the prefix int []occ = new int[n + 1]; // Count all the suffixes that // are also prefix for (int i = 0; i < n; i++) { occ[LPS[i]]++; } // Add the occurrences of // i to smaller prefixes for (int i = n - 1; i > 0; i--) { occ[LPS[i - 1]] += occ[i]; } // Adding 1 to all occ[i] for all // the original prefix for (int i = 0; i <= n; i++) occ[i]++; // Function Call to print the // occurrence of all the prefix print(occ, s);} // Driver Codepublic static void Main(String[] args){ // Given String String A = \"ABACABA\"; // Function Call count_occurrence(A);}} // This code is contributed by Amit Katiyar", "e": 38227, "s": 35905, "text": null }, { "code": "<script> // JavaScript program for the above approach // Function to print the count of all // prefix in the given string const print = (occ, s) => { // Iterate over string s for (let i = 1; i <= s.length; i++) { // Print the prefix and their // frequency document.write(`${s.substr(0, i)} occurs ${occ[i]} times.<br/>`); } } // Function to implement the LPS // array to store the longest prefix // which is also a suffix for every // substring of the string S const prefix_function = (s) => { // Array to store LPS values let LPS = new Array(s.length).fill(0); // Value of lps[0] is 0 // by definition LPS[0] = 0; // Find the values of LPS[i] for // the rest of the string using // two pointers and DP for (let i = 1; i < s.length; i++) { // Initially set the value // of j as the longest // prefix that is also a // suffix for i as LPS[i-1] let j = LPS[i - 1]; // Check if the suffix of // length j+1 is also a prefix while (j > 0 && s[i] != s[j]) { j = LPS[j - 1]; } // If s[i] = s[j] then, assign // LPS[i] as j+1 if (s[i] == s[j]) { LPS[i] = j + 1; } // If we reached j = 0, assign // LPS[i] as 0 as there was no // prefix equal to suffix else { LPS[i] = 0; } } // Return the calculated // LPS array return LPS; } // Function to count the occurrence // of all the prefix in the string S const count_occurrence = (s) => { let n = s.length; // Call the prefix_function // to get LPS let LPS = prefix_function(s); // To store the occurrence of // all the prefix let occ = new Array(n + 1).fill(0); // Count all the suffixes that // are also prefix for (let i = 0; i < n; i++) { occ[LPS[i]]++; } // Add the occurrences of // i to smaller prefixes for (let i = n - 1; i > 0; i--) { occ[LPS[i - 1]] += occ[i]; } // Adding 1 to all occ[i] for all // the original prefix for (let i = 0; i <= n; i++) occ[i]++; // Function Call to print the // occurrence of all the prefix print(occ, s); } // Driver Code // Given String let A = \"ABACABA\"; // Function Call count_occurrence(A); // This code is contributed by rakeshsahni </script>", "e": 40917, "s": 38227, "text": null }, { "code": null, "e": 41064, "s": 40917, "text": "A occurs 4 times.\nAB occurs 2 times.\nABA occurs 2 times.\nABAC occurs 1 times.\nABACA occurs 1 times.\nABACAB occurs 1 times.\nABACABA occurs 1 times." }, { "code": null, "e": 41111, "s": 41066, "text": "Time Complexity: O(N2) Auxiliary Space: O(N)" }, { "code": null, "e": 41124, "s": 41111, "text": "princi singh" }, { "code": null, "e": 41139, "s": 41124, "text": "amit143katiyar" }, { "code": null, "e": 41160, "s": 41139, "text": "avanitrachhadiya2155" }, { "code": null, "e": 41176, "s": 41160, "text": "simranarora5sos" }, { "code": null, "e": 41194, "s": 41176, "text": "germanshephered48" }, { "code": null, "e": 41206, "s": 41194, "text": "rakeshsahni" }, { "code": null, "e": 41228, "s": 41206, "text": "Longest Common Prefix" }, { "code": null, "e": 41235, "s": 41228, "text": "prefix" }, { "code": null, "e": 41243, "s": 41235, "text": "strings" }, { "code": null, "e": 41250, "s": 41243, "text": "Suffix" }, { "code": null, "e": 41270, "s": 41250, "text": "Dynamic Programming" }, { "code": null, "e": 41288, "s": 41270, "text": "Pattern Searching" }, { "code": null, "e": 41296, "s": 41288, "text": "Strings" }, { "code": null, "e": 41304, "s": 41296, "text": "Strings" }, { "code": null, "e": 41324, "s": 41304, "text": "Dynamic Programming" }, { "code": null, "e": 41342, "s": 41324, "text": "Pattern Searching" }, { "code": null, "e": 41440, "s": 41342, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 41449, "s": 41440, "text": "Comments" }, { "code": null, "e": 41462, "s": 41449, "text": "Old Comments" }, { "code": null, "e": 41493, "s": 41462, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 41526, "s": 41493, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 41561, "s": 41526, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 41629, "s": 41561, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 41650, "s": 41629, "text": "Edit Distance | DP-5" }, { "code": null, "e": 41686, "s": 41650, "text": "Pattern Searching using Suffix Tree" }, { "code": null, "e": 41738, "s": 41686, "text": "How to check if string contains only digits in Java" }, { "code": null, "e": 41764, "s": 41738, "text": "Wildcard Pattern Matching" }, { "code": null, "e": 41807, "s": 41764, "text": "Applications of String Matching Algorithms" } ]
Data Structures | Stack | Question 1 - GeeksforGeeks
08 Jan, 2013 Following is C like pseudo code of a function that takes a number as an argument, and uses a stack S to do processing. void fun(int n){ Stack S; // Say it creates an empty stack S while (n > 0) { // This line pushes the value of n%2 to stack S push(&S, n%2); n = n/2; } // Run while Stack S is not empty while (!isEmpty(&S)) printf("%d ", pop(&S)); // pop an element from S and print it} What does the above function do in general?(A) Prints binary representation of n in reverse order(B) Prints binary representation of n(C) Prints the value of Logn(D) Prints the value of Logn in reverse orderAnswer: (B) Explanation: See method 2 of https://www.geeksforgeeks.org/binary-representation-of-a-given-number/ for explanation. Data Structures Data Structures-Stack Data Structures Data Structures Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Advantages and Disadvantages of Linked List Introduction to Data Structures | 10 most commonly used Data Structures FIFO vs LIFO approach in Programming Bit manipulation | Swap Endianness of a number Data Structures | Queue | Question 11 Advantages of vector over array in C++ Program to create Custom Vector Class in C++ Multilevel Linked List Difference between data type and data structure Encryption and Decryption of String according to given technique
[ { "code": null, "e": 24830, "s": 24802, "text": "\n08 Jan, 2013" }, { "code": null, "e": 24949, "s": 24830, "text": "Following is C like pseudo code of a function that takes a number as an argument, and uses a stack S to do processing." }, { "code": "void fun(int n){ Stack S; // Say it creates an empty stack S while (n > 0) { // This line pushes the value of n%2 to stack S push(&S, n%2); n = n/2; } // Run while Stack S is not empty while (!isEmpty(&S)) printf(\"%d \", pop(&S)); // pop an element from S and print it}", "e": 25261, "s": 24949, "text": null }, { "code": null, "e": 25597, "s": 25261, "text": "What does the above function do in general?(A) Prints binary representation of n in reverse order(B) Prints binary representation of n(C) Prints the value of Logn(D) Prints the value of Logn in reverse orderAnswer: (B) Explanation: See method 2 of https://www.geeksforgeeks.org/binary-representation-of-a-given-number/ for explanation." }, { "code": null, "e": 25613, "s": 25597, "text": "Data Structures" }, { "code": null, "e": 25635, "s": 25613, "text": "Data Structures-Stack" }, { "code": null, "e": 25651, "s": 25635, "text": "Data Structures" }, { "code": null, "e": 25667, "s": 25651, "text": "Data Structures" }, { "code": null, "e": 25765, "s": 25667, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25809, "s": 25765, "text": "Advantages and Disadvantages of Linked List" }, { "code": null, "e": 25881, "s": 25809, "text": "Introduction to Data Structures | 10 most commonly used Data Structures" }, { "code": null, "e": 25918, "s": 25881, "text": "FIFO vs LIFO approach in Programming" }, { "code": null, "e": 25965, "s": 25918, "text": "Bit manipulation | Swap Endianness of a number" }, { "code": null, "e": 26003, "s": 25965, "text": "Data Structures | Queue | Question 11" }, { "code": null, "e": 26042, "s": 26003, "text": "Advantages of vector over array in C++" }, { "code": null, "e": 26087, "s": 26042, "text": "Program to create Custom Vector Class in C++" }, { "code": null, "e": 26110, "s": 26087, "text": "Multilevel Linked List" }, { "code": null, "e": 26158, "s": 26110, "text": "Difference between data type and data structure" } ]
Erlang - Case Statements
Erlang offers the case statement, which can be used to execute expressions based on the output of the case statement. The general form of this statement is − case expression of value1 -> statement#1; value2 -> statement#2; valueN -> statement#N end. The general working of this statement is as follows − The expression to be evaluated is placed in the case statement. This generally will evaluate to a value, which is used in the subsequent statements. The expression to be evaluated is placed in the case statement. This generally will evaluate to a value, which is used in the subsequent statements. Each value is evaluated against that which is passed by the case expression. Depending on which value holds true, that subsequent statement will be executed. Each value is evaluated against that which is passed by the case expression. Depending on which value holds true, that subsequent statement will be executed. The following diagram shows the flow of the case statement. The following program is an example of the case statement in Erlang − -module(helloworld). -export([start/0]). start() -> A = 5, case A of 5 -> io:fwrite("The value of A is 5"); 6 -> io:fwrite("The value of A is 6") end. The output of the above code will be − The value of A is 5. Print Add Notes Bookmark this page
[ { "code": null, "e": 2419, "s": 2301, "text": "Erlang offers the case statement, which can be used to execute expressions based on the output of the case statement." }, { "code": null, "e": 2459, "s": 2419, "text": "The general form of this statement is −" }, { "code": null, "e": 2561, "s": 2459, "text": "case expression of\n value1 -> statement#1;\n value2 -> statement#2;\n valueN -> statement#N\nend.\n" }, { "code": null, "e": 2615, "s": 2561, "text": "The general working of this statement is as follows −" }, { "code": null, "e": 2764, "s": 2615, "text": "The expression to be evaluated is placed in the case statement. This generally will evaluate to a value, which is used in the subsequent statements." }, { "code": null, "e": 2913, "s": 2764, "text": "The expression to be evaluated is placed in the case statement. This generally will evaluate to a value, which is used in the subsequent statements." }, { "code": null, "e": 3071, "s": 2913, "text": "Each value is evaluated against that which is passed by the case expression. Depending on which value holds true, that subsequent statement will be executed." }, { "code": null, "e": 3229, "s": 3071, "text": "Each value is evaluated against that which is passed by the case expression. Depending on which value holds true, that subsequent statement will be executed." }, { "code": null, "e": 3289, "s": 3229, "text": "The following diagram shows the flow of the case statement." }, { "code": null, "e": 3359, "s": 3289, "text": "The following program is an example of the case statement in Erlang −" }, { "code": null, "e": 3538, "s": 3359, "text": "-module(helloworld). \n-export([start/0]). \n\nstart() -> \n A = 5,\n case A of \n 5 -> io:fwrite(\"The value of A is 5\"); \n 6 -> io:fwrite(\"The value of A is 6\") \n end." }, { "code": null, "e": 3577, "s": 3538, "text": "The output of the above code will be −" }, { "code": null, "e": 3599, "s": 3577, "text": "The value of A is 5.\n" }, { "code": null, "e": 3606, "s": 3599, "text": " Print" }, { "code": null, "e": 3617, "s": 3606, "text": " Add Notes" } ]
Python - Data Structure
Computers store and process data with an extra ordinary speed and accuracy. So it is highly essential that the data is stored efficiently and can be accessed fast. Also the processing of data should happen in the smallest possible time but without losing the accuracy. Data structures deal with how the data is organized and held in the memory when a program processes it. It is important to note that the data that is stored in the disk as part of persistent storages (like relational tables) are not referred as data structure here. An Algorithm is step by step set of instruction to process the data for a specific purpose. So an algorithm utilizes various data structures in a logical way to solve a specific computing problem. In this tutorial we will cover these two fundamental concepts of computer science using the Python programming language. This tutorial is designed for Computer Science graduates as well as Software Professionals who are willing to learn data structures and algorithm programming in simple and easy steps using Python as a programming language. Before proceeding with this tutorial, you should have a basic knowledge of writing code in Python programming language, using any python IDE and execution of Python programs. If you are completely new to python then please refer our Python tutorial to get a sound understanding of the language. For most of the examples given in this tutorial you will find Try it option, so just make use of it and enjoy your learning. Try following example using Try it option available at the top right corner of the below sample code box #!/usr/bin/python print "Hello, Python!" 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": 2515, "s": 2244, "text": "Computers store and process data with an extra ordinary speed and accuracy. So it is highly essential that the data is stored efficiently and can be accessed fast. \nAlso the processing of data should happen in the smallest possible time but without losing the accuracy. " }, { "code": null, "e": 2783, "s": 2515, "text": "Data structures deal with how the data is organized and held in the memory when a program processes it. \nIt is important to note that the data that is stored in the disk as part of persistent storages (like relational tables) are not referred as data structure here. " }, { "code": null, "e": 2980, "s": 2783, "text": "An Algorithm is step by step set of instruction to process the data for a specific purpose. So an algorithm utilizes various data structures in a logical way to solve a specific computing problem." }, { "code": null, "e": 3101, "s": 2980, "text": "In this tutorial we will cover these two fundamental concepts of computer science using the Python programming language." }, { "code": null, "e": 3324, "s": 3101, "text": "This tutorial is designed for Computer Science graduates as well as Software Professionals who are willing to learn data structures and algorithm programming in simple and easy steps using Python as a programming language." }, { "code": null, "e": 3622, "s": 3324, "text": "Before proceeding with this tutorial, you should have a basic knowledge of writing code in Python programming language, using any python IDE and execution of Python programs.\nIf you are completely new to python then please refer our Python tutorial to get a sound understanding of the language." }, { "code": null, "e": 3747, "s": 3622, "text": "For most of the examples given in this tutorial you will find Try it option, so just make use of it and enjoy your learning." }, { "code": null, "e": 3853, "s": 3747, "text": "Try following example using Try it option available at the top right corner of the below sample code box " }, { "code": null, "e": 3897, "s": 3853, "text": "#!/usr/bin/python\n\nprint \"Hello, Python!\"\n\n" }, { "code": null, "e": 3934, "s": 3897, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3950, "s": 3934, "text": " Malhar Lathkar" }, { "code": null, "e": 3983, "s": 3950, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 4002, "s": 3983, "text": " Arnab Chakraborty" }, { "code": null, "e": 4037, "s": 4002, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 4059, "s": 4037, "text": " In28Minutes Official" }, { "code": null, "e": 4093, "s": 4059, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 4121, "s": 4093, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4156, "s": 4121, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 4170, "s": 4156, "text": " Lets Kode It" }, { "code": null, "e": 4203, "s": 4170, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 4220, "s": 4203, "text": " Abhilash Nelson" }, { "code": null, "e": 4227, "s": 4220, "text": " Print" }, { "code": null, "e": 4238, "s": 4227, "text": " Add Notes" } ]
How to create a flip card with CSS?
To create a flip card with CSS, the code is as follows − Live Demo <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; margin:20px; } .flipCard { background-color: transparent; width: 300px; height: 300px; perspective: 1000px; } .innerCard { position: relative; width: 100%; height: 100%; text-align: center; transition: transform 0.6s; transform-style: preserve-3d; box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2); } .flipCard:hover .innerCard { transform: rotateY(180deg); } .frontCard, .cardBack { position: absolute; width: 100%; height: 100%; -webkit-backface-visibility: hidden; backface-visibility: hidden; } .frontCard { background-color: rgb(124, 225, 243); color: black; } .cardBack { background-color: #3329b9; color: white; transform: rotateY(180deg); font-size: 18px; font-weight: bold; } </style> </head> <body> <h1>Card Flip with Text Example</h1> <div class="flipCard"> <div class="innerCard"> <div class="frontCard"> <img src="https://cdn.pixabay.com/photo/2016/04/01/11/25/avatar-1300331_960_720.png" alt="Avatar" style="width:300px;height:300px;"> </div> <div class="cardBack"> <h1>James Anderson</h1> <p>Architect</p> <p>Experience: 16 years</p> </div> </div> </div> <h2>Hover over the above image to see the text</h2> </body> </html> The above code will produce the following output − On hovering over the image −
[ { "code": null, "e": 1119, "s": 1062, "text": "To create a flip card with CSS, the code is as follows −" }, { "code": null, "e": 1130, "s": 1119, "text": " Live Demo" }, { "code": null, "e": 2632, "s": 1130, "text": "<!DOCTYPE html>\n<html>\n<head>\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<style>\n body {\n font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;\n margin:20px;\n }\n .flipCard {\n background-color: transparent;\n width: 300px;\n height: 300px;\n perspective: 1000px;\n }\n .innerCard {\n position: relative;\n width: 100%;\n height: 100%;\n text-align: center;\n transition: transform 0.6s;\n transform-style: preserve-3d;\n box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);\n }\n .flipCard:hover .innerCard {\n transform: rotateY(180deg);\n }\n .frontCard, .cardBack {\n position: absolute;\n width: 100%;\n height: 100%;\n -webkit-backface-visibility: hidden;\n backface-visibility: hidden;\n }\n .frontCard {\n background-color: rgb(124, 225, 243);\n color: black;\n }\n .cardBack {\n background-color: #3329b9;\n color: white;\n transform: rotateY(180deg);\n font-size: 18px;\n font-weight: bold;\n }\n</style>\n</head>\n<body>\n<h1>Card Flip with Text Example</h1>\n<div class=\"flipCard\">\n<div class=\"innerCard\">\n<div class=\"frontCard\">\n<img src=\"https://cdn.pixabay.com/photo/2016/04/01/11/25/avatar-1300331_960_720.png\" alt=\"Avatar\" style=\"width:300px;height:300px;\">\n</div>\n<div class=\"cardBack\">\n<h1>James Anderson</h1>\n<p>Architect</p>\n<p>Experience: 16 years</p>\n</div>\n</div>\n</div>\n<h2>Hover over the above image to see the text</h2>\n</body>\n</html>" }, { "code": null, "e": 2683, "s": 2632, "text": "The above code will produce the following output −" }, { "code": null, "e": 2712, "s": 2683, "text": "On hovering over the image −" } ]
Mouse over Actions with Cypress
The mouseover actions are very common in web pages where a list of elements becomes visible once we hover on it. Cypress does not support mouse over actions like other automation tools like Selenium as it considers it to be flaky. Cypress shall manipulate DOM elements to perform mouse over actions. Cypress takes the help of show() method in JQuery. The show() method displays the elements which are hidden [ having the CSS property display:none] and selected. Also, the show() method only works with the immediate parent in the DOM of the hidden element. Now to invoke any JQuery function, Cypress takes the help of the invoke() command which is used to invoke a function. The invoke() method cannot be chained directly with cy. .invoke(name of function) .invoke(options, name of function) .invoke(name of function, arguments..) .invoke(name of function, arguments..) .invoke(options, name of function, arguments...) The name of the function refers to the function that has to be invoked. Also, we can have additional arguments to the function call and there is no restriction on the count of the number of arguments. There can be of two types of options as listed below which can modify the default behavior of .invoke() − log − The default value of log is true. log − The default value of log is true. timeout − The default value of timeout parameter is defaultCommandTimeout (4000 milliseconds). This the duration to wait for .invoke() to conclude. timeout − The default value of timeout parameter is defaultCommandTimeout (4000 milliseconds). This the duration to wait for .invoke() to conclude. cy.get('#txt').invoke('show') Coding Implementation with JQuery show() method. describe('Tutorialspoint Test', function () { // test case it('Test Case5', function (){ // launch the application cy.visit("https://www.amazon.com/"); // to display hidden element with invoke() with show cy.get('#nav-flyout-ya-signin').invoke('show'); //click on the hidden element cy.contains('Sign').click(); //assert to verify the url cy.url().should('include','signin'); }); }); Cypress has another workaround to click on the hidden elements that appear only on mouse over action on the page. This is done by passing an option as an argument to the click() command in Cypress. click({ force: true }) − The click() command with the option force set to true [force:true ] modifies the default behavior of the hidden element and we can click on it. cy.get('.butn').click({ force: true }) Coding implementation with force option for hidden element. describe('Tutorialspoint Test', function () { // test case it('Test Case5', function (){ // launch the application cy.visit("https://www.amazon.com/"); //click on the hidden element with option force set to true cy.contains('Sign').click({force:true}); //assert to verify the url cy.url().should('include','signin'); }); });
[ { "code": null, "e": 1293, "s": 1062, "text": "The mouseover actions are very common in web pages where a list of elements becomes visible once we hover on it. Cypress does not support mouse over actions like other automation tools like Selenium as it considers it to be flaky." }, { "code": null, "e": 1619, "s": 1293, "text": "Cypress shall manipulate DOM elements to perform mouse over actions. Cypress takes the help of show() method in JQuery. The show() method displays the elements which are hidden [ having the CSS property display:none] and selected.\nAlso, the show() method only works with the immediate parent in the DOM of the\nhidden element." }, { "code": null, "e": 1793, "s": 1619, "text": "Now to invoke any JQuery function, Cypress takes the help of the invoke() command which is used to invoke a function. The invoke() method cannot be chained directly with cy." }, { "code": null, "e": 1981, "s": 1793, "text": ".invoke(name of function)\n.invoke(options, name of function)\n.invoke(name of function, arguments..)\n.invoke(name of function, arguments..)\n.invoke(options, name of function, arguments...)" }, { "code": null, "e": 2182, "s": 1981, "text": "The name of the function refers to the function that has to be invoked. Also, we\ncan have additional arguments to the function call and there is no restriction on\nthe count of the number of arguments." }, { "code": null, "e": 2288, "s": 2182, "text": "There can be of two types of options as listed below which can modify the default\nbehavior of .invoke() −" }, { "code": null, "e": 2328, "s": 2288, "text": "log − The default value of log is true." }, { "code": null, "e": 2368, "s": 2328, "text": "log − The default value of log is true." }, { "code": null, "e": 2516, "s": 2368, "text": "timeout − The default value of timeout parameter is defaultCommandTimeout (4000 milliseconds). This the duration to wait for .invoke() to conclude." }, { "code": null, "e": 2664, "s": 2516, "text": "timeout − The default value of timeout parameter is defaultCommandTimeout (4000 milliseconds). This the duration to wait for .invoke() to conclude." }, { "code": null, "e": 2694, "s": 2664, "text": "cy.get('#txt').invoke('show')" }, { "code": null, "e": 2743, "s": 2694, "text": "Coding Implementation with JQuery show() method." }, { "code": null, "e": 3184, "s": 2743, "text": "describe('Tutorialspoint Test', function () {\n // test case\n it('Test Case5', function (){\n // launch the application\n cy.visit(\"https://www.amazon.com/\");\n // to display hidden element with invoke() with show\n cy.get('#nav-flyout-ya-signin').invoke('show');\n //click on the hidden element\n cy.contains('Sign').click();\n //assert to verify the url\n cy.url().should('include','signin');\n });\n});" }, { "code": null, "e": 3382, "s": 3184, "text": "Cypress has another workaround to click on the hidden elements that appear only\non mouse over action on the page. This is done by passing an option as an argument\nto the click() command in Cypress." }, { "code": null, "e": 3551, "s": 3382, "text": "click({ force: true }) − The click() command with the option force set to true [force:true ] modifies the default behavior of the hidden element and we can click on it." }, { "code": null, "e": 3590, "s": 3551, "text": "cy.get('.butn').click({ force: true })" }, { "code": null, "e": 3650, "s": 3590, "text": "Coding implementation with force option for hidden element." }, { "code": null, "e": 4020, "s": 3650, "text": "describe('Tutorialspoint Test', function () {\n // test case\n it('Test Case5', function (){\n // launch the application\n cy.visit(\"https://www.amazon.com/\");\n //click on the hidden element with option force set to true\n cy.contains('Sign').click({force:true});\n //assert to verify the url\n cy.url().should('include','signin');\n });\n});" } ]
numpy.any() in Python - GeeksforGeeks
28 Mar, 2022 The numpy.any() function tests whether any array elements along the mentioned axis evaluate to True. Syntax : numpy.any(a, axis = None, out = None, keepdims = class numpy._globals._NoValue at 0x40ba726c) Parameters : array :[array_like]Input array or object whose elements, we need to test. axis : [int or tuple of ints, optional]Axis along which array elements are evaluated. The default (axis = None) is to perform a logical AND over all the dimensions of the input array. Axis may be negative, in which case it counts from the last to the first axis. out : [ndarray, optional]Output array with same dimensions as Input array, placed with result keepdmis : [boolean, optional]If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. If the default value is passed, then keepdims will not be passed through to the all method of sub-classes of ndarray, however any non-default value will be. If the sub-classes sum method does not implement keepdims any exceptions will be raised. Return : A new Boolean array as per 'out' parameter Code 1 : Python # Python Program illustrating# numpy.any() method import numpy as geek # Axis = NULL# True False# True True# True : False = True (OR) print("Bool Value with axis = NONE : ", geek.any([[True,False],[True,True]])) # Axis = 0# True False# True True# True : Falseprint("\nBool Value with axis = 0 : ", geek.any([[True,False],[True,True]], axis = 0)) print("\nBool : ", geek.any([-1, 4, 5])) # Not a Number (NaN), positive infinity and negative infinity# evaluate to True because these are not equal to zero.print("\nBool : ", geek.any([1.0, geek.nan])) print("\nBool Value : ", geek.any([[0, 0],[0, 0]])) Output : Bool Value with axis = NONE : True Bool Value with axis = 0 : [ True True] Bool : True Bool : True Bool Value : False Code 2 : Python # Python Program illustrating# numpy.any() method # Parameter : keepdmis import numpy as geek # setting keepdmis = Trueprint("\nBool Value : ", geek.any([[1, 0],[0, 4]], True)) # setting keepdmis = Trueprint("\nBool Value : ", geek.any([[0, 0],[0, 0]], False)) Output : Bool Value : [ True True] Bool Value : [False False] VisibleDeprecationWarning: using a boolean instead of an integer will result in an error in the future return umr_any(a, axis, dtype, out, keepdims) References : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.any.html#numpy.any Note : These codes won’t run on online IDE’s. So please, run them on your systems to explore the working. This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. vinayedula Python numpy-Logic Functions Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary How to Install PIP on Windows ? Read a file line by line in Python Enumerate() in Python Different ways to create Pandas Dataframe Create a Pandas DataFrame from Lists Reading and Writing to text files in Python *args and **kwargs in Python How to drop one or multiple columns in Pandas Dataframe sum() function in Python
[ { "code": null, "e": 24694, "s": 24666, "text": "\n28 Mar, 2022" }, { "code": null, "e": 24805, "s": 24694, "text": "The numpy.any() function tests whether any array elements along the mentioned axis evaluate to True. Syntax : " }, { "code": null, "e": 24929, "s": 24805, "text": "numpy.any(a,\n axis = None,\n out = None,\n keepdims = class numpy._globals._NoValue at 0x40ba726c)" }, { "code": null, "e": 24943, "s": 24929, "text": "Parameters : " }, { "code": null, "e": 25895, "s": 24943, "text": "array :[array_like]Input array or object whose elements, we need to test.\naxis : [int or tuple of ints, optional]Axis along which array elements \n are evaluated.\n The default (axis = None) is to perform a logical AND over all the dimensions of the input\n array. Axis may be negative, in which case it counts from the last to the first axis.\nout : [ndarray, optional]Output array with same dimensions as Input array, \n placed with result\nkeepdmis : [boolean, optional]If this is set to True, the axes which are \n reduced are left in the result as dimensions with size one. With this option, the result \n will broadcast correctly against the input array.\n If the default value is passed, then keepdims will not be passed through to the all \n method of sub-classes of ndarray, however any non-default value will be. If the \n sub-classes sum method does not implement keepdims any exceptions will be raised." }, { "code": null, "e": 25905, "s": 25895, "text": "Return : " }, { "code": null, "e": 25948, "s": 25905, "text": "A new Boolean array as per 'out' parameter" }, { "code": null, "e": 25958, "s": 25948, "text": "Code 1 : " }, { "code": null, "e": 25965, "s": 25958, "text": "Python" }, { "code": "# Python Program illustrating# numpy.any() method import numpy as geek # Axis = NULL# True False# True True# True : False = True (OR) print(\"Bool Value with axis = NONE : \", geek.any([[True,False],[True,True]])) # Axis = 0# True False# True True# True : Falseprint(\"\\nBool Value with axis = 0 : \", geek.any([[True,False],[True,True]], axis = 0)) print(\"\\nBool : \", geek.any([-1, 4, 5])) # Not a Number (NaN), positive infinity and negative infinity# evaluate to True because these are not equal to zero.print(\"\\nBool : \", geek.any([1.0, geek.nan])) print(\"\\nBool Value : \", geek.any([[0, 0],[0, 0]]))", "e": 26611, "s": 25965, "text": null }, { "code": null, "e": 26621, "s": 26611, "text": "Output : " }, { "code": null, "e": 26751, "s": 26621, "text": "Bool Value with axis = NONE : True\n\nBool Value with axis = 0 : [ True True]\n\nBool : True\n\nBool : True\n\nBool Value : False" }, { "code": null, "e": 26761, "s": 26751, "text": "Code 2 : " }, { "code": null, "e": 26768, "s": 26761, "text": "Python" }, { "code": "# Python Program illustrating# numpy.any() method # Parameter : keepdmis import numpy as geek # setting keepdmis = Trueprint(\"\\nBool Value : \", geek.any([[1, 0],[0, 4]], True)) # setting keepdmis = Trueprint(\"\\nBool Value : \", geek.any([[0, 0],[0, 0]], False))", "e": 27046, "s": 26768, "text": null }, { "code": null, "e": 27056, "s": 27046, "text": "Output : " }, { "code": null, "e": 27263, "s": 27056, "text": "Bool Value : [ True True]\n\nBool Value : [False False]\nVisibleDeprecationWarning: using a boolean instead of an integer \nwill result in an error in the future\nreturn umr_any(a, axis, dtype, out, keepdims)" }, { "code": null, "e": 27359, "s": 27263, "text": "References : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.any.html#numpy.any " }, { "code": null, "e": 27465, "s": 27359, "text": "Note : These codes won’t run on online IDE’s. So please, run them on your systems to explore the working." }, { "code": null, "e": 27890, "s": 27465, "text": "This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 27901, "s": 27890, "text": "vinayedula" }, { "code": null, "e": 27930, "s": 27901, "text": "Python numpy-Logic Functions" }, { "code": null, "e": 27943, "s": 27930, "text": "Python-numpy" }, { "code": null, "e": 27950, "s": 27943, "text": "Python" }, { "code": null, "e": 28048, "s": 27950, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28057, "s": 28048, "text": "Comments" }, { "code": null, "e": 28070, "s": 28057, "text": "Old Comments" }, { "code": null, "e": 28088, "s": 28070, "text": "Python Dictionary" }, { "code": null, "e": 28120, "s": 28088, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28155, "s": 28120, "text": "Read a file line by line in Python" }, { "code": null, "e": 28177, "s": 28155, "text": "Enumerate() in Python" }, { "code": null, "e": 28219, "s": 28177, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28256, "s": 28219, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 28300, "s": 28256, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 28329, "s": 28300, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28385, "s": 28329, "text": "How to drop one or multiple columns in Pandas Dataframe" } ]
Semantic similarity classifier and clustering sentences based on semantic similarity. | by Manish Chablani | Towards Data Science
Recently we have been doing some experiments to cluster semantically similar messages, by leveraging pre-trained models so we can get something off the ground using no labelled data. Task here is given a list of sentences we cluster them such that semantically similar sentences are in same cluster and number of clusters is not predetermined. Task of semantic similarity classifier is: Given two sentences/messages/paragraphs classify of they are semantically equivalent. InferSent is a sentence embeddings method that provides semantic representations for English sentences. It is trained on natural language inference data and generalizes well to many different tasks. github.com Here is the code: # Load infersent model model_version = 2MODEL_PATH = "infersent_sentence_encoder/infersent%s.pkl" % model_versionparams_model = {'bsize': 64, 'word_emb_dim': 300, 'enc_lstm_dim': 2048, 'pool_type': 'max', 'dpout_model': 0.0, 'version': model_version}model = InferSent(params_model)model.load_state_dict(torch.load(MODEL_PATH))# If infersent1 -> use GloVe embeddings. If infersent2 -> use InferSent embeddings.W2V_PATH = 'infersent_sentence_encoder/GloVe/glove.840B.300d.txt' if model_version == 1 else 'infersent_sentence_encoder/fastText/crawl-300d-2M.vec'model.set_w2v_path(W2V_PATH)#load datads = pd.read_msgpack('./ds.mp')sentences = ds['text']# generate infersent sentence embeddingsmodel.build_vocab(sentences, tokenize=True)embs = model.encode(sentences, tokenize=True) Idea here is to index representation (embedding) of each sentence/message/paragraph and pick k (=10) NN (nearest neighbor) candidates for each sentence based on distance threshold. We found that nmslib is very fast and efficient. import nmslibNTHREADS = 8def create_index(a): index = nmslib.init(space='angulardist') index.addDataPointBatch(a) index.createIndex() return indexdef get_knns(index, vecs, k=3): return zip(*index.knnQueryBatch(vecs, k=k,num_threads=NTHREADS))nn_wvs = create_index(embs)to_frame = lambda x: pd.DataFrame(np.array(x)[:,1:])idxs, dists = map(to_frame, get_knns(nn_wvs, embs, k=10))catted = pd.concat([idxs.stack().to_frame('idx'), dists.stack().to_frame('dist')], axis=1).reset_index().drop('level_1',1).rename(columns={'level_0': 'v1', 'idx': 'v2'}) Think of step 2 as candidate generation (focusing on recall) and step 3 as focusing on precision. Of all the candidates that are considered potential duplicates here we assign probability to each pair. Based on candidates that are considered duplicates in step 3 we merge clusters using agglomerative clustering implementation in scikit. In agglomerative clustering all observations start as thier own clusters and clusters are merge using the merge criteria specified until convergence, at which point no more merges are happening. scikit-learn.org This works fairly well in practice and the clusters formed have good semantic equivalence.
[ { "code": null, "e": 516, "s": 172, "text": "Recently we have been doing some experiments to cluster semantically similar messages, by leveraging pre-trained models so we can get something off the ground using no labelled data. Task here is given a list of sentences we cluster them such that semantically similar sentences are in same cluster and number of clusters is not predetermined." }, { "code": null, "e": 645, "s": 516, "text": "Task of semantic similarity classifier is: Given two sentences/messages/paragraphs classify of they are semantically equivalent." }, { "code": null, "e": 844, "s": 645, "text": "InferSent is a sentence embeddings method that provides semantic representations for English sentences. It is trained on natural language inference data and generalizes well to many different tasks." }, { "code": null, "e": 855, "s": 844, "text": "github.com" }, { "code": null, "e": 873, "s": 855, "text": "Here is the code:" }, { "code": null, "e": 1665, "s": 873, "text": "# Load infersent model model_version = 2MODEL_PATH = \"infersent_sentence_encoder/infersent%s.pkl\" % model_versionparams_model = {'bsize': 64, 'word_emb_dim': 300, 'enc_lstm_dim': 2048, 'pool_type': 'max', 'dpout_model': 0.0, 'version': model_version}model = InferSent(params_model)model.load_state_dict(torch.load(MODEL_PATH))# If infersent1 -> use GloVe embeddings. If infersent2 -> use InferSent embeddings.W2V_PATH = 'infersent_sentence_encoder/GloVe/glove.840B.300d.txt' if model_version == 1 else 'infersent_sentence_encoder/fastText/crawl-300d-2M.vec'model.set_w2v_path(W2V_PATH)#load datads = pd.read_msgpack('./ds.mp')sentences = ds['text']# generate infersent sentence embeddingsmodel.build_vocab(sentences, tokenize=True)embs = model.encode(sentences, tokenize=True)" }, { "code": null, "e": 1895, "s": 1665, "text": "Idea here is to index representation (embedding) of each sentence/message/paragraph and pick k (=10) NN (nearest neighbor) candidates for each sentence based on distance threshold. We found that nmslib is very fast and efficient." }, { "code": null, "e": 2458, "s": 1895, "text": "import nmslibNTHREADS = 8def create_index(a): index = nmslib.init(space='angulardist') index.addDataPointBatch(a) index.createIndex() return indexdef get_knns(index, vecs, k=3): return zip(*index.knnQueryBatch(vecs, k=k,num_threads=NTHREADS))nn_wvs = create_index(embs)to_frame = lambda x: pd.DataFrame(np.array(x)[:,1:])idxs, dists = map(to_frame, get_knns(nn_wvs, embs, k=10))catted = pd.concat([idxs.stack().to_frame('idx'), dists.stack().to_frame('dist')], axis=1).reset_index().drop('level_1',1).rename(columns={'level_0': 'v1', 'idx': 'v2'})" }, { "code": null, "e": 2660, "s": 2458, "text": "Think of step 2 as candidate generation (focusing on recall) and step 3 as focusing on precision. Of all the candidates that are considered potential duplicates here we assign probability to each pair." }, { "code": null, "e": 2991, "s": 2660, "text": "Based on candidates that are considered duplicates in step 3 we merge clusters using agglomerative clustering implementation in scikit. In agglomerative clustering all observations start as thier own clusters and clusters are merge using the merge criteria specified until convergence, at which point no more merges are happening." }, { "code": null, "e": 3008, "s": 2991, "text": "scikit-learn.org" } ]
C# | Graphics.DrawLine() Method | Set - 1 - GeeksforGeeks
17 Apr, 2019 Graphics.DrawLine() Method is used to draw a line connecting the two points specified by the coordinate pairs. There are 4 methods in the overload list of this method as follows: DrawLine(Pen, PointF, PointF) Method DrawLine(Pen, Int32, Int32, Int32, Int32) Method DrawLine(Pen, Single, Single, Single, Single) Method DrawLine(Pen, Point, Point) Method Here, we will discuss the first two methods. This method is used to draw line form a specified set of points to a specified set of points. It needs a PointF variable which is set of (x, y) points. Syntax: public void DrawLine (System.Drawing.Pen pen, System.Drawing.PointF pt1, System.Drawing.PointF pt2); Parameters: pen: Pen determines the color, width, and style of the line. pt1: Defines the (x, y) coordinates as a PointF variable of the initial point. pt2: Defines the (x, y) coordinates as a PointF variable of the final point. Exception: This method will give ArgumentNullexception if the pen is null. Example: // C# program to demonstrate the // DrawLine(Pen, PointF, PointF) Methodusing System;using System.Drawing;using System.Drawing.Printing;using System.Windows.Forms; namespace GFG { class PrintableForm : Form { public static void Main() { Application.Run(new PrintableForm()); } public PrintableForm() { ResizeRedraw = true; } protected override void OnPaint(PaintEventArgs pea) { // Defines pen Pen pen = new Pen(ForeColor); // Defines the both points to connect // pt1 is (30.0, 30.0) which represents (x1, y1) PointF pt1 = new PointF(30.0F, 30.0F); // pt2 is (200.0, 300.0) which represents (x2, y2) PointF pt2 = new PointF(200.0F, 300.0F); // Draws the line pea.Graphics.DrawLine(pen, pt1, pt2); }}} Output: This method is used to draw line form a specified set of coordinates given in form x1, y1, x2, y2 all discrete. Syntax: public void DrawLine (System.Drawing.Pen pen, int x1, int y1, int x2, int y2); Parameters: pen: Pen determines the color, width, and style of the line. x1: The abscissa of first point. y1: The ordinate of first point. x2: The abscissa of second point. y2: The ordinate of second point. Exception: This method will give ArgumentNullexception if the pen is null. Example 1: // C# program to draw a cross using the// DrawLine(Pen, Int32, Int32, Int32,// Int32) Methodusing System;using System.Drawing;using System.Drawing.Printing;using System.Windows.Forms; namespace GFG { class PrintableForm : Form { public static void Main() { Application.Run(new PrintableForm()); } public PrintableForm() { ResizeRedraw = true; } protected override void OnPaint(PaintEventArgs pea) { // Defines the pen Pen pen = new Pen(ForeColor); // To draw a cross we need to make 2 // diagonals from top-left to the // bottom-right and top-right to the // bottom-left to calculate these // coordinates we would take help of // our screen size top-left = (0, 0) // bottom-right = (ClientSize.Width - 1, // ClientSize.Height - 1) // top-right = (ClientSize.Width - 1, 0) // bottom-left = (0, ClientSize.Height - 1) pea.Graphics.DrawLine(pen, 0, 0, ClientSize.Width - 1, ClientSize.Height - 1); pea.Graphics.DrawLine(pen, ClientSize.Width - 1, 0, 0, ClientSize.Height - 1); }}} Output: Example 2: // C# program to Create a 8x8 square board// using // DrawLine(Pen, Int32, Int32, Int32,// Int32) Methodusing System;using System.Drawing;using System.Drawing.Printing;using System.Windows.Forms; namespace GFG { class PrintableForm : Form { public static void Main() { Application.Run(new PrintableForm()); } public PrintableForm() { ResizeRedraw = true; } protected override void OnPaint(PaintEventArgs pea) { // Define Pen Pen pen = new Pen(ForeColor); // loop for all 7 horizontal lines to draw for (int i = 0; i < 7; i++) { // Taking Block size to be 30x30 // So width and height will be 30*8=240 pea.Graphics.DrawLine(pen, i * 30, 0, i * 30, 240); } // loop for all 7 horizontal lines to draw for (int i = 0; i < 7; i++) { pea.Graphics.DrawLine(pen, 0, i * 30, 240, i * 30); } }}} Output: CSharp-Graphics-Class CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C# | Method Overriding C# Dictionary with examples Difference between Ref and Out keywords in C# C# | Delegates Top 50 C# Interview Questions & Answers C# | Constructors Introduction to .NET Framework Extension Method in C# C# | Abstract Classes C# | String.IndexOf( ) Method | Set - 1
[ { "code": null, "e": 23543, "s": 23515, "text": "\n17 Apr, 2019" }, { "code": null, "e": 23722, "s": 23543, "text": "Graphics.DrawLine() Method is used to draw a line connecting the two points specified by the coordinate pairs. There are 4 methods in the overload list of this method as follows:" }, { "code": null, "e": 23759, "s": 23722, "text": "DrawLine(Pen, PointF, PointF) Method" }, { "code": null, "e": 23808, "s": 23759, "text": "DrawLine(Pen, Int32, Int32, Int32, Int32) Method" }, { "code": null, "e": 23861, "s": 23808, "text": "DrawLine(Pen, Single, Single, Single, Single) Method" }, { "code": null, "e": 23896, "s": 23861, "text": "DrawLine(Pen, Point, Point) Method" }, { "code": null, "e": 23941, "s": 23896, "text": "Here, we will discuss the first two methods." }, { "code": null, "e": 24093, "s": 23941, "text": "This method is used to draw line form a specified set of points to a specified set of points. It needs a PointF variable which is set of (x, y) points." }, { "code": null, "e": 24101, "s": 24093, "text": "Syntax:" }, { "code": null, "e": 24202, "s": 24101, "text": "public void DrawLine (System.Drawing.Pen pen, System.Drawing.PointF pt1, System.Drawing.PointF pt2);" }, { "code": null, "e": 24214, "s": 24202, "text": "Parameters:" }, { "code": null, "e": 24275, "s": 24214, "text": "pen: Pen determines the color, width, and style of the line." }, { "code": null, "e": 24354, "s": 24275, "text": "pt1: Defines the (x, y) coordinates as a PointF variable of the initial point." }, { "code": null, "e": 24431, "s": 24354, "text": "pt2: Defines the (x, y) coordinates as a PointF variable of the final point." }, { "code": null, "e": 24506, "s": 24431, "text": "Exception: This method will give ArgumentNullexception if the pen is null." }, { "code": null, "e": 24515, "s": 24506, "text": "Example:" }, { "code": "// C# program to demonstrate the // DrawLine(Pen, PointF, PointF) Methodusing System;using System.Drawing;using System.Drawing.Printing;using System.Windows.Forms; namespace GFG { class PrintableForm : Form { public static void Main() { Application.Run(new PrintableForm()); } public PrintableForm() { ResizeRedraw = true; } protected override void OnPaint(PaintEventArgs pea) { // Defines pen Pen pen = new Pen(ForeColor); // Defines the both points to connect // pt1 is (30.0, 30.0) which represents (x1, y1) PointF pt1 = new PointF(30.0F, 30.0F); // pt2 is (200.0, 300.0) which represents (x2, y2) PointF pt2 = new PointF(200.0F, 300.0F); // Draws the line pea.Graphics.DrawLine(pen, pt1, pt2); }}}", "e": 25333, "s": 24515, "text": null }, { "code": null, "e": 25341, "s": 25333, "text": "Output:" }, { "code": null, "e": 25453, "s": 25341, "text": "This method is used to draw line form a specified set of coordinates given in form x1, y1, x2, y2 all discrete." }, { "code": null, "e": 25461, "s": 25453, "text": "Syntax:" }, { "code": null, "e": 25540, "s": 25461, "text": "public void DrawLine (System.Drawing.Pen pen, int x1, int y1, int x2, int y2);" }, { "code": null, "e": 25552, "s": 25540, "text": "Parameters:" }, { "code": null, "e": 25613, "s": 25552, "text": "pen: Pen determines the color, width, and style of the line." }, { "code": null, "e": 25646, "s": 25613, "text": "x1: The abscissa of first point." }, { "code": null, "e": 25679, "s": 25646, "text": "y1: The ordinate of first point." }, { "code": null, "e": 25713, "s": 25679, "text": "x2: The abscissa of second point." }, { "code": null, "e": 25747, "s": 25713, "text": "y2: The ordinate of second point." }, { "code": null, "e": 25822, "s": 25747, "text": "Exception: This method will give ArgumentNullexception if the pen is null." }, { "code": null, "e": 25833, "s": 25822, "text": "Example 1:" }, { "code": "// C# program to draw a cross using the// DrawLine(Pen, Int32, Int32, Int32,// Int32) Methodusing System;using System.Drawing;using System.Drawing.Printing;using System.Windows.Forms; namespace GFG { class PrintableForm : Form { public static void Main() { Application.Run(new PrintableForm()); } public PrintableForm() { ResizeRedraw = true; } protected override void OnPaint(PaintEventArgs pea) { // Defines the pen Pen pen = new Pen(ForeColor); // To draw a cross we need to make 2 // diagonals from top-left to the // bottom-right and top-right to the // bottom-left to calculate these // coordinates we would take help of // our screen size top-left = (0, 0) // bottom-right = (ClientSize.Width - 1, // ClientSize.Height - 1) // top-right = (ClientSize.Width - 1, 0) // bottom-left = (0, ClientSize.Height - 1) pea.Graphics.DrawLine(pen, 0, 0, ClientSize.Width - 1, ClientSize.Height - 1); pea.Graphics.DrawLine(pen, ClientSize.Width - 1, 0, 0, ClientSize.Height - 1); }}}", "e": 27043, "s": 25833, "text": null }, { "code": null, "e": 27051, "s": 27043, "text": "Output:" }, { "code": null, "e": 27062, "s": 27051, "text": "Example 2:" }, { "code": "// C# program to Create a 8x8 square board// using // DrawLine(Pen, Int32, Int32, Int32,// Int32) Methodusing System;using System.Drawing;using System.Drawing.Printing;using System.Windows.Forms; namespace GFG { class PrintableForm : Form { public static void Main() { Application.Run(new PrintableForm()); } public PrintableForm() { ResizeRedraw = true; } protected override void OnPaint(PaintEventArgs pea) { // Define Pen Pen pen = new Pen(ForeColor); // loop for all 7 horizontal lines to draw for (int i = 0; i < 7; i++) { // Taking Block size to be 30x30 // So width and height will be 30*8=240 pea.Graphics.DrawLine(pen, i * 30, 0, i * 30, 240); } // loop for all 7 horizontal lines to draw for (int i = 0; i < 7; i++) { pea.Graphics.DrawLine(pen, 0, i * 30, 240, i * 30); } }}}", "e": 28052, "s": 27062, "text": null }, { "code": null, "e": 28060, "s": 28052, "text": "Output:" }, { "code": null, "e": 28082, "s": 28060, "text": "CSharp-Graphics-Class" }, { "code": null, "e": 28096, "s": 28082, "text": "CSharp-method" }, { "code": null, "e": 28099, "s": 28096, "text": "C#" }, { "code": null, "e": 28197, "s": 28099, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28206, "s": 28197, "text": "Comments" }, { "code": null, "e": 28219, "s": 28206, "text": "Old Comments" }, { "code": null, "e": 28242, "s": 28219, "text": "C# | Method Overriding" }, { "code": null, "e": 28270, "s": 28242, "text": "C# Dictionary with examples" }, { "code": null, "e": 28316, "s": 28270, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 28331, "s": 28316, "text": "C# | Delegates" }, { "code": null, "e": 28371, "s": 28331, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 28389, "s": 28371, "text": "C# | Constructors" }, { "code": null, "e": 28420, "s": 28389, "text": "Introduction to .NET Framework" }, { "code": null, "e": 28443, "s": 28420, "text": "Extension Method in C#" }, { "code": null, "e": 28465, "s": 28443, "text": "C# | Abstract Classes" } ]
How to make a Bootstrap 4 accordion collapse when clicking the whole header div ? - GeeksforGeeks
28 Nov, 2019 In Bootstrap 4, Accordion collapse when anchor or button tag is clicked but lets see how to make a Bootstrap 4 accordion collapse when clicking the whole header with the help of following simple approach. First you have to remove anchor tag and button tag within div of class=”card-header” except card title. Now add class collapsed and card-link to existing class=”card-header” of div. Finally, add attributes like data-toggle=”collapse” data-target=”#collapseOne”. Note: The data-target attribute value must be the id of the collapsing div tag. <div class="card-header collapsed card-link" data-toggle="collapse" data-target="#collapseOne" > Collapsible header title</div> <div id="collapseOne" class="collapse" data-parent="#accordion"> <div class="card-body"> <!-- content to be collapsed --> </div></div> Example: Below example illustrate how to make a Bootstrap 4 accordion collapse when clicking the whole header div with simple approach. <!DOCTYPE html><html> <head> <title> Bootstrap 4 accordion collapse when clicking the whole header div </title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head> <body> <center> <div class="container"> <h1 style="color:green;padding:13px;">GeeksforGeeeks</h1> <br> <p> Bootstrap 4 accordion collapse when clicking the whole header div </p> <div id="accordion"> <div class="card "> <div class="card-header collapsed card-link" data-toggle="collapse" data-target="#collapseOne"> GeeksforGeeks </div> <div id="collapseOne" class="collapse" data-parent="#accordion"> <div class="card-body"> GeeksforGeeks is a computer science portal. It is the best platform to lean programming. </div> </div> </div> <div class="card"> <div class="card-header collapsed card-link" data-toggle="collapse" data-target="#collapseTwo"> Bootstrap </div> <div id="collapseTwo" class="collapse" data-parent="#accordion"> <div class="card-body"> Bootstrap is free and open-source collection of tools for creating websites and web applications. </div> </div> </div> <div class="card"> <div class="card-header collapsed card-link" data-toggle="collapse" data-target="#collapseThree"> HTML </div> <div id="collapseThree" class="collapse" data-parent="#accordion"> <div class="card-body"> HTML stands for HyperText Markup Language. It is used to design web pages using markup language. </div> </div> </div> </div> </center></body> </htm Output: Reference: https://getbootstrap.com/docs/4.3/components/collapse/ Bootstrap-4 Bootstrap-Misc Picked Bootstrap Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to pass data into a bootstrap modal? How to Show Images on Click using HTML ? How to set Bootstrap Timepicker using datetimepicker library ? How to Use Bootstrap with React? Difference between Bootstrap 4 and Bootstrap 5 Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 25145, "s": 25117, "text": "\n28 Nov, 2019" }, { "code": null, "e": 25350, "s": 25145, "text": "In Bootstrap 4, Accordion collapse when anchor or button tag is clicked but lets see how to make a Bootstrap 4 accordion collapse when clicking the whole header with the help of following simple approach." }, { "code": null, "e": 25612, "s": 25350, "text": "First you have to remove anchor tag and button tag within div of class=”card-header” except card title. Now add class collapsed and card-link to existing class=”card-header” of div. Finally, add attributes like data-toggle=”collapse” data-target=”#collapseOne”." }, { "code": null, "e": 25692, "s": 25612, "text": "Note: The data-target attribute value must be the id of the collapsing div tag." }, { "code": "<div class=\"card-header collapsed card-link\" data-toggle=\"collapse\" data-target=\"#collapseOne\" > Collapsible header title</div> <div id=\"collapseOne\" class=\"collapse\" data-parent=\"#accordion\"> <div class=\"card-body\"> <!-- content to be collapsed --> </div></div>", "e": 26004, "s": 25692, "text": null }, { "code": null, "e": 26140, "s": 26004, "text": "Example: Below example illustrate how to make a Bootstrap 4 accordion collapse when clicking the whole header div with simple approach." }, { "code": "<!DOCTYPE html><html> <head> <title> Bootstrap 4 accordion collapse when clicking the whole header div </title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head> <body> <center> <div class=\"container\"> <h1 style=\"color:green;padding:13px;\">GeeksforGeeeks</h1> <br> <p> Bootstrap 4 accordion collapse when clicking the whole header div </p> <div id=\"accordion\"> <div class=\"card \"> <div class=\"card-header collapsed card-link\" data-toggle=\"collapse\" data-target=\"#collapseOne\"> GeeksforGeeks </div> <div id=\"collapseOne\" class=\"collapse\" data-parent=\"#accordion\"> <div class=\"card-body\"> GeeksforGeeks is a computer science portal. It is the best platform to lean programming. </div> </div> </div> <div class=\"card\"> <div class=\"card-header collapsed card-link\" data-toggle=\"collapse\" data-target=\"#collapseTwo\"> Bootstrap </div> <div id=\"collapseTwo\" class=\"collapse\" data-parent=\"#accordion\"> <div class=\"card-body\"> Bootstrap is free and open-source collection of tools for creating websites and web applications. </div> </div> </div> <div class=\"card\"> <div class=\"card-header collapsed card-link\" data-toggle=\"collapse\" data-target=\"#collapseThree\"> HTML </div> <div id=\"collapseThree\" class=\"collapse\" data-parent=\"#accordion\"> <div class=\"card-body\"> HTML stands for HyperText Markup Language. It is used to design web pages using markup language. </div> </div> </div> </div> </center></body> </htm ", "e": 28916, "s": 26140, "text": null }, { "code": null, "e": 28924, "s": 28916, "text": "Output:" }, { "code": null, "e": 28990, "s": 28924, "text": "Reference: https://getbootstrap.com/docs/4.3/components/collapse/" }, { "code": null, "e": 29002, "s": 28990, "text": "Bootstrap-4" }, { "code": null, "e": 29017, "s": 29002, "text": "Bootstrap-Misc" }, { "code": null, "e": 29024, "s": 29017, "text": "Picked" }, { "code": null, "e": 29034, "s": 29024, "text": "Bootstrap" }, { "code": null, "e": 29051, "s": 29034, "text": "Web Technologies" }, { "code": null, "e": 29149, "s": 29051, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29158, "s": 29149, "text": "Comments" }, { "code": null, "e": 29171, "s": 29158, "text": "Old Comments" }, { "code": null, "e": 29212, "s": 29171, "text": "How to pass data into a bootstrap modal?" }, { "code": null, "e": 29253, "s": 29212, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 29316, "s": 29253, "text": "How to set Bootstrap Timepicker using datetimepicker library ?" }, { "code": null, "e": 29349, "s": 29316, "text": "How to Use Bootstrap with React?" }, { "code": null, "e": 29396, "s": 29349, "text": "Difference between Bootstrap 4 and Bootstrap 5" }, { "code": null, "e": 29452, "s": 29396, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 29485, "s": 29452, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29547, "s": 29485, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 29590, "s": 29547, "text": "How to fetch data from an API in ReactJS ?" } ]
Elm - List
The List, Tuples and Record data structures can be used to store a collection of values. This chapter discusses how to use List in Elm. A List is a collection of homogeneous values. The values in a list must all be of the same data type. Consider the following limitations while using variables to store values − Variables are scalar in nature. In other words, at the time of declaration a variable can hold only one value. This means that to store n values in a program, n variable declarations will be needed. Hence, the use of variables is not feasible when one needs to store a larger collection of values. Variables are scalar in nature. In other words, at the time of declaration a variable can hold only one value. This means that to store n values in a program, n variable declarations will be needed. Hence, the use of variables is not feasible when one needs to store a larger collection of values. Variables in a program are allocated memory in random order, thereby making it difficult to retrieve/read the values in the order of their declaration. Variables in a program are allocated memory in random order, thereby making it difficult to retrieve/read the values in the order of their declaration. List_name = [value1,value2,value3.....valuen] The following example shows how to use a List in Elm. Try this example in elm REPL − > myList1 = [10,20,30] [10,20,30] : List number > myList2 = ["hello","world"] ["hello","world"] : List String If we try adding values of different types into a list, the compiler will throw a type mismatch error. This is shown below. > myList = [1,"hello"] -- TYPE MISMATCH --------------------------------------------- repl-temp-000.elm The 1st and 2nd entries in this list are different types of values. 4| [1,"hello"] ^^^^^^^ The 1st entry has this type: number But the 2nd is: String Following table shows the common operations on a List − This function returns true if a list is empty. List.isEmpty list_name To check the signature of function, type the following in elm REPL − > List.isEmpty <function> : List a -> Bool > List.isEmpty <function> : List a -> Bool > List.isEmpty [10,20,30] False : Bool This function reverses the list. List.reverse list_name To check the signature of function, type the following in elm REPL − > List.reverse <function> : List a -> List a > List.reverse [10,20,30] [30,20,10] : List number This function returns the length of a list. List.length list_name To check the signature of function, type the following in elm REPL − > List.length <function> : List a -> Int > List.length [10,20,30] 3 : Int This function returns the maximum element in a non-empty list. List.maximum list_name To check the signature of function, type the following in elm REPL − > List.maximum <function> : List comparable -> Maybe.Maybe comparable > List.maximum [10,20,30] Just 30 : Maybe.Maybe number > List.maximum [] Nothing : Maybe.Maybe comparable This function returns the minimum element in a non-empty list. List.minimum list_name To check the signature of function, type the following in elm REPL − > List.minimum <function> : List comparable -> Maybe.Maybe comparable > List.minimum [10,20,30] Just 10 : Maybe.Maybe number This function returns the sum of all elements in a list. List.sum list_name To check the signature of function, type the following in elm REPL − > List.sum <function> : List number -> number > List.sum [10,20,30] 60 : number This function returns the product of all elements in a list. List.product list_name To check the signature of function, type the following in elm REPL − <function> : List number -> number List.product [10,20,30] 6000 : number This function sorts values from lowest to highest in a list. List.sort list_name To check the signature of function, type the following in elm REPL − > List.sort <function> : List comparable -> List comparable > List.sort [10,20,30] [10,20,30] : List number This function concatenates a bunch of lists into a single list. List.concat [ [list_name1],[list_name2],[list_name3],.....[list_nameN] ] To check the signature of function, type the following in elm REPL − > List.concat <function> : List (List a) -> List a > List.concat [[10,20], [30,40],[50,60]] [10,20,30,40,50,60] : List number This function puts two lists together. List.append [list_name1] [list_name2] To check the signature of function, type the following in elm REPL − > List.append <function> : List a -> List a -> List a > List.append [10,20] [30,40] [10,20,30,40] : List number The ++ operator can also be used to append a list to another. This is shown in the example below − > [10.1,20.2] ++ [30.3,40.4] [10.1,20.2,30.3,40.4] : List Float This function creates a list of numbers, every element increasing by one. The lowest and the highest number that should be in the list is passed to the function. List.range start_range end_range To check the signature of function, type the following in elm REPL − > List.range <function> : Int -> Int -> List Int > List.range 1 10 [1,2,3,4,5,6,7,8,9,10] : List Int This function filters a set of values from input list. Keep only the values that pass the test. List.filter test_function input_list To check the signature of function, type the following in elm REPL − > List.filter <function> : (a -> Bool) -> List a -> List a Following example filters all even numbers from an input list > List.filter (\n -> n%2==0) [10,20,30,55] [10,20,30] : List Int This function returns the first element from input list. List.head input_list To check the signature of function, type the following in elm REPL − > List.head <function> : List a -> Maybe.Maybe a > List.head [10,20,30,40] Just 10 : Maybe.Maybe number > List.head [] Nothing : Maybe.Maybe a This function returns all elements after first in the list. List.tail input_list To check the signature of function, type the following in elm REPL − > List.tail <function> : List a -> Maybe.Maybe (List a) > List.tail [10,20,30,40,50] Just [20,30,40,50] : Maybe.Maybe (List number) > List.tail [10] Just [] : Maybe.Maybe (List number) > List.tail [] Nothing : Maybe.Maybe (List a) The cons operator ( :: ) adds an element to the front of a list. > 10::[20,30,40,50] [10,20,30,40,50] : List number The new element to be added and the data-type of the values in the list must match. The compiler throws an error if the data types do not match. > [1,2,3,4]::[5,6,7,8] -- TYPE MISMATCH --------------------------------- ------------ repl-temp-000.elm The right side of (::) is causing a type mismatch. 3| [1,2,3,4]::[5,6,7,8] ^^^^^^^^^ (::) is expecting the right side to be a: List (List number) But the right side is: List number Hint: With operators like (::) I always check the left side first. If it seems fine, I assume it is correct and check the right side. So the problem may be in how the left and right arguments interact. Let us check if lists are immutable in Elm. The first list myList when concatenated with value 1 creates a new list and is returned to myListCopy. Therefore, if we display initial list, its values will not be changed. > myList = [10,20,30] [10,20,30] : List number > myListCopy = 1::myList [1,10,20,30] : List number > myList [10,20,30] : List number >myList == myListCopy False : Bool 27 Lectures 2.5 hours Ahmed Elfakharany Print Add Notes Bookmark this page
[ { "code": null, "e": 1969, "s": 1880, "text": "The List, Tuples and Record data structures can be used to store a collection of values." }, { "code": null, "e": 2016, "s": 1969, "text": "This chapter discusses how to use List in Elm." }, { "code": null, "e": 2118, "s": 2016, "text": "A List is a collection of homogeneous values. The values in a list must all be of the same data type." }, { "code": null, "e": 2193, "s": 2118, "text": "Consider the following limitations while using variables to store values −" }, { "code": null, "e": 2491, "s": 2193, "text": "Variables are scalar in nature. In other words, at the time of declaration a variable can hold only one value. This means that to store n values in a program, n variable declarations will be needed. Hence, the use of variables is not feasible when one needs to store a larger collection of values." }, { "code": null, "e": 2789, "s": 2491, "text": "Variables are scalar in nature. In other words, at the time of declaration a variable can hold only one value. This means that to store n values in a program, n variable declarations will be needed. Hence, the use of variables is not feasible when one needs to store a larger collection of values." }, { "code": null, "e": 2941, "s": 2789, "text": "Variables in a program are allocated memory in random order, thereby making it difficult to retrieve/read the values in the order of their declaration." }, { "code": null, "e": 3093, "s": 2941, "text": "Variables in a program are allocated memory in random order, thereby making it difficult to retrieve/read the values in the order of their declaration." }, { "code": null, "e": 3140, "s": 3093, "text": "List_name = [value1,value2,value3.....valuen]\n" }, { "code": null, "e": 3225, "s": 3140, "text": "The following example shows how to use a List in Elm. Try this example in elm REPL −" }, { "code": null, "e": 3335, "s": 3225, "text": "> myList1 = [10,20,30]\n[10,20,30] : List number\n> myList2 = [\"hello\",\"world\"]\n[\"hello\",\"world\"] : List String" }, { "code": null, "e": 3459, "s": 3335, "text": "If we try adding values of different types into a list, the compiler will throw a type mismatch error. This is shown below." }, { "code": null, "e": 3723, "s": 3459, "text": "> myList = [1,\"hello\"]\n-- TYPE MISMATCH \n--------------------------------------------- \nrepl-temp-000.elm\n\nThe 1st and 2nd entries in this list are different types of values.\n\n4| [1,\"hello\"]\n^^^^^^^\nThe 1st entry has this type:\n number\nBut the 2nd is:\n String" }, { "code": null, "e": 3779, "s": 3723, "text": "Following table shows the common operations on a List −" }, { "code": null, "e": 3826, "s": 3779, "text": "This function returns true if a list is empty." }, { "code": null, "e": 3850, "s": 3826, "text": "List.isEmpty list_name\n" }, { "code": null, "e": 3919, "s": 3850, "text": "To check the signature of function, type the following in elm REPL −" }, { "code": null, "e": 3963, "s": 3919, "text": "> List.isEmpty\n<function> : List a -> Bool\n" }, { "code": null, "e": 4046, "s": 3963, "text": "> List.isEmpty\n<function> : List a -> Bool\n\n> List.isEmpty [10,20,30]\nFalse : Bool" }, { "code": null, "e": 4079, "s": 4046, "text": "This function reverses the list." }, { "code": null, "e": 4103, "s": 4079, "text": "List.reverse list_name\n" }, { "code": null, "e": 4172, "s": 4103, "text": "To check the signature of function, type the following in elm REPL −" }, { "code": null, "e": 4218, "s": 4172, "text": "> List.reverse\n<function> : List a -> List a\n" }, { "code": null, "e": 4269, "s": 4218, "text": "> List.reverse [10,20,30]\n[30,20,10] : List number" }, { "code": null, "e": 4313, "s": 4269, "text": "This function returns the length of a list." }, { "code": null, "e": 4336, "s": 4313, "text": "List.length list_name\n" }, { "code": null, "e": 4405, "s": 4336, "text": "To check the signature of function, type the following in elm REPL −" }, { "code": null, "e": 4447, "s": 4405, "text": "> List.length\n<function> : List a -> Int\n" }, { "code": null, "e": 4480, "s": 4447, "text": "> List.length [10,20,30]\n3 : Int" }, { "code": null, "e": 4543, "s": 4480, "text": "This function returns the maximum element in a non-empty list." }, { "code": null, "e": 4567, "s": 4543, "text": "List.maximum list_name\n" }, { "code": null, "e": 4636, "s": 4567, "text": "To check the signature of function, type the following in elm REPL −" }, { "code": null, "e": 4707, "s": 4636, "text": "> List.maximum\n<function> : List comparable -> Maybe.Maybe comparable\n" }, { "code": null, "e": 4813, "s": 4707, "text": "> List.maximum [10,20,30]\nJust 30 : Maybe.Maybe number\n> List.maximum []\nNothing : Maybe.Maybe comparable" }, { "code": null, "e": 4876, "s": 4813, "text": "This function returns the minimum element in a non-empty list." }, { "code": null, "e": 4900, "s": 4876, "text": "List.minimum list_name\n" }, { "code": null, "e": 4969, "s": 4900, "text": "To check the signature of function, type the following in elm REPL −" }, { "code": null, "e": 5040, "s": 4969, "text": "> List.minimum\n<function> : List comparable -> Maybe.Maybe comparable\n" }, { "code": null, "e": 5095, "s": 5040, "text": "> List.minimum [10,20,30]\nJust 10 : Maybe.Maybe number" }, { "code": null, "e": 5152, "s": 5095, "text": "This function returns the sum of all elements in a list." }, { "code": null, "e": 5172, "s": 5152, "text": "List.sum list_name\n" }, { "code": null, "e": 5241, "s": 5172, "text": "To check the signature of function, type the following in elm REPL −" }, { "code": null, "e": 5288, "s": 5241, "text": "> List.sum\n<function> : List number -> number\n" }, { "code": null, "e": 5322, "s": 5288, "text": "> List.sum [10,20,30]\n60 : number" }, { "code": null, "e": 5383, "s": 5322, "text": "This function returns the product of all elements in a list." }, { "code": null, "e": 5407, "s": 5383, "text": "List.product list_name\n" }, { "code": null, "e": 5476, "s": 5407, "text": "To check the signature of function, type the following in elm REPL −" }, { "code": null, "e": 5514, "s": 5476, "text": "<function> : List number -> number\n" }, { "code": null, "e": 5552, "s": 5514, "text": "List.product [10,20,30]\n6000 : number" }, { "code": null, "e": 5613, "s": 5552, "text": "This function sorts values from lowest to highest in a list." }, { "code": null, "e": 5634, "s": 5613, "text": "List.sort list_name\n" }, { "code": null, "e": 5703, "s": 5634, "text": "To check the signature of function, type the following in elm REPL −" }, { "code": null, "e": 5764, "s": 5703, "text": "> List.sort\n<function> : List comparable -> List comparable\n" }, { "code": null, "e": 5812, "s": 5764, "text": "> List.sort [10,20,30]\n[10,20,30] : List number" }, { "code": null, "e": 5876, "s": 5812, "text": "This function concatenates a bunch of lists into a single list." }, { "code": null, "e": 5950, "s": 5876, "text": "List.concat [ [list_name1],[list_name2],[list_name3],.....[list_nameN] ]\n" }, { "code": null, "e": 6019, "s": 5950, "text": "To check the signature of function, type the following in elm REPL −" }, { "code": null, "e": 6071, "s": 6019, "text": "> List.concat\n<function> : List (List a) -> List a\n" }, { "code": null, "e": 6146, "s": 6071, "text": "> List.concat [[10,20], [30,40],[50,60]]\n[10,20,30,40,50,60] : List number" }, { "code": null, "e": 6185, "s": 6146, "text": "This function puts two lists together." }, { "code": null, "e": 6224, "s": 6185, "text": "List.append [list_name1] [list_name2]\n" }, { "code": null, "e": 6293, "s": 6224, "text": "To check the signature of function, type the following in elm REPL −" }, { "code": null, "e": 6348, "s": 6293, "text": "> List.append\n<function> : List a -> List a -> List a\n" }, { "code": null, "e": 6406, "s": 6348, "text": "> List.append [10,20] [30,40]\n[10,20,30,40] : List number" }, { "code": null, "e": 6505, "s": 6406, "text": "The ++ operator can also be used to append a list to another. This is shown in the example below −" }, { "code": null, "e": 6569, "s": 6505, "text": "> [10.1,20.2] ++ [30.3,40.4]\n[10.1,20.2,30.3,40.4] : List Float" }, { "code": null, "e": 6731, "s": 6569, "text": "This function creates a list of numbers, every element increasing by one. The lowest and the highest number that should be in the list is passed to the function." }, { "code": null, "e": 6765, "s": 6731, "text": "List.range start_range end_range\n" }, { "code": null, "e": 6834, "s": 6765, "text": "To check the signature of function, type the following in elm REPL −" }, { "code": null, "e": 6884, "s": 6834, "text": "> List.range\n<function> : Int -> Int -> List Int\n" }, { "code": null, "e": 6936, "s": 6884, "text": "> List.range 1 10\n[1,2,3,4,5,6,7,8,9,10] : List Int" }, { "code": null, "e": 7032, "s": 6936, "text": "This function filters a set of values from input list. Keep only the values that pass the test." }, { "code": null, "e": 7070, "s": 7032, "text": "List.filter test_function input_list\n" }, { "code": null, "e": 7139, "s": 7070, "text": "To check the signature of function, type the following in elm REPL −" }, { "code": null, "e": 7199, "s": 7139, "text": "> List.filter\n<function> : (a -> Bool) -> List a -> List a\n" }, { "code": null, "e": 7261, "s": 7199, "text": "Following example filters all even numbers from an input list" }, { "code": null, "e": 7326, "s": 7261, "text": "> List.filter (\\n -> n%2==0) [10,20,30,55]\n[10,20,30] : List Int" }, { "code": null, "e": 7383, "s": 7326, "text": "This function returns the first element from input list." }, { "code": null, "e": 7405, "s": 7383, "text": "List.head input_list\n" }, { "code": null, "e": 7474, "s": 7405, "text": "To check the signature of function, type the following in elm REPL −" }, { "code": null, "e": 7524, "s": 7474, "text": "> List.head\n<function> : List a -> Maybe.Maybe a\n" }, { "code": null, "e": 7618, "s": 7524, "text": "> List.head [10,20,30,40]\nJust 10 : Maybe.Maybe number\n> List.head []\nNothing : Maybe.Maybe a" }, { "code": null, "e": 7678, "s": 7618, "text": "This function returns all elements after first in the list." }, { "code": null, "e": 7700, "s": 7678, "text": "List.tail input_list\n" }, { "code": null, "e": 7769, "s": 7700, "text": "To check the signature of function, type the following in elm REPL −" }, { "code": null, "e": 7826, "s": 7769, "text": "> List.tail\n<function> : List a -> Maybe.Maybe (List a)\n" }, { "code": null, "e": 8001, "s": 7826, "text": "> List.tail [10,20,30,40,50]\nJust [20,30,40,50] : Maybe.Maybe (List number)\n> List.tail [10]\nJust [] : Maybe.Maybe (List number)\n> List.tail []\nNothing : Maybe.Maybe (List a)" }, { "code": null, "e": 8066, "s": 8001, "text": "The cons operator ( :: ) adds an element to the front of a list." }, { "code": null, "e": 8117, "s": 8066, "text": "> 10::[20,30,40,50]\n[10,20,30,40,50] : List number" }, { "code": null, "e": 8262, "s": 8117, "text": "The new element to be added and the data-type of the values in the list must match. The compiler throws an error if the data types do not match." }, { "code": null, "e": 8768, "s": 8262, "text": "> [1,2,3,4]::[5,6,7,8]\n-- TYPE MISMATCH ---------------------------------\n------------ repl-temp-000.elm\n\nThe right side of (::) is causing a type mismatch.\n\n3| [1,2,3,4]::[5,6,7,8]\n\t\t\t ^^^^^^^^^\n(::) is expecting the right side to be a:\n\n List (List number)\n\nBut the right side is:\n\n List number\nHint: With operators like (::) I always check the left side first. If it seems fine, \nI assume it is correct and check the right side. So the \nproblem may be in how the left and right arguments interact." }, { "code": null, "e": 8986, "s": 8768, "text": "Let us check if lists are immutable in Elm. The first list myList when concatenated with value 1 creates a new list and is returned to myListCopy. Therefore, if we display initial list, its values will not be changed." }, { "code": null, "e": 9154, "s": 8986, "text": "> myList = [10,20,30]\n[10,20,30] : List number\n> myListCopy = 1::myList\n[1,10,20,30] : List number\n> myList\n[10,20,30] : List number\n>myList == myListCopy\nFalse : Bool" }, { "code": null, "e": 9189, "s": 9154, "text": "\n 27 Lectures \n 2.5 hours \n" }, { "code": null, "e": 9208, "s": 9189, "text": " Ahmed Elfakharany" }, { "code": null, "e": 9215, "s": 9208, "text": " Print" }, { "code": null, "e": 9226, "s": 9215, "text": " Add Notes" } ]
How to change Entry.get() into an integer in Tkinter?
The Entry widget in Tkinter is generally used to accept one-line input in the text field. We can get the output from the Entry widget using .get() method. However, the .get() method returns the output in string format. For example, if the user types an integer number in the Entry widget, it gets converted to a string. To change the type of the Entry input into an integer, we can cast the string to an integer. In this example, we have shown how to calculate the sum while taking an integer input from the user. # Import the required libraries from tkinter import * # Create an instance of tkinter frame or window win=Tk() # Set the size of the tkinter window win.geometry("700x350") def cal_sum(): t1=int(a.get()) t2=int(b.get()) sum=t1+t2 label.config(text=sum) # Create an Entry widget Label(win, text="Enter First Number", font=('Calibri 10')).pack() a=Entry(win, width=35) a.pack() Label(win, text="Enter Second Number", font=('Calibri 10')).pack() b=Entry(win, width=35) b.pack() label=Label(win, text="Total Sum : ", font=('Calibri 15')) label.pack(pady=20) Button(win, text="Calculate Sum", command=cal_sum).pack() win.mainloop()
[ { "code": null, "e": 1475, "s": 1062, "text": "The Entry widget in Tkinter is generally used to accept one-line input in the text field. We can get the output from the Entry widget using .get() method. However, the .get() method returns the output in string format. For example, if the user types an integer number in the Entry widget, it gets converted to a string. To change the type of the Entry input into an integer, we can cast the string to an integer." }, { "code": null, "e": 1576, "s": 1475, "text": "In this example, we have shown how to calculate the sum while taking an integer input from the user." }, { "code": null, "e": 2221, "s": 1576, "text": "# Import the required libraries\nfrom tkinter import *\n\n# Create an instance of tkinter frame or window\nwin=Tk()\n\n# Set the size of the tkinter window\nwin.geometry(\"700x350\")\n\ndef cal_sum():\n t1=int(a.get())\n t2=int(b.get())\n sum=t1+t2\n label.config(text=sum)\n\n# Create an Entry widget\nLabel(win, text=\"Enter First Number\", font=('Calibri 10')).pack()\na=Entry(win, width=35)\na.pack()\nLabel(win, text=\"Enter Second Number\", font=('Calibri 10')).pack()\nb=Entry(win, width=35)\nb.pack()\n\nlabel=Label(win, text=\"Total Sum : \", font=('Calibri 15'))\nlabel.pack(pady=20)\n\nButton(win, text=\"Calculate Sum\", command=cal_sum).pack()\n\nwin.mainloop()" } ]
Collect.js | diff() Function - GeeksforGeeks
11 Jun, 2020 The diff() function compares the main collection against the given collection and returns the values which are in original collection but not in the given collection. In JavaScript, the array is first converted to a collection and then the function is applied to the collection. Syntax: data.diff(collection) Parameters: This function accept a single parameter as mentioned above and described below: collection: Hold the collection that will be compared with the main collection. Return Value: Returns a new collection with difference between collection items. Below examples illustrate the diff() function in collect.jsExample 1: Here in this example, we take a collection and then using the diff() function and return the value not in the new collection. Javascript // It is used to import collect.js library const collect = require('collect.js'); const collection = collect([1, 2, 3, 4, 5 ,6]);console.log(collection.diff([1, 2, 5])); Output: Collection { items: [ 3, 4, 6 ] } Example 2: There is one thing to notice that this function holds a collection, compare with the main collection but only return only those items that are extra in the main collection. Javascript // It is used to import collect.js libraryconst collect = require('collect.js'); const col1 = [1, 2, 3, 4];const col2 = [3, 4, 5, 6]; const x = collect(col1);const y = collect(col2); const difference = x.diff(y); console.log(difference.all()); Output: [ 1 , 2] Reference: https://collect.js.org/api/count.html Collect.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request Remove elements from a JavaScript Array How to get character array from string in JavaScript? How to filter object array based on attributes? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 25300, "s": 25272, "text": "\n11 Jun, 2020" }, { "code": null, "e": 25579, "s": 25300, "text": "The diff() function compares the main collection against the given collection and returns the values which are in original collection but not in the given collection. In JavaScript, the array is first converted to a collection and then the function is applied to the collection." }, { "code": null, "e": 25588, "s": 25579, "text": "Syntax: " }, { "code": null, "e": 25611, "s": 25588, "text": "data.diff(collection)\n" }, { "code": null, "e": 25703, "s": 25611, "text": "Parameters: This function accept a single parameter as mentioned above and described below:" }, { "code": null, "e": 25783, "s": 25703, "text": "collection: Hold the collection that will be compared with the main collection." }, { "code": null, "e": 25866, "s": 25783, "text": "Return Value: Returns a new collection with difference between collection items. " }, { "code": null, "e": 26062, "s": 25866, "text": "Below examples illustrate the diff() function in collect.jsExample 1: Here in this example, we take a collection and then using the diff() function and return the value not in the new collection." }, { "code": null, "e": 26073, "s": 26062, "text": "Javascript" }, { "code": "// It is used to import collect.js library const collect = require('collect.js'); const collection = collect([1, 2, 3, 4, 5 ,6]);console.log(collection.diff([1, 2, 5]));", "e": 26244, "s": 26073, "text": null }, { "code": null, "e": 26253, "s": 26244, "text": " Output:" }, { "code": null, "e": 26288, "s": 26253, "text": "Collection { items: [ 3, 4, 6 ] }\n" }, { "code": null, "e": 26472, "s": 26288, "text": "Example 2: There is one thing to notice that this function holds a collection, compare with the main collection but only return only those items that are extra in the main collection." }, { "code": null, "e": 26483, "s": 26472, "text": "Javascript" }, { "code": "// It is used to import collect.js libraryconst collect = require('collect.js'); const col1 = [1, 2, 3, 4];const col2 = [3, 4, 5, 6]; const x = collect(col1);const y = collect(col2); const difference = x.diff(y); console.log(difference.all());", "e": 26730, "s": 26483, "text": null }, { "code": null, "e": 26738, "s": 26730, "text": "Output:" }, { "code": null, "e": 26748, "s": 26738, "text": "[ 1 , 2]\n" }, { "code": null, "e": 26797, "s": 26748, "text": "Reference: https://collect.js.org/api/count.html" }, { "code": null, "e": 26808, "s": 26797, "text": "Collect.js" }, { "code": null, "e": 26819, "s": 26808, "text": "JavaScript" }, { "code": null, "e": 26836, "s": 26819, "text": "Web Technologies" }, { "code": null, "e": 26934, "s": 26836, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26995, "s": 26934, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27036, "s": 26995, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 27076, "s": 27036, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27130, "s": 27076, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 27178, "s": 27130, "text": "How to filter object array based on attributes?" }, { "code": null, "e": 27220, "s": 27178, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 27253, "s": 27220, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27296, "s": 27253, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27358, "s": 27296, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
How to convert Java Array to Iterable?
To make an array iterable either you need to convert it to a stream or as a list using the asList() or stream() methods respectively. Then you can get an iterator for these objects using the iterator() method. Live Demo import java.util.Arrays; import java.util.Iterator; public class ArrayToIterable { public static void main(String args[]){ Integer[] myArray = {897, 56, 78, 90, 12, 123, 75}; Iterator<Integer> iterator = Arrays.stream(myArray).iterator(); while(iterator.hasNext()) { System.out.println(iterator.next()); } } } 897 56 78 90 12 123 75 As mentioned above, you can also convert an array to list and get an iterator from that list using the iterator() method. Integer[] myArray = {897, 56, 78, 90, 12, 123, 75}; Iterator<Integer> iterator = Arrays.asList(myArray).iterator(); //Iterator<Integer> iterator = Arrays.stream(myArray).iterator(); while(iterator.hasNext()) { System.out.println(iterator.next()); }
[ { "code": null, "e": 1272, "s": 1062, "text": "To make an array iterable either you need to convert it to a stream or as a list using the asList() or stream() methods respectively. Then you can get an iterator for these objects using the iterator() method." }, { "code": null, "e": 1282, "s": 1272, "text": "Live Demo" }, { "code": null, "e": 1632, "s": 1282, "text": "import java.util.Arrays;\nimport java.util.Iterator;\n\npublic class ArrayToIterable {\n public static void main(String args[]){\n Integer[] myArray = {897, 56, 78, 90, 12, 123, 75};\n Iterator<Integer> iterator = Arrays.stream(myArray).iterator();\n while(iterator.hasNext()) {\n System.out.println(iterator.next());\n }\n }\n}" }, { "code": null, "e": 1655, "s": 1632, "text": "897\n56\n78\n90\n12\n123\n75" }, { "code": null, "e": 1777, "s": 1655, "text": "As mentioned above, you can also convert an array to list and get an iterator from that list using the iterator() method." }, { "code": null, "e": 2030, "s": 1777, "text": "Integer[] myArray = {897, 56, 78, 90, 12, 123, 75};\nIterator<Integer> iterator = Arrays.asList(myArray).iterator();\n\n//Iterator<Integer> iterator = Arrays.stream(myArray).iterator();\nwhile(iterator.hasNext()) {\n System.out.println(iterator.next());\n}" } ]
How to hide ticks label in Python but keep the ticks in place?
To hide ticks label and keep the ticks in place, we can take the following steps − Initialize x1 and x10 variables to get the x and y points, using numpy. Initialize x1 and x10 variables to get the x and y points, using numpy. Plot points x and y using the plot() method. Plot points x and y using the plot() method. Using xticks method, get or set the current tick locations and labels of the X-axis. Pass no arguments to return the current values without modifying them. So, pass the range(x1, x10) to get ticks but pass an empty list to hide the labels. Using xticks method, get or set the current tick locations and labels of the X-axis. Pass no arguments to return the current values without modifying them. So, pass the range(x1, x10) to get ticks but pass an empty list to hide the labels. To display the figure, use the show() method. To display the figure, use the show() method. import numpy as np from matplotlib import pyplot as plt plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True x1 = 1 x10 = 10 x = np.linspace(1, 10, 100) y = np.log(x) plt.plot(x, y) plt.xticks(ticks=range(x1, x10), labels=[]) plt.show()
[ { "code": null, "e": 1145, "s": 1062, "text": "To hide ticks label and keep the ticks in place, we can take the following steps −" }, { "code": null, "e": 1217, "s": 1145, "text": "Initialize x1 and x10 variables to get the x and y points, using numpy." }, { "code": null, "e": 1289, "s": 1217, "text": "Initialize x1 and x10 variables to get the x and y points, using numpy." }, { "code": null, "e": 1334, "s": 1289, "text": "Plot points x and y using the plot() method." }, { "code": null, "e": 1379, "s": 1334, "text": "Plot points x and y using the plot() method." }, { "code": null, "e": 1619, "s": 1379, "text": "Using xticks method, get or set the current tick locations and labels of the X-axis. Pass no arguments to return the current values without modifying them. So, pass the range(x1, x10) to get ticks but pass an empty list to hide the labels." }, { "code": null, "e": 1859, "s": 1619, "text": "Using xticks method, get or set the current tick locations and labels of the X-axis. Pass no arguments to return the current values without modifying them. So, pass the range(x1, x10) to get ticks but pass an empty list to hide the labels." }, { "code": null, "e": 1905, "s": 1859, "text": "To display the figure, use the show() method." }, { "code": null, "e": 1951, "s": 1905, "text": "To display the figure, use the show() method." }, { "code": null, "e": 2222, "s": 1951, "text": "import numpy as np\nfrom matplotlib import pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nx1 = 1\nx10 = 10\nx = np.linspace(1, 10, 100)\ny = np.log(x)\nplt.plot(x, y)\nplt.xticks(ticks=range(x1, x10), labels=[])\nplt.show()" } ]
Bringing More Humans into the AI Lifecycle | by Daniel Vila Suero | Towards Data Science
Starting AI projects has become easier than ever before. Initiatives like the Hugging Face Hub or Papers with Code give developers instant access to the latest research. The rise of transfer learning and AutoML methods means you don’t need to spend months to train a model for your project. However, in my experience, this is only (a small) part of the story. Almost everyone dealing with “applied” AI projects would agree that things like data collection and management, or model serving and monitoring are far more crucial and difficult to get right. While these things are getting easier too, the task of managing data and models still feels like patching tools and processes together. And when we talk about tools and processes, we are ultimately talking about people, we, the humans using the tools and trying to follow the processes. “We are human after all.Flesh uncovered after all” «Human after all» by Daft Punk, 2005. A lot has been written about the so-called ML/data science project life cycles, but not so much about the interrelationship between tools, data, models, and people inside such “life cycles”. Let’s take a look at a “simplified” life cycle: The above picture shows a sequence of activities and roles involved in the process: Data collection and labeling: typical roles involved in this activity are data engineers, data scientists, business and subject matter experts, and even crowd-workers for data-hungry projects. Model development and experimentation: the central role here is data scientist. Model testing: typical roles are ML engineers and data scientists. Model deployment: the roles here are ML and DevOps engineers. Monitoring and observability: the main roles are again ML and DevOps engineers. So far so good, we have processes and we have roles. But there are two key ingredients we are missing: the “life” and the “cycle”. Data and models are not static, they are “living” things, and training/testing/serving models are not one-off activities, they form cycles. “It’s a modern life but it reads better on TVWhoa. It’s a modern life” «Modern Life» by Devo, 1981 Moving into the production use of ML models, things can start to get complicated. Several key questions emerge in practice, such as: Can data scientists easily go back to business and subject matter experts to collect more data? Can we easily share “live” predictions with experts for collecting more training examples? Can we measure production accuracy without continuously moving production data to the data collection and labeling phase? Can we seamlessly collect feedback directly from end-users? All of the above questions share an underlying theme: the friction between roles, tools, and processes to manage data for AI-based solutions. At Recognai, we’ve suffered from these frictions since we started working on enterprise NLP projects with clients four years ago. We’ve developed internal and open-source tools to help us better support our clients. But there’s something we’ve been building, rebuilding, and rethinking this whole time: a tool for connecting the models, the data, and the people involved in projects so they can all contribute to improving data at any step of the process. After many iterations around this idea, we are finally happy to share Rubrix, a free and open-source, human-in-the-loop1 tool for AI projects. Rubrix is: A Python library enables data scientists, data engineers, and ML engineers to build bridges between data, models, and users, for data collection, model development, testing, deployment, and monitoring. A web app for exploring, curating, and labeling data throughout projects' workflows. An open API for storing, retrieving, and searching human annotations and model predictions. Rubrix can be installed with pip: pip install rubrix The only non-Python dependency is Elasticsearch. You can launch it using Docker and docker-compose, or use an existing Elasticsearch instance. For a more detailed setup guide, check Rubrix’s guide, but if you are eager to try it out and are familiar with Docker: Download the docker-compose.yml and launch Rubrix server and Elasticsearch: mkdir rubrix && cd rubrixwget -O docker-compose.yml https://git.io/rb-docker && docker-compose up Now, before getting into more details, let’s see Rubrix in action! The following code loads a zero-shot text classifier from the Hugging Face hub, the AG News dataset, a well-known benchmark for text classification, and uses Rubrix for storing the predictions as well as the human-annotated labels: And that’s it! you and other members of your team can now explore how this classifier works on an unseen dataset: Exploring model predictions against a labeled dataset, it’s only one of the many things you can do with Rubrix, because in “real life” sometimes you don’t have labels to start with, or you don’t have a model, or you just want to see your data while you start training your first models. Model development has been one of the very first uses Rubrix was designed for. This tweet from Andrej Karpathy summarizes the whole point of looking at your data as early as possible. Another great inspiration about the importance of curating data for AI is Vincent D. Warmerdam, Research Advocate at Rasa and creator of the amazing calmcode.io and libraries like human-learn: To close our first example with the zero-shot classifier, let’s see another interesting use case for Rubrix: model monitoring and observability. If you are interested in model monitoring I highly recommend you this article from Ben Lorica and Paco Nathan. As I mentioned above, Rubrix is tightly integrated with the Elasticsearch stack. Thanks to Kibana’s ease of use and Rubrix’s data model, it’s a breeze to build custom dashboards on top of Rubrix datasets. This is how a real-time dashboard looks like while we log our zero-shot predictions inside a Jupyter notebook: Coming back to why we built Rubrix, let’s introduce Rubrix guiding principles: For data scientists, this principle means that Rubrix doesn’t ask them to leave the tools they love such as Jupyter Lab or Colab, to extend any classes or wrap their models around any new abstraction. For data and ML engineers, this means Rubrix offers simple but efficient methods for reading and writing (a lot of) data. We’ve designed Rubrix to be easy to use in automation scripts. For business and subject matter experts, this means a clean and easy-to-use UI where they feel in control and where they can transparently inspect data and model predictions. Another use case we’re excited about to improve transparency and trust is model interpretability in Rubrix paired with Kibana’s dashboards. Here’s an example of a Rubrix Dataset, which includes token-level attributions for a sentiment classifier extracted with the Integrated Gradients method, using Transformers Interpret, and the captum.ai library. Rubrix provides an agnostic data model so you can use other libraries and techniques like Lime. And here’s the code to log predictions and token attributions: The data model fits this short description: A Dataset is a collection of Records whose shape is defined by a Task (for example Text Classification). A Snapshot is a stored version of a Dataset to be used for reproducibility and automation pipelines. A Record is defined by its Inputs and optionally contains Annotations, Predictions, and Metadata. Annotations are typically the ground-truth defined by a human Agent for a given Task and Inputs. Predictions typically come from a machine Agent (for example the output of a text classifier). and into this little diagram: Let’s see how to create and log a Record for NER (Named Entity Recognition), a widely known NLP Task: The above code logs a NER example with the SONG and BAND tags using the rb.log method, which also creates a Dataset if it does not exist. Datasets are incremental and you can use rb.log for bulk logging large datasets (as we’ve seen on our monitoring example). This is how this record looks in the web app: Rubrix has simply two main methods to call: rb.log(records, name) to store records into a Rubrix Dataset. rb.load(name) to read records from a Rubrix Dataset into a Pandas Dataframe. To understand the kind of workflows these two methods enable, let’s see an example of loading a Rubrix Dataset for fine-tuning a pre-trained model. We’ll follow the guide “Fine-tuning a pre-trained model” from Hugging Face. The workflow is following: 1- We’ve used rb.log to create a Rubrix dataset with zero-shot predictions and we’ve spent some time using the Rubrix web-app annotation mode for manually labeling a few examples. It’s the same example as before, but we don’t have any prior labels in this case. 2- After spending some time with the annotation, we are ready to use rb.load and prepare our dataset for fine-tuning the model. Normally, we would split it into train, test, and validation, but let’s keep the example as straightforward as possible: 3- From this point on, it’s just regular fine-tuning with the Trainer API as described in the guide. Please note we are using distilbert-base-uncased instead of bert-base-cased: If this got you interested, you can: Read more about Rubrix’s data model and the Python API reference. Check our in-depth tutorial about using Rubrix together with 🤗 Transformers and Datasets. We’re living in exciting times with new libraries and tools being released every month. People feel comfortable with many tools for different things, such as data annotation, or model experiment tracking, and we want to embrace this diversity. Rubrix is not an all-or-nothing tool or a platform, our goal is to enable users to build novel workflows and combine Rubrix with their tools of choice. That’s why, besides the Python library and the web app, we’ve designed an open REST API for developers to build on. Also, to spur your imagination and creativity, check out Rubrix’s docs: A guide for integrating Rubrix into Streamlit apps, A tutorial for using Rubrix with Snorkel’s weak-supervision The Cookbook with code-snippets for using Rubrix with major NLP libraries such as our beloved spaCy, Flair, or Stanza from Stanford. A basic tutorial of active learning with scikit-learn and ModAL. As you might have noticed, I’ve been talking about AI projects but we’ve only seen examples of natural language processing. The reason is simple: natural language processing and knowledge graph use cases have been the original driver for Rubrix’s development at Recognai. However, Rubrix’s data model and architecture are designed to easily add new use cases and applications. Rubrix covers a wide range of NLP and knowledge graph applications with only two supported tasks, Text Classification, and Token Classification. For knowledge graph use cases, feel free to check the node classification tutorial using the amazing kglab and PyTorch Geometric libraries with Rubrix. Immediate use cases we envision are text2text, which will cover many other NLP applications such as text summarization or machine translation; computer vision tasks such as Image Classification; and speech recognition tasks such as speech2text. But before this, we want to hear your voice. This is why we are excited to announce Rubrix so you can be part of an open and friendly community and drive what comes next. If you want to join the Rubrix community or talk about your immediate and envisioned applications, drop us a message on Rubrix’s Github’s Discussion forum. “I call this numberFor a data dateI don’t know what to doI need a rendez-vous” «Computer love» by Kraftwerk, 1981 Thanks to Paco Nathan, Amélie Viallet, David Carreto, Ignacio Talavera, and Francisco Aranda for their great help and suggestions for improving this article. If you are not familiar with the concept of human-in-the-loop, I highly recommend you this article from Stanford’s Institute for Human-Centered AI. If you are not familiar with the concept of human-in-the-loop, I highly recommend you this article from Stanford’s Institute for Human-Centered AI.
[ { "code": null, "e": 532, "s": 172, "text": "Starting AI projects has become easier than ever before. Initiatives like the Hugging Face Hub or Papers with Code give developers instant access to the latest research. The rise of transfer learning and AutoML methods means you don’t need to spend months to train a model for your project. However, in my experience, this is only (a small) part of the story." }, { "code": null, "e": 1012, "s": 532, "text": "Almost everyone dealing with “applied” AI projects would agree that things like data collection and management, or model serving and monitoring are far more crucial and difficult to get right. While these things are getting easier too, the task of managing data and models still feels like patching tools and processes together. And when we talk about tools and processes, we are ultimately talking about people, we, the humans using the tools and trying to follow the processes." }, { "code": null, "e": 1063, "s": 1012, "text": "“We are human after all.Flesh uncovered after all”" }, { "code": null, "e": 1101, "s": 1063, "text": "«Human after all» by Daft Punk, 2005." }, { "code": null, "e": 1340, "s": 1101, "text": "A lot has been written about the so-called ML/data science project life cycles, but not so much about the interrelationship between tools, data, models, and people inside such “life cycles”. Let’s take a look at a “simplified” life cycle:" }, { "code": null, "e": 1424, "s": 1340, "text": "The above picture shows a sequence of activities and roles involved in the process:" }, { "code": null, "e": 1617, "s": 1424, "text": "Data collection and labeling: typical roles involved in this activity are data engineers, data scientists, business and subject matter experts, and even crowd-workers for data-hungry projects." }, { "code": null, "e": 1697, "s": 1617, "text": "Model development and experimentation: the central role here is data scientist." }, { "code": null, "e": 1764, "s": 1697, "text": "Model testing: typical roles are ML engineers and data scientists." }, { "code": null, "e": 1826, "s": 1764, "text": "Model deployment: the roles here are ML and DevOps engineers." }, { "code": null, "e": 1906, "s": 1826, "text": "Monitoring and observability: the main roles are again ML and DevOps engineers." }, { "code": null, "e": 2177, "s": 1906, "text": "So far so good, we have processes and we have roles. But there are two key ingredients we are missing: the “life” and the “cycle”. Data and models are not static, they are “living” things, and training/testing/serving models are not one-off activities, they form cycles." }, { "code": null, "e": 2248, "s": 2177, "text": "“It’s a modern life but it reads better on TVWhoa. It’s a modern life”" }, { "code": null, "e": 2276, "s": 2248, "text": "«Modern Life» by Devo, 1981" }, { "code": null, "e": 2409, "s": 2276, "text": "Moving into the production use of ML models, things can start to get complicated. Several key questions emerge in practice, such as:" }, { "code": null, "e": 2505, "s": 2409, "text": "Can data scientists easily go back to business and subject matter experts to collect more data?" }, { "code": null, "e": 2596, "s": 2505, "text": "Can we easily share “live” predictions with experts for collecting more training examples?" }, { "code": null, "e": 2718, "s": 2596, "text": "Can we measure production accuracy without continuously moving production data to the data collection and labeling phase?" }, { "code": null, "e": 2778, "s": 2718, "text": "Can we seamlessly collect feedback directly from end-users?" }, { "code": null, "e": 2920, "s": 2778, "text": "All of the above questions share an underlying theme: the friction between roles, tools, and processes to manage data for AI-based solutions." }, { "code": null, "e": 3376, "s": 2920, "text": "At Recognai, we’ve suffered from these frictions since we started working on enterprise NLP projects with clients four years ago. We’ve developed internal and open-source tools to help us better support our clients. But there’s something we’ve been building, rebuilding, and rethinking this whole time: a tool for connecting the models, the data, and the people involved in projects so they can all contribute to improving data at any step of the process." }, { "code": null, "e": 3519, "s": 3376, "text": "After many iterations around this idea, we are finally happy to share Rubrix, a free and open-source, human-in-the-loop1 tool for AI projects." }, { "code": null, "e": 3530, "s": 3519, "text": "Rubrix is:" }, { "code": null, "e": 3732, "s": 3530, "text": "A Python library enables data scientists, data engineers, and ML engineers to build bridges between data, models, and users, for data collection, model development, testing, deployment, and monitoring." }, { "code": null, "e": 3817, "s": 3732, "text": "A web app for exploring, curating, and labeling data throughout projects' workflows." }, { "code": null, "e": 3909, "s": 3817, "text": "An open API for storing, retrieving, and searching human annotations and model predictions." }, { "code": null, "e": 3943, "s": 3909, "text": "Rubrix can be installed with pip:" }, { "code": null, "e": 3962, "s": 3943, "text": "pip install rubrix" }, { "code": null, "e": 4105, "s": 3962, "text": "The only non-Python dependency is Elasticsearch. You can launch it using Docker and docker-compose, or use an existing Elasticsearch instance." }, { "code": null, "e": 4225, "s": 4105, "text": "For a more detailed setup guide, check Rubrix’s guide, but if you are eager to try it out and are familiar with Docker:" }, { "code": null, "e": 4301, "s": 4225, "text": "Download the docker-compose.yml and launch Rubrix server and Elasticsearch:" }, { "code": null, "e": 4399, "s": 4301, "text": "mkdir rubrix && cd rubrixwget -O docker-compose.yml https://git.io/rb-docker && docker-compose up" }, { "code": null, "e": 4466, "s": 4399, "text": "Now, before getting into more details, let’s see Rubrix in action!" }, { "code": null, "e": 4698, "s": 4466, "text": "The following code loads a zero-shot text classifier from the Hugging Face hub, the AG News dataset, a well-known benchmark for text classification, and uses Rubrix for storing the predictions as well as the human-annotated labels:" }, { "code": null, "e": 4812, "s": 4698, "text": "And that’s it! you and other members of your team can now explore how this classifier works on an unseen dataset:" }, { "code": null, "e": 5178, "s": 4812, "text": "Exploring model predictions against a labeled dataset, it’s only one of the many things you can do with Rubrix, because in “real life” sometimes you don’t have labels to start with, or you don’t have a model, or you just want to see your data while you start training your first models. Model development has been one of the very first uses Rubrix was designed for." }, { "code": null, "e": 5283, "s": 5178, "text": "This tweet from Andrej Karpathy summarizes the whole point of looking at your data as early as possible." }, { "code": null, "e": 5476, "s": 5283, "text": "Another great inspiration about the importance of curating data for AI is Vincent D. Warmerdam, Research Advocate at Rasa and creator of the amazing calmcode.io and libraries like human-learn:" }, { "code": null, "e": 6048, "s": 5476, "text": "To close our first example with the zero-shot classifier, let’s see another interesting use case for Rubrix: model monitoring and observability. If you are interested in model monitoring I highly recommend you this article from Ben Lorica and Paco Nathan. As I mentioned above, Rubrix is tightly integrated with the Elasticsearch stack. Thanks to Kibana’s ease of use and Rubrix’s data model, it’s a breeze to build custom dashboards on top of Rubrix datasets. This is how a real-time dashboard looks like while we log our zero-shot predictions inside a Jupyter notebook:" }, { "code": null, "e": 6127, "s": 6048, "text": "Coming back to why we built Rubrix, let’s introduce Rubrix guiding principles:" }, { "code": null, "e": 6328, "s": 6127, "text": "For data scientists, this principle means that Rubrix doesn’t ask them to leave the tools they love such as Jupyter Lab or Colab, to extend any classes or wrap their models around any new abstraction." }, { "code": null, "e": 6513, "s": 6328, "text": "For data and ML engineers, this means Rubrix offers simple but efficient methods for reading and writing (a lot of) data. We’ve designed Rubrix to be easy to use in automation scripts." }, { "code": null, "e": 6688, "s": 6513, "text": "For business and subject matter experts, this means a clean and easy-to-use UI where they feel in control and where they can transparently inspect data and model predictions." }, { "code": null, "e": 6828, "s": 6688, "text": "Another use case we’re excited about to improve transparency and trust is model interpretability in Rubrix paired with Kibana’s dashboards." }, { "code": null, "e": 7039, "s": 6828, "text": "Here’s an example of a Rubrix Dataset, which includes token-level attributions for a sentiment classifier extracted with the Integrated Gradients method, using Transformers Interpret, and the captum.ai library." }, { "code": null, "e": 7135, "s": 7039, "text": "Rubrix provides an agnostic data model so you can use other libraries and techniques like Lime." }, { "code": null, "e": 7198, "s": 7135, "text": "And here’s the code to log predictions and token attributions:" }, { "code": null, "e": 7242, "s": 7198, "text": "The data model fits this short description:" }, { "code": null, "e": 7347, "s": 7242, "text": "A Dataset is a collection of Records whose shape is defined by a Task (for example Text Classification)." }, { "code": null, "e": 7448, "s": 7347, "text": "A Snapshot is a stored version of a Dataset to be used for reproducibility and automation pipelines." }, { "code": null, "e": 7546, "s": 7448, "text": "A Record is defined by its Inputs and optionally contains Annotations, Predictions, and Metadata." }, { "code": null, "e": 7643, "s": 7546, "text": "Annotations are typically the ground-truth defined by a human Agent for a given Task and Inputs." }, { "code": null, "e": 7738, "s": 7643, "text": "Predictions typically come from a machine Agent (for example the output of a text classifier)." }, { "code": null, "e": 7768, "s": 7738, "text": "and into this little diagram:" }, { "code": null, "e": 7870, "s": 7768, "text": "Let’s see how to create and log a Record for NER (Named Entity Recognition), a widely known NLP Task:" }, { "code": null, "e": 8177, "s": 7870, "text": "The above code logs a NER example with the SONG and BAND tags using the rb.log method, which also creates a Dataset if it does not exist. Datasets are incremental and you can use rb.log for bulk logging large datasets (as we’ve seen on our monitoring example). This is how this record looks in the web app:" }, { "code": null, "e": 8221, "s": 8177, "text": "Rubrix has simply two main methods to call:" }, { "code": null, "e": 8283, "s": 8221, "text": "rb.log(records, name) to store records into a Rubrix Dataset." }, { "code": null, "e": 8360, "s": 8283, "text": "rb.load(name) to read records from a Rubrix Dataset into a Pandas Dataframe." }, { "code": null, "e": 8584, "s": 8360, "text": "To understand the kind of workflows these two methods enable, let’s see an example of loading a Rubrix Dataset for fine-tuning a pre-trained model. We’ll follow the guide “Fine-tuning a pre-trained model” from Hugging Face." }, { "code": null, "e": 8611, "s": 8584, "text": "The workflow is following:" }, { "code": null, "e": 8873, "s": 8611, "text": "1- We’ve used rb.log to create a Rubrix dataset with zero-shot predictions and we’ve spent some time using the Rubrix web-app annotation mode for manually labeling a few examples. It’s the same example as before, but we don’t have any prior labels in this case." }, { "code": null, "e": 9122, "s": 8873, "text": "2- After spending some time with the annotation, we are ready to use rb.load and prepare our dataset for fine-tuning the model. Normally, we would split it into train, test, and validation, but let’s keep the example as straightforward as possible:" }, { "code": null, "e": 9300, "s": 9122, "text": "3- From this point on, it’s just regular fine-tuning with the Trainer API as described in the guide. Please note we are using distilbert-base-uncased instead of bert-base-cased:" }, { "code": null, "e": 9337, "s": 9300, "text": "If this got you interested, you can:" }, { "code": null, "e": 9403, "s": 9337, "text": "Read more about Rubrix’s data model and the Python API reference." }, { "code": null, "e": 9493, "s": 9403, "text": "Check our in-depth tutorial about using Rubrix together with 🤗 Transformers and Datasets." }, { "code": null, "e": 9737, "s": 9493, "text": "We’re living in exciting times with new libraries and tools being released every month. People feel comfortable with many tools for different things, such as data annotation, or model experiment tracking, and we want to embrace this diversity." }, { "code": null, "e": 10005, "s": 9737, "text": "Rubrix is not an all-or-nothing tool or a platform, our goal is to enable users to build novel workflows and combine Rubrix with their tools of choice. That’s why, besides the Python library and the web app, we’ve designed an open REST API for developers to build on." }, { "code": null, "e": 10077, "s": 10005, "text": "Also, to spur your imagination and creativity, check out Rubrix’s docs:" }, { "code": null, "e": 10129, "s": 10077, "text": "A guide for integrating Rubrix into Streamlit apps," }, { "code": null, "e": 10189, "s": 10129, "text": "A tutorial for using Rubrix with Snorkel’s weak-supervision" }, { "code": null, "e": 10322, "s": 10189, "text": "The Cookbook with code-snippets for using Rubrix with major NLP libraries such as our beloved spaCy, Flair, or Stanza from Stanford." }, { "code": null, "e": 10387, "s": 10322, "text": "A basic tutorial of active learning with scikit-learn and ModAL." }, { "code": null, "e": 10909, "s": 10387, "text": "As you might have noticed, I’ve been talking about AI projects but we’ve only seen examples of natural language processing. The reason is simple: natural language processing and knowledge graph use cases have been the original driver for Rubrix’s development at Recognai. However, Rubrix’s data model and architecture are designed to easily add new use cases and applications. Rubrix covers a wide range of NLP and knowledge graph applications with only two supported tasks, Text Classification, and Token Classification." }, { "code": null, "e": 11061, "s": 10909, "text": "For knowledge graph use cases, feel free to check the node classification tutorial using the amazing kglab and PyTorch Geometric libraries with Rubrix." }, { "code": null, "e": 11351, "s": 11061, "text": "Immediate use cases we envision are text2text, which will cover many other NLP applications such as text summarization or machine translation; computer vision tasks such as Image Classification; and speech recognition tasks such as speech2text. But before this, we want to hear your voice." }, { "code": null, "e": 11477, "s": 11351, "text": "This is why we are excited to announce Rubrix so you can be part of an open and friendly community and drive what comes next." }, { "code": null, "e": 11633, "s": 11477, "text": "If you want to join the Rubrix community or talk about your immediate and envisioned applications, drop us a message on Rubrix’s Github’s Discussion forum." }, { "code": null, "e": 11712, "s": 11633, "text": "“I call this numberFor a data dateI don’t know what to doI need a rendez-vous”" }, { "code": null, "e": 11747, "s": 11712, "text": "«Computer love» by Kraftwerk, 1981" }, { "code": null, "e": 11906, "s": 11747, "text": "Thanks to Paco Nathan, Amélie Viallet, David Carreto, Ignacio Talavera, and Francisco Aranda for their great help and suggestions for improving this article." }, { "code": null, "e": 12054, "s": 11906, "text": "If you are not familiar with the concept of human-in-the-loop, I highly recommend you this article from Stanford’s Institute for Human-Centered AI." } ]
Fisher’s F-Test in R Programming - GeeksforGeeks
22 Jul, 2020 Fisher’s F test calculates the ratio between the larger variance and the smaller variance. We use the F test when we want to check where means of three or more groups are different or not. F-test is used to assess whether the variances of two populations (A and B) are equal. The method is simple; it consists of taking the ratio between the larger variance and the smaller variance. var.test() function in R Programming performs an F-test between 2 normal populations with the hypothesis that variances of the 2 populations are equal. F = Larger Sample Variance / Smaller Sample Variance To test the equality of variances between the two sample use var.test(x, y) To compare two variance use var.test(x, y, alternative = "two.sided") Syntax:var.test(x, y, alternative = “two.sided”) Parameters:x, y: numeric vectorsalternative: a character string specifying the alternative hypothesis. Example 1:Let we have two samples x, y. The R function var.test() can be used to compare two variances as follow: # Taking two samplesx <- rnorm(249, mean = 20)y <- rnorm(79, mean = 30)# var test in Rvar.test(x, y, alternative = "two.sided") Output: F test to compare two variances data: x and y F = 0.88707, num df = 248, denom df = 78, p-value = 0.4901 alternative hypothesis: true ratio of variances is not equal to 1 95 percent confidence interval: 0.6071405 1.2521004 sample estimates: ratio of variances 0.8870677 It returns the following: the value of the F test statistic.the degrees of the freedom of the F distribution of the test statistic.the p-value of the test 0.4901a confidence interval for the ratio of the population variances.the ratio of the sample variances 0.8870677 the value of the F test statistic. the degrees of the freedom of the F distribution of the test statistic. the p-value of the test 0.4901 a confidence interval for the ratio of the population variances. the ratio of the sample variances 0.8870677 The p-value of F-test is p = 0.4901 which is greater than the alpha level 0.05. In conclusion, there is no difference between the two sample. Example 2:Let we have two random samples from two random population. Test whether two population have same variance. # Taking two random samplesA = c(16, 17, 25, 26, 32, 34, 38, 40, 42)B = c(600, 590, 590, 630, 610, 630)# var test in Rvar.test(A, B, alternative = "two.sided") Output: F test to compare two variances data: A and B F = 0.27252, num df = 8, denom df = 5, p-value = 0.1012 alternative hypothesis: true ratio of variances is not equal to 1 95 percent confidence interval: 0.04033118 1.31282683 sample estimates: ratio of variances 0.2725248 It returns the following: the value of the F test statistic.the degrees of the freedom of the F distribution of the test statistic.the p-value of the test 0.101295% confidence interval for the ratio of the population variances.the ratio of the sample variances 0.2725248 the value of the F test statistic. the degrees of the freedom of the F distribution of the test statistic. the p-value of the test 0.1012 95% confidence interval for the ratio of the population variances. the ratio of the sample variances 0.2725248 The p-value of F-test is p = 0.1012 which is greater than the alpha level 0.05. In conclusion, there is no difference between the two samples. Example 3:Let we have two random sample. # Taking two random samplesx = c(25, 29, 35, 46, 58, 66, 68)y = c(14, 16, 24, 28, 32, 35, 37, 42, 43, 45, 47)# var test in Rvar.test(x, y) Output: F test to compare two variances data: x and y F = 2.4081, num df = 6, denom df = 10, p-value = 0.2105 alternative hypothesis: true ratio of variances is not equal to 1 95 percent confidence interval: 0.5913612 13.1514157 sample estimates: ratio of variances 2.4081 It returns the following: the value of the F test statistic.the degrees of the freedom of the F distribution of the test statistic.the p-value of the test 0.210595% confidence interval for the ratio of the population variances.the ratio of the sample variances 2.4081 the value of the F test statistic. the degrees of the freedom of the F distribution of the test statistic. the p-value of the test 0.2105 95% confidence interval for the ratio of the population variances. the ratio of the sample variances 2.4081 The p-value of F-test is p = 0.2105 which is greater than the alpha level 0.05. In conclusion, there is no difference between the two samples. Picked R Machine-Learning 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 How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? How to import an Excel File into R ? How to filter R dataframe by multiple conditions? Replace Specific Characters in String in R Time Series Analysis in R R - if statement
[ { "code": null, "e": 25242, "s": 25214, "text": "\n22 Jul, 2020" }, { "code": null, "e": 25778, "s": 25242, "text": "Fisher’s F test calculates the ratio between the larger variance and the smaller variance. We use the F test when we want to check where means of three or more groups are different or not. F-test is used to assess whether the variances of two populations (A and B) are equal. The method is simple; it consists of taking the ratio between the larger variance and the smaller variance. var.test() function in R Programming performs an F-test between 2 normal populations with the hypothesis that variances of the 2 populations are equal." }, { "code": null, "e": 25831, "s": 25778, "text": "F = Larger Sample Variance / Smaller Sample Variance" }, { "code": null, "e": 25907, "s": 25831, "text": "To test the equality of variances between the two sample use var.test(x, y)" }, { "code": null, "e": 25977, "s": 25907, "text": "To compare two variance use var.test(x, y, alternative = \"two.sided\")" }, { "code": null, "e": 26026, "s": 25977, "text": "Syntax:var.test(x, y, alternative = “two.sided”)" }, { "code": null, "e": 26129, "s": 26026, "text": "Parameters:x, y: numeric vectorsalternative: a character string specifying the alternative hypothesis." }, { "code": null, "e": 26243, "s": 26129, "text": "Example 1:Let we have two samples x, y. The R function var.test() can be used to compare two variances as follow:" }, { "code": "# Taking two samplesx <- rnorm(249, mean = 20)y <- rnorm(79, mean = 30)# var test in Rvar.test(x, y, alternative = \"two.sided\")", "e": 26371, "s": 26243, "text": null }, { "code": null, "e": 26379, "s": 26371, "text": "Output:" }, { "code": null, "e": 26669, "s": 26379, "text": " F test to compare two variances\ndata: x and y\nF = 0.88707, num df = 248, denom df = 78, p-value = 0.4901\nalternative hypothesis: true ratio of variances is not equal to 1\n95 percent confidence interval:\n0.6071405 1.2521004\nsample estimates:\nratio of variances \n 0.8870677 \n" }, { "code": null, "e": 26695, "s": 26669, "text": "It returns the following:" }, { "code": null, "e": 26938, "s": 26695, "text": "the value of the F test statistic.the degrees of the freedom of the F distribution of the test statistic.the p-value of the test 0.4901a confidence interval for the ratio of the population variances.the ratio of the sample variances 0.8870677" }, { "code": null, "e": 26973, "s": 26938, "text": "the value of the F test statistic." }, { "code": null, "e": 27045, "s": 26973, "text": "the degrees of the freedom of the F distribution of the test statistic." }, { "code": null, "e": 27076, "s": 27045, "text": "the p-value of the test 0.4901" }, { "code": null, "e": 27141, "s": 27076, "text": "a confidence interval for the ratio of the population variances." }, { "code": null, "e": 27185, "s": 27141, "text": "the ratio of the sample variances 0.8870677" }, { "code": null, "e": 27327, "s": 27185, "text": "The p-value of F-test is p = 0.4901 which is greater than the alpha level 0.05. In conclusion, there is no difference between the two sample." }, { "code": null, "e": 27444, "s": 27327, "text": "Example 2:Let we have two random samples from two random population. Test whether two population have same variance." }, { "code": "# Taking two random samplesA = c(16, 17, 25, 26, 32, 34, 38, 40, 42)B = c(600, 590, 590, 630, 610, 630)# var test in Rvar.test(A, B, alternative = \"two.sided\")", "e": 27613, "s": 27444, "text": null }, { "code": null, "e": 27621, "s": 27613, "text": "Output:" }, { "code": null, "e": 27909, "s": 27621, "text": " F test to compare two variances\ndata: A and B\nF = 0.27252, num df = 8, denom df = 5, p-value = 0.1012\nalternative hypothesis: true ratio of variances is not equal to 1\n95 percent confidence interval:\n0.04033118 1.31282683\nsample estimates:\nratio of variances \n 0.2725248\n" }, { "code": null, "e": 27935, "s": 27909, "text": "It returns the following:" }, { "code": null, "e": 28180, "s": 27935, "text": "the value of the F test statistic.the degrees of the freedom of the F distribution of the test statistic.the p-value of the test 0.101295% confidence interval for the ratio of the population variances.the ratio of the sample variances 0.2725248" }, { "code": null, "e": 28215, "s": 28180, "text": "the value of the F test statistic." }, { "code": null, "e": 28287, "s": 28215, "text": "the degrees of the freedom of the F distribution of the test statistic." }, { "code": null, "e": 28318, "s": 28287, "text": "the p-value of the test 0.1012" }, { "code": null, "e": 28385, "s": 28318, "text": "95% confidence interval for the ratio of the population variances." }, { "code": null, "e": 28429, "s": 28385, "text": "the ratio of the sample variances 0.2725248" }, { "code": null, "e": 28572, "s": 28429, "text": "The p-value of F-test is p = 0.1012 which is greater than the alpha level 0.05. In conclusion, there is no difference between the two samples." }, { "code": null, "e": 28613, "s": 28572, "text": "Example 3:Let we have two random sample." }, { "code": "# Taking two random samplesx = c(25, 29, 35, 46, 58, 66, 68)y = c(14, 16, 24, 28, 32, 35, 37, 42, 43, 45, 47)# var test in Rvar.test(x, y)", "e": 28762, "s": 28613, "text": null }, { "code": null, "e": 28770, "s": 28762, "text": "Output:" }, { "code": null, "e": 29057, "s": 28770, "text": " F test to compare two variances\ndata: x and y\nF = 2.4081, num df = 6, denom df = 10, p-value = 0.2105\nalternative hypothesis: true ratio of variances is not equal to 1\n95 percent confidence interval:\n0.5913612 13.1514157\nsample estimates:\nratio of variances \n 2.4081\n" }, { "code": null, "e": 29083, "s": 29057, "text": "It returns the following:" }, { "code": null, "e": 29325, "s": 29083, "text": "the value of the F test statistic.the degrees of the freedom of the F distribution of the test statistic.the p-value of the test 0.210595% confidence interval for the ratio of the population variances.the ratio of the sample variances 2.4081" }, { "code": null, "e": 29360, "s": 29325, "text": "the value of the F test statistic." }, { "code": null, "e": 29432, "s": 29360, "text": "the degrees of the freedom of the F distribution of the test statistic." }, { "code": null, "e": 29463, "s": 29432, "text": "the p-value of the test 0.2105" }, { "code": null, "e": 29530, "s": 29463, "text": "95% confidence interval for the ratio of the population variances." }, { "code": null, "e": 29571, "s": 29530, "text": "the ratio of the sample variances 2.4081" }, { "code": null, "e": 29714, "s": 29571, "text": "The p-value of F-test is p = 0.2105 which is greater than the alpha level 0.05. In conclusion, there is no difference between the two samples." }, { "code": null, "e": 29721, "s": 29714, "text": "Picked" }, { "code": null, "e": 29740, "s": 29721, "text": "R Machine-Learning" }, { "code": null, "e": 29751, "s": 29740, "text": "R Language" }, { "code": null, "e": 29849, "s": 29751, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29901, "s": 29849, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 29939, "s": 29901, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 29974, "s": 29939, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 30032, "s": 29974, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 30081, "s": 30032, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 30118, "s": 30081, "text": "How to import an Excel File into R ?" }, { "code": null, "e": 30168, "s": 30118, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 30211, "s": 30168, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 30237, "s": 30211, "text": "Time Series Analysis in R" } ]
Python 3 - Tkinter pack() Method
This geometry manager organizes widgets in blocks before placing them in the parent widget. widget.pack( pack_options ) Here is the list of possible options − expand − When set to true, widget expands to fill any space not otherwise used in widget's parent. expand − When set to true, widget expands to fill any space not otherwise used in widget's parent. fill − Determines whether widget fills any extra space allocated to it by the packer, or keeps its own minimal dimensions: NONE (default), X (fill only horizontally), Y (fill only vertically), or BOTH (fill both horizontally and vertically). fill − Determines whether widget fills any extra space allocated to it by the packer, or keeps its own minimal dimensions: NONE (default), X (fill only horizontally), Y (fill only vertically), or BOTH (fill both horizontally and vertically). side − Determines which side of the parent widget packs against: TOP (default), BOTTOM, LEFT, or RIGHT. side − Determines which side of the parent widget packs against: TOP (default), BOTTOM, LEFT, or RIGHT. Try the following example by moving cursor on different buttons − # !/usr/bin/python3 from tkinter import * root = Tk() frame = Frame(root) frame.pack() bottomframe = Frame(root) bottomframe.pack( side = BOTTOM ) redbutton = Button(frame, text = "Red", fg = "red") redbutton.pack( side = LEFT) greenbutton = Button(frame, text = "Brown", fg = "brown") greenbutton.pack( side = LEFT ) bluebutton = Button(frame, text = "Blue", fg = "blue") bluebutton.pack( side = LEFT ) blackbutton = Button(bottomframe, text = "Black", fg = "black") blackbutton.pack( side = BOTTOM) root.mainloop() When the above code is executed, it produces the following result − 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": 2432, "s": 2340, "text": "This geometry manager organizes widgets in blocks before placing them in the parent widget." }, { "code": null, "e": 2461, "s": 2432, "text": "widget.pack( pack_options )\n" }, { "code": null, "e": 2501, "s": 2461, "text": "Here is the list of possible options −" }, { "code": null, "e": 2600, "s": 2501, "text": "expand − When set to true, widget expands to fill any space not otherwise used in widget's parent." }, { "code": null, "e": 2699, "s": 2600, "text": "expand − When set to true, widget expands to fill any space not otherwise used in widget's parent." }, { "code": null, "e": 2941, "s": 2699, "text": "fill − Determines whether widget fills any extra space allocated to it by the packer, or keeps its own minimal dimensions: NONE (default), X (fill only horizontally), Y (fill only vertically), or BOTH (fill both horizontally and vertically)." }, { "code": null, "e": 3183, "s": 2941, "text": "fill − Determines whether widget fills any extra space allocated to it by the packer, or keeps its own minimal dimensions: NONE (default), X (fill only horizontally), Y (fill only vertically), or BOTH (fill both horizontally and vertically)." }, { "code": null, "e": 3287, "s": 3183, "text": "side − Determines which side of the parent widget packs against: TOP (default), BOTTOM, LEFT, or RIGHT." }, { "code": null, "e": 3391, "s": 3287, "text": "side − Determines which side of the parent widget packs against: TOP (default), BOTTOM, LEFT, or RIGHT." }, { "code": null, "e": 3457, "s": 3391, "text": "Try the following example by moving cursor on different buttons −" }, { "code": null, "e": 3981, "s": 3457, "text": "# !/usr/bin/python3\nfrom tkinter import *\n\nroot = Tk()\nframe = Frame(root)\nframe.pack()\n\nbottomframe = Frame(root)\nbottomframe.pack( side = BOTTOM )\n\nredbutton = Button(frame, text = \"Red\", fg = \"red\")\nredbutton.pack( side = LEFT)\n\ngreenbutton = Button(frame, text = \"Brown\", fg = \"brown\")\ngreenbutton.pack( side = LEFT )\n\nbluebutton = Button(frame, text = \"Blue\", fg = \"blue\")\nbluebutton.pack( side = LEFT )\n\nblackbutton = Button(bottomframe, text = \"Black\", fg = \"black\")\nblackbutton.pack( side = BOTTOM)\n\nroot.mainloop()" }, { "code": null, "e": 4049, "s": 3981, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 4086, "s": 4049, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 4102, "s": 4086, "text": " Malhar Lathkar" }, { "code": null, "e": 4135, "s": 4102, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 4154, "s": 4135, "text": " Arnab Chakraborty" }, { "code": null, "e": 4189, "s": 4154, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 4211, "s": 4189, "text": " In28Minutes Official" }, { "code": null, "e": 4245, "s": 4211, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 4273, "s": 4245, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4308, "s": 4273, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 4322, "s": 4308, "text": " Lets Kode It" }, { "code": null, "e": 4355, "s": 4322, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 4372, "s": 4355, "text": " Abhilash Nelson" }, { "code": null, "e": 4379, "s": 4372, "text": " Print" }, { "code": null, "e": 4390, "s": 4379, "text": " Add Notes" } ]
Flutter - Introduction to Package
Dart’s way of organizing and sharing a set of functionality is through Package. Dart Package is simply sharable libraries or modules. In general, the Dart Package is same as that of Dart Application except Dart Package does not have application entry point, main. The general structure of Package (consider a demo package, my_demo_package) is as below − lib/src/* − Private Dart code files. lib/src/* − Private Dart code files. lib/my_demo_package.dart − Main Dart code file. It can be imported into an application as − lib/my_demo_package.dart − Main Dart code file. It can be imported into an application as − import 'package:my_demo_package/my_demo_package.dart' Other private code file may be exported into the main code file (my_demo_package.dart), if necessary as shown below − Other private code file may be exported into the main code file (my_demo_package.dart), if necessary as shown below − export src/my_private_code.dart lib/* − Any number of Dart code files arranged in any custom folder structure. The code can be accessed as, lib/* − Any number of Dart code files arranged in any custom folder structure. The code can be accessed as, import 'package:my_demo_package/custom_folder/custom_file.dart' pubspec.yaml − Project specification, same as that of application, pubspec.yaml − Project specification, same as that of application, All Dart code files in the Package are simply Dart classes and it does not have any special requirement for a Dart code to include it in a Package. Since Dart Packages are basically a small collection of similar functionality, it can be categorized based on its functionality. Generic Dart code, which can be used in both web and mobile environment. For example, english_words is one such package which contains around 5000 words and has basic utility functions like nouns (list nouns in the English), syllables (specify number of syllables in a word. Generic Dart code, which depends on Flutter framework and can be used only in mobile environment. For example, fluro is a custom router for flutter. It depends on the Flutter framework. Generic Dart code, which depends on Flutter framework as well as the underlying platform code (Android SDK or iOS SDK). For example, camera is a plugin to interact with device camera. It depends on the Flutter framework as well as the underlying framework to get access to camera. Dart Packages are hosted and published into the live server, https://pub.dartlang.org. Also, Flutter provides simple tool, pub to manage Dart Packages in the application. The steps needed to use as Package is as follows − Include the package name and the version needed into the pubspec.yaml as shown below − Include the package name and the version needed into the pubspec.yaml as shown below − dependencies: english_words: ^3.1.5 The latest version number can be found by checking the online server. The latest version number can be found by checking the online server. Install the package into the application by using the following command − Install the package into the application by using the following command − flutter packages get While developing in the Android studio, Android Studio detects any change in the pubspec.yaml and displays an Android studio package alert to the developer as shown below − While developing in the Android studio, Android Studio detects any change in the pubspec.yaml and displays an Android studio package alert to the developer as shown below − Dart Packages can be installed or updated in Android Studio using the menu options. Dart Packages can be installed or updated in Android Studio using the menu options. Import the necessary file using the command shown below and start working − Import the necessary file using the command shown below and start working − import 'package:english_words/english_words.dart'; Use any method available in the package, Use any method available in the package, nouns.take(50).forEach(print); Here, we have used nouns function to get and print the top 50 words. Here, we have used nouns function to get and print the top 50 words. Developing a Flutter Plugin is similar to developing a Dart application or Dart Package. The only exception is that the plugin is going to use System API (Android or iOS) to get the required platform specific functionality. As we have already learned how to access platform code in the previous chapters, let us develop a simple plugin, my_browser to understand the plugin development process. The functionality of the my_browser plugin is to allow the application to open the given website in the platform specific browser. Start Android Studio. Start Android Studio. Click File → New Flutter Project and select Flutter Plugin option. Click File → New Flutter Project and select Flutter Plugin option. You can see a Flutter plugin selection window as shown here − You can see a Flutter plugin selection window as shown here − Enter my_browser as project name and click Next. Enter my_browser as project name and click Next. Enter the plugin name and other details in the window as shown here − Enter the plugin name and other details in the window as shown here − Enter company domain, flutterplugins.tutorialspoint.com in the window shown below and then click on Finish. It will generate a startup code to develop our new plugin. Enter company domain, flutterplugins.tutorialspoint.com in the window shown below and then click on Finish. It will generate a startup code to develop our new plugin. Open my_browser.dart file and write a method, openBrowser to invoke platform specific openBrowser method. Open my_browser.dart file and write a method, openBrowser to invoke platform specific openBrowser method. Future<void> openBrowser(String urlString) async { try { final int result = await _channel.invokeMethod( 'openBrowser', <String, String>{ 'url': urlString } ); } on PlatformException catch (e) { // Unable to open the browser print(e); } } Open MyBrowserPlugin.java file and import the following classes − Open MyBrowserPlugin.java file and import the following classes − import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; Here, we have to import library required for opening a browser from Android. Here, we have to import library required for opening a browser from Android. Add new private variable mRegistrar of type Registrar in MyBrowserPlugin class. Add new private variable mRegistrar of type Registrar in MyBrowserPlugin class. private final Registrar mRegistrar; Here, Registrar is used to get context information of the invoking code. Here, Registrar is used to get context information of the invoking code. Add a constructor to set Registrar in MyBrowserPlugin class. Add a constructor to set Registrar in MyBrowserPlugin class. private MyBrowserPlugin(Registrar registrar) { this.mRegistrar = registrar; } Change registerWith to include our new constructor in MyBrowserPlugin class. Change registerWith to include our new constructor in MyBrowserPlugin class. public static void registerWith(Registrar registrar) { final MethodChannel channel = new MethodChannel(registrar.messenger(), "my_browser"); MyBrowserPlugin instance = new MyBrowserPlugin(registrar); channel.setMethodCallHandler(instance); } Change the onMethodCall to include openBrowser method in MyBrowserPlugin class. Change the onMethodCall to include openBrowser method in MyBrowserPlugin class. @Override public void onMethodCall(MethodCall call, Result result) { String url = call.argument("url"); if (call.method.equals("getPlatformVersion")) { result.success("Android " + android.os.Build.VERSION.RELEASE); } else if (call.method.equals("openBrowser")) { openBrowser(call, result, url); } else { result.notImplemented(); } } Write the platform specific openBrowser method to access browser in MyBrowserPlugin class. Write the platform specific openBrowser method to access browser in MyBrowserPlugin class. private void openBrowser(MethodCall call, Result result, String url) { Activity activity = mRegistrar.activity(); if (activity == null) { result.error("ACTIVITY_NOT_AVAILABLE", "Browser cannot be opened without foreground activity", null); return; } Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); activity.startActivity(intent); result.success((Object) true); } The complete source code of the my_browser plugin is as follows − The complete source code of the my_browser plugin is as follows − my_browser.dart import 'dart:async'; import 'package:flutter/services.dart'; class MyBrowser { static const MethodChannel _channel = const MethodChannel('my_browser'); static Future<String> get platformVersion async { final String version = await _channel.invokeMethod('getPlatformVersion'); return version; } Future<void> openBrowser(String urlString) async { try { final int result = await _channel.invokeMethod( 'openBrowser', <String, String>{'url': urlString}); } on PlatformException catch (e) { // Unable to open the browser print(e); } } } MyBrowserPlugin.java package com.tutorialspoint.flutterplugins.my_browser; import io.flutter.plugin.common.MethodCall; import io.flutter.plugin.common.MethodChannel; import io.flutter.plugin.common.MethodChannel.MethodCallHandler; import io.flutter.plugin.common.MethodChannel.Result; import io.flutter.plugin.common.PluginRegistry.Registrar; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; /** MyBrowserPlugin */ public class MyBrowserPlugin implements MethodCallHandler { private final Registrar mRegistrar; private MyBrowserPlugin(Registrar registrar) { this.mRegistrar = registrar; } /** Plugin registration. */ public static void registerWith(Registrar registrar) { final MethodChannel channel = new MethodChannel( registrar.messenger(), "my_browser"); MyBrowserPlugin instance = new MyBrowserPlugin(registrar); channel.setMethodCallHandler(instance); } @Override public void onMethodCall(MethodCall call, Result result) { String url = call.argument("url"); if (call.method.equals("getPlatformVersion")) { result.success("Android " + android.os.Build.VERSION.RELEASE); } else if (call.method.equals("openBrowser")) { openBrowser(call, result, url); } else { result.notImplemented(); } } private void openBrowser(MethodCall call, Result result, String url) { Activity activity = mRegistrar.activity(); if (activity == null) { result.error("ACTIVITY_NOT_AVAILABLE", "Browser cannot be opened without foreground activity", null); return; } Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); activity.startActivity(intent); result.success((Object) true); } } Create a new project, my_browser_plugin_test to test our newly created plugin. Create a new project, my_browser_plugin_test to test our newly created plugin. Open pubspec.yaml and set my_browser as a plugin dependency. Open pubspec.yaml and set my_browser as a plugin dependency. dependencies: flutter: sdk: flutter my_browser: path: ../my_browser Android studio will alert that the pubspec.yaml is updated as shown in the Android studio package alert given below − Android studio will alert that the pubspec.yaml is updated as shown in the Android studio package alert given below − Click Get dependencies option. Android studio will get the package from Internet and properly configure it for the application. Click Get dependencies option. Android studio will get the package from Internet and properly configure it for the application. Open main.dart and include my_browser plugin as below − Open main.dart and include my_browser plugin as below − import 'package:my_browser/my_browser.dart'; Call the openBrowser function from my_browser plugin as shown below − Call the openBrowser function from my_browser plugin as shown below − onPressed: () => MyBrowser().openBrowser("https://flutter.dev"), The complete code of the main.dart is as follows − The complete code of the main.dart is as follows − import 'package:flutter/material.dart'; import 'package:my_browser/my_browser.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage( title: 'Flutter Demo Home Page' ), );, } } class MyHomePage extends StatelessWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(this.title), ), body: Center( child: RaisedButton( child: Text('Open Browser'), onPressed: () => MyBrowser().openBrowser("https://flutter.dev"), ), ), ); } } Run the application and click the Open Browser button and see that the browser is launched. You can see a Browser app - Home page as shown in the screenshot shown below − Run the application and click the Open Browser button and see that the browser is launched. You can see a Browser app - Home page as shown in the screenshot shown below − You can see a Browser app – Browser screen as shown in the screenshot shown below − 34 Lectures 4 hours Sriyank Siddhartha 117 Lectures 10 hours Frahaan Hussain 27 Lectures 1 hours Skillbakerystudios 17 Lectures 51 mins Harsh Kumar Khatri 17 Lectures 1.5 hours Pramila Rawat 85 Lectures 16.5 hours Rahul Agarwal Print Add Notes Bookmark this page
[ { "code": null, "e": 2482, "s": 2218, "text": "Dart’s way of organizing and sharing a set of functionality is through Package. Dart Package is simply sharable libraries or modules. In general, the Dart Package is same as that of Dart Application except Dart Package does not have application entry point, main." }, { "code": null, "e": 2572, "s": 2482, "text": "The general structure of Package (consider a demo package, my_demo_package) is as below −" }, { "code": null, "e": 2609, "s": 2572, "text": "lib/src/* − Private Dart code files." }, { "code": null, "e": 2646, "s": 2609, "text": "lib/src/* − Private Dart code files." }, { "code": null, "e": 2738, "s": 2646, "text": "lib/my_demo_package.dart − Main Dart code file. It can be imported into an application as −" }, { "code": null, "e": 2830, "s": 2738, "text": "lib/my_demo_package.dart − Main Dart code file. It can be imported into an application as −" }, { "code": null, "e": 2885, "s": 2830, "text": "import 'package:my_demo_package/my_demo_package.dart'\n" }, { "code": null, "e": 3003, "s": 2885, "text": "Other private code file may be exported into the main code file (my_demo_package.dart), if necessary as shown below −" }, { "code": null, "e": 3121, "s": 3003, "text": "Other private code file may be exported into the main code file (my_demo_package.dart), if necessary as shown below −" }, { "code": null, "e": 3154, "s": 3121, "text": "export src/my_private_code.dart\n" }, { "code": null, "e": 3262, "s": 3154, "text": "lib/* − Any number of Dart code files arranged in any custom folder structure. The code can be accessed as," }, { "code": null, "e": 3370, "s": 3262, "text": "lib/* − Any number of Dart code files arranged in any custom folder structure. The code can be accessed as," }, { "code": null, "e": 3435, "s": 3370, "text": "import 'package:my_demo_package/custom_folder/custom_file.dart'\n" }, { "code": null, "e": 3502, "s": 3435, "text": "pubspec.yaml − Project specification, same as that of application," }, { "code": null, "e": 3569, "s": 3502, "text": "pubspec.yaml − Project specification, same as that of application," }, { "code": null, "e": 3717, "s": 3569, "text": "All Dart code files in the Package are simply Dart classes and it does not have any special requirement for a Dart code to include it in a Package." }, { "code": null, "e": 3846, "s": 3717, "text": "Since Dart Packages are basically a small collection of similar functionality, it can be categorized based on its functionality." }, { "code": null, "e": 4121, "s": 3846, "text": "Generic Dart code, which can be used in both web and mobile environment. For example, english_words is one such package which contains around 5000 words and has basic utility functions like nouns (list nouns in the English), syllables (specify number of syllables in a word." }, { "code": null, "e": 4307, "s": 4121, "text": "Generic Dart code, which depends on Flutter framework and can be used only in mobile environment. For example, fluro is a custom router for flutter. It depends on the Flutter framework." }, { "code": null, "e": 4588, "s": 4307, "text": "Generic Dart code, which depends on Flutter framework as well as the underlying platform code (Android SDK or iOS SDK). For example, camera is a plugin to interact with device camera. It depends on the Flutter framework as well as the underlying framework to get access to camera." }, { "code": null, "e": 4810, "s": 4588, "text": "Dart Packages are hosted and published into the live server, https://pub.dartlang.org. Also, Flutter provides simple tool, pub to manage Dart Packages in the application. The steps needed to use as Package is as follows −" }, { "code": null, "e": 4897, "s": 4810, "text": "Include the package name and the version needed into the pubspec.yaml as shown below −" }, { "code": null, "e": 4984, "s": 4897, "text": "Include the package name and the version needed into the pubspec.yaml as shown below −" }, { "code": null, "e": 5021, "s": 4984, "text": "dependencies: english_words: ^3.1.5\n" }, { "code": null, "e": 5091, "s": 5021, "text": "The latest version number can be found by checking the online server." }, { "code": null, "e": 5161, "s": 5091, "text": "The latest version number can be found by checking the online server." }, { "code": null, "e": 5235, "s": 5161, "text": "Install the package into the application by using the following command −" }, { "code": null, "e": 5309, "s": 5235, "text": "Install the package into the application by using the following command −" }, { "code": null, "e": 5331, "s": 5309, "text": "flutter packages get\n" }, { "code": null, "e": 5504, "s": 5331, "text": "While developing in the Android studio, Android Studio detects any change in the pubspec.yaml and displays an Android studio package alert to the developer as shown below −" }, { "code": null, "e": 5677, "s": 5504, "text": "While developing in the Android studio, Android Studio detects any change in the pubspec.yaml and displays an Android studio package alert to the developer as shown below −" }, { "code": null, "e": 5761, "s": 5677, "text": "Dart Packages can be installed or updated in Android Studio using the menu options." }, { "code": null, "e": 5845, "s": 5761, "text": "Dart Packages can be installed or updated in Android Studio using the menu options." }, { "code": null, "e": 5921, "s": 5845, "text": "Import the necessary file using the command shown below and start working −" }, { "code": null, "e": 5997, "s": 5921, "text": "Import the necessary file using the command shown below and start working −" }, { "code": null, "e": 6049, "s": 5997, "text": "import 'package:english_words/english_words.dart';\n" }, { "code": null, "e": 6090, "s": 6049, "text": "Use any method available in the package," }, { "code": null, "e": 6131, "s": 6090, "text": "Use any method available in the package," }, { "code": null, "e": 6163, "s": 6131, "text": "nouns.take(50).forEach(print);\n" }, { "code": null, "e": 6232, "s": 6163, "text": "Here, we have used nouns function to get and print the top 50 words." }, { "code": null, "e": 6301, "s": 6232, "text": "Here, we have used nouns function to get and print the top 50 words." }, { "code": null, "e": 6525, "s": 6301, "text": "Developing a Flutter Plugin is similar to developing a Dart application or Dart Package. The only exception is that the plugin is going to use System API (Android or iOS) to get the required platform specific functionality." }, { "code": null, "e": 6826, "s": 6525, "text": "As we have already learned how to access platform code in the previous chapters, let us develop a simple plugin, my_browser to understand the plugin development process. The functionality of the my_browser plugin is to allow the application to open the given website in the platform specific browser." }, { "code": null, "e": 6848, "s": 6826, "text": "Start Android Studio." }, { "code": null, "e": 6870, "s": 6848, "text": "Start Android Studio." }, { "code": null, "e": 6937, "s": 6870, "text": "Click File → New Flutter Project and select Flutter Plugin option." }, { "code": null, "e": 7004, "s": 6937, "text": "Click File → New Flutter Project and select Flutter Plugin option." }, { "code": null, "e": 7066, "s": 7004, "text": "You can see a Flutter plugin selection window as shown here −" }, { "code": null, "e": 7128, "s": 7066, "text": "You can see a Flutter plugin selection window as shown here −" }, { "code": null, "e": 7177, "s": 7128, "text": "Enter my_browser as project name and click Next." }, { "code": null, "e": 7226, "s": 7177, "text": "Enter my_browser as project name and click Next." }, { "code": null, "e": 7296, "s": 7226, "text": "Enter the plugin name and other details in the window as shown here −" }, { "code": null, "e": 7366, "s": 7296, "text": "Enter the plugin name and other details in the window as shown here −" }, { "code": null, "e": 7533, "s": 7366, "text": "Enter company domain, flutterplugins.tutorialspoint.com in the window shown below and then click on Finish. It will generate a startup code to develop our new plugin." }, { "code": null, "e": 7700, "s": 7533, "text": "Enter company domain, flutterplugins.tutorialspoint.com in the window shown below and then click on Finish. It will generate a startup code to develop our new plugin." }, { "code": null, "e": 7806, "s": 7700, "text": "Open my_browser.dart file and write a method, openBrowser to invoke platform specific openBrowser method." }, { "code": null, "e": 7912, "s": 7806, "text": "Open my_browser.dart file and write a method, openBrowser to invoke platform specific openBrowser method." }, { "code": null, "e": 8194, "s": 7912, "text": "Future<void> openBrowser(String urlString) async { \n try {\n final int result = await _channel.invokeMethod(\n 'openBrowser', <String, String>{ 'url': urlString }\n );\n }\n on PlatformException catch (e) { \n // Unable to open the browser print(e); \n } \n}" }, { "code": null, "e": 8260, "s": 8194, "text": "Open MyBrowserPlugin.java file and import the following classes −" }, { "code": null, "e": 8326, "s": 8260, "text": "Open MyBrowserPlugin.java file and import the following classes −" }, { "code": null, "e": 8440, "s": 8326, "text": "import android.app.Activity; \nimport android.content.Intent; \nimport android.net.Uri; \nimport android.os.Bundle;\n" }, { "code": null, "e": 8517, "s": 8440, "text": "Here, we have to import library required for opening a browser from Android." }, { "code": null, "e": 8594, "s": 8517, "text": "Here, we have to import library required for opening a browser from Android." }, { "code": null, "e": 8674, "s": 8594, "text": "Add new private variable mRegistrar of type Registrar in MyBrowserPlugin class." }, { "code": null, "e": 8754, "s": 8674, "text": "Add new private variable mRegistrar of type Registrar in MyBrowserPlugin class." }, { "code": null, "e": 8791, "s": 8754, "text": "private final Registrar mRegistrar;\n" }, { "code": null, "e": 8864, "s": 8791, "text": "Here, Registrar is used to get context information of the invoking code." }, { "code": null, "e": 8937, "s": 8864, "text": "Here, Registrar is used to get context information of the invoking code." }, { "code": null, "e": 8998, "s": 8937, "text": "Add a constructor to set Registrar in MyBrowserPlugin class." }, { "code": null, "e": 9059, "s": 8998, "text": "Add a constructor to set Registrar in MyBrowserPlugin class." }, { "code": null, "e": 9143, "s": 9059, "text": "private MyBrowserPlugin(Registrar registrar) { \n this.mRegistrar = registrar; \n}\n" }, { "code": null, "e": 9220, "s": 9143, "text": "Change registerWith to include our new constructor in MyBrowserPlugin class." }, { "code": null, "e": 9297, "s": 9220, "text": "Change registerWith to include our new constructor in MyBrowserPlugin class." }, { "code": null, "e": 9552, "s": 9297, "text": "public static void registerWith(Registrar registrar) { \n final MethodChannel channel = new MethodChannel(registrar.messenger(), \"my_browser\"); \n MyBrowserPlugin instance = new MyBrowserPlugin(registrar); \n channel.setMethodCallHandler(instance); \n}" }, { "code": null, "e": 9632, "s": 9552, "text": "Change the onMethodCall to include openBrowser method in MyBrowserPlugin class." }, { "code": null, "e": 9712, "s": 9632, "text": "Change the onMethodCall to include openBrowser method in MyBrowserPlugin class." }, { "code": null, "e": 10091, "s": 9712, "text": "@Override \npublic void onMethodCall(MethodCall call, Result result) { \n String url = call.argument(\"url\");\n if (call.method.equals(\"getPlatformVersion\")) { \n result.success(\"Android \" + android.os.Build.VERSION.RELEASE); \n } \n else if (call.method.equals(\"openBrowser\")) { \n openBrowser(call, result, url); \n } else { \n result.notImplemented(); \n } \n}" }, { "code": null, "e": 10182, "s": 10091, "text": "Write the platform specific openBrowser method to access browser in MyBrowserPlugin class." }, { "code": null, "e": 10273, "s": 10182, "text": "Write the platform specific openBrowser method to access browser in MyBrowserPlugin class." }, { "code": null, "e": 10717, "s": 10273, "text": "private void openBrowser(MethodCall call, Result result, String url) { \n Activity activity = mRegistrar.activity(); \n if (activity == null) {\n result.error(\"ACTIVITY_NOT_AVAILABLE\", \n \"Browser cannot be opened without foreground activity\", null); \n return; \n } \n Intent intent = new Intent(Intent.ACTION_VIEW); \n intent.setData(Uri.parse(url)); \n activity.startActivity(intent); \n result.success((Object) true); \n}" }, { "code": null, "e": 10783, "s": 10717, "text": "The complete source code of the my_browser plugin is as follows −" }, { "code": null, "e": 10849, "s": 10783, "text": "The complete source code of the my_browser plugin is as follows −" }, { "code": null, "e": 10865, "s": 10849, "text": "my_browser.dart" }, { "code": null, "e": 11484, "s": 10865, "text": "import 'dart:async'; \nimport 'package:flutter/services.dart'; \n\nclass MyBrowser {\n static const MethodChannel _channel = const MethodChannel('my_browser'); \n static Future<String> get platformVersion async { \n final String version = await _channel.invokeMethod('getPlatformVersion'); return version; \n } \n Future<void> openBrowser(String urlString) async { \n try {\n final int result = await _channel.invokeMethod(\n 'openBrowser', <String, String>{'url': urlString}); \n } \n on PlatformException catch (e) { \n // Unable to open the browser print(e); \n }\n }\n}" }, { "code": null, "e": 11505, "s": 11484, "text": "MyBrowserPlugin.java" }, { "code": null, "e": 13378, "s": 11505, "text": "package com.tutorialspoint.flutterplugins.my_browser; \n\nimport io.flutter.plugin.common.MethodCall; \nimport io.flutter.plugin.common.MethodChannel; \nimport io.flutter.plugin.common.MethodChannel.MethodCallHandler; \nimport io.flutter.plugin.common.MethodChannel.Result; \nimport io.flutter.plugin.common.PluginRegistry.Registrar; \nimport android.app.Activity; \nimport android.content.Intent; \nimport android.net.Uri; \nimport android.os.Bundle; \n\n/** MyBrowserPlugin */ \npublic class MyBrowserPlugin implements MethodCallHandler {\n private final Registrar mRegistrar; \n private MyBrowserPlugin(Registrar registrar) { \n this.mRegistrar = registrar; \n } \n /** Plugin registration. */\n public static void registerWith(Registrar registrar) {\n final MethodChannel channel = new MethodChannel(\n registrar.messenger(), \"my_browser\"); \n MyBrowserPlugin instance = new MyBrowserPlugin(registrar); \n channel.setMethodCallHandler(instance); \n } \n @Override \n public void onMethodCall(MethodCall call, Result result) { \n String url = call.argument(\"url\"); \n if (call.method.equals(\"getPlatformVersion\")) { \n result.success(\"Android \" + android.os.Build.VERSION.RELEASE); \n } \n else if (call.method.equals(\"openBrowser\")) { \n openBrowser(call, result, url); \n } else { \n result.notImplemented(); \n } \n } \n private void openBrowser(MethodCall call, Result result, String url) { \n Activity activity = mRegistrar.activity(); \n if (activity == null) {\n result.error(\"ACTIVITY_NOT_AVAILABLE\",\n \"Browser cannot be opened without foreground activity\", null); \n return; \n }\n Intent intent = new Intent(Intent.ACTION_VIEW); \n intent.setData(Uri.parse(url)); \n activity.startActivity(intent); \n result.success((Object) true); \n } \n}" }, { "code": null, "e": 13457, "s": 13378, "text": "Create a new project, my_browser_plugin_test to test our newly created plugin." }, { "code": null, "e": 13536, "s": 13457, "text": "Create a new project, my_browser_plugin_test to test our newly created plugin." }, { "code": null, "e": 13597, "s": 13536, "text": "Open pubspec.yaml and set my_browser as a plugin dependency." }, { "code": null, "e": 13658, "s": 13597, "text": "Open pubspec.yaml and set my_browser as a plugin dependency." }, { "code": null, "e": 13748, "s": 13658, "text": "dependencies: \n flutter: \n sdk: flutter \n my_browser: \n path: ../my_browser" }, { "code": null, "e": 13866, "s": 13748, "text": "Android studio will alert that the pubspec.yaml is updated as shown in the Android studio package alert given below −" }, { "code": null, "e": 13984, "s": 13866, "text": "Android studio will alert that the pubspec.yaml is updated as shown in the Android studio package alert given below −" }, { "code": null, "e": 14112, "s": 13984, "text": "Click Get dependencies option. Android studio will get the package from Internet and properly configure it for the application." }, { "code": null, "e": 14240, "s": 14112, "text": "Click Get dependencies option. Android studio will get the package from Internet and properly configure it for the application." }, { "code": null, "e": 14296, "s": 14240, "text": "Open main.dart and include my_browser plugin as below −" }, { "code": null, "e": 14352, "s": 14296, "text": "Open main.dart and include my_browser plugin as below −" }, { "code": null, "e": 14398, "s": 14352, "text": "import 'package:my_browser/my_browser.dart';\n" }, { "code": null, "e": 14468, "s": 14398, "text": "Call the openBrowser function from my_browser plugin as shown below −" }, { "code": null, "e": 14538, "s": 14468, "text": "Call the openBrowser function from my_browser plugin as shown below −" }, { "code": null, "e": 14604, "s": 14538, "text": "onPressed: () => MyBrowser().openBrowser(\"https://flutter.dev\"),\n" }, { "code": null, "e": 14655, "s": 14604, "text": "The complete code of the main.dart is as follows −" }, { "code": null, "e": 14706, "s": 14655, "text": "The complete code of the main.dart is as follows −" }, { "code": null, "e": 15671, "s": 14706, "text": "import 'package:flutter/material.dart'; \nimport 'package:my_browser/my_browser.dart'; \n\nvoid main() => runApp(MyApp()); \n\nclass MyApp extends StatelessWidget { \n @override \n Widget build(BuildContext context) {\n return MaterialApp( \n title: 'Flutter Demo', \n theme: ThemeData( \n primarySwatch: Colors.blue, \n ), \n home: MyHomePage(\n title: 'Flutter Demo Home Page'\n ), \n );,\n }\n} \nclass MyHomePage extends StatelessWidget { \n MyHomePage({Key key, this.title}) : super(key: key); \n final String title; \n @override \n Widget build(BuildContext context) {\n return Scaffold(\n appBar: AppBar( \n title: Text(this.title), \n ), \n body: Center(\n child: RaisedButton(\n child: Text('Open Browser'), \n onPressed: () => MyBrowser().openBrowser(\"https://flutter.dev\"), \n ),\n ), \n ); \n }\n}" }, { "code": null, "e": 15842, "s": 15671, "text": "Run the application and click the Open Browser button and see that the browser is launched. You can see a Browser app - Home page as shown in the screenshot shown below −" }, { "code": null, "e": 16013, "s": 15842, "text": "Run the application and click the Open Browser button and see that the browser is launched. You can see a Browser app - Home page as shown in the screenshot shown below −" }, { "code": null, "e": 16097, "s": 16013, "text": "You can see a Browser app – Browser screen as shown in the screenshot shown below −" }, { "code": null, "e": 16130, "s": 16097, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 16150, "s": 16130, "text": " Sriyank Siddhartha" }, { "code": null, "e": 16185, "s": 16150, "text": "\n 117 Lectures \n 10 hours \n" }, { "code": null, "e": 16202, "s": 16185, "text": " Frahaan Hussain" }, { "code": null, "e": 16235, "s": 16202, "text": "\n 27 Lectures \n 1 hours \n" }, { "code": null, "e": 16255, "s": 16235, "text": " Skillbakerystudios" }, { "code": null, "e": 16287, "s": 16255, "text": "\n 17 Lectures \n 51 mins\n" }, { "code": null, "e": 16307, "s": 16287, "text": " Harsh Kumar Khatri" }, { "code": null, "e": 16342, "s": 16307, "text": "\n 17 Lectures \n 1.5 hours \n" }, { "code": null, "e": 16357, "s": 16342, "text": " Pramila Rawat" }, { "code": null, "e": 16393, "s": 16357, "text": "\n 85 Lectures \n 16.5 hours \n" }, { "code": null, "e": 16408, "s": 16393, "text": " Rahul Agarwal" }, { "code": null, "e": 16415, "s": 16408, "text": " Print" }, { "code": null, "e": 16426, "s": 16415, "text": " Add Notes" } ]
C# program to find IP Address of the client
Firstly find the hostname using the Dns.GetHostName() method in C# − String hostName = string.Empty; hostName = Dns.GetHostName(); Console.WriteLine("Hostname: "+hostName); Now, use the IPHostEntry.AddressList Property to get IP Address − IPHostEntry myIP = Dns.GetHostEntry(hostName); IPAddress[] address = myIP.AddressList; Try the following code to display IP address − using System; using System.Net; class Program { static void Main() { String hostName = string.Empty; hostName = Dns.GetHostName(); IPHostEntry myIP = Dns.GetHostEntry(hostName); IPAddress[] address = myIP.AddressList; for (int i = 0; i < address.Length; i++) { Console.WriteLine("IP Address {1} : ",address[i].ToString()); } Console.ReadLine(); } }
[ { "code": null, "e": 1131, "s": 1062, "text": "Firstly find the hostname using the Dns.GetHostName() method in C# −" }, { "code": null, "e": 1235, "s": 1131, "text": "String hostName = string.Empty;\nhostName = Dns.GetHostName();\nConsole.WriteLine(\"Hostname: \"+hostName);" }, { "code": null, "e": 1301, "s": 1235, "text": "Now, use the IPHostEntry.AddressList Property to get IP Address −" }, { "code": null, "e": 1388, "s": 1301, "text": "IPHostEntry myIP = Dns.GetHostEntry(hostName);\nIPAddress[] address = myIP.AddressList;" }, { "code": null, "e": 1435, "s": 1388, "text": "Try the following code to display IP address −" }, { "code": null, "e": 1841, "s": 1435, "text": "using System;\nusing System.Net;\nclass Program {\n static void Main() {\n String hostName = string.Empty;\n hostName = Dns.GetHostName();\n IPHostEntry myIP = Dns.GetHostEntry(hostName);\n IPAddress[] address = myIP.AddressList;\n for (int i = 0; i < address.Length; i++) {\n Console.WriteLine(\"IP Address {1} : \",address[i].ToString());\n }\n Console.ReadLine();\n }\n}" } ]
PyQt - QList Widget
QListWidget class is an item-based interface to add or remove items from a list. Each item in the list is a QListWidgetItem object. ListWidget can be set to be multiselectable. Following are the frequently used methods of QListWidget class − addItem() Adds QListWidgetItem object or string in the list addItems() Adds each item in the list insertItem() Inserts item at the specified index clear() Removes contents of the list setCurrentItem() Sets currently selected item programmatically sortItems() Rearranges items in ascending order Following are the signals emitted by QListWidget − currentItemChanged() Whenever current item changes itemClicked() Whenever an item in the list is clicked The following example shows the click event being captured to pop up a message box. from PyQt4.QtGui import * from PyQt4.QtCore import * import sys class myListWidget(QListWidget): def Clicked(self,item): QMessageBox.information(self, "ListWidget", "You clicked: "+item.text()) def main(): app = QApplication(sys.argv) listWidget = myListWidget() #Resize width and height listWidget.resize(300,120) listWidget.addItem("Item 1"); listWidget.addItem("Item 2"); listWidget.addItem("Item 3"); listWidget.addItem("Item 4"); listWidget.setWindowTitle('PyQT QListwidget Demo') listWidget.itemClicked.connect(listWidget.Clicked) listWidget.show() sys.exit(app.exec_()) if __name__ == '__main__': main() 146 Lectures 22.5 hours ALAA EID Print Add Notes Bookmark this page
[ { "code": null, "e": 2103, "s": 1926, "text": "QListWidget class is an item-based interface to add or remove items from a list. Each item in the list is a QListWidgetItem object. ListWidget can be set to be multiselectable." }, { "code": null, "e": 2168, "s": 2103, "text": "Following are the frequently used methods of QListWidget class −" }, { "code": null, "e": 2178, "s": 2168, "text": "addItem()" }, { "code": null, "e": 2228, "s": 2178, "text": "Adds QListWidgetItem object or string in the list" }, { "code": null, "e": 2239, "s": 2228, "text": "addItems()" }, { "code": null, "e": 2266, "s": 2239, "text": "Adds each item in the list" }, { "code": null, "e": 2279, "s": 2266, "text": "insertItem()" }, { "code": null, "e": 2315, "s": 2279, "text": "Inserts item at the specified index" }, { "code": null, "e": 2323, "s": 2315, "text": "clear()" }, { "code": null, "e": 2352, "s": 2323, "text": "Removes contents of the list" }, { "code": null, "e": 2369, "s": 2352, "text": "setCurrentItem()" }, { "code": null, "e": 2415, "s": 2369, "text": "Sets currently selected item programmatically" }, { "code": null, "e": 2427, "s": 2415, "text": "sortItems()" }, { "code": null, "e": 2463, "s": 2427, "text": "Rearranges items in ascending order" }, { "code": null, "e": 2514, "s": 2463, "text": "Following are the signals emitted by QListWidget −" }, { "code": null, "e": 2535, "s": 2514, "text": "currentItemChanged()" }, { "code": null, "e": 2565, "s": 2535, "text": "Whenever current item changes" }, { "code": null, "e": 2579, "s": 2565, "text": "itemClicked()" }, { "code": null, "e": 2619, "s": 2579, "text": "Whenever an item in the list is clicked" }, { "code": null, "e": 2703, "s": 2619, "text": "The following example shows the click event being captured to pop up a message box." }, { "code": null, "e": 3381, "s": 2703, "text": "from PyQt4.QtGui import *\nfrom PyQt4.QtCore import *\n\nimport sys\n\nclass myListWidget(QListWidget):\n\n def Clicked(self,item):\n QMessageBox.information(self, \"ListWidget\", \"You clicked: \"+item.text())\n\t\t\ndef main():\n app = QApplication(sys.argv)\n listWidget = myListWidget()\n\t\n #Resize width and height\n listWidget.resize(300,120)\n\t\n listWidget.addItem(\"Item 1\"); \n listWidget.addItem(\"Item 2\");\n listWidget.addItem(\"Item 3\");\n listWidget.addItem(\"Item 4\");\n\t\n listWidget.setWindowTitle('PyQT QListwidget Demo')\n listWidget.itemClicked.connect(listWidget.Clicked)\n \n listWidget.show()\n sys.exit(app.exec_())\n\t\nif __name__ == '__main__':\n main()" }, { "code": null, "e": 3418, "s": 3381, "text": "\n 146 Lectures \n 22.5 hours \n" }, { "code": null, "e": 3428, "s": 3418, "text": " ALAA EID" }, { "code": null, "e": 3435, "s": 3428, "text": " Print" }, { "code": null, "e": 3446, "s": 3435, "text": " Add Notes" } ]
Working with APIs using Flask, Flask-RESTPlus and Swagger UI | by Karan Bhanot | Towards Data Science
While working on Machine Learning projects, I decided that I would like to develop complete applications. This would require developing APIs, so that we can post values and get responses of predictions. This is where Flask and Flask-RESTPlus come into the picture. Flask enables exposure of Python functions as APIs. Flask-RESTPlus is an extension to Flask which improves upon its capabilities. It allows us to not only define REST APIs but also brings in Swagger UI for all the APIs. In this article, I’ll explain how I developed a Flask application with several APIs and dummy data. The project is available as a GitHub Repository. I began the process by creating a virtual environment using pipenv. You can read more about it in my article on comparison of virtual environments. I installed Flask and Flask-RESTPlus. pipenv install flaskpipenv install flask-restplus However, if you do not wish to work inside a pipenv environment, you can simply use the following commands. pip install flaskpip install flask-restplus I began by importing Flask from flask. From flask_restplus, I imported Api to define the app and Resource which is received as a parameter in the various classes defined in the project. I defined the application as a flask application using the method Flask() which sets the name using __name__. Next, I’ll used Api to initialise the application. I defined a namespace here. The concept is very simple. Whenever APIs are defined under a given namespace, they appear under a given heading in Swagger (we’ll explore Swagger later in this article). In namespace, the first variable defines the path and second defines the description for that space. In the example above, the url for the namespace is http://127.0.0.1:5000/main and has the description as Main APIs in Swagger. Lastly, I defined the endpoints. As our namespace is name_space, I’ll define the url through route as @name_space.route("/"). Next, Flask-RESTPlus requires us to define all endpoints under a given route inside a class. The methods can beget(), put(), and many others. In the example above, the APIs can be accessed at the path http://127.0.0.1:5000/main. The classname is set as MainClass with two methods, get() and post(). Whenever, I make a GET call, I get the reply with status field as Got new data and with POST call, I get the reply as Posted new data. Now, everything is set up. The file is saved as basic.py. I run the app by the following command using pipenv. pipenv shellFLASK_APP=basic.py flask run Using pip, you can use the following command. FLASK_APP=basic.py flask run The best part of Flask-RESTPlus is that it automatically documents the APIs that we have created and they are visible in the Swagger UI. Go to http://127.0.0.1:5000/ and you can see all the APIs. Both APIs are visible under the main namespace with the description Main APIs. We can try either API and check their functioning by clicking the Try it out button. I used curl to make GET and POST requests from the terminal. While using the curl command, first use the word curl followed by the method after the character -X. Finally, the endpoint is specified. Taking a look at our curl responses, we see that I received the correct data for both GET and POST APIs. There is so much more to Flask and Flask REST-Plus. Let’s explore them in even more depth and understand them better. The following code is available as app.py in the GitHub Repository. We can use a POST request to send data and save it. We can then use the GET request to get that data. Let’s say we have a project that manages names of individuals and stores them. We create a GET endpoint to fetch the name using id and POST endpoint to save a name against an id. Here, I have created the path as http://127.0.0.1:5000/names/<int:id> where we will pass the id each time. To store names, I have created an object list_of_names which will be used to get and receive data. We have already imported Flask, Api, and Resource. We also import request from the flask package. This helps us get the request object and then retrieve information such as JSON data from it. We also import fields from flask_restplus package to define the type of elements such as String. We can also add extra information to our Flask app. This information is useful and is displayed in the Swagger UI. We can define the version, title and the description of our application. We’ve set only one namespace namely names. The Swagger UI header would now look like the image below. Whenever we want to receive or send information in a particular format (JSON) we accomplish this with the help of model. We specify the name of the model. Next, we describe the information it expects and the properties of each expected value. We define the model name as Name Model. It includes one parameter, namely name which is a required field, and define its description and help text. The API which will use this model will expect a JSON with a key as name. To keep track of all names, I’ll store them in list_of_names. Let’s break down the code snippet above into smaller parts to understand it better. We’ll explore the POST endpoint. The functionality of GET would be very similar. Define route and class We use the name_space namespace to define the route i.e. http://127.0.0.1:5000/main/<int:id>. It expects an Id to be sent as an integer. The name of out class is MainClass which has one parameter, Resource. Define docs for the API Using doc we can define the documentation for the API in Swagger. The responses key defines the various possible HTTP Status Codes. For each status code, we also define a text that describes it to the user. The params key defines the expected parameter. The API expects id in the URL and we specify a help text for the user. The Swagger UI looks like the image below. The parameters are defined in the top part. All the expected responses with their description appear in the lower part. Define the method We can now define our method. Before our method, we add the line expect(model) which defines that the API expects model. We wrap our code inside a try block and catch all errors that might occur. The request.json['name] gets us the received name and we can save it as well as send it back in the response. If the name key is missing, we get KeyError and we send Status Code 500. In other cases, we send Status Code 400. Let’s start the app. FLASK_APP=app.py flask run POSTWe parse the response from the request, read the name and store it against the id in list_of_names. We also return the status and the name of the newly added person. Error in POST Request Say, we forgot to supply the name parameter in the data object. In this case, we’ll get an error. On not supplying the key name, we got an error with Status Code 500 and the message Mapping key not found. GETWe just pass the id that we want to get the name for and we get the status and the name of the person back if available. Error in GET Request Say, we don’t have any person against Id 2. If we try to retrieve that information, it’ll throw an error. As that specific Id is not found, we get Status Code 500 and the message Mapping key not found. In this article, we explored creation of APIs using Flask and Flask-RESTPlus. Both of these are great libraries to develop as well as document APIs in Python and interact with APIs using Swagger. Please feel free to share your thoughts and ideas.
[ { "code": null, "e": 437, "s": 172, "text": "While working on Machine Learning projects, I decided that I would like to develop complete applications. This would require developing APIs, so that we can post values and get responses of predictions. This is where Flask and Flask-RESTPlus come into the picture." }, { "code": null, "e": 657, "s": 437, "text": "Flask enables exposure of Python functions as APIs. Flask-RESTPlus is an extension to Flask which improves upon its capabilities. It allows us to not only define REST APIs but also brings in Swagger UI for all the APIs." }, { "code": null, "e": 806, "s": 657, "text": "In this article, I’ll explain how I developed a Flask application with several APIs and dummy data. The project is available as a GitHub Repository." }, { "code": null, "e": 992, "s": 806, "text": "I began the process by creating a virtual environment using pipenv. You can read more about it in my article on comparison of virtual environments. I installed Flask and Flask-RESTPlus." }, { "code": null, "e": 1042, "s": 992, "text": "pipenv install flaskpipenv install flask-restplus" }, { "code": null, "e": 1150, "s": 1042, "text": "However, if you do not wish to work inside a pipenv environment, you can simply use the following commands." }, { "code": null, "e": 1194, "s": 1150, "text": "pip install flaskpip install flask-restplus" }, { "code": null, "e": 1380, "s": 1194, "text": "I began by importing Flask from flask. From flask_restplus, I imported Api to define the app and Resource which is received as a parameter in the various classes defined in the project." }, { "code": null, "e": 1541, "s": 1380, "text": "I defined the application as a flask application using the method Flask() which sets the name using __name__. Next, I’ll used Api to initialise the application." }, { "code": null, "e": 1841, "s": 1541, "text": "I defined a namespace here. The concept is very simple. Whenever APIs are defined under a given namespace, they appear under a given heading in Swagger (we’ll explore Swagger later in this article). In namespace, the first variable defines the path and second defines the description for that space." }, { "code": null, "e": 1968, "s": 1841, "text": "In the example above, the url for the namespace is http://127.0.0.1:5000/main and has the description as Main APIs in Swagger." }, { "code": null, "e": 2236, "s": 1968, "text": "Lastly, I defined the endpoints. As our namespace is name_space, I’ll define the url through route as @name_space.route(\"/\"). Next, Flask-RESTPlus requires us to define all endpoints under a given route inside a class. The methods can beget(), put(), and many others." }, { "code": null, "e": 2528, "s": 2236, "text": "In the example above, the APIs can be accessed at the path http://127.0.0.1:5000/main. The classname is set as MainClass with two methods, get() and post(). Whenever, I make a GET call, I get the reply with status field as Got new data and with POST call, I get the reply as Posted new data." }, { "code": null, "e": 2639, "s": 2528, "text": "Now, everything is set up. The file is saved as basic.py. I run the app by the following command using pipenv." }, { "code": null, "e": 2680, "s": 2639, "text": "pipenv shellFLASK_APP=basic.py flask run" }, { "code": null, "e": 2726, "s": 2680, "text": "Using pip, you can use the following command." }, { "code": null, "e": 2755, "s": 2726, "text": "FLASK_APP=basic.py flask run" }, { "code": null, "e": 2951, "s": 2755, "text": "The best part of Flask-RESTPlus is that it automatically documents the APIs that we have created and they are visible in the Swagger UI. Go to http://127.0.0.1:5000/ and you can see all the APIs." }, { "code": null, "e": 3115, "s": 2951, "text": "Both APIs are visible under the main namespace with the description Main APIs. We can try either API and check their functioning by clicking the Try it out button." }, { "code": null, "e": 3176, "s": 3115, "text": "I used curl to make GET and POST requests from the terminal." }, { "code": null, "e": 3418, "s": 3176, "text": "While using the curl command, first use the word curl followed by the method after the character -X. Finally, the endpoint is specified. Taking a look at our curl responses, we see that I received the correct data for both GET and POST APIs." }, { "code": null, "e": 3604, "s": 3418, "text": "There is so much more to Flask and Flask REST-Plus. Let’s explore them in even more depth and understand them better. The following code is available as app.py in the GitHub Repository." }, { "code": null, "e": 3885, "s": 3604, "text": "We can use a POST request to send data and save it. We can then use the GET request to get that data. Let’s say we have a project that manages names of individuals and stores them. We create a GET endpoint to fetch the name using id and POST endpoint to save a name against an id." }, { "code": null, "e": 4091, "s": 3885, "text": "Here, I have created the path as http://127.0.0.1:5000/names/<int:id> where we will pass the id each time. To store names, I have created an object list_of_names which will be used to get and receive data." }, { "code": null, "e": 4380, "s": 4091, "text": "We have already imported Flask, Api, and Resource. We also import request from the flask package. This helps us get the request object and then retrieve information such as JSON data from it. We also import fields from flask_restplus package to define the type of elements such as String." }, { "code": null, "e": 4495, "s": 4380, "text": "We can also add extra information to our Flask app. This information is useful and is displayed in the Swagger UI." }, { "code": null, "e": 4670, "s": 4495, "text": "We can define the version, title and the description of our application. We’ve set only one namespace namely names. The Swagger UI header would now look like the image below." }, { "code": null, "e": 4913, "s": 4670, "text": "Whenever we want to receive or send information in a particular format (JSON) we accomplish this with the help of model. We specify the name of the model. Next, we describe the information it expects and the properties of each expected value." }, { "code": null, "e": 5134, "s": 4913, "text": "We define the model name as Name Model. It includes one parameter, namely name which is a required field, and define its description and help text. The API which will use this model will expect a JSON with a key as name." }, { "code": null, "e": 5196, "s": 5134, "text": "To keep track of all names, I’ll store them in list_of_names." }, { "code": null, "e": 5361, "s": 5196, "text": "Let’s break down the code snippet above into smaller parts to understand it better. We’ll explore the POST endpoint. The functionality of GET would be very similar." }, { "code": null, "e": 5384, "s": 5361, "text": "Define route and class" }, { "code": null, "e": 5591, "s": 5384, "text": "We use the name_space namespace to define the route i.e. http://127.0.0.1:5000/main/<int:id>. It expects an Id to be sent as an integer. The name of out class is MainClass which has one parameter, Resource." }, { "code": null, "e": 5615, "s": 5591, "text": "Define docs for the API" }, { "code": null, "e": 5983, "s": 5615, "text": "Using doc we can define the documentation for the API in Swagger. The responses key defines the various possible HTTP Status Codes. For each status code, we also define a text that describes it to the user. The params key defines the expected parameter. The API expects id in the URL and we specify a help text for the user. The Swagger UI looks like the image below." }, { "code": null, "e": 6103, "s": 5983, "text": "The parameters are defined in the top part. All the expected responses with their description appear in the lower part." }, { "code": null, "e": 6121, "s": 6103, "text": "Define the method" }, { "code": null, "e": 6541, "s": 6121, "text": "We can now define our method. Before our method, we add the line expect(model) which defines that the API expects model. We wrap our code inside a try block and catch all errors that might occur. The request.json['name] gets us the received name and we can save it as well as send it back in the response. If the name key is missing, we get KeyError and we send Status Code 500. In other cases, we send Status Code 400." }, { "code": null, "e": 6562, "s": 6541, "text": "Let’s start the app." }, { "code": null, "e": 6589, "s": 6562, "text": "FLASK_APP=app.py flask run" }, { "code": null, "e": 6759, "s": 6589, "text": "POSTWe parse the response from the request, read the name and store it against the id in list_of_names. We also return the status and the name of the newly added person." }, { "code": null, "e": 6781, "s": 6759, "text": "Error in POST Request" }, { "code": null, "e": 6879, "s": 6781, "text": "Say, we forgot to supply the name parameter in the data object. In this case, we’ll get an error." }, { "code": null, "e": 6986, "s": 6879, "text": "On not supplying the key name, we got an error with Status Code 500 and the message Mapping key not found." }, { "code": null, "e": 7110, "s": 6986, "text": "GETWe just pass the id that we want to get the name for and we get the status and the name of the person back if available." }, { "code": null, "e": 7131, "s": 7110, "text": "Error in GET Request" }, { "code": null, "e": 7237, "s": 7131, "text": "Say, we don’t have any person against Id 2. If we try to retrieve that information, it’ll throw an error." }, { "code": null, "e": 7333, "s": 7237, "text": "As that specific Id is not found, we get Status Code 500 and the message Mapping key not found." }, { "code": null, "e": 7529, "s": 7333, "text": "In this article, we explored creation of APIs using Flask and Flask-RESTPlus. Both of these are great libraries to develop as well as document APIs in Python and interact with APIs using Swagger." } ]
What are getters and setters methods in PHP?
In this article, we learn the best way to create getter and setter strategies in PHP. Getter and setter strategies are utilized when we need to restrict the direct access to the variables by end-users. Getters and setters are methods used to define or retrieve the values of variables, normally private ones. Just as the name suggests, a getter method is a technique that gets or recovers the value of an object. Also, a setter method is a technique that sets the value of an object. Let's understand the use of getter and setter methods through an example. <?php class Person{ private $name; public function setName($name){ $this->name = $name; } public function getName(){ return $this->name; } } $person = new Person(); echo $person->name; ?> PHP Error Cannot access private property Person::$name In our Person class above, we have a private property called $name. Because it is private property, we are unable to access them directly like the above and that will produce a fatal error. To run the code above and get our desired output Let's test this example. <?php class Person{ private $name; public function setName($name){ $this->name = $name; } public function getName(){ return 'welocme'. $this->name; } } $person = new Person(); $person->setName('Alex'); $name = $person->getName(); echo $name; ?> welcomeAlex Here to give access to our private properties, we have made a "getter" function called getData, again because the visibility of the properties is set to private, you will likewise unable to change or modify their values. So, you should utilize one of the "setter" functions that we made: setName. After that, we have Instantiated our Person object. We "set" the namepropertyto"Alex"utilizingoursettertechniquesetData.ThenWeretrievedthevalueofthename property by using our getter function getData.
[ { "code": null, "e": 1371, "s": 1062, "text": "In this article, we learn the best way to create getter and setter strategies in PHP. Getter and setter strategies are utilized when we need to restrict the direct access to the variables by end-users. Getters and setters are methods used to define or retrieve the values of variables, normally private ones." }, { "code": null, "e": 1546, "s": 1371, "text": "Just as the name suggests, a getter method is a technique that gets or recovers the value of an object. Also, a setter method is a technique that sets the value of an object." }, { "code": null, "e": 1620, "s": 1546, "text": "Let's understand the use of getter and setter methods through an example." }, { "code": null, "e": 1868, "s": 1620, "text": "<?php\n class Person{\n private $name;\n public function setName($name){\n $this->name = $name;\n }\n public function getName(){\n return $this->name;\n }\n }\n $person = new Person();\n echo $person->name;\n?>" }, { "code": null, "e": 1923, "s": 1868, "text": "PHP Error Cannot access private property Person::$name" }, { "code": null, "e": 2113, "s": 1923, "text": "In our Person class above, we have a private property called $name. Because it is private property, we are unable to access them directly like the above and that will produce a fatal error." }, { "code": null, "e": 2187, "s": 2113, "text": "To run the code above and get our desired output Let's test this example." }, { "code": null, "e": 2498, "s": 2187, "text": "<?php\n class Person{\n private $name;\n public function setName($name){\n $this->name = $name;\n }\n public function getName(){\n return 'welocme'. $this->name;\n }\n }\n $person = new Person();\n $person->setName('Alex');\n $name = $person->getName();\n echo $name;\n?>" }, { "code": null, "e": 2510, "s": 2498, "text": "welcomeAlex" }, { "code": null, "e": 2859, "s": 2510, "text": "Here to give access to our private properties, we have made a \"getter\" function called getData, again because the visibility of the properties is set to private, you will likewise unable to change or modify their values. So, you should utilize one of the \"setter\" functions that we made: setName. After that, we have Instantiated our Person object." }, { "code": null, "e": 3007, "s": 2859, "text": "We \"set\" the namepropertyto\"Alex\"utilizingoursettertechniquesetData.ThenWeretrievedthevalueofthename property by using our getter function getData." } ]
Java Examples - View classpath?
How to view current classpath? Following example demonstrates how to view current classpath using echo command. C:> echo %CLASSPATH% The above code sample will produce the following result. .;C:\Program Files\Java\jre1.6.0_03\lib\ext\QTJava.zip Print Add Notes Bookmark this page
[ { "code": null, "e": 2099, "s": 2068, "text": "How to view current classpath?" }, { "code": null, "e": 2180, "s": 2099, "text": "Following example demonstrates how to view current classpath using echo command." }, { "code": null, "e": 2202, "s": 2180, "text": "C:> echo %CLASSPATH%\n" }, { "code": null, "e": 2259, "s": 2202, "text": "The above code sample will produce the following result." }, { "code": null, "e": 2315, "s": 2259, "text": ".;C:\\Program Files\\Java\\jre1.6.0_03\\lib\\ext\\QTJava.zip\n" }, { "code": null, "e": 2322, "s": 2315, "text": " Print" }, { "code": null, "e": 2333, "s": 2322, "text": " Add Notes" } ]
How I Taught Myself Linked Lists. Breaking down the definition of linked... | by Cleon W | Towards Data Science
Linked lists are amongst the simplest and most common data structures. If you have ever attempted to learn more about basic data structures, it is likely that you’ve come across linked lists and have read definitions similar to the following: A linked list is a data structure where the objects are arranged in a linear order. Unlike an array, however, in which the linear order is determined by the array indices, the order in a linked list is determined by a pointer in each object. Based on personal experience when learning about data structures, the above probably makes no sense to the absolute beginner. As such, this post aims to show that linked lists are conceptually simple by breaking down its definition in an intuitive and layman way to you, as though you were a complete beginner. We will leave the “So what?” of studying linked lists to the end of this post, as I believe that we will be able to ask more meaningful ‘so whats’ when equipped with a better understanding of linked lists. Note that we will be referencing the above definition throughout the article. So let’s get started. A linked list is a data structure... Since linked list is a type of data structure, it pays to briefly understand what is a data structure. Simply put, a data structure is how data is stored and organised. Then, depending on how the data is stored and organised, different operations can be applied to the data. What differentiates data structures from each other can either be how the data is stored and organised, what can be done with and/or to the data, or both. A bulk of the problems in computer science requires some sort of data, and our need to efficiently retrieve information from the data depending on the problem type is what motivates the creation of the different data structures that we have today. For example, a linked list stores and organises data in a linear order with the help of pointers (this is the “how data is organised”), and these pointers allow us to easily insert and remove elements without reorganising the entire data structure (this is the “what can be done”). This makes a linked list a linear data structure (as opposed to a non-linear one). ... where the objects are arranged in a linear order. Storing elements in a linear order means organising them in a sequential order such that there is: Only one first element and it has only one next element Only one last element and it has only one previous element All other elements have a previous and next element For example, apart from linked lists, arrays are also linear data structures that store data in a linear order. Again, whether linear or non-linear data structures are better depends on your use case. Both types have their pros and cons, as usual. ... Unlike an array, however, ... By now, you should have noticed that linked lists are most commonly compared to arrays. What is wrong (or right) with arrays depends on your use case. As with any other data structure, an array does have its own pros and cons. While arrays offer very fast indexed access and assignment of elements, they have fixed, immutable lengths. That means that they cannot grow or shrink, and it is impossible to append or insert items. Consequently, we must know how many elements we want to store when creating an array, which might cause certain issues depending on the problem at hand. Dynamic arrays (e.g. Python’s list) have variable lengths and this is done by reserving additional memory space. However, inserting an element at the start of a dynamic array can be really expensive compared to inserting it at the end. This might pose as a huge blocker, again depending on the problem that you are trying to address. Using Python’s list object, we can run the following code to illustrate this: n = 500000example_list1 = []example_list2 = []# Slow insertion of at the front of Python listsfor i in range(0, n): example_list1.insert(0, i)# Fast insertion of at the end of Python listsfor i in range(0, n): example_list2.insert(i, i) Recording and printing the time taken to completely insert 500,000 elements, we get: Insertion at start took: 110.1042 secondsInsertion at end took: 0.1853 seconds With a dynamic array, in order to insert an element in the first position (or first index), you would need to move all of the other elements ‘to the right’ to make room for this new element. Naturally, you can imagine that if you have an array with a large number of elements this would be really inefficient. Furthermore, there is a possibility of you needing to allocate more memory space to the array before shifting the elements. This is where linked lists can do better. ...the order in a linked list is determined by a pointer in each object. Pointers, pointers, pointers. Despite both linked lists and arrays being linear data structures, a linked list maintains the linear order of its elements using pointers (as compared to the indices in arrays). The use of pointers allows us to insert or remove nodes at arbitrary positions more efficiently than we could with arrays. In its most basic form (i.e. containing only the required attributes), linked lists are made up of: Objects called Nodes with the attributes: (a) Item, which is assigned the data that it stores (required), (b) Next pointer, which points to the next Node in the linear order (required) and (c) Previous pointer, which points to the previous Node in the linear order (not required).A pointer to the head of the list (required)A pointer to the tail of the list (not required) Objects called Nodes with the attributes: (a) Item, which is assigned the data that it stores (required), (b) Next pointer, which points to the next Node in the linear order (required) and (c) Previous pointer, which points to the previous Node in the linear order (not required). A pointer to the head of the list (required) A pointer to the tail of the list (not required) To see how a linked list allows us to efficiently insert objects at the head and tail, we will implement a linked list with 3 nodes holding the integers 14, 5 and 22 as data in linear order. Each node has a pointer to the next node and the linked list has both a pointer to the head of the list and a pointer to its tail. Since the position of a node in the list is stored in the pointer of the previous node, the nodes of a linked list do not necessarily have to be organised consecutively in memory. In fact, it can be stored anywhere in memory. Hence, it would look more like this: To insert a node that carries integer 50 at the tail of the linked list, we do the following: Create a new node with its item = 50Let its next pointer point to NoneLet the current tail node point to this new node instead of NoneReset the tail pointer of the linked list to point to this newly created node Create a new node with its item = 50 Let its next pointer point to None Let the current tail node point to this new node instead of None Reset the tail pointer of the linked list to point to this newly created node Similarly, to add an item at the head of the linked list, we do the following: Create a new NodeLet its next pointer point to the current head of the linked listReset the head pointer of the linked list to point to this newly created node Create a new Node Let its next pointer point to the current head of the linked list Reset the head pointer of the linked list to point to this newly created node That essentially is a linked list in its simplest form. As promised, so what? We can see that the main benefit of a linked list as compared to a (dynamic) array is that it allows for fast insertion (and removal) of items. Unlike arrays, there is no need to restructure the entire data structure and reallocate memory for that restructuring. This stems from the use of pointers to maintain the linear order of the data, which removes the need for the data items to be stored in a consecutive manner in memory. In other words, linked lists allow the insertion and removal of items using a fixed number of operations (as listed in the steps above), regardless of the length of the list. Using these fundamental concepts of a node, how it stores data and points to its neighbour(s), we can build other (more complicated) types of linked lists depending on our needs, such as doubly linked lists and circular linked lists. More excitingly, understanding linked lists and their nodes can lead us to exploring and understanding other data structures and even algorithms. A linked list is one of the many ways to implement other abstract data types such as stacks, queues, hash tables and graphs, which we will sink our teeth into another day. For the record, this is how the above singly linked list will look like in a conventional textbook, without the colours of course:
[ { "code": null, "e": 415, "s": 172, "text": "Linked lists are amongst the simplest and most common data structures. If you have ever attempted to learn more about basic data structures, it is likely that you’ve come across linked lists and have read definitions similar to the following:" }, { "code": null, "e": 657, "s": 415, "text": "A linked list is a data structure where the objects are arranged in a linear order. Unlike an array, however, in which the linear order is determined by the array indices, the order in a linked list is determined by a pointer in each object." }, { "code": null, "e": 968, "s": 657, "text": "Based on personal experience when learning about data structures, the above probably makes no sense to the absolute beginner. As such, this post aims to show that linked lists are conceptually simple by breaking down its definition in an intuitive and layman way to you, as though you were a complete beginner." }, { "code": null, "e": 1252, "s": 968, "text": "We will leave the “So what?” of studying linked lists to the end of this post, as I believe that we will be able to ask more meaningful ‘so whats’ when equipped with a better understanding of linked lists. Note that we will be referencing the above definition throughout the article." }, { "code": null, "e": 1274, "s": 1252, "text": "So let’s get started." }, { "code": null, "e": 1311, "s": 1274, "text": "A linked list is a data structure..." }, { "code": null, "e": 1414, "s": 1311, "text": "Since linked list is a type of data structure, it pays to briefly understand what is a data structure." }, { "code": null, "e": 1480, "s": 1414, "text": "Simply put, a data structure is how data is stored and organised." }, { "code": null, "e": 1586, "s": 1480, "text": "Then, depending on how the data is stored and organised, different operations can be applied to the data." }, { "code": null, "e": 1989, "s": 1586, "text": "What differentiates data structures from each other can either be how the data is stored and organised, what can be done with and/or to the data, or both. A bulk of the problems in computer science requires some sort of data, and our need to efficiently retrieve information from the data depending on the problem type is what motivates the creation of the different data structures that we have today." }, { "code": null, "e": 2354, "s": 1989, "text": "For example, a linked list stores and organises data in a linear order with the help of pointers (this is the “how data is organised”), and these pointers allow us to easily insert and remove elements without reorganising the entire data structure (this is the “what can be done”). This makes a linked list a linear data structure (as opposed to a non-linear one)." }, { "code": null, "e": 2408, "s": 2354, "text": "... where the objects are arranged in a linear order." }, { "code": null, "e": 2507, "s": 2408, "text": "Storing elements in a linear order means organising them in a sequential order such that there is:" }, { "code": null, "e": 2563, "s": 2507, "text": "Only one first element and it has only one next element" }, { "code": null, "e": 2622, "s": 2563, "text": "Only one last element and it has only one previous element" }, { "code": null, "e": 2674, "s": 2622, "text": "All other elements have a previous and next element" }, { "code": null, "e": 2786, "s": 2674, "text": "For example, apart from linked lists, arrays are also linear data structures that store data in a linear order." }, { "code": null, "e": 2922, "s": 2786, "text": "Again, whether linear or non-linear data structures are better depends on your use case. Both types have their pros and cons, as usual." }, { "code": null, "e": 2956, "s": 2922, "text": "... Unlike an array, however, ..." }, { "code": null, "e": 3183, "s": 2956, "text": "By now, you should have noticed that linked lists are most commonly compared to arrays. What is wrong (or right) with arrays depends on your use case. As with any other data structure, an array does have its own pros and cons." }, { "code": null, "e": 3536, "s": 3183, "text": "While arrays offer very fast indexed access and assignment of elements, they have fixed, immutable lengths. That means that they cannot grow or shrink, and it is impossible to append or insert items. Consequently, we must know how many elements we want to store when creating an array, which might cause certain issues depending on the problem at hand." }, { "code": null, "e": 3870, "s": 3536, "text": "Dynamic arrays (e.g. Python’s list) have variable lengths and this is done by reserving additional memory space. However, inserting an element at the start of a dynamic array can be really expensive compared to inserting it at the end. This might pose as a huge blocker, again depending on the problem that you are trying to address." }, { "code": null, "e": 3948, "s": 3870, "text": "Using Python’s list object, we can run the following code to illustrate this:" }, { "code": null, "e": 4191, "s": 3948, "text": "n = 500000example_list1 = []example_list2 = []# Slow insertion of at the front of Python listsfor i in range(0, n): example_list1.insert(0, i)# Fast insertion of at the end of Python listsfor i in range(0, n): example_list2.insert(i, i)" }, { "code": null, "e": 4276, "s": 4191, "text": "Recording and printing the time taken to completely insert 500,000 elements, we get:" }, { "code": null, "e": 4355, "s": 4276, "text": "Insertion at start took: 110.1042 secondsInsertion at end took: 0.1853 seconds" }, { "code": null, "e": 4789, "s": 4355, "text": "With a dynamic array, in order to insert an element in the first position (or first index), you would need to move all of the other elements ‘to the right’ to make room for this new element. Naturally, you can imagine that if you have an array with a large number of elements this would be really inefficient. Furthermore, there is a possibility of you needing to allocate more memory space to the array before shifting the elements." }, { "code": null, "e": 4831, "s": 4789, "text": "This is where linked lists can do better." }, { "code": null, "e": 4904, "s": 4831, "text": "...the order in a linked list is determined by a pointer in each object." }, { "code": null, "e": 4934, "s": 4904, "text": "Pointers, pointers, pointers." }, { "code": null, "e": 5236, "s": 4934, "text": "Despite both linked lists and arrays being linear data structures, a linked list maintains the linear order of its elements using pointers (as compared to the indices in arrays). The use of pointers allows us to insert or remove nodes at arbitrary positions more efficiently than we could with arrays." }, { "code": null, "e": 5336, "s": 5236, "text": "In its most basic form (i.e. containing only the required attributes), linked lists are made up of:" }, { "code": null, "e": 5709, "s": 5336, "text": "Objects called Nodes with the attributes: (a) Item, which is assigned the data that it stores (required), (b) Next pointer, which points to the next Node in the linear order (required) and (c) Previous pointer, which points to the previous Node in the linear order (not required).A pointer to the head of the list (required)A pointer to the tail of the list (not required)" }, { "code": null, "e": 5990, "s": 5709, "text": "Objects called Nodes with the attributes: (a) Item, which is assigned the data that it stores (required), (b) Next pointer, which points to the next Node in the linear order (required) and (c) Previous pointer, which points to the previous Node in the linear order (not required)." }, { "code": null, "e": 6035, "s": 5990, "text": "A pointer to the head of the list (required)" }, { "code": null, "e": 6084, "s": 6035, "text": "A pointer to the tail of the list (not required)" }, { "code": null, "e": 6406, "s": 6084, "text": "To see how a linked list allows us to efficiently insert objects at the head and tail, we will implement a linked list with 3 nodes holding the integers 14, 5 and 22 as data in linear order. Each node has a pointer to the next node and the linked list has both a pointer to the head of the list and a pointer to its tail." }, { "code": null, "e": 6669, "s": 6406, "text": "Since the position of a node in the list is stored in the pointer of the previous node, the nodes of a linked list do not necessarily have to be organised consecutively in memory. In fact, it can be stored anywhere in memory. Hence, it would look more like this:" }, { "code": null, "e": 6763, "s": 6669, "text": "To insert a node that carries integer 50 at the tail of the linked list, we do the following:" }, { "code": null, "e": 6975, "s": 6763, "text": "Create a new node with its item = 50Let its next pointer point to NoneLet the current tail node point to this new node instead of NoneReset the tail pointer of the linked list to point to this newly created node" }, { "code": null, "e": 7012, "s": 6975, "text": "Create a new node with its item = 50" }, { "code": null, "e": 7047, "s": 7012, "text": "Let its next pointer point to None" }, { "code": null, "e": 7112, "s": 7047, "text": "Let the current tail node point to this new node instead of None" }, { "code": null, "e": 7190, "s": 7112, "text": "Reset the tail pointer of the linked list to point to this newly created node" }, { "code": null, "e": 7269, "s": 7190, "text": "Similarly, to add an item at the head of the linked list, we do the following:" }, { "code": null, "e": 7429, "s": 7269, "text": "Create a new NodeLet its next pointer point to the current head of the linked listReset the head pointer of the linked list to point to this newly created node" }, { "code": null, "e": 7447, "s": 7429, "text": "Create a new Node" }, { "code": null, "e": 7513, "s": 7447, "text": "Let its next pointer point to the current head of the linked list" }, { "code": null, "e": 7591, "s": 7513, "text": "Reset the head pointer of the linked list to point to this newly created node" }, { "code": null, "e": 7647, "s": 7591, "text": "That essentially is a linked list in its simplest form." }, { "code": null, "e": 7669, "s": 7647, "text": "As promised, so what?" }, { "code": null, "e": 8275, "s": 7669, "text": "We can see that the main benefit of a linked list as compared to a (dynamic) array is that it allows for fast insertion (and removal) of items. Unlike arrays, there is no need to restructure the entire data structure and reallocate memory for that restructuring. This stems from the use of pointers to maintain the linear order of the data, which removes the need for the data items to be stored in a consecutive manner in memory. In other words, linked lists allow the insertion and removal of items using a fixed number of operations (as listed in the steps above), regardless of the length of the list." }, { "code": null, "e": 8509, "s": 8275, "text": "Using these fundamental concepts of a node, how it stores data and points to its neighbour(s), we can build other (more complicated) types of linked lists depending on our needs, such as doubly linked lists and circular linked lists." }, { "code": null, "e": 8827, "s": 8509, "text": "More excitingly, understanding linked lists and their nodes can lead us to exploring and understanding other data structures and even algorithms. A linked list is one of the many ways to implement other abstract data types such as stacks, queues, hash tables and graphs, which we will sink our teeth into another day." } ]
How do malloc() and free() work in C/C++?
The function malloc() is used to allocate the requested size of bytes and it returns a pointer to the first byte of allocated memory. It returns null pointer, if it fails. Here is the syntax of malloc() in C language, pointer_name = (cast-type*) malloc(size); Here, pointer_name − Any name given to the pointer. pointer_name − Any name given to the pointer. cast-type − The datatype in which you want to cast the allocated memory by malloc(). cast-type − The datatype in which you want to cast the allocated memory by malloc(). size − Size of allocated memory in bytes. size − Size of allocated memory in bytes. Here is an example of malloc() in C language, Live Demo #include <stdio.h> #include <stdlib.h> int main() { int n = 4, i, *p, s = 0; p = (int*) malloc(n * sizeof(int)); if(p == NULL) { printf("\nError! memory not allocated."); exit(0); } printf("\nEnter elements of array : "); for(i = 0; i < n; ++i) { scanf("%d", p + i); s += *(p + i); } printf("\nSum : %d", s); return 0; } Here is the output Enter elements of array : 32 23 21 8 Sum : 84 The function free() is used to deallocate the allocated memory by malloc(). It does not change the value of the pointer which means it still points to the same memory location. Here is the syntax of free() in C language, void free(void *pointer_name); Here, pointer_name − Any name given to the pointer. pointer_name − Any name given to the pointer. Here is an example of free() in C language, Live Demo #include <stdio.h> #include <stdlib.h> int main() { int n = 4, i, *p, s = 0; p = (int*) malloc(n * sizeof(int)); if(p == NULL) { printf("\nError! memory not allocated."); exit(0); } printf("\nEnter elements of array : "); for(i = 0; i < n; ++i) { scanf("%d", p + i); s += *(p + i); } printf("\nSum : %d", s); free(p); return 0; } Here is the output Enter elements of array : 32 23 21 28 Sum : 104
[ { "code": null, "e": 1234, "s": 1062, "text": "The function malloc() is used to allocate the requested size of bytes and it returns a pointer to the first byte of allocated memory. It returns null pointer, if it fails." }, { "code": null, "e": 1280, "s": 1234, "text": "Here is the syntax of malloc() in C language," }, { "code": null, "e": 1322, "s": 1280, "text": "pointer_name = (cast-type*) malloc(size);" }, { "code": null, "e": 1328, "s": 1322, "text": "Here," }, { "code": null, "e": 1375, "s": 1328, "text": "pointer_name − Any name given to the pointer." }, { "code": null, "e": 1422, "s": 1375, "text": "pointer_name − Any name given to the pointer." }, { "code": null, "e": 1508, "s": 1422, "text": "cast-type − The datatype in which you want to cast the allocated memory by malloc()." }, { "code": null, "e": 1594, "s": 1508, "text": "cast-type − The datatype in which you want to cast the allocated memory by malloc()." }, { "code": null, "e": 1637, "s": 1594, "text": "size − Size of allocated memory in bytes." }, { "code": null, "e": 1680, "s": 1637, "text": "size − Size of allocated memory in bytes." }, { "code": null, "e": 1726, "s": 1680, "text": "Here is an example of malloc() in C language," }, { "code": null, "e": 1737, "s": 1726, "text": " Live Demo" }, { "code": null, "e": 2115, "s": 1737, "text": "#include <stdio.h>\n#include <stdlib.h>\n\nint main() {\n int n = 4, i, *p, s = 0;\n p = (int*) malloc(n * sizeof(int));\n \n if(p == NULL) {\n printf(\"\\nError! memory not allocated.\");\n exit(0);\n }\n printf(\"\\nEnter elements of array : \");\n\n for(i = 0; i < n; ++i) {\n scanf(\"%d\", p + i);\n s += *(p + i);\n }\n printf(\"\\nSum : %d\", s);\n return 0;\n}" }, { "code": null, "e": 2134, "s": 2115, "text": "Here is the output" }, { "code": null, "e": 2180, "s": 2134, "text": "Enter elements of array : 32 23 21 8\nSum : 84" }, { "code": null, "e": 2357, "s": 2180, "text": "The function free() is used to deallocate the allocated memory by malloc(). It does not change the value of the pointer which means it still points to the same memory location." }, { "code": null, "e": 2401, "s": 2357, "text": "Here is the syntax of free() in C language," }, { "code": null, "e": 2432, "s": 2401, "text": "void free(void *pointer_name);" }, { "code": null, "e": 2438, "s": 2432, "text": "Here," }, { "code": null, "e": 2484, "s": 2438, "text": "pointer_name − Any name given to the pointer." }, { "code": null, "e": 2530, "s": 2484, "text": "pointer_name − Any name given to the pointer." }, { "code": null, "e": 2574, "s": 2530, "text": "Here is an example of free() in C language," }, { "code": null, "e": 2585, "s": 2574, "text": " Live Demo" }, { "code": null, "e": 2972, "s": 2585, "text": "#include <stdio.h>\n#include <stdlib.h>\n\nint main() {\n int n = 4, i, *p, s = 0;\n p = (int*) malloc(n * sizeof(int));\n\n if(p == NULL) {\n printf(\"\\nError! memory not allocated.\");\n exit(0);\n }\n printf(\"\\nEnter elements of array : \");\n\n for(i = 0; i < n; ++i) {\n scanf(\"%d\", p + i);\n s += *(p + i);\n }\n printf(\"\\nSum : %d\", s);\n free(p);\n return 0;\n}" }, { "code": null, "e": 2991, "s": 2972, "text": "Here is the output" }, { "code": null, "e": 3039, "s": 2991, "text": "Enter elements of array : 32 23 21 28\nSum : 104" } ]
CountDownLatch in Java - GeeksforGeeks
19 Apr, 2018 CountDownLatch is used to make sure that a task waits for other threads before it starts. To understand its application, let us consider a server where the main task can only start when all the required services have started. Working of CountDownLatch:When we create an object of CountDownLatch, we specify the number of threads it should wait for, all such thread are required to do count down by calling CountDownLatch.countDown() once they are completed or ready to the job. As soon as count reaches zero, the waiting task starts running. Example of CountDownLatch in JAVA: // Java Program to demonstrate how // to use CountDownLatch, Its used // when a thread needs to wait for other // threads before starting its work.import java.util.concurrent.CountDownLatch; public class CountDownLatchDemo{ public static void main(String args[]) throws InterruptedException { // Let us create task that is going to // wait for four threads before it starts CountDownLatch latch = new CountDownLatch(4); // Let us create four worker // threads and start them. Worker first = new Worker(1000, latch, "WORKER-1"); Worker second = new Worker(2000, latch, "WORKER-2"); Worker third = new Worker(3000, latch, "WORKER-3"); Worker fourth = new Worker(4000, latch, "WORKER-4"); first.start(); second.start(); third.start(); fourth.start(); // The main task waits for four threads latch.await(); // Main thread has started System.out.println(Thread.currentThread().getName() + " has finished"); }} // A class to represent threads for which// the main thread waits.class Worker extends Thread{ private int delay; private CountDownLatch latch; public Worker(int delay, CountDownLatch latch, String name) { super(name); this.delay = delay; this.latch = latch; } @Override public void run() { try { Thread.sleep(delay); latch.countDown(); System.out.println(Thread.currentThread().getName() + " finished"); } catch (InterruptedException e) { e.printStackTrace(); } }} Output: WORKER-1 finished WORKER-2 finished WORKER-3 finished WORKER-4 finished main has finished Facts about CountDownLatch: Creating an object of CountDownLatch by passing an int to its constructor (the count), is actually number of invited parties (threads) for an event.The thread, which is dependent on other threads to start processing, waits on until every other thread has called count down. All threads, which are waiting on await() proceed together once count down reaches to zero.countDown() method decrements the count and await() method blocks until count == 0 Creating an object of CountDownLatch by passing an int to its constructor (the count), is actually number of invited parties (threads) for an event. The thread, which is dependent on other threads to start processing, waits on until every other thread has called count down. All threads, which are waiting on await() proceed together once count down reaches to zero. countDown() method decrements the count and await() method blocks until count == 0 This article is contributed by Pratik Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. chantiya chowhai Java-Multithreading Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Arrays in Java Split() String method in Java with examples For-each loop in Java Reverse a string in Java Arrays.sort() in Java with examples Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples How to iterate any Map in Java Initialize an ArrayList in Java Interfaces in Java
[ { "code": null, "e": 23559, "s": 23531, "text": "\n19 Apr, 2018" }, { "code": null, "e": 23785, "s": 23559, "text": "CountDownLatch is used to make sure that a task waits for other threads before it starts. To understand its application, let us consider a server where the main task can only start when all the required services have started." }, { "code": null, "e": 24101, "s": 23785, "text": "Working of CountDownLatch:When we create an object of CountDownLatch, we specify the number of threads it should wait for, all such thread are required to do count down by calling CountDownLatch.countDown() once they are completed or ready to the job. As soon as count reaches zero, the waiting task starts running." }, { "code": null, "e": 24136, "s": 24101, "text": "Example of CountDownLatch in JAVA:" }, { "code": "// Java Program to demonstrate how // to use CountDownLatch, Its used // when a thread needs to wait for other // threads before starting its work.import java.util.concurrent.CountDownLatch; public class CountDownLatchDemo{ public static void main(String args[]) throws InterruptedException { // Let us create task that is going to // wait for four threads before it starts CountDownLatch latch = new CountDownLatch(4); // Let us create four worker // threads and start them. Worker first = new Worker(1000, latch, \"WORKER-1\"); Worker second = new Worker(2000, latch, \"WORKER-2\"); Worker third = new Worker(3000, latch, \"WORKER-3\"); Worker fourth = new Worker(4000, latch, \"WORKER-4\"); first.start(); second.start(); third.start(); fourth.start(); // The main task waits for four threads latch.await(); // Main thread has started System.out.println(Thread.currentThread().getName() + \" has finished\"); }} // A class to represent threads for which// the main thread waits.class Worker extends Thread{ private int delay; private CountDownLatch latch; public Worker(int delay, CountDownLatch latch, String name) { super(name); this.delay = delay; this.latch = latch; } @Override public void run() { try { Thread.sleep(delay); latch.countDown(); System.out.println(Thread.currentThread().getName() + \" finished\"); } catch (InterruptedException e) { e.printStackTrace(); } }}", "e": 26026, "s": 24136, "text": null }, { "code": null, "e": 26034, "s": 26026, "text": "Output:" }, { "code": null, "e": 26125, "s": 26034, "text": "WORKER-1 finished\nWORKER-2 finished\nWORKER-3 finished\nWORKER-4 finished\nmain has finished\n" }, { "code": null, "e": 26153, "s": 26125, "text": "Facts about CountDownLatch:" }, { "code": null, "e": 26601, "s": 26153, "text": "Creating an object of CountDownLatch by passing an int to its constructor (the count), is actually number of invited parties (threads) for an event.The thread, which is dependent on other threads to start processing, waits on until every other thread has called count down. All threads, which are waiting on await() proceed together once count down reaches to zero.countDown() method decrements the count and await() method blocks until count == 0" }, { "code": null, "e": 26750, "s": 26601, "text": "Creating an object of CountDownLatch by passing an int to its constructor (the count), is actually number of invited parties (threads) for an event." }, { "code": null, "e": 26968, "s": 26750, "text": "The thread, which is dependent on other threads to start processing, waits on until every other thread has called count down. All threads, which are waiting on await() proceed together once count down reaches to zero." }, { "code": null, "e": 27051, "s": 26968, "text": "countDown() method decrements the count and await() method blocks until count == 0" }, { "code": null, "e": 27353, "s": 27051, "text": "This article is contributed by Pratik Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 27370, "s": 27353, "text": "chantiya chowhai" }, { "code": null, "e": 27390, "s": 27370, "text": "Java-Multithreading" }, { "code": null, "e": 27395, "s": 27390, "text": "Java" }, { "code": null, "e": 27400, "s": 27395, "text": "Java" }, { "code": null, "e": 27498, "s": 27400, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27507, "s": 27498, "text": "Comments" }, { "code": null, "e": 27520, "s": 27507, "text": "Old Comments" }, { "code": null, "e": 27535, "s": 27520, "text": "Arrays in Java" }, { "code": null, "e": 27579, "s": 27535, "text": "Split() String method in Java with examples" }, { "code": null, "e": 27601, "s": 27579, "text": "For-each loop in Java" }, { "code": null, "e": 27626, "s": 27601, "text": "Reverse a string in Java" }, { "code": null, "e": 27662, "s": 27626, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 27713, "s": 27662, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 27743, "s": 27713, "text": "HashMap in Java with Examples" }, { "code": null, "e": 27774, "s": 27743, "text": "How to iterate any Map in Java" }, { "code": null, "e": 27806, "s": 27774, "text": "Initialize an ArrayList in Java" } ]
Docly: Generate Comments Automatically for Python Code | by Satyam Kumar | Towards Data Science
Artificial Intelligence is extensively used for developing models to help developers write better source code. Various AI models are used to accelerate the work of developers, such as code autocompletion, autosuggestions, unit test assistance, bug detection, code summarization, etc. Documentation of code is essential while delivering the project. For large code snippets having thousands of lines of code, it's very difficult to understand the code functionality for the next set of developers, testers, or clients, and hence code documentation of comments is essential. Most of the developers find it difficult or forget to write documentation or comments. It is a big challenge for the developers to cope up with writing code, testing the code, and keeping up with its documentation. Docly comes to the rescue, as it automatically generates documentation for python code using state-of-the-art natural language processing. Docly is a python package by Codist.AI that can automatically generate documentation for your python code. It extensively used natural language processing to go through all the functions in the code snippet and generate docstring or comments automatically and can also update any missing or outdated docstring. Docly is provided in the command-line interface and can review or complete the documentation in one-line command in few seconds. Pypl installation for the required packages. pip install -U PyYAMLpip install docly To generate documentation of a given python code snippet, use a single line of the command-line statement: docly-gen <name_of_python_file.py> After the docly engine is loaded and the docstring is generated, it will seek permission to show the suggestions. Taking input as ‘y’, it generates all the function names in the code snippets along with the generated docstring for each function. If you want to edit and add these suggested docstrings to the original python file, return input with ‘y’. It adds the suggested docstring to each of the functions with the arguments in the first line of each function. In the modified python script, the generated docstring is edited and added inside each function. Format of docstring (Inside ‘‘‘ --- ’’’): Each of the docstring contains a comment that signifies what that function holistically. It also specifies the input arguments (parameters) for their respective functions. In the last, it generates its credit statement: (Generated by docly)\ To revert back to the applied changes then below-mentioned command line statement: docly-restore As of December 2020, Docly library is currently in the beta stage and free to use. Docly uses natural language processing to understand what each of the functions is doing and generates docstring accordingly. It is currently in the initial stage but still, it does amazing work in analyzing and providing great insights by documentation the functions. There are a lot of drawbacks to generating the comments for function arguments. Still, it's a great package to generate insights and saves a lot of developers time. [1] Codist.AI website: https://codist-ai.com/ [2] PyPl documentation for docly: https://pypi.org/project/docly/ Thank You for Reading
[ { "code": null, "e": 456, "s": 172, "text": "Artificial Intelligence is extensively used for developing models to help developers write better source code. Various AI models are used to accelerate the work of developers, such as code autocompletion, autosuggestions, unit test assistance, bug detection, code summarization, etc." }, { "code": null, "e": 832, "s": 456, "text": "Documentation of code is essential while delivering the project. For large code snippets having thousands of lines of code, it's very difficult to understand the code functionality for the next set of developers, testers, or clients, and hence code documentation of comments is essential. Most of the developers find it difficult or forget to write documentation or comments." }, { "code": null, "e": 1099, "s": 832, "text": "It is a big challenge for the developers to cope up with writing code, testing the code, and keeping up with its documentation. Docly comes to the rescue, as it automatically generates documentation for python code using state-of-the-art natural language processing." }, { "code": null, "e": 1410, "s": 1099, "text": "Docly is a python package by Codist.AI that can automatically generate documentation for your python code. It extensively used natural language processing to go through all the functions in the code snippet and generate docstring or comments automatically and can also update any missing or outdated docstring." }, { "code": null, "e": 1539, "s": 1410, "text": "Docly is provided in the command-line interface and can review or complete the documentation in one-line command in few seconds." }, { "code": null, "e": 1584, "s": 1539, "text": "Pypl installation for the required packages." }, { "code": null, "e": 1623, "s": 1584, "text": "pip install -U PyYAMLpip install docly" }, { "code": null, "e": 1730, "s": 1623, "text": "To generate documentation of a given python code snippet, use a single line of the command-line statement:" }, { "code": null, "e": 1765, "s": 1730, "text": "docly-gen <name_of_python_file.py>" }, { "code": null, "e": 1879, "s": 1765, "text": "After the docly engine is loaded and the docstring is generated, it will seek permission to show the suggestions." }, { "code": null, "e": 2011, "s": 1879, "text": "Taking input as ‘y’, it generates all the function names in the code snippets along with the generated docstring for each function." }, { "code": null, "e": 2230, "s": 2011, "text": "If you want to edit and add these suggested docstrings to the original python file, return input with ‘y’. It adds the suggested docstring to each of the functions with the arguments in the first line of each function." }, { "code": null, "e": 2327, "s": 2230, "text": "In the modified python script, the generated docstring is edited and added inside each function." }, { "code": null, "e": 2369, "s": 2327, "text": "Format of docstring (Inside ‘‘‘ --- ’’’):" }, { "code": null, "e": 2458, "s": 2369, "text": "Each of the docstring contains a comment that signifies what that function holistically." }, { "code": null, "e": 2541, "s": 2458, "text": "It also specifies the input arguments (parameters) for their respective functions." }, { "code": null, "e": 2611, "s": 2541, "text": "In the last, it generates its credit statement: (Generated by docly)\\" }, { "code": null, "e": 2694, "s": 2611, "text": "To revert back to the applied changes then below-mentioned command line statement:" }, { "code": null, "e": 2708, "s": 2694, "text": "docly-restore" }, { "code": null, "e": 2917, "s": 2708, "text": "As of December 2020, Docly library is currently in the beta stage and free to use. Docly uses natural language processing to understand what each of the functions is doing and generates docstring accordingly." }, { "code": null, "e": 3225, "s": 2917, "text": "It is currently in the initial stage but still, it does amazing work in analyzing and providing great insights by documentation the functions. There are a lot of drawbacks to generating the comments for function arguments. Still, it's a great package to generate insights and saves a lot of developers time." }, { "code": null, "e": 3271, "s": 3225, "text": "[1] Codist.AI website: https://codist-ai.com/" }, { "code": null, "e": 3337, "s": 3271, "text": "[2] PyPl documentation for docly: https://pypi.org/project/docly/" } ]
Python - Grouping columns in Pandas Dataframe
To group columns in Pandas dataframe, use the groupby(). At first, let us create Pandas dataframe − dataFrame = pd.DataFrame( { "Car": ["Audi", "Lexus", "Audi", "Mercedes", "Audi", "Lexus", "Mercedes", "Lexus", "Mercedes"], "Reg_Price": [1000, 1400, 1100, 900, 1700, 1800, 1300, 1150, 1350] } ) Let us now group according to Car column − res = dataFrame.groupby("Car") After grouping, we will use functions to find the means Registration prices (Reg_Price) of grouped car names − res.mean() This calculates mean of the Registration price according to column Car. Following is the code − import pandas as pd # dataframe with one of the columns as Reg_Price dataFrame = pd.DataFrame( { "Car": ["Audi", "Lexus", "Audi", "Mercedes", "Audi", "Lexus", "Mercedes", "Lexus", "Mercedes"], "Reg_Price": [1000, 1400, 1100, 900, 1700, 1800, 1300, 1150, 1350] } ) print"DataFrame...\n",dataFrame # grouped according to Car res = dataFrame.groupby("Car") print"\nMean of Registration Price grouped according to Car names...\n",res.mean() This will produce the following output − DataFrame... Car Reg_Price 0 Audi 1000 1 Lexus 1400 2 Audi 1100 3 Mercedes 900 4 Audi 1700 5 Lexus 1800 6 Mercedes 1300 7 Lexus 1150 8 Mercedes 1350 Mean of Registration Price grouped according to Car names... Reg_Price Car Audi 1266.666667 Lexus 1450.000000 Mercedes 1183.333333
[ { "code": null, "e": 1162, "s": 1062, "text": "To group columns in Pandas dataframe, use the groupby(). At first, let us create Pandas dataframe −" }, { "code": null, "e": 1375, "s": 1162, "text": "dataFrame = pd.DataFrame(\n {\n \"Car\": [\"Audi\", \"Lexus\", \"Audi\", \"Mercedes\", \"Audi\", \"Lexus\", \"Mercedes\", \"Lexus\", \"Mercedes\"],\n \"Reg_Price\": [1000, 1400, 1100, 900, 1700, 1800, 1300, 1150, 1350]\n }\n)" }, { "code": null, "e": 1418, "s": 1375, "text": "Let us now group according to Car column −" }, { "code": null, "e": 1449, "s": 1418, "text": "res = dataFrame.groupby(\"Car\")" }, { "code": null, "e": 1560, "s": 1449, "text": "After grouping, we will use functions to find the means Registration prices (Reg_Price) of grouped car names −" }, { "code": null, "e": 1571, "s": 1560, "text": "res.mean()" }, { "code": null, "e": 1643, "s": 1571, "text": "This calculates mean of the Registration price according to column Car." }, { "code": null, "e": 1667, "s": 1643, "text": "Following is the code −" }, { "code": null, "e": 2126, "s": 1667, "text": "import pandas as pd\n\n# dataframe with one of the columns as Reg_Price\ndataFrame = pd.DataFrame(\n {\n \"Car\": [\"Audi\", \"Lexus\", \"Audi\", \"Mercedes\", \"Audi\", \"Lexus\", \"Mercedes\", \"Lexus\", \"Mercedes\"],\n \"Reg_Price\": [1000, 1400, 1100, 900, 1700, 1800, 1300, 1150, 1350]\n }\n)\n\nprint\"DataFrame...\\n\",dataFrame\n\n# grouped according to Car\nres = dataFrame.groupby(\"Car\")\n\nprint\"\\nMean of Registration Price grouped according to Car names...\\n\",res.mean()" }, { "code": null, "e": 2167, "s": 2126, "text": "This will produce the following output −" }, { "code": null, "e": 2569, "s": 2167, "text": "DataFrame...\n Car Reg_Price\n0 Audi 1000\n1 Lexus 1400\n2 Audi 1100\n3 Mercedes 900\n4 Audi 1700\n5 Lexus 1800\n6 Mercedes 1300\n7 Lexus 1150\n8 Mercedes 1350\nMean of Registration Price grouped according to Car names...\n Reg_Price\n Car\n Audi 1266.666667\n Lexus 1450.000000\nMercedes 1183.333333" } ]
Use of fflush(stdin) in C
The function fflush(stdin) is used to flush the output buffer of the stream. It returns zero, if successful otherwise, returns EOF and feof error indicator is set. Here is the syntax of fflush(stdin) in C language, int fflush(FILE *stream); Here is an example of fflush(stdin) in C language, Live Demo #include #include int main() { char s[20] = "Helloworld"; printf("The string : %s", s); fflush(stdin); return 0; } The string : Helloworld
[ { "code": null, "e": 1226, "s": 1062, "text": "The function fflush(stdin) is used to flush the output buffer of the stream. It returns zero, if successful otherwise, returns EOF and feof error indicator is set." }, { "code": null, "e": 1277, "s": 1226, "text": "Here is the syntax of fflush(stdin) in C language," }, { "code": null, "e": 1303, "s": 1277, "text": "int fflush(FILE *stream);" }, { "code": null, "e": 1354, "s": 1303, "text": "Here is an example of fflush(stdin) in C language," }, { "code": null, "e": 1365, "s": 1354, "text": " Live Demo" }, { "code": null, "e": 1492, "s": 1365, "text": "#include\n#include\nint main() {\n char s[20] = \"Helloworld\";\n printf(\"The string : %s\", s);\n fflush(stdin);\n return 0;\n}" }, { "code": null, "e": 1516, "s": 1492, "text": "The string : Helloworld" } ]
What to press ctrl +f on a page in Selenium with python?
We can perform the action of pressing ctrl+f keys in Selenium. There are multiple special Keys available that enable the act of pressing keys via a keyboard like ctrl+c, ctrl+v, ctrl+f and many more. These special Keys are a part of selenium.webdriver.common.keys.Keys class. key_up() – This method releases a modifier key. The key_up() method is a part of Action Chains class and used to release a key pressed via key_down(). This method is widely used for coping and pasting actions via (ctrl+c, ctrl+v). In order to carry out this action, we need to first press the ctrl key downwards and simultaneously press the F key. These two steps can be automated by key_up() method and can only be used along with Shift, Alt and Control keys. key_up(args1, args2) Here args1 is the key to be sent. The key is defined in Keys class. The args2 parameter is the element to send keys. If omitted, it shall send a key to the element which is presently in focus. Code Implementation to press ctrl+f. from selenium import webdriver from selenium.webdriver import ActionChains from selenium.webdriver.common.keys import Keys #browser exposes an executable file #Through Selenium test we will invoke the executable file which will then #invoke actual browser driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe") # to maximize the browser window driver.maximize_window() #get method to launch the URL driver.get("https://www.tutorialspoint.com/about/about_careers.htm") #to refresh the browser driver.refresh() # action chain object creation a = ActionChains(driver) # perform the ctrl+f pressing action a.key_down(Keys.CONTROL).send_keys('F').key_up(Keys.CONTROL).perfo rm() #to close the browser driver.close()
[ { "code": null, "e": 1338, "s": 1062, "text": "We can perform the action of pressing ctrl+f keys in Selenium. There are multiple special Keys available that enable the act of pressing keys via a keyboard like ctrl+c, ctrl+v, ctrl+f and many more. These special Keys are a part of selenium.webdriver.common.keys.Keys class." }, { "code": null, "e": 1569, "s": 1338, "text": "key_up() – This method releases a modifier key. The key_up() method is a part of\nAction Chains class and used to release a key pressed via key_down(). This method\nis widely used for coping and pasting actions via (ctrl+c, ctrl+v)." }, { "code": null, "e": 1799, "s": 1569, "text": "In order to carry out this action, we need to first press the ctrl key downwards and\nsimultaneously press the F key. These two steps can be automated by key_up()\nmethod and can only be used along with Shift, Alt and Control keys." }, { "code": null, "e": 1820, "s": 1799, "text": "key_up(args1, args2)" }, { "code": null, "e": 1888, "s": 1820, "text": "Here args1 is the key to be sent. The key is defined in Keys class." }, { "code": null, "e": 2013, "s": 1888, "text": "The args2 parameter is the element to send keys. If omitted, it shall send a key to\nthe element which is presently in focus." }, { "code": null, "e": 2050, "s": 2013, "text": "Code Implementation to press ctrl+f." }, { "code": null, "e": 2772, "s": 2050, "text": "from selenium import webdriver\nfrom selenium.webdriver import ActionChains\nfrom selenium.webdriver.common.keys import Keys\n#browser exposes an executable file\n#Through Selenium test we will invoke the executable file which will then\n#invoke actual browser\ndriver = webdriver.Chrome(executable_path=\"C:\\\\chromedriver.exe\")\n# to maximize the browser window\ndriver.maximize_window()\n#get method to launch the URL\ndriver.get(\"https://www.tutorialspoint.com/about/about_careers.htm\")\n#to refresh the browser\ndriver.refresh()\n# action chain object creation\na = ActionChains(driver)\n# perform the ctrl+f pressing action\na.key_down(Keys.CONTROL).send_keys('F').key_up(Keys.CONTROL).perfo\nrm()\n#to close the browser\ndriver.close()" } ]
Triangle in C++
Suppose we have a triangle. We have to find the minimum path sum from top to the bottom. In each step, we can move to adjacent numbers on the row below. For example, if the following triangle is like [ [2], [3,4], [6,5,7], [4,1,8,3] ] The minimum path sum from top to bottom is 11 (2 + 3 + 5 + 1 = 11). Let us see the steps − Create one table to use in Dynamic programming approach. Create one table to use in Dynamic programming approach. n := size of triangle n := size of triangle for i := n – 2 down to 0for j := 0 to idp[j] := triangle[i, j] + minimum of dp[j] and dp[j + 1] for i := n – 2 down to 0 for j := 0 to idp[j] := triangle[i, j] + minimum of dp[j] and dp[j + 1] for j := 0 to i dp[j] := triangle[i, j] + minimum of dp[j] and dp[j + 1] dp[j] := triangle[i, j] + minimum of dp[j] and dp[j + 1] return dp[0] return dp[0] Let us see the following implementation to get better understanding − Live Demo #include <bits/stdc++.h> using namespace std; class Solution { public: int minimumTotal(vector<vector<int>>& triangle) { vector <int> dp(triangle.back()); int n = triangle.size(); for(int i = n - 2; i >= 0; i--){ for(int j = 0; j <= i; j++){ dp[j] = triangle[i][j] + min(dp[j], dp[j + 1]); } } return dp[0]; } }; main(){ Solution ob; vector<vector<int> > v = {{2},{3,4},{6,5,7},{4,1,8,3}}; cout << ob.minimumTotal(v); } [[2],[3,4],[6,5,7],[4,1,8,3]] 11
[ { "code": null, "e": 1215, "s": 1062, "text": "Suppose we have a triangle. We have to find the minimum path sum from top to the bottom. In each step, we can move to adjacent numbers on the row below." }, { "code": null, "e": 1262, "s": 1215, "text": "For example, if the following triangle is like" }, { "code": null, "e": 1315, "s": 1262, "text": "[\n [2],\n [3,4],\n [6,5,7],\n [4,1,8,3]\n]" }, { "code": null, "e": 1383, "s": 1315, "text": "The minimum path sum from top to bottom is 11 (2 + 3 + 5 + 1 = 11)." }, { "code": null, "e": 1406, "s": 1383, "text": "Let us see the steps −" }, { "code": null, "e": 1463, "s": 1406, "text": "Create one table to use in Dynamic programming approach." }, { "code": null, "e": 1520, "s": 1463, "text": "Create one table to use in Dynamic programming approach." }, { "code": null, "e": 1542, "s": 1520, "text": "n := size of triangle" }, { "code": null, "e": 1564, "s": 1542, "text": "n := size of triangle" }, { "code": null, "e": 1660, "s": 1564, "text": "for i := n – 2 down to 0for j := 0 to idp[j] := triangle[i, j] + minimum of dp[j] and dp[j + 1]" }, { "code": null, "e": 1685, "s": 1660, "text": "for i := n – 2 down to 0" }, { "code": null, "e": 1757, "s": 1685, "text": "for j := 0 to idp[j] := triangle[i, j] + minimum of dp[j] and dp[j + 1]" }, { "code": null, "e": 1773, "s": 1757, "text": "for j := 0 to i" }, { "code": null, "e": 1830, "s": 1773, "text": "dp[j] := triangle[i, j] + minimum of dp[j] and dp[j + 1]" }, { "code": null, "e": 1887, "s": 1830, "text": "dp[j] := triangle[i, j] + minimum of dp[j] and dp[j + 1]" }, { "code": null, "e": 1900, "s": 1887, "text": "return dp[0]" }, { "code": null, "e": 1913, "s": 1900, "text": "return dp[0]" }, { "code": null, "e": 1983, "s": 1913, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 1994, "s": 1983, "text": " Live Demo" }, { "code": null, "e": 2489, "s": 1994, "text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\npublic:\n int minimumTotal(vector<vector<int>>& triangle) {\n vector <int> dp(triangle.back());\n int n = triangle.size();\n for(int i = n - 2; i >= 0; i--){\n for(int j = 0; j <= i; j++){\n dp[j] = triangle[i][j] + min(dp[j], dp[j + 1]);\n }\n }\n return dp[0];\n }\n};\nmain(){\n Solution ob;\n vector<vector<int> > v = {{2},{3,4},{6,5,7},{4,1,8,3}};\n cout << ob.minimumTotal(v);\n}" }, { "code": null, "e": 2519, "s": 2489, "text": "[[2],[3,4],[6,5,7],[4,1,8,3]]" }, { "code": null, "e": 2522, "s": 2519, "text": "11" } ]
Pandas to_csv - Pandas Save Dataframe to CSV file - onlinetutorialspoint
PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC EXCEPTIONS COLLECTIONS SWING JDBC JAVA 8 SPRING SPRING BOOT HIBERNATE PYTHON PHP JQUERY PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws In this tutorial, we will see how we can save pandas dataframe to CSV file (comma separated values). The to_csv() method of pandas will save the data frame object as a comma-separated values file having a .csv extension. The official documentation provides the syntax below, We will learn the most commonly used among these in the following sections with an example. DataFrame.to_csv(path, sep=',', na_rep='', columns=None, header=True, index=True, index_label=None, mode='w', encoding=None, compression='infer', quoting=None, quotechar='"', line_terminator=None, chunksize=None, date_format=None, doublequote=True, escapechar=None, decimal='.', errors='strict') Let us look at some of the arguments to save the data-frame as a CSV file path – The path of the location where the file needs to be saved which end with the name of the file having a .csv extension. If only the name of the file is provided it will be saved in the same location as the script. sep – Delimiter to be used while saving the file. default is ‘,’. columns – Names to the columns from the data to write in the file. header – The name to be given to the columns when writing the file. index – A boolean value which determines whether the column index to be included or not in the output file. encoding – String representing the encoding to use in the output file, the default value is ‘utf-8’. See the code below to save the data frame that we have created above including its column indexes and changing the names of columns. data1.to_csv('saved_data.csv', header=['person_age','product_purchased'], sep=',',index=True) Output: Country,person_age,product_purchased Germany,30,No Spain,38,No Germany,40,Yes France,35,Yes See the code below to save the 10 rows data frame that we have parsed from the employee dataset above but using whitespace as the separator. import pandas as pd url = "https://raw.githubusercontent.com/kunalgupta2616/datasets/master/employees.csv" data2 = pd.read_csv(url,nrows=5,parse_dates=[2]) data2.to_csv('modified_emp_data.csv',sep=' ',index=False) Output: "First Name" Gender "Start Date" "Last Login Time" Salary "Bonus %" "Senior Management" Team Douglas Male 1993-08-06 "12:42 PM" 97308 6.945 True Marketing Thomas Male 1996-03-31 "6:53 AM" 61933 4.17 True Maria Female 1993-04-23 "11:17 AM" 130590 11.857999999999999 False Finance Jerry Male 2005-03-04 "1:00 PM" 138705 9.34 True Finance Larry Male 1998-01-24 "4:47 PM" 101004 1.389 True "Client Services" For convenience output file is uploaded at GitHub whose raw file link – modified_emp_data.csv So we learned about how we can read a CSV file and save a data frame as a CSV file along with customisations. What is Python NumPy Library Read CSV file in Pandas Happy Learning 🙂 Pandas read_csv – Read CSV file in Pandas and prepare Dataframe How to Convert Python List Of Objects to CSV File How to Read CSV File in Python Java – How to read CSV file and Map to Java Object How to check whether a file exists python ? How to read a text file in Python ? How to Delete a File or Directory in Python Python – How to create Zip File in Python ? Java How to create Jar File ? PHP File Handling fopen fread and fclose Example Python – Selenium Download a File in Headless Mode How to write (PHP fwrite) a file in PHP How to get Words Count in Python from a File Spring Boot Batch Example Csv to Database How to read JSON file in Python ? Pandas read_csv – Read CSV file in Pandas and prepare Dataframe How to Convert Python List Of Objects to CSV File How to Read CSV File in Python Java – How to read CSV file and Map to Java Object How to check whether a file exists python ? How to read a text file in Python ? How to Delete a File or Directory in Python Python – How to create Zip File in Python ? Java How to create Jar File ? PHP File Handling fopen fread and fclose Example Python – Selenium Download a File in Headless Mode How to write (PHP fwrite) a file in PHP How to get Words Count in Python from a File Spring Boot Batch Example Csv to Database How to read JSON file in Python ? Δ Python – Introduction Python – Features Python – Install on Windows Python – Modes of Program Python – Number System Python – Identifiers Python – Operators Python – Ternary Operator Python – Command Line Arguments Python – Keywords Python – Data Types Python – Upgrade Python PIP Python – Virtual Environment Pyhton – Type Casting Python – String to Int Python – Conditional Statements Python – if statement Python – *args and **kwargs Python – Date Formatting Python – Read input from keyboard Python – raw_input Python – List In Depth Python – List Comprehension Python – Set in Depth Python – Dictionary in Depth Python – Tuple in Depth Python – Stack Datastructure Python – Classes and Objects Python – Constructors Python – Object Introspection Python – Inheritance Python – Decorators Python – Serialization with Pickle Python – Exceptions Handling Python – User defined Exceptions Python – Multiprocessing Python – Default function parameters Python – Lambdas Functions Python – NumPy Library Python – MySQL Connector Python – MySQL Create Database Python – MySQL Read Data Python – MySQL Insert Data Python – MySQL Update Records Python – MySQL Delete Records Python – String Case Conversion Howto – Find biggest of 2 numbers Howto – Remove duplicates from List Howto – Convert any Number to Binary Howto – Merge two Lists Howto – Merge two dicts Howto – Get Characters Count in a File Howto – Get Words Count in a File Howto – Remove Spaces from String Howto – Read Env variables Howto – Read a text File Howto – Read a JSON File Howto – Read Config.ini files Howto – Iterate Dictionary Howto – Convert List Of Objects to CSV Howto – Merge two dict in Python Howto – create Zip File Howto – Get OS info Howto – Get size of Directory Howto – Check whether a file exists Howto – Remove key from dictionary Howto – Sort Objects Howto – Create or Delete Directories Howto – Read CSV File Howto – Create Python Iterable class Howto – Access for loop index Howto – Clear all elements from List Howto – Remove empty lists from a List Howto – Remove special characters from String Howto – Sort dictionary by key Howto – Filter a list
[ { "code": null, "e": 158, "s": 123, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 172, "s": 158, "text": "Java Examples" }, { "code": null, "e": 183, "s": 172, "text": "C Examples" }, { "code": null, "e": 195, "s": 183, "text": "C Tutorials" }, { "code": null, "e": 199, "s": 195, "text": "aws" }, { "code": null, "e": 234, "s": 199, "text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC" }, { "code": null, "e": 245, "s": 234, "text": "EXCEPTIONS" }, { "code": null, "e": 257, "s": 245, "text": "COLLECTIONS" }, { "code": null, "e": 263, "s": 257, "text": "SWING" }, { "code": null, "e": 268, "s": 263, "text": "JDBC" }, { "code": null, "e": 275, "s": 268, "text": "JAVA 8" }, { "code": null, "e": 282, "s": 275, "text": "SPRING" }, { "code": null, "e": 294, "s": 282, "text": "SPRING BOOT" }, { "code": null, "e": 304, "s": 294, "text": "HIBERNATE" }, { "code": null, "e": 311, "s": 304, "text": "PYTHON" }, { "code": null, "e": 315, "s": 311, "text": "PHP" }, { "code": null, "e": 322, "s": 315, "text": "JQUERY" }, { "code": null, "e": 357, "s": 322, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 371, "s": 357, "text": "Java Examples" }, { "code": null, "e": 382, "s": 371, "text": "C Examples" }, { "code": null, "e": 394, "s": 382, "text": "C Tutorials" }, { "code": null, "e": 398, "s": 394, "text": "aws" }, { "code": null, "e": 499, "s": 398, "text": "In this tutorial, we will see how we can save pandas dataframe to CSV file (comma separated values)." }, { "code": null, "e": 619, "s": 499, "text": "The to_csv() method of pandas will save the data frame object as a comma-separated values file having a .csv extension." }, { "code": null, "e": 765, "s": 619, "text": "The official documentation provides the syntax below, We will learn the most commonly used among these in the following sections with an example." }, { "code": null, "e": 1063, "s": 765, "text": "DataFrame.to_csv(path, sep=',', na_rep='', columns=None, header=True, index=True, index_label=None, mode='w', \nencoding=None, compression='infer', quoting=None, quotechar='\"', line_terminator=None, chunksize=None, date_format=None, \ndoublequote=True, escapechar=None, decimal='.', errors='strict')" }, { "code": null, "e": 1137, "s": 1063, "text": "Let us look at some of the arguments to save the data-frame as a CSV file" }, { "code": null, "e": 1357, "s": 1137, "text": "path – The path of the location where the file needs to be saved which end with the name of the file having a .csv extension. If only the name of the file is provided it will be saved in the same location as the script." }, { "code": null, "e": 1423, "s": 1357, "text": "sep – Delimiter to be used while saving the file. default is ‘,’." }, { "code": null, "e": 1490, "s": 1423, "text": "columns – Names to the columns from the data to write in the file." }, { "code": null, "e": 1558, "s": 1490, "text": "header – The name to be given to the columns when writing the file." }, { "code": null, "e": 1666, "s": 1558, "text": "index – A boolean value which determines whether the column index to be included or not in the output file." }, { "code": null, "e": 1767, "s": 1666, "text": "encoding – String representing the encoding to use in the output file, the default value is ‘utf-8’." }, { "code": null, "e": 1900, "s": 1767, "text": "See the code below to save the data frame that we have created above including its column indexes and changing the names of columns." }, { "code": null, "e": 2010, "s": 1900, "text": "data1.to_csv('saved_data.csv',\n header=['person_age','product_purchased'],\n sep=',',index=True)" }, { "code": null, "e": 2018, "s": 2010, "text": "Output:" }, { "code": null, "e": 2110, "s": 2018, "text": "Country,person_age,product_purchased\nGermany,30,No\nSpain,38,No\nGermany,40,Yes\nFrance,35,Yes" }, { "code": null, "e": 2251, "s": 2110, "text": "See the code below to save the 10 rows data frame that we have parsed from the employee dataset above but using whitespace as the separator." }, { "code": null, "e": 2465, "s": 2251, "text": "import pandas as pd\nurl = \"https://raw.githubusercontent.com/kunalgupta2616/datasets/master/employees.csv\"\ndata2 = pd.read_csv(url,nrows=5,parse_dates=[2])\ndata2.to_csv('modified_emp_data.csv',sep=' ',index=False)" }, { "code": null, "e": 2473, "s": 2465, "text": "Output:" }, { "code": null, "e": 2878, "s": 2473, "text": "\"First Name\" Gender \"Start Date\" \"Last Login Time\" Salary \"Bonus %\" \"Senior Management\" Team\nDouglas Male 1993-08-06 \"12:42 PM\" 97308 6.945 True Marketing\nThomas Male 1996-03-31 \"6:53 AM\" 61933 4.17 True \nMaria Female 1993-04-23 \"11:17 AM\" 130590 11.857999999999999 False Finance\nJerry Male 2005-03-04 \"1:00 PM\" 138705 9.34 True Finance\nLarry Male 1998-01-24 \"4:47 PM\" 101004 1.389 True \"Client Services\"" }, { "code": null, "e": 2972, "s": 2878, "text": "For convenience output file is uploaded at GitHub whose raw file link – modified_emp_data.csv" }, { "code": null, "e": 3082, "s": 2972, "text": "So we learned about how we can read a CSV file and save a data frame as a CSV file along with customisations." }, { "code": null, "e": 3111, "s": 3082, "text": "What is Python NumPy Library" }, { "code": null, "e": 3135, "s": 3111, "text": "Read CSV file in Pandas" }, { "code": null, "e": 3152, "s": 3135, "text": "Happy Learning 🙂" }, { "code": null, "e": 3810, "s": 3152, "text": "\nPandas read_csv – Read CSV file in Pandas and prepare Dataframe\nHow to Convert Python List Of Objects to CSV File\nHow to Read CSV File in Python\nJava – How to read CSV file and Map to Java Object\nHow to check whether a file exists python ?\nHow to read a text file in Python ?\nHow to Delete a File or Directory in Python\nPython – How to create Zip File in Python ?\nJava How to create Jar File ?\nPHP File Handling fopen fread and fclose Example\nPython – Selenium Download a File in Headless Mode\nHow to write (PHP fwrite) a file in PHP\nHow to get Words Count in Python from a File\nSpring Boot Batch Example Csv to Database\nHow to read JSON file in Python ?\n" }, { "code": null, "e": 3874, "s": 3810, "text": "Pandas read_csv – Read CSV file in Pandas and prepare Dataframe" }, { "code": null, "e": 3924, "s": 3874, "text": "How to Convert Python List Of Objects to CSV File" }, { "code": null, "e": 3955, "s": 3924, "text": "How to Read CSV File in Python" }, { "code": null, "e": 4006, "s": 3955, "text": "Java – How to read CSV file and Map to Java Object" }, { "code": null, "e": 4050, "s": 4006, "text": "How to check whether a file exists python ?" }, { "code": null, "e": 4086, "s": 4050, "text": "How to read a text file in Python ?" }, { "code": null, "e": 4130, "s": 4086, "text": "How to Delete a File or Directory in Python" }, { "code": null, "e": 4174, "s": 4130, "text": "Python – How to create Zip File in Python ?" }, { "code": null, "e": 4204, "s": 4174, "text": "Java How to create Jar File ?" }, { "code": null, "e": 4254, "s": 4204, "text": "PHP File Handling fopen fread and fclose Example" }, { "code": null, "e": 4305, "s": 4254, "text": "Python – Selenium Download a File in Headless Mode" }, { "code": null, "e": 4345, "s": 4305, "text": "How to write (PHP fwrite) a file in PHP" }, { "code": null, "e": 4390, "s": 4345, "text": "How to get Words Count in Python from a File" }, { "code": null, "e": 4432, "s": 4390, "text": "Spring Boot Batch Example Csv to Database" }, { "code": null, "e": 4466, "s": 4432, "text": "How to read JSON file in Python ?" }, { "code": null, "e": 4472, "s": 4470, "text": "Δ" }, { "code": null, "e": 4495, "s": 4472, "text": " Python – Introduction" }, { "code": null, "e": 4514, "s": 4495, "text": " Python – Features" }, { "code": null, "e": 4543, "s": 4514, "text": " Python – Install on Windows" }, { "code": null, "e": 4570, "s": 4543, "text": " Python – Modes of Program" }, { "code": null, "e": 4594, "s": 4570, "text": " Python – Number System" }, { "code": null, "e": 4616, "s": 4594, "text": " Python – Identifiers" }, { "code": null, "e": 4636, "s": 4616, "text": " Python – Operators" }, { "code": null, "e": 4663, "s": 4636, "text": " Python – Ternary Operator" }, { "code": null, "e": 4696, "s": 4663, "text": " Python – Command Line Arguments" }, { "code": null, "e": 4715, "s": 4696, "text": " Python – Keywords" }, { "code": null, "e": 4736, "s": 4715, "text": " Python – Data Types" }, { "code": null, "e": 4765, "s": 4736, "text": " Python – Upgrade Python PIP" }, { "code": null, "e": 4795, "s": 4765, "text": " Python – Virtual Environment" }, { "code": null, "e": 4818, "s": 4795, "text": " Pyhton – Type Casting" }, { "code": null, "e": 4842, "s": 4818, "text": " Python – String to Int" }, { "code": null, "e": 4875, "s": 4842, "text": " Python – Conditional Statements" }, { "code": null, "e": 4898, "s": 4875, "text": " Python – if statement" }, { "code": null, "e": 4927, "s": 4898, "text": " Python – *args and **kwargs" }, { "code": null, "e": 4953, "s": 4927, "text": " Python – Date Formatting" }, { "code": null, "e": 4988, "s": 4953, "text": " Python – Read input from keyboard" }, { "code": null, "e": 5008, "s": 4988, "text": " Python – raw_input" }, { "code": null, "e": 5032, "s": 5008, "text": " Python – List In Depth" }, { "code": null, "e": 5061, "s": 5032, "text": " Python – List Comprehension" }, { "code": null, "e": 5084, "s": 5061, "text": " Python – Set in Depth" }, { "code": null, "e": 5114, "s": 5084, "text": " Python – Dictionary in Depth" }, { "code": null, "e": 5139, "s": 5114, "text": " Python – Tuple in Depth" }, { "code": null, "e": 5169, "s": 5139, "text": " Python – Stack Datastructure" }, { "code": null, "e": 5199, "s": 5169, "text": " Python – Classes and Objects" }, { "code": null, "e": 5222, "s": 5199, "text": " Python – Constructors" }, { "code": null, "e": 5253, "s": 5222, "text": " Python – Object Introspection" }, { "code": null, "e": 5275, "s": 5253, "text": " Python – Inheritance" }, { "code": null, "e": 5296, "s": 5275, "text": " Python – Decorators" }, { "code": null, "e": 5332, "s": 5296, "text": " Python – Serialization with Pickle" }, { "code": null, "e": 5362, "s": 5332, "text": " Python – Exceptions Handling" }, { "code": null, "e": 5396, "s": 5362, "text": " Python – User defined Exceptions" }, { "code": null, "e": 5422, "s": 5396, "text": " Python – Multiprocessing" }, { "code": null, "e": 5460, "s": 5422, "text": " Python – Default function parameters" }, { "code": null, "e": 5488, "s": 5460, "text": " Python – Lambdas Functions" }, { "code": null, "e": 5512, "s": 5488, "text": " Python – NumPy Library" }, { "code": null, "e": 5538, "s": 5512, "text": " Python – MySQL Connector" }, { "code": null, "e": 5570, "s": 5538, "text": " Python – MySQL Create Database" }, { "code": null, "e": 5596, "s": 5570, "text": " Python – MySQL Read Data" }, { "code": null, "e": 5624, "s": 5596, "text": " Python – MySQL Insert Data" }, { "code": null, "e": 5655, "s": 5624, "text": " Python – MySQL Update Records" }, { "code": null, "e": 5686, "s": 5655, "text": " Python – MySQL Delete Records" }, { "code": null, "e": 5719, "s": 5686, "text": " Python – String Case Conversion" }, { "code": null, "e": 5754, "s": 5719, "text": " Howto – Find biggest of 2 numbers" }, { "code": null, "e": 5791, "s": 5754, "text": " Howto – Remove duplicates from List" }, { "code": null, "e": 5829, "s": 5791, "text": " Howto – Convert any Number to Binary" }, { "code": null, "e": 5855, "s": 5829, "text": " Howto – Merge two Lists" }, { "code": null, "e": 5880, "s": 5855, "text": " Howto – Merge two dicts" }, { "code": null, "e": 5920, "s": 5880, "text": " Howto – Get Characters Count in a File" }, { "code": null, "e": 5955, "s": 5920, "text": " Howto – Get Words Count in a File" }, { "code": null, "e": 5990, "s": 5955, "text": " Howto – Remove Spaces from String" }, { "code": null, "e": 6019, "s": 5990, "text": " Howto – Read Env variables" }, { "code": null, "e": 6045, "s": 6019, "text": " Howto – Read a text File" }, { "code": null, "e": 6071, "s": 6045, "text": " Howto – Read a JSON File" }, { "code": null, "e": 6103, "s": 6071, "text": " Howto – Read Config.ini files" }, { "code": null, "e": 6131, "s": 6103, "text": " Howto – Iterate Dictionary" }, { "code": null, "e": 6171, "s": 6131, "text": " Howto – Convert List Of Objects to CSV" }, { "code": null, "e": 6205, "s": 6171, "text": " Howto – Merge two dict in Python" }, { "code": null, "e": 6230, "s": 6205, "text": " Howto – create Zip File" }, { "code": null, "e": 6251, "s": 6230, "text": " Howto – Get OS info" }, { "code": null, "e": 6282, "s": 6251, "text": " Howto – Get size of Directory" }, { "code": null, "e": 6319, "s": 6282, "text": " Howto – Check whether a file exists" }, { "code": null, "e": 6356, "s": 6319, "text": " Howto – Remove key from dictionary" }, { "code": null, "e": 6378, "s": 6356, "text": " Howto – Sort Objects" }, { "code": null, "e": 6416, "s": 6378, "text": " Howto – Create or Delete Directories" }, { "code": null, "e": 6439, "s": 6416, "text": " Howto – Read CSV File" }, { "code": null, "e": 6477, "s": 6439, "text": " Howto – Create Python Iterable class" }, { "code": null, "e": 6508, "s": 6477, "text": " Howto – Access for loop index" }, { "code": null, "e": 6546, "s": 6508, "text": " Howto – Clear all elements from List" }, { "code": null, "e": 6586, "s": 6546, "text": " Howto – Remove empty lists from a List" }, { "code": null, "e": 6633, "s": 6586, "text": " Howto – Remove special characters from String" }, { "code": null, "e": 6665, "s": 6633, "text": " Howto – Sort dictionary by key" } ]
Count Occurences of Anagrams | Practice | GeeksforGeeks
Given a word pat and a text txt. Return the count of the occurences of anagrams of the word in the text. Example 1: Input: txt = forxxorfxdofr pat = for Output: 3 Explanation: for, orf and ofr appears in the txt, hence answer is 3. Example 2: Input: txt = aabaabaa pat = aaba Output: 4 Explanation: aaba is present 4 times in txt. Your Task: Complete the function search() which takes two strings pat, txt, as input parameters and returns an integer denoting the answer. You don't to print answer or take inputs. Expected Time Complexity: O(N) Expected Auxiliary Space: O(26) or O(256) Constraints: 1 <= |pat| <= |txt| <= 105 Both string contains lowercase english letters. 0 abhinavverma281 week ago int search(string pat, string txt) { int K = pat.size(); int N = txt.size(); int start = 0; int end = 0; int countOfAnagrams = 0; vector<int> pattern_hash(26, 0); vector<int> hash(26, 0); for (char ch : pat) ++pattern_hash[ch - 'a']; while (end < N) { ++hash[txt[end] - 'a']; if (end - start + 1 < K) ++end; else if (end - start + 1 == K) { if (pattern_hash == hash) { ++countOfAnagrams; } if(hash[txt[start] - 'a'] != 0) --hash[txt[start] - 'a']; ++start; ++end; } } return countOfAnagrams; } 0 abhinavverma28 This comment was deleted. -1 19bcs13142 weeks ago Simplest java soln class Solution { int search(String pat, String txt) { // code here Map<Character,Integer> map=new HashMap<>(); for(int k=0;k<pat.length();k++){ map.put(pat.charAt(k),map.getOrDefault(pat.charAt(k),0)+1); } int i=0,j=0,count=map.size(),total=0,n=txt.length(); int k=pat.length(); while(j<n){ char temp=txt.charAt(j); if(map.containsKey(temp)){ map.replace(temp,map.get(temp)-1); if(map.get(temp)==0){ count--; } } if(j-i+1<k){ j++; }else if(j-i+1==k){ if(count==0){ total++; } char x=txt.charAt(i); if(map.containsKey(x)){ if(map.get(x)==0) count++; map.replace(x,map.get(x)+1); i++; j++; }else{ i++; j++; } } } return total; } } 0 ravikant021113 weeks ago //simplest solution using sliding window technique class Solution { int search(String pat, String txt) { // code here if(txt.length() < pat.length()){ return 0; } int countpat[] = new int[26]; int counttxt[] = new int[26]; for(int i = 0; i < pat.length(); i++){ countpat[pat.charAt(i)-'a']++; counttxt[txt.charAt(i)-'a']++; } int count = 0; if(Arrays.equals(countpat, counttxt)){ count++; } for(int i = pat.length(); i < txt.length(); i++){ counttxt[txt.charAt(i)-'a']++; counttxt[txt.charAt(i-pat.length())-'a']--; if(Arrays.equals(countpat, counttxt)){ count++; } } return count; }} +3 hiphopsamreen4 weeks ago // Sliding Window Approach: = Easiest Approach int search(string pat, string txt) { int K = pat.size(); int N = txt.size(); int i = 0; int j = 0; int countOfAnagrams = 0; vector<int> pattern_hash(26, 0); vector<int> hash(26, 0); for (char ch : pat) ++pattern_hash[ch - 'a']; while (j < N) { ++hash[txt[j] - 'a']; if (j - i + 1 < K) { ++j; } else if (j - i + 1 == K) { if (pattern_hash == hash) { ++countOfAnagrams; } // 'i' will be a char in txt and that char's ascii value is the index of hash if(hash[txt[i] - 'a'] != 0) --hash[txt[i] - 'a']; ++i; ++j; } } return countOfAnagrams; } // Note: See Constraints of this problem: // Both string contains lowercase english letters. //cout << 'a'-'a' << endl; // 0 //cout << 'b'-'a' << endl; // 1 //cout << 'c'-'a' << endl; // 2 0 rishavdey20001 month ago //Simple Java Solution by Sliding Window Technique class Solution { int search(String pat, String txt) { // code here int CP[] = new int[26]; int CT[] = new int[26]; for(int i=0;i<pat.length();i++) { CP[pat.charAt(i)-'a']++; CT[txt.charAt(i)-'a']++; } int count = 0; for(int i=pat.length();i<txt.length();i++) { if(isSame(CP,CT)) count++; CT[txt.charAt(i)-'a']++; CT[txt.charAt(i-pat.length())-'a']--; } return count; } boolean isSame(int CP[], int CT[]) { for(int i=0;i<26;i++) { if(CP[i]!=CT[i]) return false; } return true; }} 0 pavansunny5671 month ago HINT ---Create hash like list to compare Python solution among 26 alphabets the given PAT has some occurances.....fill the occurances in a list like this PAT="for" then list=[0,0,0,0,0,1,........], 1 at f's place and and 1 at ‘o’ and ‘r’ place . this act as comparing hash Now do similar addition and subtraction in ans list for every k elements, where k represents length of PAT given if both lists matches add +1 to answer.....hehe anthe def search(self,pat, txt): # code here k=len(pat) n=len(txt) #Two lists pat_list=[0]*26 ans_list=[0]*26 if n<k: return 0 ret=0 #creating hash list to compare #97 is ord(a) so , subtracting from it gives #index number for ele in pat: index=ord(ele.lower())-97 pat_list[index]+=1 #first k elements for i in range(k): index=ord(txt[i].lower())-97 ans_list[index]+=1 #repeating the process for n for i in range(k,n): #comparing if match occured if ans_list==pat_list: ret+=1 remove=ord(txt[i-k].lower())-97 ans_list[remove]-=1 index=ord(txt[i].lower())-97 ans_list[index]+=1 if ans_list==pat_list: ret+=1 return ret +1 archit232001 month ago JAVA Simple and Easy to Understand approach: int search(String s2, String s1) { char []c=s2.toCharArray(); char[] c1=s1.toCharArray(); Map<Character,Integer> m=new LinkedHashMap<>(); Map<Character,Integer> m1=new LinkedHashMap<>(); for(int j=0;j<s2.length();j++){ m.put(c[j],(m.get(c[j])==null?1:m.get(c[j])+1)); } int i=0; int j=0; int finalAns=0; int k=s2.length(); while(j<s1.length()){ m1.put(c1[j],m1.get(c1[j])==null?1:(m1.get(c1[j])+1)); if(j-i+1<k){ j++; } else if(j-i+1==k){ if(m1.equals(m)) { finalAns++; } m1.put(c1[i],(m1.get(c1[i])-1)); if(m1.get(c1[i])==0){ m1.remove(c1[i]); } i++; j++; } } return finalAns; } 0 sourabhgharad19062 months ago int search(String pat, String txt) { HashMap<Character,Integer> pmap = new HashMap<>(); HashMap<Character,Integer> tmap = new HashMap<>(); int j = 0; int k; int count = 0; for(int i=0;i<pat.length();i++){ char ch = pat.charAt(i); pmap.put(ch,pmap.getOrDefault(ch,0)+1); } for(k=0;k<pat.length();k++){ char ch = txt.charAt(k); tmap.put(ch,tmap.getOrDefault(ch,0)+1); } if(pmap.equals(tmap)){ count++; } while(j<txt.length()-pat.length() && k<txt.length()){ char ch = txt.charAt(j); char c = txt.charAt(k); if(tmap.get(ch) == 1){ tmap.remove(ch); } else{ tmap.put(ch,tmap.get(ch)-1); } tmap.put(c,tmap.getOrDefault(c,0)+1); if(pmap.equals(tmap)){ count++; } j++; k++; } return count; } 0 shalini15052 months ago *USING SLIDING WINDOW* int search(string pat, string txt) { int i=0,j=0; vector<int>ans(26,0); for(int c=0;c<pat.size();c++) { ans[pat[c]-'a']++; } int sum=0; vector<int>arr(26,0); while(j<txt.size()) { while((j-i)<pat.size()) { arr[txt[j]-'a']++; j++; } if(ans==arr) { sum++; } arr[txt[i]-'a']--; i++; } return sum;} 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": 331, "s": 226, "text": "Given a word pat and a text txt. Return the count of the occurences of anagrams of the word in the text." }, { "code": null, "e": 342, "s": 331, "text": "Example 1:" }, { "code": null, "e": 459, "s": 342, "text": "Input:\ntxt = forxxorfxdofr\npat = for\nOutput: 3\nExplanation: for, orf and ofr appears\nin the txt, hence answer is 3.\n" }, { "code": null, "e": 470, "s": 459, "text": "Example 2:" }, { "code": null, "e": 559, "s": 470, "text": "Input:\ntxt = aabaabaa\npat = aaba\nOutput: 4\nExplanation: aaba is present 4 times\nin txt.\n" }, { "code": null, "e": 741, "s": 559, "text": "Your Task:\nComplete the function search() which takes two strings pat, txt, as input parameters and returns an integer denoting the answer. You don't to print answer or take inputs." }, { "code": null, "e": 814, "s": 741, "text": "Expected Time Complexity: O(N)\nExpected Auxiliary Space: O(26) or O(256)" }, { "code": null, "e": 902, "s": 814, "text": "Constraints:\n1 <= |pat| <= |txt| <= 105\nBoth string contains lowercase english letters." }, { "code": null, "e": 906, "s": 904, "text": "0" }, { "code": null, "e": 931, "s": 906, "text": "abhinavverma281 week ago" }, { "code": null, "e": 1626, "s": 931, "text": " int search(string pat, string txt) { int K = pat.size(); int N = txt.size(); int start = 0; int end = 0; int countOfAnagrams = 0; vector<int> pattern_hash(26, 0); vector<int> hash(26, 0); for (char ch : pat) ++pattern_hash[ch - 'a']; while (end < N) { ++hash[txt[end] - 'a']; if (end - start + 1 < K) ++end; else if (end - start + 1 == K) { if (pattern_hash == hash) { ++countOfAnagrams; } if(hash[txt[start] - 'a'] != 0) --hash[txt[start] - 'a']; ++start; ++end; } }" }, { "code": null, "e": 1657, "s": 1626, "text": " return countOfAnagrams; } " }, { "code": null, "e": 1659, "s": 1657, "text": "0" }, { "code": null, "e": 1674, "s": 1659, "text": "abhinavverma28" }, { "code": null, "e": 1700, "s": 1674, "text": "This comment was deleted." }, { "code": null, "e": 1703, "s": 1700, "text": "-1" }, { "code": null, "e": 1724, "s": 1703, "text": "19bcs13142 weeks ago" }, { "code": null, "e": 2972, "s": 1724, "text": "\nSimplest java soln\nclass Solution {\n\n int search(String pat, String txt) {\n // code here\n \n Map<Character,Integer> map=new HashMap<>();\n for(int k=0;k<pat.length();k++){\n map.put(pat.charAt(k),map.getOrDefault(pat.charAt(k),0)+1);\n \n }\n \n int i=0,j=0,count=map.size(),total=0,n=txt.length();\n int k=pat.length();\n \n while(j<n){\n \n char temp=txt.charAt(j);\n if(map.containsKey(temp)){\n map.replace(temp,map.get(temp)-1);\n if(map.get(temp)==0){\n count--;\n }\n }\n \n if(j-i+1<k){\n j++;\n }else if(j-i+1==k){\n if(count==0){\n total++;\n }\n char x=txt.charAt(i);\n if(map.containsKey(x)){\n if(map.get(x)==0) count++;\n \n map.replace(x,map.get(x)+1);\n i++;\n j++;\n }else{\n i++;\n j++;\n }\n \n }\n }\n \n return total;\n }\n}" }, { "code": null, "e": 2974, "s": 2972, "text": "0" }, { "code": null, "e": 2999, "s": 2974, "text": "ravikant021113 weeks ago" }, { "code": null, "e": 3067, "s": 2999, "text": "//simplest solution using sliding window technique class Solution {" }, { "code": null, "e": 3867, "s": 3067, "text": " int search(String pat, String txt) { // code here if(txt.length() < pat.length()){ return 0; } int countpat[] = new int[26]; int counttxt[] = new int[26]; for(int i = 0; i < pat.length(); i++){ countpat[pat.charAt(i)-'a']++; counttxt[txt.charAt(i)-'a']++; } int count = 0; if(Arrays.equals(countpat, counttxt)){ count++; } for(int i = pat.length(); i < txt.length(); i++){ counttxt[txt.charAt(i)-'a']++; counttxt[txt.charAt(i-pat.length())-'a']--; if(Arrays.equals(countpat, counttxt)){ count++; } } return count; }}" }, { "code": null, "e": 3870, "s": 3867, "text": "+3" }, { "code": null, "e": 3895, "s": 3870, "text": "hiphopsamreen4 weeks ago" }, { "code": null, "e": 3942, "s": 3895, "text": "// Sliding Window Approach: = Easiest Approach" }, { "code": null, "e": 3977, "s": 3942, "text": "int search(string pat, string txt)" }, { "code": null, "e": 3979, "s": 3977, "text": "{" }, { "code": null, "e": 4001, "s": 3979, "text": " int K = pat.size();" }, { "code": null, "e": 4023, "s": 4001, "text": " int N = txt.size();" }, { "code": null, "e": 4036, "s": 4023, "text": " int i = 0;" }, { "code": null, "e": 4049, "s": 4036, "text": " int j = 0;" }, { "code": null, "e": 4076, "s": 4049, "text": " int countOfAnagrams = 0;" }, { "code": null, "e": 4113, "s": 4078, "text": " vector<int> pattern_hash(26, 0);" }, { "code": null, "e": 4140, "s": 4113, "text": " vector<int> hash(26, 0);" }, { "code": null, "e": 4164, "s": 4142, "text": " for (char ch : pat)" }, { "code": null, "e": 4194, "s": 4164, "text": " ++pattern_hash[ch - 'a'];" }, { "code": null, "e": 4212, "s": 4196, "text": " while (j < N)" }, { "code": null, "e": 4216, "s": 4212, "text": " {" }, { "code": null, "e": 4242, "s": 4216, "text": " ++hash[txt[j] - 'a'];" }, { "code": null, "e": 4265, "s": 4242, "text": " if (j - i + 1 < K)" }, { "code": null, "e": 4271, "s": 4265, "text": " {" }, { "code": null, "e": 4282, "s": 4271, "text": " ++j;" }, { "code": null, "e": 4288, "s": 4282, "text": " }" }, { "code": null, "e": 4317, "s": 4288, "text": " else if (j - i + 1 == K)" }, { "code": null, "e": 4323, "s": 4317, "text": " {" }, { "code": null, "e": 4355, "s": 4323, "text": " if (pattern_hash == hash)" }, { "code": null, "e": 4363, "s": 4355, "text": " {" }, { "code": null, "e": 4390, "s": 4363, "text": " ++countOfAnagrams;" }, { "code": null, "e": 4398, "s": 4390, "text": " }" }, { "code": null, "e": 4482, "s": 4398, "text": " // 'i' will be a char in txt and that char's ascii value is the index of hash" }, { "code": null, "e": 4516, "s": 4482, "text": " if(hash[txt[i] - 'a'] != 0)" }, { "code": null, "e": 4544, "s": 4516, "text": " --hash[txt[i] - 'a'];" }, { "code": null, "e": 4555, "s": 4544, "text": " ++i;" }, { "code": null, "e": 4566, "s": 4555, "text": " ++j;" }, { "code": null, "e": 4572, "s": 4566, "text": " }" }, { "code": null, "e": 4576, "s": 4572, "text": " }" }, { "code": null, "e": 4602, "s": 4576, "text": " return countOfAnagrams;" }, { "code": null, "e": 4604, "s": 4602, "text": "}" }, { "code": null, "e": 4646, "s": 4604, "text": "// Note: See Constraints of this problem:" }, { "code": null, "e": 4697, "s": 4646, "text": "// Both string contains lowercase english letters." }, { "code": null, "e": 4733, "s": 4697, "text": " //cout << 'a'-'a' << endl; // 0" }, { "code": null, "e": 4769, "s": 4733, "text": " //cout << 'b'-'a' << endl; // 1" }, { "code": null, "e": 4805, "s": 4769, "text": " //cout << 'c'-'a' << endl; // 2" }, { "code": null, "e": 4807, "s": 4805, "text": "0" }, { "code": null, "e": 4832, "s": 4807, "text": "rishavdey20001 month ago" }, { "code": null, "e": 4883, "s": 4832, "text": "//Simple Java Solution by Sliding Window Technique" }, { "code": null, "e": 5587, "s": 4883, "text": "class Solution { int search(String pat, String txt) { // code here int CP[] = new int[26]; int CT[] = new int[26]; for(int i=0;i<pat.length();i++) { CP[pat.charAt(i)-'a']++; CT[txt.charAt(i)-'a']++; } int count = 0; for(int i=pat.length();i<txt.length();i++) { if(isSame(CP,CT)) count++; CT[txt.charAt(i)-'a']++; CT[txt.charAt(i-pat.length())-'a']--; } return count; } boolean isSame(int CP[], int CT[]) { for(int i=0;i<26;i++) { if(CP[i]!=CT[i]) return false; } return true; }}" }, { "code": null, "e": 5589, "s": 5587, "text": "0" }, { "code": null, "e": 5614, "s": 5589, "text": "pavansunny5671 month ago" }, { "code": null, "e": 5655, "s": 5614, "text": "HINT ---Create hash like list to compare" }, { "code": null, "e": 5671, "s": 5655, "text": "Python solution" }, { "code": null, "e": 5887, "s": 5671, "text": "among 26 alphabets the given PAT has some occurances.....fill the occurances in a list like this PAT=\"for\" then list=[0,0,0,0,0,1,........], 1 at f's place and and 1 at ‘o’ and ‘r’ place . this act as comparing hash" }, { "code": null, "e": 6000, "s": 5887, "text": "Now do similar addition and subtraction in ans list for every k elements, where k represents length of PAT given" }, { "code": null, "e": 6054, "s": 6000, "text": "if both lists matches add +1 to answer.....hehe anthe" }, { "code": null, "e": 6986, "s": 6054, "text": "def search(self,pat, txt):\n\t # code here\n\t k=len(pat)\n\t n=len(txt)\n\t #Two lists\n\t pat_list=[0]*26\n\t ans_list=[0]*26\n\t if n<k:\n\t return 0\n ret=0\n #creating hash list to compare\n #97 is ord(a) so , subtracting from it gives\n #index number\n for ele in pat:\n index=ord(ele.lower())-97\n pat_list[index]+=1\n \n #first k elements\n for i in range(k):\n index=ord(txt[i].lower())-97\n ans_list[index]+=1\n \n #repeating the process for n\n for i in range(k,n):\n #comparing if match occured\n if ans_list==pat_list:\n ret+=1\n remove=ord(txt[i-k].lower())-97\n ans_list[remove]-=1\n index=ord(txt[i].lower())-97\n ans_list[index]+=1\n \n if ans_list==pat_list:\n ret+=1\n \n return ret" }, { "code": null, "e": 6989, "s": 6986, "text": "+1" }, { "code": null, "e": 7012, "s": 6989, "text": "archit232001 month ago" }, { "code": null, "e": 7057, "s": 7012, "text": "JAVA Simple and Easy to Understand approach:" }, { "code": null, "e": 7985, "s": 7057, "text": "int search(String s2, String s1) {\n char []c=s2.toCharArray();\n char[] c1=s1.toCharArray();\n Map<Character,Integer> m=new LinkedHashMap<>();\n Map<Character,Integer> m1=new LinkedHashMap<>();\n for(int j=0;j<s2.length();j++){\n m.put(c[j],(m.get(c[j])==null?1:m.get(c[j])+1));\n }\n int i=0;\n int j=0;\n int finalAns=0;\n int k=s2.length();\n while(j<s1.length()){\n m1.put(c1[j],m1.get(c1[j])==null?1:(m1.get(c1[j])+1));\n if(j-i+1<k){\n j++;\n }\n else if(j-i+1==k){\n if(m1.equals(m)) {\n finalAns++;\n }\n m1.put(c1[i],(m1.get(c1[i])-1));\n if(m1.get(c1[i])==0){\n m1.remove(c1[i]);\n }\n i++;\n j++;\n }\n }\n return finalAns;\n }" }, { "code": null, "e": 7987, "s": 7985, "text": "0" }, { "code": null, "e": 8017, "s": 7987, "text": "sourabhgharad19062 months ago" }, { "code": null, "e": 8989, "s": 8017, "text": "int search(String pat, String txt) { HashMap<Character,Integer> pmap = new HashMap<>(); HashMap<Character,Integer> tmap = new HashMap<>(); int j = 0; int k; int count = 0; for(int i=0;i<pat.length();i++){ char ch = pat.charAt(i); pmap.put(ch,pmap.getOrDefault(ch,0)+1); } for(k=0;k<pat.length();k++){ char ch = txt.charAt(k); tmap.put(ch,tmap.getOrDefault(ch,0)+1); } if(pmap.equals(tmap)){ count++; } while(j<txt.length()-pat.length() && k<txt.length()){ char ch = txt.charAt(j); char c = txt.charAt(k); if(tmap.get(ch) == 1){ tmap.remove(ch); } else{ tmap.put(ch,tmap.get(ch)-1); } tmap.put(c,tmap.getOrDefault(c,0)+1); if(pmap.equals(tmap)){ count++; } j++; k++; } return count; }" }, { "code": null, "e": 8991, "s": 8989, "text": "0" }, { "code": null, "e": 9015, "s": 8991, "text": "shalini15052 months ago" }, { "code": null, "e": 9038, "s": 9015, "text": "*USING SLIDING WINDOW*" }, { "code": null, "e": 9463, "s": 9038, "text": "int search(string pat, string txt) { int i=0,j=0; vector<int>ans(26,0); for(int c=0;c<pat.size();c++) { ans[pat[c]-'a']++; } int sum=0; vector<int>arr(26,0); while(j<txt.size()) { while((j-i)<pat.size()) { arr[txt[j]-'a']++; j++; } if(ans==arr) { sum++; } arr[txt[i]-'a']--; i++; } return sum;} " }, { "code": null, "e": 9609, "s": 9463, "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": 9645, "s": 9609, "text": " Login to access your submissions. " }, { "code": null, "e": 9655, "s": 9645, "text": "\nProblem\n" }, { "code": null, "e": 9665, "s": 9655, "text": "\nContest\n" }, { "code": null, "e": 9728, "s": 9665, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 9876, "s": 9728, "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": 10084, "s": 9876, "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": 10190, "s": 10084, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Count of distinct permutations of length N having no similar adjacent characters - GeeksforGeeks
29 Apr, 2021 Given an integer N, the task is to calculate the total number of distinct permutations of length N, consisting only of letters ‘a’, ‘b’, and ‘c’, with repetitions allowed, such that no two adjacent characters are the same. Input: N = 3 Output: 12 Explanation: Possible permutations satisfying the required conditions are {aba, abc, aca, acb, bac, bab, bca, bcb, cac, cab, cba, cbc}Input: N = 5 Output: 48 Approach: Following observations need to be made to solve the given problem: Let us fix the first letter as ‘a’.Now, the 2nd letter can either be ‘b’ or ‘c’, which leaves 2 ways to fill the second letter.Similarly, the third letter can also be filled in two ways. If the character in 2nd position is ‘b’, the third character can either be ‘a’ or ‘c’. If the character in 2nd position is ‘c’, the third character can either be ‘a’ or ‘b’.Similarly, for all the remaining positions, there will always be two possibilities depending on the character in the previous position. Therefore, the total number of possible permutation if ‘a’ occupies the first position is 1*2*2*2...*2 = 1 * 2N – 1.Therefore, the total number of permutations, considering the first character can also be ‘b’ or ‘c’ as well, is 3 * 2N – 1. Let us fix the first letter as ‘a’. Now, the 2nd letter can either be ‘b’ or ‘c’, which leaves 2 ways to fill the second letter. Similarly, the third letter can also be filled in two ways. If the character in 2nd position is ‘b’, the third character can either be ‘a’ or ‘c’. If the character in 2nd position is ‘c’, the third character can either be ‘a’ or ‘b’. Similarly, for all the remaining positions, there will always be two possibilities depending on the character in the previous position. Therefore, the total number of possible permutation if ‘a’ occupies the first position is 1*2*2*2...*2 = 1 * 2N – 1. Therefore, the total number of permutations, considering the first character can also be ‘b’ or ‘c’ as well, is 3 * 2N – 1. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ Program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to print the number of// permutations possibleint countofPermutations(int N){ return int(3 * pow(2, N - 1));} // Driver Codeint main(){ int N = 5; cout << countofPermutations(N); return 0;} // Java program to implement// the above approachclass GFG{ // Function to print the number of// permutations possiblestatic int countofPermutations(int N){ return (int)(3 * Math.pow(2, N - 1));} // Driver Codepublic static void main(String[] args){ int N = 5; System.out.print(countofPermutations(N));}} // This code is contributed by 29AjayKumar # Python3 program to implement# the above approach # Function to print the number of# permutations possibledef countofPermutations(N): return int((3 * pow(2, N - 1))); # Driver Codeif __name__ == '__main__': N = 5; print(countofPermutations(N)); # This code is contributed by amal kumar choubey // C# program to implement// the above approachusing System; class GFG{ // Function to print the number of// permutations possiblestatic int countofPermutations(int N){ return (int)(3 * Math.Pow(2, N - 1));} // Driver Codepublic static void Main(String[] args){ int N = 5; Console.Write(countofPermutations(N));}} // This code is contributed by Amit Katiyar <script> // Javascript Program to implement// the above approach // Function to print the number of// permutations possiblefunction countofPermutations(N){ return parseInt(3 * Math.pow(2, N - 1));} // Driver Codevar N = 5;document.write( countofPermutations(N)); </script> 48 Time Complexity: O(logN) Auxiliary Space: O(1) 29AjayKumar amit143katiyar Amal Kumar Choubey rutvik_56 Permutation and Combination Combinatorial Mathematical School Programming Mathematical Combinatorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Combinations with repetitions Ways to sum to N using Natural Numbers up to K with repetitions allowed Largest number by rearranging digits of a given positive or negative number Given number of matches played, find number of teams in tournament Generate all possible combinations of at most X characters from a given array Program for Fibonacci numbers C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7 Program to find GCD or HCF of two numbers
[ { "code": null, "e": 25398, "s": 25370, "text": "\n29 Apr, 2021" }, { "code": null, "e": 25621, "s": 25398, "text": "Given an integer N, the task is to calculate the total number of distinct permutations of length N, consisting only of letters ‘a’, ‘b’, and ‘c’, with repetitions allowed, such that no two adjacent characters are the same." }, { "code": null, "e": 25803, "s": 25621, "text": "Input: N = 3 Output: 12 Explanation: Possible permutations satisfying the required conditions are {aba, abc, aca, acb, bac, bab, bca, bcb, cac, cab, cba, cbc}Input: N = 5 Output: 48" }, { "code": null, "e": 25882, "s": 25803, "text": "Approach: Following observations need to be made to solve the given problem: " }, { "code": null, "e": 26618, "s": 25882, "text": "Let us fix the first letter as ‘a’.Now, the 2nd letter can either be ‘b’ or ‘c’, which leaves 2 ways to fill the second letter.Similarly, the third letter can also be filled in two ways. If the character in 2nd position is ‘b’, the third character can either be ‘a’ or ‘c’. If the character in 2nd position is ‘c’, the third character can either be ‘a’ or ‘b’.Similarly, for all the remaining positions, there will always be two possibilities depending on the character in the previous position. Therefore, the total number of possible permutation if ‘a’ occupies the first position is 1*2*2*2...*2 = 1 * 2N – 1.Therefore, the total number of permutations, considering the first character can also be ‘b’ or ‘c’ as well, is 3 * 2N – 1." }, { "code": null, "e": 26654, "s": 26618, "text": "Let us fix the first letter as ‘a’." }, { "code": null, "e": 26747, "s": 26654, "text": "Now, the 2nd letter can either be ‘b’ or ‘c’, which leaves 2 ways to fill the second letter." }, { "code": null, "e": 26981, "s": 26747, "text": "Similarly, the third letter can also be filled in two ways. If the character in 2nd position is ‘b’, the third character can either be ‘a’ or ‘c’. If the character in 2nd position is ‘c’, the third character can either be ‘a’ or ‘b’." }, { "code": null, "e": 27234, "s": 26981, "text": "Similarly, for all the remaining positions, there will always be two possibilities depending on the character in the previous position. Therefore, the total number of possible permutation if ‘a’ occupies the first position is 1*2*2*2...*2 = 1 * 2N – 1." }, { "code": null, "e": 27358, "s": 27234, "text": "Therefore, the total number of permutations, considering the first character can also be ‘b’ or ‘c’ as well, is 3 * 2N – 1." }, { "code": null, "e": 27410, "s": 27358, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27414, "s": 27410, "text": "C++" }, { "code": null, "e": 27419, "s": 27414, "text": "Java" }, { "code": null, "e": 27427, "s": 27419, "text": "Python3" }, { "code": null, "e": 27430, "s": 27427, "text": "C#" }, { "code": null, "e": 27441, "s": 27430, "text": "Javascript" }, { "code": "// C++ Program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to print the number of// permutations possibleint countofPermutations(int N){ return int(3 * pow(2, N - 1));} // Driver Codeint main(){ int N = 5; cout << countofPermutations(N); return 0;}", "e": 27748, "s": 27441, "text": null }, { "code": "// Java program to implement// the above approachclass GFG{ // Function to print the number of// permutations possiblestatic int countofPermutations(int N){ return (int)(3 * Math.pow(2, N - 1));} // Driver Codepublic static void main(String[] args){ int N = 5; System.out.print(countofPermutations(N));}} // This code is contributed by 29AjayKumar", "e": 28105, "s": 27748, "text": null }, { "code": "# Python3 program to implement# the above approach # Function to print the number of# permutations possibledef countofPermutations(N): return int((3 * pow(2, N - 1))); # Driver Codeif __name__ == '__main__': N = 5; print(countofPermutations(N)); # This code is contributed by amal kumar choubey", "e": 28419, "s": 28105, "text": null }, { "code": "// C# program to implement// the above approachusing System; class GFG{ // Function to print the number of// permutations possiblestatic int countofPermutations(int N){ return (int)(3 * Math.Pow(2, N - 1));} // Driver Codepublic static void Main(String[] args){ int N = 5; Console.Write(countofPermutations(N));}} // This code is contributed by Amit Katiyar", "e": 28791, "s": 28419, "text": null }, { "code": "<script> // Javascript Program to implement// the above approach // Function to print the number of// permutations possiblefunction countofPermutations(N){ return parseInt(3 * Math.pow(2, N - 1));} // Driver Codevar N = 5;document.write( countofPermutations(N)); </script>", "e": 29067, "s": 28791, "text": null }, { "code": null, "e": 29070, "s": 29067, "text": "48" }, { "code": null, "e": 29119, "s": 29072, "text": "Time Complexity: O(logN) Auxiliary Space: O(1)" }, { "code": null, "e": 29131, "s": 29119, "text": "29AjayKumar" }, { "code": null, "e": 29146, "s": 29131, "text": "amit143katiyar" }, { "code": null, "e": 29165, "s": 29146, "text": "Amal Kumar Choubey" }, { "code": null, "e": 29175, "s": 29165, "text": "rutvik_56" }, { "code": null, "e": 29203, "s": 29175, "text": "Permutation and Combination" }, { "code": null, "e": 29217, "s": 29203, "text": "Combinatorial" }, { "code": null, "e": 29230, "s": 29217, "text": "Mathematical" }, { "code": null, "e": 29249, "s": 29230, "text": "School Programming" }, { "code": null, "e": 29262, "s": 29249, "text": "Mathematical" }, { "code": null, "e": 29276, "s": 29262, "text": "Combinatorial" }, { "code": null, "e": 29374, "s": 29276, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29383, "s": 29374, "text": "Comments" }, { "code": null, "e": 29396, "s": 29383, "text": "Old Comments" }, { "code": null, "e": 29426, "s": 29396, "text": "Combinations with repetitions" }, { "code": null, "e": 29498, "s": 29426, "text": "Ways to sum to N using Natural Numbers up to K with repetitions allowed" }, { "code": null, "e": 29574, "s": 29498, "text": "Largest number by rearranging digits of a given positive or negative number" }, { "code": null, "e": 29641, "s": 29574, "text": "Given number of matches played, find number of teams in tournament" }, { "code": null, "e": 29719, "s": 29641, "text": "Generate all possible combinations of at most X characters from a given array" }, { "code": null, "e": 29749, "s": 29719, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 29764, "s": 29749, "text": "C++ Data Types" }, { "code": null, "e": 29807, "s": 29764, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 29826, "s": 29807, "text": "Coin Change | DP-7" } ]
Amazon Internship Interview Experience | On-Campus 2021 - GeeksforGeeks
11 Oct, 2021 Amazon arrived for hiring in the last week of Sept 2021 on our campus for the 6 months Software Development Engineer Role. We had a total of 3 rounds (1 Online Coding on Amazon’s Assessment Portal + 2 Technical Interviews). Round 1: Online Assessment Round The coding round comprised of 4 sections: Debugging: We had to choose a language and debug up to 10 questions most probably. Codes were very basic like sorting, etc. Coding: There were two medium-hard level questions. Work-style Assessment Aptitude: 25 aptitude questions (most probably) Round 2: Technical Interview Round 1 Next Greater Frequency of Element: same as next greater element but print greater frequency instead. I was asked to write only the function. Eg - 1 1 2 1 3 2 -> -1 -1 1 -1 1 -1 Design a data structure that does insert, delete, max, min deletes max, delete min operations in less time complexity preferred O(1) (with duplicate elements),.I answered accordingly as given in GFG using a doubly-linked list and min and max heaps. But he asked for a more optimized delete min/max operation in O(1) but I wasn’t able to come up. He explained to me that we could use one more data structure to store addresses of the elements in the heaps. I was asked only the intuition. Round 3: Technical Interview Round 2 Clone a Binary tree having random pointers The structure of the node was already provided.Tell me about any technology that you have started learning or have worked on recently – Use the STAR method to explain. I was from ECE so I was also allowed to speak about any technology which may be related to ECE too. Clone a Binary tree having random pointers The structure of the node was already provided. Tell me about any technology that you have started learning or have worked on recently – Use the STAR method to explain. I was from ECE so I was also allowed to speak about any technology which may be related to ECE too. Tips: Start from brute force and keep on optimizing when asked. Speak while coding or thinking. Repeat the question how you have understood it. Keep track of edge cases. Use STAR method for behavioral questions. I guess they didn’t ask me any theory as I was from ECE and also not much time was left. Don’t take it for granted, it’s just an assumption of mine. Verdict: Selected Amazon Marketing On-Campus Internship Interview Experiences Amazon Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Microsoft Interview Experience for Internship (Via Engage) Zoho Interview Experience (Off-Campus ) 2022 OLX Interview Experience (On-Campus) Zoho Corporation (Internship cum Offer Experience ) Difference Between ON Page and OFF Page SEO Amazon Interview Questions Commonly Asked Java Programming Interview Questions | Set 2 Amazon Interview Experience for SDE-1 (On-Campus) Amazon Interview Experience for SDE-1 Difference between ANN, CNN and RNN
[ { "code": null, "e": 25156, "s": 25128, "text": "\n11 Oct, 2021" }, { "code": null, "e": 25380, "s": 25156, "text": "Amazon arrived for hiring in the last week of Sept 2021 on our campus for the 6 months Software Development Engineer Role. We had a total of 3 rounds (1 Online Coding on Amazon’s Assessment Portal + 2 Technical Interviews)." }, { "code": null, "e": 25413, "s": 25380, "text": "Round 1: Online Assessment Round" }, { "code": null, "e": 25455, "s": 25413, "text": "The coding round comprised of 4 sections:" }, { "code": null, "e": 25579, "s": 25455, "text": "Debugging: We had to choose a language and debug up to 10 questions most probably. Codes were very basic like sorting, etc." }, { "code": null, "e": 25631, "s": 25579, "text": "Coding: There were two medium-hard level questions." }, { "code": null, "e": 25653, "s": 25631, "text": "Work-style Assessment" }, { "code": null, "e": 25701, "s": 25653, "text": "Aptitude: 25 aptitude questions (most probably)" }, { "code": null, "e": 25738, "s": 25701, "text": "Round 2: Technical Interview Round 1" }, { "code": null, "e": 25879, "s": 25738, "text": "Next Greater Frequency of Element: same as next greater element but print greater frequency instead. I was asked to write only the function." }, { "code": null, "e": 25917, "s": 25879, "text": "Eg - 1 1 2 1 3 2 -> -1 -1 1 -1 1 -1" }, { "code": null, "e": 26405, "s": 25917, "text": "Design a data structure that does insert, delete, max, min deletes max, delete min operations in less time complexity preferred O(1) (with duplicate elements),.I answered accordingly as given in GFG using a doubly-linked list and min and max heaps. But he asked for a more optimized delete min/max operation in O(1) but I wasn’t able to come up. He explained to me that we could use one more data structure to store addresses of the elements in the heaps. I was asked only the intuition." }, { "code": null, "e": 26442, "s": 26405, "text": "Round 3: Technical Interview Round 2" }, { "code": null, "e": 26753, "s": 26442, "text": "Clone a Binary tree having random pointers The structure of the node was already provided.Tell me about any technology that you have started learning or have worked on recently – Use the STAR method to explain. I was from ECE so I was also allowed to speak about any technology which may be related to ECE too." }, { "code": null, "e": 26844, "s": 26753, "text": "Clone a Binary tree having random pointers The structure of the node was already provided." }, { "code": null, "e": 27065, "s": 26844, "text": "Tell me about any technology that you have started learning or have worked on recently – Use the STAR method to explain. I was from ECE so I was also allowed to speak about any technology which may be related to ECE too." }, { "code": null, "e": 27071, "s": 27065, "text": "Tips:" }, { "code": null, "e": 27129, "s": 27071, "text": "Start from brute force and keep on optimizing when asked." }, { "code": null, "e": 27161, "s": 27129, "text": "Speak while coding or thinking." }, { "code": null, "e": 27209, "s": 27161, "text": "Repeat the question how you have understood it." }, { "code": null, "e": 27235, "s": 27209, "text": "Keep track of edge cases." }, { "code": null, "e": 27277, "s": 27235, "text": "Use STAR method for behavioral questions." }, { "code": null, "e": 27426, "s": 27277, "text": "I guess they didn’t ask me any theory as I was from ECE and also not much time was left. Don’t take it for granted, it’s just an assumption of mine." }, { "code": null, "e": 27444, "s": 27426, "text": "Verdict: Selected" }, { "code": null, "e": 27451, "s": 27444, "text": "Amazon" }, { "code": null, "e": 27461, "s": 27451, "text": "Marketing" }, { "code": null, "e": 27471, "s": 27461, "text": "On-Campus" }, { "code": null, "e": 27482, "s": 27471, "text": "Internship" }, { "code": null, "e": 27504, "s": 27482, "text": "Interview Experiences" }, { "code": null, "e": 27511, "s": 27504, "text": "Amazon" }, { "code": null, "e": 27609, "s": 27511, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27618, "s": 27609, "text": "Comments" }, { "code": null, "e": 27631, "s": 27618, "text": "Old Comments" }, { "code": null, "e": 27690, "s": 27631, "text": "Microsoft Interview Experience for Internship (Via Engage)" }, { "code": null, "e": 27735, "s": 27690, "text": "Zoho Interview Experience (Off-Campus ) 2022" }, { "code": null, "e": 27772, "s": 27735, "text": "OLX Interview Experience (On-Campus)" }, { "code": null, "e": 27824, "s": 27772, "text": "Zoho Corporation (Internship cum Offer Experience )" }, { "code": null, "e": 27868, "s": 27824, "text": "Difference Between ON Page and OFF Page SEO" }, { "code": null, "e": 27895, "s": 27868, "text": "Amazon Interview Questions" }, { "code": null, "e": 27955, "s": 27895, "text": "Commonly Asked Java Programming Interview Questions | Set 2" }, { "code": null, "e": 28005, "s": 27955, "text": "Amazon Interview Experience for SDE-1 (On-Campus)" }, { "code": null, "e": 28043, "s": 28005, "text": "Amazon Interview Experience for SDE-1" } ]
DAX Time Intelligence - TOTALYTD function
Evaluates the year-to-date value of the expression in the current context. TOTALYTD (<expression>, <dates>, [<filter>], [<year_end_date>]) expression An expression that returns a scalar value. dates A column that contains dates. filter Optional. An expression that specifies a filter to apply to the current context. year_end_date Optional. A literal string with a date that defines the year-end date. If omitted, the default is December 31. A scalar value. The dates parameter can be any of the following − A reference to a date/time column. A reference to a date/time column. A table expression that returns a single column of date/time values. A table expression that returns a single column of date/time values. A Boolean expression that defines a single-column table of date/time values. A Boolean expression that defines a single-column table of date/time values. Constraints on Boolean expressions − The expression cannot reference a calculated field. The expression cannot reference a calculated field. The expression cannot use CALCULATE function. The expression cannot use CALCULATE function. The expression cannot use any function that scans a table or returns a table, including aggregation functions. The expression cannot use any function that scans a table or returns a table, including aggregation functions. However, a Boolean expression can use any function that looks up a single value, or that calculates a scalar value. The filter parameter can be a Boolean expression or a table expression that defines a filter. If the data has been filtered, the function changes the context in which the data is filtered, and evaluates the expression in the new context that you specify. For each column used in a filter parameter, any existing filters on that column are removed, and the filter used in the filter parameter is applied instead. The year_end_date parameter is a string literal of a date, in the locale where the workbook was created. The year portion of the date is ignored. Year Running Sum:= TOTALYTD (SUM (Sales[Sales Amount]),Sales[Date]) 53 Lectures 5.5 hours Abhay Gadiya 24 Lectures 2 hours Randy Minder 26 Lectures 4.5 hours Randy Minder Print Add Notes Bookmark this page
[ { "code": null, "e": 2076, "s": 2001, "text": "Evaluates the year-to-date value of the expression in the current context." }, { "code": null, "e": 2142, "s": 2076, "text": "TOTALYTD (<expression>, <dates>, [<filter>], [<year_end_date>]) \n" }, { "code": null, "e": 2153, "s": 2142, "text": "expression" }, { "code": null, "e": 2196, "s": 2153, "text": "An expression that returns a scalar value." }, { "code": null, "e": 2202, "s": 2196, "text": "dates" }, { "code": null, "e": 2232, "s": 2202, "text": "A column that contains dates." }, { "code": null, "e": 2239, "s": 2232, "text": "filter" }, { "code": null, "e": 2249, "s": 2239, "text": "Optional." }, { "code": null, "e": 2320, "s": 2249, "text": "An expression that specifies a filter to apply to the current context." }, { "code": null, "e": 2334, "s": 2320, "text": "year_end_date" }, { "code": null, "e": 2344, "s": 2334, "text": "Optional." }, { "code": null, "e": 2445, "s": 2344, "text": "A literal string with a date that defines the year-end date. If omitted, the default is December 31." }, { "code": null, "e": 2461, "s": 2445, "text": "A scalar value." }, { "code": null, "e": 2511, "s": 2461, "text": "The dates parameter can be any of the following −" }, { "code": null, "e": 2546, "s": 2511, "text": "A reference to a date/time column." }, { "code": null, "e": 2581, "s": 2546, "text": "A reference to a date/time column." }, { "code": null, "e": 2650, "s": 2581, "text": "A table expression that returns a single column of date/time values." }, { "code": null, "e": 2719, "s": 2650, "text": "A table expression that returns a single column of date/time values." }, { "code": null, "e": 2796, "s": 2719, "text": "A Boolean expression that defines a single-column table of date/time values." }, { "code": null, "e": 2873, "s": 2796, "text": "A Boolean expression that defines a single-column table of date/time values." }, { "code": null, "e": 2910, "s": 2873, "text": "Constraints on Boolean expressions −" }, { "code": null, "e": 2962, "s": 2910, "text": "The expression cannot reference a calculated field." }, { "code": null, "e": 3014, "s": 2962, "text": "The expression cannot reference a calculated field." }, { "code": null, "e": 3060, "s": 3014, "text": "The expression cannot use CALCULATE function." }, { "code": null, "e": 3106, "s": 3060, "text": "The expression cannot use CALCULATE function." }, { "code": null, "e": 3217, "s": 3106, "text": "The expression cannot use any function that scans a table or returns a table, including aggregation functions." }, { "code": null, "e": 3328, "s": 3217, "text": "The expression cannot use any function that scans a table or returns a table, including aggregation functions." }, { "code": null, "e": 3444, "s": 3328, "text": "However, a Boolean expression can use any function that looks up a single value, or that calculates a scalar value." }, { "code": null, "e": 3538, "s": 3444, "text": "The filter parameter can be a Boolean expression or a table expression that defines a filter." }, { "code": null, "e": 3856, "s": 3538, "text": "If the data has been filtered, the function changes the context in which the data is filtered, and evaluates the expression in the new context that you specify. For each column used in a filter parameter, any existing filters on that column are removed, and the filter used in the filter parameter is applied instead." }, { "code": null, "e": 4002, "s": 3856, "text": "The year_end_date parameter is a string literal of a date, in the locale where the workbook was created. The year portion of the date is ignored." }, { "code": null, "e": 4071, "s": 4002, "text": "Year Running Sum:= TOTALYTD (SUM (Sales[Sales Amount]),Sales[Date]) " }, { "code": null, "e": 4106, "s": 4071, "text": "\n 53 Lectures \n 5.5 hours \n" }, { "code": null, "e": 4120, "s": 4106, "text": " Abhay Gadiya" }, { "code": null, "e": 4153, "s": 4120, "text": "\n 24 Lectures \n 2 hours \n" }, { "code": null, "e": 4167, "s": 4153, "text": " Randy Minder" }, { "code": null, "e": 4202, "s": 4167, "text": "\n 26 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4216, "s": 4202, "text": " Randy Minder" }, { "code": null, "e": 4223, "s": 4216, "text": " Print" }, { "code": null, "e": 4234, "s": 4223, "text": " Add Notes" } ]
C# | Math.DivRem() Method - GeeksforGeeks
01 Feb, 2019 In C#, Math.DivRem() is a Math class method which divides two numbers and returns the remainder. By using Division operator, we do not get the remainder in a separate variable but using DivRem() method, we get both.This method can be overloaded by passing different type and number of arguments to it. Math.DivRem(Int32, Int32, Int32)Math.DivRem(Int64, Int64, Int64) Math.DivRem(Int32, Int32, Int32) Math.DivRem(Int64, Int64, Int64) This method is used to calculate the quotient of two 32-bit signed integers and returns the remainder in an output parameter. Syntax: public static int DivRem(int dividend, int divisor, int result); Parameter: dividend: It is an Input Dividend number of type Int32.divisor: It is an Input Divisor number of type Int32.result: It is an output Remainder of type Int32. Return Type: This function returns the quotient of the specified numbers of type Int32. Exception: If the value of Divisor is zero then this method will give DivideByZeroException. Example: // C# program to demonstrate working// of Math.DivRem(Int32, Int32, Int32)using System; class DivRemGeeks { // Main method static void Main() { // Input +ve dividend and divisor number int dividend_A = 9845324; int divisor_A = 7; // Input negative dividend and divisor number int dividend_B = -99999; int divisor_B = 2; int result_1; int result_2; // Using the MATH.DivRem() Method int quotient_ONE = Math.DivRem(dividend_A, divisor_A, out result_1); int quotient_TWO = Math.DivRem(dividend_B, divisor_B, out result_2); // Print Result Console.WriteLine(quotient_ONE); Console.WriteLine(result_1); Console.WriteLine(quotient_TWO); Console.WriteLine(result_2); }} 1406474 6 -49999 -1 This method is used to calculates the quotient of two 64-bit signed integers(long) and returns the remainder in an output parameter. Syntax: public static long DivRem(int dividend, int divisor, int result); Parameter: dividend: It is an Input Dividend number of type Int64.divisor: It is an Input Divisor number of type Int64.result: It is an output Remainder of type Int64. Return Type: This function returns the quotient of the specified numbers of type Int64. Exception: If the value of Divisor is zero then this method will give DivideByZeroException. Example: // C# program to demonstrate working// of Math.DivRem(Int64, Int64, Int64) methodusing System; class DivRemGeeks { // Main method static void Main() { // Input +ve dividend and divisor number long dividend_A = 9223372036854775779; long divisor_A = 2000; // Input negative dividend and divisor number long dividend_B = -99999888844499233; long divisor_B = 768933; long result_1; long result_2; // Using the MATH.DivRem() Method long quotient_ONE = Math.DivRem(dividend_A, divisor_A, out result_1); long quotient_TWO = Math.DivRem(dividend_B, divisor_B, out result_2); // Print Result Console.WriteLine(quotient_ONE); Console.WriteLine(result_1); Console.WriteLine(quotient_TWO); Console.WriteLine(result_2); }} 4611686018427387 1779 -130050197929 -359476 References: https://docs.microsoft.com/en-us/dotnet/api/system.math.divrem?view=netframework-4.7.2 CSharp-Math CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C# | Method Overriding C# Dictionary with examples Difference between Ref and Out keywords in C# C# | Delegates Top 50 C# Interview Questions & Answers Introduction to .NET Framework C# | Constructors Extension Method in C# C# | Class and Object C# | Abstract Classes
[ { "code": null, "e": 24009, "s": 23981, "text": "\n01 Feb, 2019" }, { "code": null, "e": 24311, "s": 24009, "text": "In C#, Math.DivRem() is a Math class method which divides two numbers and returns the remainder. By using Division operator, we do not get the remainder in a separate variable but using DivRem() method, we get both.This method can be overloaded by passing different type and number of arguments to it." }, { "code": null, "e": 24376, "s": 24311, "text": "Math.DivRem(Int32, Int32, Int32)Math.DivRem(Int64, Int64, Int64)" }, { "code": null, "e": 24409, "s": 24376, "text": "Math.DivRem(Int32, Int32, Int32)" }, { "code": null, "e": 24442, "s": 24409, "text": "Math.DivRem(Int64, Int64, Int64)" }, { "code": null, "e": 24568, "s": 24442, "text": "This method is used to calculate the quotient of two 32-bit signed integers and returns the remainder in an output parameter." }, { "code": null, "e": 24576, "s": 24568, "text": "Syntax:" }, { "code": null, "e": 24642, "s": 24576, "text": "public static int DivRem(int dividend, int divisor, int result);\n" }, { "code": null, "e": 24653, "s": 24642, "text": "Parameter:" }, { "code": null, "e": 24810, "s": 24653, "text": "dividend: It is an Input Dividend number of type Int32.divisor: It is an Input Divisor number of type Int32.result: It is an output Remainder of type Int32." }, { "code": null, "e": 24898, "s": 24810, "text": "Return Type: This function returns the quotient of the specified numbers of type Int32." }, { "code": null, "e": 24991, "s": 24898, "text": "Exception: If the value of Divisor is zero then this method will give DivideByZeroException." }, { "code": null, "e": 25000, "s": 24991, "text": "Example:" }, { "code": "// C# program to demonstrate working// of Math.DivRem(Int32, Int32, Int32)using System; class DivRemGeeks { // Main method static void Main() { // Input +ve dividend and divisor number int dividend_A = 9845324; int divisor_A = 7; // Input negative dividend and divisor number int dividend_B = -99999; int divisor_B = 2; int result_1; int result_2; // Using the MATH.DivRem() Method int quotient_ONE = Math.DivRem(dividend_A, divisor_A, out result_1); int quotient_TWO = Math.DivRem(dividend_B, divisor_B, out result_2); // Print Result Console.WriteLine(quotient_ONE); Console.WriteLine(result_1); Console.WriteLine(quotient_TWO); Console.WriteLine(result_2); }}", "e": 25801, "s": 25000, "text": null }, { "code": null, "e": 25822, "s": 25801, "text": "1406474\n6\n-49999\n-1\n" }, { "code": null, "e": 25955, "s": 25822, "text": "This method is used to calculates the quotient of two 64-bit signed integers(long) and returns the remainder in an output parameter." }, { "code": null, "e": 25963, "s": 25955, "text": "Syntax:" }, { "code": null, "e": 26030, "s": 25963, "text": "public static long DivRem(int dividend, int divisor, int result);\n" }, { "code": null, "e": 26041, "s": 26030, "text": "Parameter:" }, { "code": null, "e": 26198, "s": 26041, "text": "dividend: It is an Input Dividend number of type Int64.divisor: It is an Input Divisor number of type Int64.result: It is an output Remainder of type Int64." }, { "code": null, "e": 26286, "s": 26198, "text": "Return Type: This function returns the quotient of the specified numbers of type Int64." }, { "code": null, "e": 26379, "s": 26286, "text": "Exception: If the value of Divisor is zero then this method will give DivideByZeroException." }, { "code": null, "e": 26388, "s": 26379, "text": "Example:" }, { "code": "// C# program to demonstrate working// of Math.DivRem(Int64, Int64, Int64) methodusing System; class DivRemGeeks { // Main method static void Main() { // Input +ve dividend and divisor number long dividend_A = 9223372036854775779; long divisor_A = 2000; // Input negative dividend and divisor number long dividend_B = -99999888844499233; long divisor_B = 768933; long result_1; long result_2; // Using the MATH.DivRem() Method long quotient_ONE = Math.DivRem(dividend_A, divisor_A, out result_1); long quotient_TWO = Math.DivRem(dividend_B, divisor_B, out result_2); // Print Result Console.WriteLine(quotient_ONE); Console.WriteLine(result_1); Console.WriteLine(quotient_TWO); Console.WriteLine(result_2); }}", "e": 27237, "s": 26388, "text": null }, { "code": null, "e": 27282, "s": 27237, "text": "4611686018427387\n1779\n-130050197929\n-359476\n" }, { "code": null, "e": 27381, "s": 27282, "text": "References: https://docs.microsoft.com/en-us/dotnet/api/system.math.divrem?view=netframework-4.7.2" }, { "code": null, "e": 27393, "s": 27381, "text": "CSharp-Math" }, { "code": null, "e": 27407, "s": 27393, "text": "CSharp-method" }, { "code": null, "e": 27410, "s": 27407, "text": "C#" }, { "code": null, "e": 27508, "s": 27410, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27517, "s": 27508, "text": "Comments" }, { "code": null, "e": 27530, "s": 27517, "text": "Old Comments" }, { "code": null, "e": 27553, "s": 27530, "text": "C# | Method Overriding" }, { "code": null, "e": 27581, "s": 27553, "text": "C# Dictionary with examples" }, { "code": null, "e": 27627, "s": 27581, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 27642, "s": 27627, "text": "C# | Delegates" }, { "code": null, "e": 27682, "s": 27642, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 27713, "s": 27682, "text": "Introduction to .NET Framework" }, { "code": null, "e": 27731, "s": 27713, "text": "C# | Constructors" }, { "code": null, "e": 27754, "s": 27731, "text": "Extension Method in C#" }, { "code": null, "e": 27776, "s": 27754, "text": "C# | Class and Object" } ]
How to center a popup window on screen? - GeeksforGeeks
28 Mar, 2022 JavaScript window.open() method is used to open a popup window. This popup window will place into the center of the screen. popupWinHeight: The height of pop up window on the screen. popupWinWidth: The width of pop up window on the screen. Example 1: This example creates the pop up window without placing it into center. html <!DOCTYPE html><html> <head> <title> Non-centered popup window on the screen </title></head> <body> <h1>GeeksforGeeks</h1> <p> Non-centered popup window on the screen </p> <script> function createPopupWin(pageURL, pageTitle, popupWinWidth, popupWinHeight) { var left = (screen.width ) ; var top = (screen.height ) ; var myWindow = window.open(pageURL, pageTitle, 'resizable=yes, width=' + popupWinWidth + ', height=' + popupWinHeight + ', top=' + top + ', left=' + left); } </script> <button onclick = "createPopupWin('https://www.geeksforgeeks.org', 'GeeksforGeeks Website', 1200, 650);"> GeeksforGeeks </button></body> </html> Output: Before Clicking the button: After Clicking the button: Center popup window: To center the popup window we are changing the values of parameters of open() method as follows: left = (screen.width – popupWinWidth) / 2 top = (screen.height – popupWinHeight) / 4 Example 2: This example creates the pop up window and placing it into center. html <!DOCTYPE html><html> <head> <title> Centered popup window on the screen </title></head> <body> <h1>GeeksforGeeks</h1> <p> Centered popup window on the screen </p> <script> function createPopupWin(pageURL, pageTitle, popupWinWidth, popupWinHeight) { var left = (screen.width - popupWinWidth) / 2; var top = (screen.height - popupWinHeight) / 4; var myWindow = window.open(pageURL, pageTitle, 'resizable=yes, width=' + popupWinWidth + ', height=' + popupWinHeight + ', top=' + top + ', left=' + left); } </script> <button onclick = "createPopupWin('https://www.geeksforgeeks.org', 'GeeksforGeeks Website', 1200, 650);"> GeeksforGeeks </button></body> </html> Output: Before Clicking the button: After Clicking the button: simranarora5sos Picked JavaScript 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 Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Difference Between PUT and PATCH Request 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": 25558, "s": 25530, "text": "\n28 Mar, 2022" }, { "code": null, "e": 25682, "s": 25558, "text": "JavaScript window.open() method is used to open a popup window. This popup window will place into the center of the screen." }, { "code": null, "e": 25741, "s": 25682, "text": "popupWinHeight: The height of pop up window on the screen." }, { "code": null, "e": 25798, "s": 25741, "text": "popupWinWidth: The width of pop up window on the screen." }, { "code": null, "e": 25881, "s": 25798, "text": "Example 1: This example creates the pop up window without placing it into center. " }, { "code": null, "e": 25886, "s": 25881, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> Non-centered popup window on the screen </title></head> <body> <h1>GeeksforGeeks</h1> <p> Non-centered popup window on the screen </p> <script> function createPopupWin(pageURL, pageTitle, popupWinWidth, popupWinHeight) { var left = (screen.width ) ; var top = (screen.height ) ; var myWindow = window.open(pageURL, pageTitle, 'resizable=yes, width=' + popupWinWidth + ', height=' + popupWinHeight + ', top=' + top + ', left=' + left); } </script> <button onclick = \"createPopupWin('https://www.geeksforgeeks.org', 'GeeksforGeeks Website', 1200, 650);\"> GeeksforGeeks </button></body> </html>", "e": 26732, "s": 25886, "text": null }, { "code": null, "e": 26740, "s": 26732, "text": "Output:" }, { "code": null, "e": 26769, "s": 26740, "text": "Before Clicking the button: " }, { "code": null, "e": 26797, "s": 26769, "text": "After Clicking the button: " }, { "code": null, "e": 26915, "s": 26797, "text": "Center popup window: To center the popup window we are changing the values of parameters of open() method as follows:" }, { "code": null, "e": 26957, "s": 26915, "text": "left = (screen.width – popupWinWidth) / 2" }, { "code": null, "e": 27000, "s": 26957, "text": "top = (screen.height – popupWinHeight) / 4" }, { "code": null, "e": 27079, "s": 27000, "text": "Example 2: This example creates the pop up window and placing it into center. " }, { "code": null, "e": 27084, "s": 27079, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> Centered popup window on the screen </title></head> <body> <h1>GeeksforGeeks</h1> <p> Centered popup window on the screen </p> <script> function createPopupWin(pageURL, pageTitle, popupWinWidth, popupWinHeight) { var left = (screen.width - popupWinWidth) / 2; var top = (screen.height - popupWinHeight) / 4; var myWindow = window.open(pageURL, pageTitle, 'resizable=yes, width=' + popupWinWidth + ', height=' + popupWinHeight + ', top=' + top + ', left=' + left); } </script> <button onclick = \"createPopupWin('https://www.geeksforgeeks.org', 'GeeksforGeeks Website', 1200, 650);\"> GeeksforGeeks </button></body> </html>", "e": 27972, "s": 27084, "text": null }, { "code": null, "e": 27980, "s": 27972, "text": "Output:" }, { "code": null, "e": 28009, "s": 27980, "text": "Before Clicking the button: " }, { "code": null, "e": 28037, "s": 28009, "text": "After Clicking the button: " }, { "code": null, "e": 28053, "s": 28037, "text": "simranarora5sos" }, { "code": null, "e": 28060, "s": 28053, "text": "Picked" }, { "code": null, "e": 28071, "s": 28060, "text": "JavaScript" }, { "code": null, "e": 28088, "s": 28071, "text": "Web Technologies" }, { "code": null, "e": 28115, "s": 28088, "text": "Web technologies Questions" }, { "code": null, "e": 28213, "s": 28115, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28253, "s": 28213, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28298, "s": 28253, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28359, "s": 28298, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28431, "s": 28359, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 28472, "s": 28431, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 28512, "s": 28472, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28545, "s": 28512, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28590, "s": 28545, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28633, "s": 28590, "text": "How to fetch data from an API in ReactJS ?" } ]
Print the nodes having exactly one child in a Binary tree - GeeksforGeeks
06 Mar, 2022 Given a binary tree, the task is to print all the nodes having exactly one child. Print “-1” if no such node exists.Examples: Input: 2 / \ 3 5 / / \ 7 8 6 Output: 3 Explanation: There is only one node having single child that is 3. Input: 9 / \ 7 8 / \ 4 3 Output: -1 Explanation: There is no node having exactly one child in the binary tree. Approach: The idea is to traverse the tree in the inorder traversal and at each step of the traversal check that if the node is having exactly one child. Then append that node into a result array to keep track of such nodes. After the traversal, simply print each element of this result array. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation to print// the nodes having a single child#include <bits/stdc++.h>using namespace std; // Class of the Binary Tree nodestruct Node{ int data; Node *left, *right; Node(int x) { data = x; left = right = NULL; }}; vector<int> lst; // Function to find the nodes// having single childvoid printNodesOneChild(Node* root){ // Base case if (root == NULL) return; // Condition to check if the // node is having only one child if (root->left != NULL && root->right == NULL || root->left == NULL && root->right != NULL) { lst.push_back(root->data); } // Traversing the left child printNodesOneChild(root -> left); // Traversing the right child printNodesOneChild(root -> right);} //Driver codeint main(){ // Constructing the binary tree Node *root = new Node(2); root -> left = new Node(3); root -> right = new Node(5); root -> left -> left = new Node(7); root -> right -> left = new Node(8); root -> right -> right = new Node(6); // Function calling printNodesOneChild(root); // Condition to check if there is // no such node having single child if (lst.size() == 0) printf("-1"); else { for(int value : lst) { cout << (value) << endl; } }} // This code is contributed by Mohit Kumar 29 // Java implementation to print// the nodes having a single childimport java.util.Vector; // Class of the Binary Tree nodeclass Node{ int data; Node left, right; Node(int data) { this.data = data; }} class GFG{ // List to keep track of nodes// having single childstatic Vector<Integer> list = new Vector<>(); // Function to find the nodes // having single child static void printNodesOneChild(Node root){ // Base case if (root == null) return; // Condition to check if the node // is having only one child if (root.left != null && root.right == null || root.left == null && root.right != null) { list.add(root.data); } // Traversing the left child printNodesOneChild(root.left); // Traversing the right child printNodesOneChild(root.right);} // Driver codepublic static void main(String[] args){ // Constructing the binary tree Node root = new Node(2); root.left = new Node(3); root.right = new Node(5); root.left.left = new Node(7); root.right.left = new Node(8); root.right.right = new Node(6); // Function calling printNodesOneChild(root); // Condition to check if there is // no such node having single child if (list.size() == 0) System.out.println(-1); else { for(int value : list) { System.out.println(value); } }}} // This code is contributed by sumit_9 # Python3 implementation to print# the nodes having a single child # Class of the Binary Tree nodeclass node: # Constructor to construct # the node of the Binary tree def __init__(self, val): self.val = val self.left = None self.right = None # List to keep track of# nodes having single childsingle_child_nodes = [] # Function to find the nodes# having single childdef printNodesOneChild(root): # Base Case if not root: return # Condition to check if the node # is having only one child if not root.left and root.right: single_child_nodes.append(root) elif root.left and not root.right: single_child_nodes.append(root) # Traversing the left child printNodesOneChild(root.left) # Traversing the right child printNodesOneChild(root.right) return # Driver Codeif __name__ == "__main__": # Construction of Binary Tree root = node(2) root.left = node(3) root.right = node(5) root.left.left = node(7) root.right.left = node(8) root.right.right = node(6) # Function Call printNodesOneChild(root) # Condition to check if there is # no such node having single child if not len(single_child_nodes): print(-1) else: for i in single_child_nodes: print(i.val, end = " ") print() // C# implementation to print// the nodes having a single childusing System;using System.Collections; class GFG{ // Structure of binary treepublic class Node { public Node left; public Node right; public int data;}; // Function to create a new nodestatic Node newNode(int key){ Node node = new Node(); node.left = node.right = null; node.data = key; return node;} // List to keep track of nodes// having single childstatic ArrayList list = new ArrayList(); // Function to find the nodes // having single child static void printNodesOneChild(Node root){ // Base case if (root == null) return; // Condition to check if the node // is having only one child if (root.left != null && root.right == null || root.left == null && root.right != null) { list.Add(root.data); } // Traversing the left child printNodesOneChild(root.left); // Traversing the right child printNodesOneChild(root.right);} // Driver codestatic public void Main(){ // Constructing the binary tree Node root = newNode(2); root.left = newNode(3); root.right = newNode(5); root.left.left = newNode(7); root.right.left = newNode(8); root.right.right = newNode(6); // Function calling printNodesOneChild(root); // Condition to check if there is // no such node having single child if (list.Count == 0) Console.WriteLine(-1); else { foreach(int value in list) { Console.WriteLine(value); } }}} // This code is contributed by offbeat <script>// Javascript implementation to print// the nodes having a single child // Class of the Binary Tree nodeclass Node{ constructor(data) { this.data = data; this.left=this.right=null; } } // List to keep track of nodes// having single childlet list = []; // Function to find the nodes// having single childfunction printNodesOneChild(root){ // Base case if (root == null) return; // Condition to check if the node // is having only one child if (root.left != null && root.right == null || root.left == null && root.right != null) { list.push(root.data); } // Traversing the left child printNodesOneChild(root.left); // Traversing the right child printNodesOneChild(root.right);} // Driver code// Constructing the binary tree let root = new Node(2); root.left = new Node(3); root.right = new Node(5); root.left.left = new Node(7); root.right.left = new Node(8); root.right.right = new Node(6); // Function calling printNodesOneChild(root); // Condition to check if there is // no such node having single child if (list.length == 0) document.write(-1); else { document.write(list.join("<br>")) } // This code is contributed by patel2127</script> 3 sumit_9 offbeat mohit kumar 29 patel2127 sumitgumber28 tree-traversal Data Structures Tree Data Structures Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Data Structures | Tree Traversals | Question 4 Data Structures | Graph | Question 9 Data Structures | Stack | Question 1 Binary Search Tree | Set 3 (Iterative Delete) Program to create Custom Vector Class in C++ Tree Traversals (Inorder, Preorder and Postorder) Binary Tree | Set 1 (Introduction) AVL Tree | Set 1 (Insertion) Level Order Binary Tree Traversal Binary Tree | Set 3 (Types of Binary Tree)
[ { "code": null, "e": 26201, "s": 26173, "text": "\n06 Mar, 2022" }, { "code": null, "e": 26328, "s": 26201, "text": "Given a binary tree, the task is to print all the nodes having exactly one child. Print “-1” if no such node exists.Examples: " }, { "code": null, "e": 26663, "s": 26328, "text": "Input: \n 2\n / \\\n 3 5\n / / \\\n 7 8 6\nOutput: 3\nExplanation:\nThere is only one node having\nsingle child that is 3.\n\nInput:\n 9\n / \\\n 7 8\n / \\\n 4 3\nOutput: -1\nExplanation:\nThere is no node having exactly one\nchild in the binary tree. " }, { "code": null, "e": 26957, "s": 26663, "text": "Approach: The idea is to traverse the tree in the inorder traversal and at each step of the traversal check that if the node is having exactly one child. Then append that node into a result array to keep track of such nodes. After the traversal, simply print each element of this result array." }, { "code": null, "e": 27009, "s": 26957, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27013, "s": 27009, "text": "C++" }, { "code": null, "e": 27018, "s": 27013, "text": "Java" }, { "code": null, "e": 27026, "s": 27018, "text": "Python3" }, { "code": null, "e": 27029, "s": 27026, "text": "C#" }, { "code": null, "e": 27040, "s": 27029, "text": "Javascript" }, { "code": "// C++ implementation to print// the nodes having a single child#include <bits/stdc++.h>using namespace std; // Class of the Binary Tree nodestruct Node{ int data; Node *left, *right; Node(int x) { data = x; left = right = NULL; }}; vector<int> lst; // Function to find the nodes// having single childvoid printNodesOneChild(Node* root){ // Base case if (root == NULL) return; // Condition to check if the // node is having only one child if (root->left != NULL && root->right == NULL || root->left == NULL && root->right != NULL) { lst.push_back(root->data); } // Traversing the left child printNodesOneChild(root -> left); // Traversing the right child printNodesOneChild(root -> right);} //Driver codeint main(){ // Constructing the binary tree Node *root = new Node(2); root -> left = new Node(3); root -> right = new Node(5); root -> left -> left = new Node(7); root -> right -> left = new Node(8); root -> right -> right = new Node(6); // Function calling printNodesOneChild(root); // Condition to check if there is // no such node having single child if (lst.size() == 0) printf(\"-1\"); else { for(int value : lst) { cout << (value) << endl; } }} // This code is contributed by Mohit Kumar 29", "e": 28320, "s": 27040, "text": null }, { "code": "// Java implementation to print// the nodes having a single childimport java.util.Vector; // Class of the Binary Tree nodeclass Node{ int data; Node left, right; Node(int data) { this.data = data; }} class GFG{ // List to keep track of nodes// having single childstatic Vector<Integer> list = new Vector<>(); // Function to find the nodes // having single child static void printNodesOneChild(Node root){ // Base case if (root == null) return; // Condition to check if the node // is having only one child if (root.left != null && root.right == null || root.left == null && root.right != null) { list.add(root.data); } // Traversing the left child printNodesOneChild(root.left); // Traversing the right child printNodesOneChild(root.right);} // Driver codepublic static void main(String[] args){ // Constructing the binary tree Node root = new Node(2); root.left = new Node(3); root.right = new Node(5); root.left.left = new Node(7); root.right.left = new Node(8); root.right.right = new Node(6); // Function calling printNodesOneChild(root); // Condition to check if there is // no such node having single child if (list.size() == 0) System.out.println(-1); else { for(int value : list) { System.out.println(value); } }}} // This code is contributed by sumit_9", "e": 29761, "s": 28320, "text": null }, { "code": "# Python3 implementation to print# the nodes having a single child # Class of the Binary Tree nodeclass node: # Constructor to construct # the node of the Binary tree def __init__(self, val): self.val = val self.left = None self.right = None # List to keep track of# nodes having single childsingle_child_nodes = [] # Function to find the nodes# having single childdef printNodesOneChild(root): # Base Case if not root: return # Condition to check if the node # is having only one child if not root.left and root.right: single_child_nodes.append(root) elif root.left and not root.right: single_child_nodes.append(root) # Traversing the left child printNodesOneChild(root.left) # Traversing the right child printNodesOneChild(root.right) return # Driver Codeif __name__ == \"__main__\": # Construction of Binary Tree root = node(2) root.left = node(3) root.right = node(5) root.left.left = node(7) root.right.left = node(8) root.right.right = node(6) # Function Call printNodesOneChild(root) # Condition to check if there is # no such node having single child if not len(single_child_nodes): print(-1) else: for i in single_child_nodes: print(i.val, end = \" \") print()", "e": 31134, "s": 29761, "text": null }, { "code": "// C# implementation to print// the nodes having a single childusing System;using System.Collections; class GFG{ // Structure of binary treepublic class Node { public Node left; public Node right; public int data;}; // Function to create a new nodestatic Node newNode(int key){ Node node = new Node(); node.left = node.right = null; node.data = key; return node;} // List to keep track of nodes// having single childstatic ArrayList list = new ArrayList(); // Function to find the nodes // having single child static void printNodesOneChild(Node root){ // Base case if (root == null) return; // Condition to check if the node // is having only one child if (root.left != null && root.right == null || root.left == null && root.right != null) { list.Add(root.data); } // Traversing the left child printNodesOneChild(root.left); // Traversing the right child printNodesOneChild(root.right);} // Driver codestatic public void Main(){ // Constructing the binary tree Node root = newNode(2); root.left = newNode(3); root.right = newNode(5); root.left.left = newNode(7); root.right.left = newNode(8); root.right.right = newNode(6); // Function calling printNodesOneChild(root); // Condition to check if there is // no such node having single child if (list.Count == 0) Console.WriteLine(-1); else { foreach(int value in list) { Console.WriteLine(value); } }}} // This code is contributed by offbeat", "e": 32732, "s": 31134, "text": null }, { "code": "<script>// Javascript implementation to print// the nodes having a single child // Class of the Binary Tree nodeclass Node{ constructor(data) { this.data = data; this.left=this.right=null; } } // List to keep track of nodes// having single childlet list = []; // Function to find the nodes// having single childfunction printNodesOneChild(root){ // Base case if (root == null) return; // Condition to check if the node // is having only one child if (root.left != null && root.right == null || root.left == null && root.right != null) { list.push(root.data); } // Traversing the left child printNodesOneChild(root.left); // Traversing the right child printNodesOneChild(root.right);} // Driver code// Constructing the binary tree let root = new Node(2); root.left = new Node(3); root.right = new Node(5); root.left.left = new Node(7); root.right.left = new Node(8); root.right.right = new Node(6); // Function calling printNodesOneChild(root); // Condition to check if there is // no such node having single child if (list.length == 0) document.write(-1); else { document.write(list.join(\"<br>\")) } // This code is contributed by patel2127</script>", "e": 34036, "s": 32732, "text": null }, { "code": null, "e": 34038, "s": 34036, "text": "3" }, { "code": null, "e": 34046, "s": 34038, "text": "sumit_9" }, { "code": null, "e": 34054, "s": 34046, "text": "offbeat" }, { "code": null, "e": 34069, "s": 34054, "text": "mohit kumar 29" }, { "code": null, "e": 34079, "s": 34069, "text": "patel2127" }, { "code": null, "e": 34093, "s": 34079, "text": "sumitgumber28" }, { "code": null, "e": 34108, "s": 34093, "text": "tree-traversal" }, { "code": null, "e": 34124, "s": 34108, "text": "Data Structures" }, { "code": null, "e": 34129, "s": 34124, "text": "Tree" }, { "code": null, "e": 34145, "s": 34129, "text": "Data Structures" }, { "code": null, "e": 34150, "s": 34145, "text": "Tree" }, { "code": null, "e": 34248, "s": 34150, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34295, "s": 34248, "text": "Data Structures | Tree Traversals | Question 4" }, { "code": null, "e": 34332, "s": 34295, "text": "Data Structures | Graph | Question 9" }, { "code": null, "e": 34369, "s": 34332, "text": "Data Structures | Stack | Question 1" }, { "code": null, "e": 34415, "s": 34369, "text": "Binary Search Tree | Set 3 (Iterative Delete)" }, { "code": null, "e": 34460, "s": 34415, "text": "Program to create Custom Vector Class in C++" }, { "code": null, "e": 34510, "s": 34460, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 34545, "s": 34510, "text": "Binary Tree | Set 1 (Introduction)" }, { "code": null, "e": 34574, "s": 34545, "text": "AVL Tree | Set 1 (Insertion)" }, { "code": null, "e": 34608, "s": 34574, "text": "Level Order Binary Tree Traversal" } ]
Introduction To Machine Learning using Python - GeeksforGeeks
30 Nov, 2021 Machine learning is a type of artificial intelligence (AI) that provides computers with the ability to learn without being explicitly programmed. Machine learning focuses on the development of Computer Programs that can change when exposed to new data. In this article, we’ll see basics of Machine Learning, and implementation of a simple machine learning algorithm using python. Setting up the environment Python community has developed many modules to help programmers implement machine learning. In this article, we will be using numpy, scipy and scikit-learn modules. We can install them using cmd command: pip install numpy scipy scikit-learn A better option would be downloading miniconda or anaconda packages for python, which come prebundled with these packages. Follow the instructions given here to use anaconda. Machine Learning overview Machine learning involves a computer to be trained using a given data set, and use this training to predict the properties of a given new data. For example, we can train a computer by feeding it 1000 images of cats and 1000 more images which are not of a cat, and tell each time to the computer whether a picture is cat or not. Then if we show the computer a new image, then from the above training, the computer should be able to tell whether this new image is a cat or not. The process of training and prediction involves the use of specialized algorithms. We feed the training data to an algorithm, and the algorithm uses this training data to give predictions on a new test data. One such algorithm is K-Nearest-Neighbor classification (KNN classification). It takes a test data, and finds k nearest data values to this data from test data set. Then it selects the neighbor of maximum frequency and gives its properties as the prediction result. For example if the training set is: Now we want to predict flower type for petal of size 2.5 cm. So if we decide no. of neighbors (K)=3, we see that the 3 nearest neighbors of 2.5 are 1, 2 and 3. Their frequencies are 2, 3 and 2 respectively. Therefore the neighbor of maximum frequency is 2 and flower type corresponding to it is b. So for a petal of size 2.5, the prediction will be flower type b. Implementing KNN- classification algorithm using Python on IRIS dataset Here is a python script which demonstrates knn classification algorithm. Here we use the famous iris flower dataset to train the computer, and then give a new value to the computer to make predictions about it. The data set consists of 50 samples from each of three species of Iris (Iris setosa, Iris virginica and Iris versicolor). Four features are measured from each sample: The length and Width of Sepals & Petals, in centimeters. We train our program using this dataset, and then use this training to predict species of a iris flower with given measurements. Note that this program might not run on Geeksforgeeks IDE, but it can run easily on your local python interpreter, provided, you have installed the required libraries. # Python program to demonstrate# KNN classification algorithm# on IRIS dataset from sklearn.datasets import load_irisfrom sklearn.neighbors import KNeighborsClassifierimport numpy as npfrom sklearn.model_selection import train_test_split iris_dataset=load_iris() X_train, X_test, y_train, y_test = train_test_split(iris_dataset["data"], iris_dataset["target"], random_state=0) kn = KNeighborsClassifier(n_neighbors=1)kn.fit(X_train, y_train) x_new = np.array([[5, 2.9, 1, 0.2]])prediction = kn.predict(x_new) print("Predicted target value: {}\n".format(prediction))print("Predicted feature name: {}\n".format (iris_dataset["target_names"][prediction]))print("Test score: {:.2f}".format(kn.score(X_test, y_test))) Output: Predicted target name: [0] Predicted feature name: ['setosa'] Test score: 0.97 Explanation of the program: Training the Dataset The first line imports iris data set which is already predefined in sklearn module. Iris data set is basically a table which contains information about various varieties of iris flowers. We import kNeighborsClassifier algorithm and train_test_split class from sklearn and numpy module for use in this program. Then we encapsulate load_iris() method in iris_dataset variable. Further we divide the dataset into training data and test data using train_test_split method. The X prefix in variable denotes the feature values (eg. petal length etc) and y prefix denotes target values (eg. 0 for setosa, 1 for virginica and 2 for versicolor). This method divides dataset into training and test data randomly in ratio of 75:25. Then we encapsulate KNeighborsClassifier method in kn variable while keeping value of k=1. This method contains K Nearest Neighbor algorithm in it. In the next line, we fit our training data into this algorithm so that computer can get trained using this data. Now the training part is complete. Testing the Dataset Now we have dimensions of a new flower in a numpy array called x_new and we want to predict the species of this flower. We do this using the predict method which takes this array as input and spits out predicted target value as output. So the predicted target value comes out to be 0 which stands for setosa. So this flower has good chances to be of setosa species. Finally we find the test score which is the ratio of no. of predictions found correct and total predictions made. We do this using the score method which basically compares the actual values of the test set with the predicted values. Thus, we saw how machine learning works and developed a basic program to implement it using scikit-learn module in python.This article is contributed by tkkhhaarree. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. BudhathokiBijaya charalambous99 kalrap615 Advanced Computer Subject GBlog Machine Learning Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ML | Linear Regression System Design Tutorial Copying Files to and from Docker Containers ML | Underfitting and Overfitting Clustering in Machine Learning Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ... DSA Sheet by Love Babbar Socket Programming in C/C++ GET and POST requests using Python Must Do Coding Questions for Product Based Companies
[ { "code": null, "e": 25519, "s": 25491, "text": "\n30 Nov, 2021" }, { "code": null, "e": 25900, "s": 25519, "text": "Machine learning is a type of artificial intelligence (AI) that provides computers with the ability to learn without being explicitly programmed. Machine learning focuses on the development of Computer Programs that can change when exposed to new data. In this article, we’ll see basics of Machine Learning, and implementation of a simple machine learning algorithm using python. " }, { "code": null, "e": 25927, "s": 25900, "text": "Setting up the environment" }, { "code": null, "e": 26133, "s": 25927, "text": "Python community has developed many modules to help programmers implement machine learning. In this article, we will be using numpy, scipy and scikit-learn modules. We can install them using cmd command: " }, { "code": null, "e": 26171, "s": 26133, "text": "pip install numpy scipy scikit-learn " }, { "code": null, "e": 26348, "s": 26171, "text": "A better option would be downloading miniconda or anaconda packages for python, which come prebundled with these packages. Follow the instructions given here to use anaconda. " }, { "code": null, "e": 26374, "s": 26348, "text": "Machine Learning overview" }, { "code": null, "e": 27361, "s": 26374, "text": "Machine learning involves a computer to be trained using a given data set, and use this training to predict the properties of a given new data. For example, we can train a computer by feeding it 1000 images of cats and 1000 more images which are not of a cat, and tell each time to the computer whether a picture is cat or not. Then if we show the computer a new image, then from the above training, the computer should be able to tell whether this new image is a cat or not. The process of training and prediction involves the use of specialized algorithms. We feed the training data to an algorithm, and the algorithm uses this training data to give predictions on a new test data. One such algorithm is K-Nearest-Neighbor classification (KNN classification). It takes a test data, and finds k nearest data values to this data from test data set. Then it selects the neighbor of maximum frequency and gives its properties as the prediction result. For example if the training set is: " }, { "code": null, "e": 27727, "s": 27361, "text": "Now we want to predict flower type for petal of size 2.5 cm. So if we decide no. of neighbors (K)=3, we see that the 3 nearest neighbors of 2.5 are 1, 2 and 3. Their frequencies are 2, 3 and 2 respectively. Therefore the neighbor of maximum frequency is 2 and flower type corresponding to it is b. So for a petal of size 2.5, the prediction will be flower type b. " }, { "code": null, "e": 27799, "s": 27727, "text": "Implementing KNN- classification algorithm using Python on IRIS dataset" }, { "code": null, "e": 28532, "s": 27799, "text": "Here is a python script which demonstrates knn classification algorithm. Here we use the famous iris flower dataset to train the computer, and then give a new value to the computer to make predictions about it. The data set consists of 50 samples from each of three species of Iris (Iris setosa, Iris virginica and Iris versicolor). Four features are measured from each sample: The length and Width of Sepals & Petals, in centimeters. We train our program using this dataset, and then use this training to predict species of a iris flower with given measurements. Note that this program might not run on Geeksforgeeks IDE, but it can run easily on your local python interpreter, provided, you have installed the required libraries. " }, { "code": "# Python program to demonstrate# KNN classification algorithm# on IRIS dataset from sklearn.datasets import load_irisfrom sklearn.neighbors import KNeighborsClassifierimport numpy as npfrom sklearn.model_selection import train_test_split iris_dataset=load_iris() X_train, X_test, y_train, y_test = train_test_split(iris_dataset[\"data\"], iris_dataset[\"target\"], random_state=0) kn = KNeighborsClassifier(n_neighbors=1)kn.fit(X_train, y_train) x_new = np.array([[5, 2.9, 1, 0.2]])prediction = kn.predict(x_new) print(\"Predicted target value: {}\\n\".format(prediction))print(\"Predicted feature name: {}\\n\".format (iris_dataset[\"target_names\"][prediction]))print(\"Test score: {:.2f}\".format(kn.score(X_test, y_test)))", "e": 29248, "s": 28532, "text": null }, { "code": null, "e": 29257, "s": 29248, "text": "Output: " }, { "code": null, "e": 29336, "s": 29257, "text": "Predicted target name: [0]\nPredicted feature name: ['setosa']\nTest score: 0.97" }, { "code": null, "e": 29366, "s": 29336, "text": "Explanation of the program: " }, { "code": null, "e": 29387, "s": 29366, "text": "Training the Dataset" }, { "code": null, "e": 29574, "s": 29387, "text": "The first line imports iris data set which is already predefined in sklearn module. Iris data set is basically a table which contains information about various varieties of iris flowers." }, { "code": null, "e": 29697, "s": 29574, "text": "We import kNeighborsClassifier algorithm and train_test_split class from sklearn and numpy module for use in this program." }, { "code": null, "e": 30024, "s": 29697, "text": "Then we encapsulate load_iris() method in iris_dataset variable. Further we divide the dataset into training data and test data using train_test_split method. The X prefix in variable denotes the feature values (eg. petal length etc) and y prefix denotes target values (eg. 0 for setosa, 1 for virginica and 2 for versicolor)." }, { "code": null, "e": 30256, "s": 30024, "text": "This method divides dataset into training and test data randomly in ratio of 75:25. Then we encapsulate KNeighborsClassifier method in kn variable while keeping value of k=1. This method contains K Nearest Neighbor algorithm in it." }, { "code": null, "e": 30404, "s": 30256, "text": "In the next line, we fit our training data into this algorithm so that computer can get trained using this data. Now the training part is complete." }, { "code": null, "e": 30425, "s": 30404, "text": "Testing the Dataset " }, { "code": null, "e": 30661, "s": 30425, "text": "Now we have dimensions of a new flower in a numpy array called x_new and we want to predict the species of this flower. We do this using the predict method which takes this array as input and spits out predicted target value as output." }, { "code": null, "e": 30791, "s": 30661, "text": "So the predicted target value comes out to be 0 which stands for setosa. So this flower has good chances to be of setosa species." }, { "code": null, "e": 31027, "s": 30791, "text": "Finally we find the test score which is the ratio of no. of predictions found correct and total predictions made. We do this using the score method which basically compares the actual values of the test set with the predicted values. " }, { "code": null, "e": 31444, "s": 31027, "text": "Thus, we saw how machine learning works and developed a basic program to implement it using scikit-learn module in python.This article is contributed by tkkhhaarree. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 31461, "s": 31444, "text": "BudhathokiBijaya" }, { "code": null, "e": 31476, "s": 31461, "text": "charalambous99" }, { "code": null, "e": 31486, "s": 31476, "text": "kalrap615" }, { "code": null, "e": 31512, "s": 31486, "text": "Advanced Computer Subject" }, { "code": null, "e": 31518, "s": 31512, "text": "GBlog" }, { "code": null, "e": 31535, "s": 31518, "text": "Machine Learning" }, { "code": null, "e": 31552, "s": 31535, "text": "Machine Learning" }, { "code": null, "e": 31650, "s": 31552, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31673, "s": 31650, "text": "ML | Linear Regression" }, { "code": null, "e": 31696, "s": 31673, "text": "System Design Tutorial" }, { "code": null, "e": 31740, "s": 31696, "text": "Copying Files to and from Docker Containers" }, { "code": null, "e": 31774, "s": 31740, "text": "ML | Underfitting and Overfitting" }, { "code": null, "e": 31805, "s": 31774, "text": "Clustering in Machine Learning" }, { "code": null, "e": 31879, "s": 31805, "text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..." }, { "code": null, "e": 31904, "s": 31879, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 31932, "s": 31904, "text": "Socket Programming in C/C++" }, { "code": null, "e": 31967, "s": 31932, "text": "GET and POST requests using Python" } ]
How to lowercase column names in Pandas dataframe - GeeksforGeeks
06 Dec, 2018 Analyzing real-world data is somewhat difficult because we need to take various things into consideration. Apart from getting the useful data from large datasets, keeping data in required format is also very important. One might encounter a situation where we need to lowercase each letter in any specific column in given dataframe. Let’s see how to lowercase column names in Pandas dataframe. Let’s create a dataframe from the dict of lists. # Create a simple dataframe # importing pandas as pdimport pandas as pd # creating a dataframedf = pd.DataFrame({'A': ['John', 'bODAY', 'MinA', 'Peter', 'nicky'], 'B': ['masters', 'graduate', 'graduate', 'Masters', 'Graduate'], 'C': [27, 23, 21, 23, 24]}) df Output: There are certain methods we can change/modify the case of column in pandas dataframe. Let’s see how can we lowercase column names in Pandas dataframe using lower() method. Method #1: # Create a simple dataframe # importing pandas as pdimport pandas as pd # creating a dataframedf = pd.DataFrame({'A': ['John', 'bODAY', 'MinA', 'Peter', 'nicky'], 'B': ['masters', 'graduate', 'graduate', 'Masters', 'Graduate'], 'C': [27, 23, 21, 23, 24]}) df['A'] = df['A'].str.lower() df Output: Method #2: # Create a simple dataframe # importing pandas as pdimport pandas as pd # creating a dataframedf = pd.DataFrame({'A': ['John', 'bODAY', 'MinA', 'Peter', 'nicky'], 'B': ['masters', 'graduate', 'graduate', 'Masters', 'Graduate'], 'C': [27, 23, 21, 23, 24]}) df['A'].apply(lambda x: x.lower()) Output: pandas-dataframe-program Python pandas-dataFrame Python-pandas 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? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n06 Dec, 2018" }, { "code": null, "e": 25756, "s": 25537, "text": "Analyzing real-world data is somewhat difficult because we need to take various things into consideration. Apart from getting the useful data from large datasets, keeping data in required format is also very important." }, { "code": null, "e": 25931, "s": 25756, "text": "One might encounter a situation where we need to lowercase each letter in any specific column in given dataframe. Let’s see how to lowercase column names in Pandas dataframe." }, { "code": null, "e": 25980, "s": 25931, "text": "Let’s create a dataframe from the dict of lists." }, { "code": "# Create a simple dataframe # importing pandas as pdimport pandas as pd # creating a dataframedf = pd.DataFrame({'A': ['John', 'bODAY', 'MinA', 'Peter', 'nicky'], 'B': ['masters', 'graduate', 'graduate', 'Masters', 'Graduate'], 'C': [27, 23, 21, 23, 24]}) df", "e": 26312, "s": 25980, "text": null }, { "code": null, "e": 26320, "s": 26312, "text": "Output:" }, { "code": null, "e": 26493, "s": 26320, "text": "There are certain methods we can change/modify the case of column in pandas dataframe. Let’s see how can we lowercase column names in Pandas dataframe using lower() method." }, { "code": null, "e": 26504, "s": 26493, "text": "Method #1:" }, { "code": "# Create a simple dataframe # importing pandas as pdimport pandas as pd # creating a dataframedf = pd.DataFrame({'A': ['John', 'bODAY', 'MinA', 'Peter', 'nicky'], 'B': ['masters', 'graduate', 'graduate', 'Masters', 'Graduate'], 'C': [27, 23, 21, 23, 24]}) df['A'] = df['A'].str.lower() df", "e": 26871, "s": 26504, "text": null }, { "code": null, "e": 26890, "s": 26871, "text": "Output: Method #2:" }, { "code": "# Create a simple dataframe # importing pandas as pdimport pandas as pd # creating a dataframedf = pd.DataFrame({'A': ['John', 'bODAY', 'MinA', 'Peter', 'nicky'], 'B': ['masters', 'graduate', 'graduate', 'Masters', 'Graduate'], 'C': [27, 23, 21, 23, 24]}) df['A'].apply(lambda x: x.lower())", "e": 27257, "s": 26890, "text": null }, { "code": null, "e": 27265, "s": 27257, "text": "Output:" }, { "code": null, "e": 27290, "s": 27265, "text": "pandas-dataframe-program" }, { "code": null, "e": 27314, "s": 27290, "text": "Python pandas-dataFrame" }, { "code": null, "e": 27328, "s": 27314, "text": "Python-pandas" }, { "code": null, "e": 27335, "s": 27328, "text": "Python" }, { "code": null, "e": 27433, "s": 27335, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27465, "s": 27433, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27507, "s": 27465, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27549, "s": 27507, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27576, "s": 27549, "text": "Python Classes and Objects" }, { "code": null, "e": 27632, "s": 27576, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27654, "s": 27632, "text": "Defaultdict in Python" }, { "code": null, "e": 27693, "s": 27654, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27724, "s": 27693, "text": "Python | os.path.join() method" }, { "code": null, "e": 27753, "s": 27724, "text": "Create a directory in Python" } ]
C++ program to divide a number by 3 without using *, / , +, -, % operators - GeeksforGeeks
07 Sep, 2021 For a given positive number we need to divide a number by 3 without using any of these *, /, +, – % operatorsExamples: Input : 48 Output : 16 Input : 16 Output : 5 Algorithm Take a number num, sum = 0while(num>3), shift the number left by 2 bits and sum = add(num >> 2, sum). Create a function add(x, y) for adding two number by bitwise operator Take x, yrun a do while loop till a is not zeroa = x & y, b = x ^ y;, y = b;after terminating loop return value of b which gives sum of x and yTake bitwise AND of num with 3 for new num = add( num >> 2, num & 3)After terminating while loop print the value of sum which give final result . Take a number num, sum = 0 while(num>3), shift the number left by 2 bits and sum = add(num >> 2, sum). Create a function add(x, y) for adding two number by bitwise operator Take x, yrun a do while loop till a is not zeroa = x & y, b = x ^ y;, y = b;after terminating loop return value of b which gives sum of x and y Take x, y run a do while loop till a is not zero a = x & y, b = x ^ y;, y = b; after terminating loop return value of b which gives sum of x and y Take bitwise AND of num with 3 for new num = add( num >> 2, num & 3) After terminating while loop print the value of sum which give final result . For example if your number is 10 then convert to binary 10 => 00001010 If 10 > 3 then shift the binary number 2 bits, Now num will be 00000010 i.e, 2 Now sum will be 2 num = (shift the number by 2 bits) + (number BITWISE AND 3) num = 2+2 Now the number will be 4 then, 4 > 3 => true so loop will be repeated 4 => 00000100 then shift the binary number 2 bits Now sum = 2 + 1 ie, sum = 3 (this value is returned) num = (shift the number(00000100) by 2 bits) + (number BITWISE AND 3) num = 1 + 0 ie remainder = 1 CPP // C++ program for divided a number by// 3 without using operator#include <bits/stdc++.h>using namespace std; // A function to add 2 numbers without using +int add(int x, int y){ int a, b; do { a = x & y; b = x ^ y; x = a << 1; y = b; } while (a); return b;} // Function to divide by 3int divideby3(int num){ int sum = 0; while (num > 3) { sum = add(num >> 2, sum); num = add(num >> 2, num & 3); } if (num == 3) sum = add(sum, 1); return sum;} // Driver programint main(void){ int num = 48; cout << "The number divided by 3 is "; cout << divideby3(num); return 0;} The number divided by 3 is 16 This article is contributed by DANISH_RAZA. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. gulshankumarar231 Oracle Mathematical Oracle Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program to print prime numbers from 1 to N. Segment Tree | Set 1 (Sum of given range) Modular multiplicative inverse Count all possible paths from top left to bottom right of a mXn matrix Fizz Buzz Implementation Check if a number is Palindrome Program to multiply two matrices Count ways to reach the n'th stair Merge two sorted arrays with O(1) extra space Generate all permutation of a set in Python
[ { "code": null, "e": 25961, "s": 25933, "text": "\n07 Sep, 2021" }, { "code": null, "e": 26082, "s": 25961, "text": "For a given positive number we need to divide a number by 3 without using any of these *, /, +, – % operatorsExamples: " }, { "code": null, "e": 26132, "s": 26082, "text": "Input : 48 \nOutput : 16\n\nInput : 16 \nOutput : 5 " }, { "code": null, "e": 26146, "s": 26134, "text": "Algorithm " }, { "code": null, "e": 26607, "s": 26146, "text": "Take a number num, sum = 0while(num>3), shift the number left by 2 bits and sum = add(num >> 2, sum). Create a function add(x, y) for adding two number by bitwise operator Take x, yrun a do while loop till a is not zeroa = x & y, b = x ^ y;, y = b;after terminating loop return value of b which gives sum of x and yTake bitwise AND of num with 3 for new num = add( num >> 2, num & 3)After terminating while loop print the value of sum which give final result ." }, { "code": null, "e": 26634, "s": 26607, "text": "Take a number num, sum = 0" }, { "code": null, "e": 26924, "s": 26634, "text": "while(num>3), shift the number left by 2 bits and sum = add(num >> 2, sum). Create a function add(x, y) for adding two number by bitwise operator Take x, yrun a do while loop till a is not zeroa = x & y, b = x ^ y;, y = b;after terminating loop return value of b which gives sum of x and y" }, { "code": null, "e": 26934, "s": 26924, "text": "Take x, y" }, { "code": null, "e": 26973, "s": 26934, "text": "run a do while loop till a is not zero" }, { "code": null, "e": 27003, "s": 26973, "text": "a = x & y, b = x ^ y;, y = b;" }, { "code": null, "e": 27071, "s": 27003, "text": "after terminating loop return value of b which gives sum of x and y" }, { "code": null, "e": 27140, "s": 27071, "text": "Take bitwise AND of num with 3 for new num = add( num >> 2, num & 3)" }, { "code": null, "e": 27218, "s": 27140, "text": "After terminating while loop print the value of sum which give final result ." }, { "code": null, "e": 27732, "s": 27220, "text": "For example if your number is 10 then convert to binary 10 => 00001010 If 10 > 3 then shift the binary number 2 bits, Now num will be 00000010 i.e, 2 Now sum will be 2 num = (shift the number by 2 bits) + (number BITWISE AND 3) num = 2+2 Now the number will be 4 then, 4 > 3 => true so loop will be repeated 4 => 00000100 then shift the binary number 2 bits Now sum = 2 + 1 ie, sum = 3 (this value is returned) num = (shift the number(00000100) by 2 bits) + (number BITWISE AND 3) num = 1 + 0 ie remainder = 1 " }, { "code": null, "e": 27738, "s": 27734, "text": "CPP" }, { "code": "// C++ program for divided a number by// 3 without using operator#include <bits/stdc++.h>using namespace std; // A function to add 2 numbers without using +int add(int x, int y){ int a, b; do { a = x & y; b = x ^ y; x = a << 1; y = b; } while (a); return b;} // Function to divide by 3int divideby3(int num){ int sum = 0; while (num > 3) { sum = add(num >> 2, sum); num = add(num >> 2, num & 3); } if (num == 3) sum = add(sum, 1); return sum;} // Driver programint main(void){ int num = 48; cout << \"The number divided by 3 is \"; cout << divideby3(num); return 0;}", "e": 28396, "s": 27738, "text": null }, { "code": null, "e": 28426, "s": 28396, "text": "The number divided by 3 is 16" }, { "code": null, "e": 28848, "s": 28428, "text": "This article is contributed by DANISH_RAZA. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 28866, "s": 28848, "text": "gulshankumarar231" }, { "code": null, "e": 28873, "s": 28866, "text": "Oracle" }, { "code": null, "e": 28886, "s": 28873, "text": "Mathematical" }, { "code": null, "e": 28893, "s": 28886, "text": "Oracle" }, { "code": null, "e": 28906, "s": 28893, "text": "Mathematical" }, { "code": null, "e": 29004, "s": 28906, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29048, "s": 29004, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 29090, "s": 29048, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 29121, "s": 29090, "text": "Modular multiplicative inverse" }, { "code": null, "e": 29192, "s": 29121, "text": "Count all possible paths from top left to bottom right of a mXn matrix" }, { "code": null, "e": 29217, "s": 29192, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 29249, "s": 29217, "text": "Check if a number is Palindrome" }, { "code": null, "e": 29282, "s": 29249, "text": "Program to multiply two matrices" }, { "code": null, "e": 29317, "s": 29282, "text": "Count ways to reach the n'th stair" }, { "code": null, "e": 29363, "s": 29317, "text": "Merge two sorted arrays with O(1) extra space" } ]
JavaScript JSON - GeeksforGeeks
23 Feb, 2022 What is JSON?JSON or JavaScript Object Notation is a format for structuring data. What is it used for?Like XML, it is one of the way of formatting the data. Such format of data is used by web applications to communicate with each other. Why JSON? The fact that whenever we declare a variable and assign a value to it, it’s not the variable that holds the value but rather the variable just holds an address in the memory where the initialized value is stored. Further explaining, take for example: let age=21; when we use age, it gets replaced with 21, but that does not mean that age contains 21, rather what it means is that the variable age contains the address of the memory location where 21 is stored. you might think what is the problem, how is JSON helpful? well, yes, you are right! it is fine here till now but imagine you have to transfer the data and use it somewhere else (like an API maybe), so how will we share this? One way could be to send your computers entire memory along with the address of the locations that is required, as you might have understood now that this is not at all a good way to do it, also it is risky to send your entire computer memory. Here comes JSON to the rescue, JSON serializes the data and converts it into human-readable and understandable format, which also makes it transferal and to be able to communicate. Characteristics of JSON It is Human-readable and writable. It is light weight text based data interchange format which means, it is simpler to read and write when compared to XML. It is widely used as data storage and communication format on the web. Though it is derived from a subset of JavaScript, yet it is Language independent. Thus, the code for generating and parsing JSON data can be written in any other programming language. JSON Syntax RulesJSON syntax is derived from JavaScript object notation syntax: Data is in name/value pairsExample:{ “name”:”Thanos” }Types of Values:Array: An associative array of values.Boolean: True or false.Number: An integer.Object: An associative array of key/value pairs.String: Several plain text characters which usually form a word. { “name”:”Thanos” } Types of Values:Array: An associative array of values.Boolean: True or false.Number: An integer.Object: An associative array of key/value pairs.String: Several plain text characters which usually form a word. Data is separated by commasExample:{ “name”:”Thanos”, “Occupation”:”Destroying half of humanity” } { “name”:”Thanos”, “Occupation”:”Destroying half of humanity” } Curly braces hold objectsExample:var person={ “name”:”Thanos”, “Occupation”:”Destroying half of humanity” }Here person is the object. var person={ “name”:”Thanos”, “Occupation”:”Destroying half of humanity” } Here person is the object. Square brackets hold arraysExample:var person={ “name”:”Thanos”, “Occupation”:”Destroying half of humanity”,“powers”:[“Can destroy anything with snap of his fingers”,“Damage resistance”, “Superhuman reflexes”] }Here person is the object and powers is an array. var person={ “name”:”Thanos”, “Occupation”:”Destroying half of humanity”,“powers”:[“Can destroy anything with snap of his fingers”,“Damage resistance”, “Superhuman reflexes”] } Here person is the object and powers is an array. Examples: { "Avengers": [ { "Name" : "Tony stark", "also known as" : "Iron man", "Abilities" : [ "Genius", "Billionaire", "Playboy", "Philanthropist" ] }, { "Name" : "Peter parker", "also known as" : "Spider man", "Abilities" : [ "Spider web", "Spidy sense" ] } ]} perveenneha3 javascript-basics JSON JavaScript 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 Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to calculate the number of days between two dates in javascript? How to append HTML code to a div using JavaScript ? File uploading in React.js Hide or show elements in HTML using display property How to Open URL in New Tab using JavaScript ? Difference Between PUT and PATCH Request
[ { "code": null, "e": 31327, "s": 31299, "text": "\n23 Feb, 2022" }, { "code": null, "e": 31409, "s": 31327, "text": "What is JSON?JSON or JavaScript Object Notation is a format for structuring data." }, { "code": null, "e": 31564, "s": 31409, "text": "What is it used for?Like XML, it is one of the way of formatting the data. Such format of data is used by web applications to communicate with each other." }, { "code": null, "e": 31574, "s": 31564, "text": "Why JSON?" }, { "code": null, "e": 31825, "s": 31574, "text": "The fact that whenever we declare a variable and assign a value to it, it’s not the variable that holds the value but rather the variable just holds an address in the memory where the initialized value is stored. Further explaining, take for example:" }, { "code": null, "e": 31837, "s": 31825, "text": "let age=21;" }, { "code": null, "e": 32035, "s": 31837, "text": "when we use age, it gets replaced with 21, but that does not mean that age contains 21, rather what it means is that the variable age contains the address of the memory location where 21 is stored." }, { "code": null, "e": 32093, "s": 32035, "text": "you might think what is the problem, how is JSON helpful?" }, { "code": null, "e": 32685, "s": 32093, "text": "well, yes, you are right! it is fine here till now but imagine you have to transfer the data and use it somewhere else (like an API maybe), so how will we share this? One way could be to send your computers entire memory along with the address of the locations that is required, as you might have understood now that this is not at all a good way to do it, also it is risky to send your entire computer memory. Here comes JSON to the rescue, JSON serializes the data and converts it into human-readable and understandable format, which also makes it transferal and to be able to communicate." }, { "code": null, "e": 32709, "s": 32685, "text": "Characteristics of JSON" }, { "code": null, "e": 32744, "s": 32709, "text": "It is Human-readable and writable." }, { "code": null, "e": 32865, "s": 32744, "text": "It is light weight text based data interchange format which means, it is simpler to read and write when compared to XML." }, { "code": null, "e": 32936, "s": 32865, "text": "It is widely used as data storage and communication format on the web." }, { "code": null, "e": 33120, "s": 32936, "text": "Though it is derived from a subset of JavaScript, yet it is Language independent. Thus, the code for generating and parsing JSON data can be written in any other programming language." }, { "code": null, "e": 33200, "s": 33120, "text": "JSON Syntax RulesJSON syntax is derived from JavaScript object notation syntax:" }, { "code": null, "e": 33463, "s": 33200, "text": "Data is in name/value pairsExample:{ “name”:”Thanos” }Types of Values:Array: An associative array of values.Boolean: True or false.Number: An integer.Object: An associative array of key/value pairs.String: Several plain text characters which usually form a word." }, { "code": null, "e": 33483, "s": 33463, "text": "{ “name”:”Thanos” }" }, { "code": null, "e": 33692, "s": 33483, "text": "Types of Values:Array: An associative array of values.Boolean: True or false.Number: An integer.Object: An associative array of key/value pairs.String: Several plain text characters which usually form a word." }, { "code": null, "e": 33791, "s": 33692, "text": "Data is separated by commasExample:{ “name”:”Thanos”, “Occupation”:”Destroying half of humanity” }" }, { "code": null, "e": 33855, "s": 33791, "text": "{ “name”:”Thanos”, “Occupation”:”Destroying half of humanity” }" }, { "code": null, "e": 33989, "s": 33855, "text": "Curly braces hold objectsExample:var person={ “name”:”Thanos”, “Occupation”:”Destroying half of humanity” }Here person is the object." }, { "code": null, "e": 34064, "s": 33989, "text": "var person={ “name”:”Thanos”, “Occupation”:”Destroying half of humanity” }" }, { "code": null, "e": 34091, "s": 34064, "text": "Here person is the object." }, { "code": null, "e": 34352, "s": 34091, "text": "Square brackets hold arraysExample:var person={ “name”:”Thanos”, “Occupation”:”Destroying half of humanity”,“powers”:[“Can destroy anything with snap of his fingers”,“Damage resistance”, “Superhuman reflexes”] }Here person is the object and powers is an array." }, { "code": null, "e": 34529, "s": 34352, "text": "var person={ “name”:”Thanos”, “Occupation”:”Destroying half of humanity”,“powers”:[“Can destroy anything with snap of his fingers”,“Damage resistance”, “Superhuman reflexes”] }" }, { "code": null, "e": 34579, "s": 34529, "text": "Here person is the object and powers is an array." }, { "code": null, "e": 34589, "s": 34579, "text": "Examples:" }, { "code": "{ \"Avengers\": [ { \"Name\" : \"Tony stark\", \"also known as\" : \"Iron man\", \"Abilities\" : [ \"Genius\", \"Billionaire\", \"Playboy\", \"Philanthropist\" ] }, { \"Name\" : \"Peter parker\", \"also known as\" : \"Spider man\", \"Abilities\" : [ \"Spider web\", \"Spidy sense\" ] } ]}", "e": 34959, "s": 34589, "text": null }, { "code": null, "e": 34972, "s": 34959, "text": "perveenneha3" }, { "code": null, "e": 34990, "s": 34972, "text": "javascript-basics" }, { "code": null, "e": 34995, "s": 34990, "text": "JSON" }, { "code": null, "e": 35006, "s": 34995, "text": "JavaScript" }, { "code": null, "e": 35104, "s": 35006, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35144, "s": 35104, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 35189, "s": 35144, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 35250, "s": 35189, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 35322, "s": 35250, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 35391, "s": 35322, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 35443, "s": 35391, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 35470, "s": 35443, "text": "File uploading in React.js" }, { "code": null, "e": 35523, "s": 35470, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 35569, "s": 35523, "text": "How to Open URL in New Tab using JavaScript ?" } ]
Maximum and Minimum Values of an Algebraic Expression - GeeksforGeeks
11 Oct, 2021 Given an algebraic expression of the form (x1 + x2 + x3 + . . . + xn) * (y1 + y2 + . . . + ym) and (n + m) integers. Find the maximum and minimum value of the expression using the given integers. Constraint : n <= 50 m <= 50 -50 <= x1, x2, .. xn <= 50 Examples : Input : n = 2, m = 2 arr[] = {1, 2, 3, 4} Output : Maximum : 25 Minimum : 21 The expression is (x1 + x2) * (y1 + y2) and the given integers are 1, 2, 3 and 4. Then maximum value is (1 + 4) * (2 + 3) = 25 whereas minimum value is (4 + 3) * (2 + 1) = 21. Input : n = 3, m = 1 arr[] = {1, 2, 3, 4} Output : Maximum : 24 Minimum : 9 A simple solution is to consider all possible combinations of n numbers and remaining m numbers and calculating their values, from which maximum value and minimum value can be derived.Below is an efficient solution. The idea is based on limited values of n, m, x1, x2, .. y1, y2, .. Let suppose S be the sum of all the (n + m) numbers in the expression and X be the sum of the n numbers on the left of expression. Obviously, the sum of the m numbers on the right of expression will be represented as (S – X). There can be many possible values of X from the given (n + m) numbers and hence the problem gets reduced to simply iterate through all values of X and keeping track of the minimum and maximum value of X * (S – X). Now, the problem is equivalent to finding all possible values of X. Since the given numbers are in the range of -50 to 50 and the maximum value of (n + m) is 100, X will lie in between -2500 and 2500 which results into overall 5000 values of X. We will use dynamic programming approach to solve this problem. Consider a dp[i][j] array which can value either 1 or 0, where 1 means X can be equal to j by choosing i numbers from the (n + m) numbers and 0 otherwise. Then for each number k, if dp[i][j] is 1 then dp[i + 1][j + k] is also 1 where k belongs to given (n + m) numbers. Thus, by iterating through all k, we can determine whether a value of X is reachable by choosing a total of n numbers Below is the implementation of the above approach. C++ Java Python3 C# PHP Javascript // CPP program to find the maximum// and minimum values of an Algebraic// expression of given form#include <bits/stdc++.h>using namespace std; #define INF 1e9#define MAX 50 int minMaxValues(int arr[], int n, int m){ // Finding sum of array elements int sum = 0; for (int i = 0; i < (n + m); i++) { sum += arr[i]; // shifting the integers by 50 // so that they become positive arr[i] += 50; } // dp[i][j] represents true if sum// j can be reachable by choosing// i numbersbool dp[MAX+1][MAX * MAX + 1]; // initialize the dp array to 01 memset(dp, 0, sizeof(dp)); dp[0][0] = 1; // if dp[i][j] is true, that means // it is possible to select i numbers // from (n + m) numbers to sum upto j for (int i = 0; i < (n + m); i++) { // k can be at max n because the // left expression has n numbers for (int k = min(n, i + 1); k >= 1; k--) { for (int j = 0; j < MAX * MAX + 1; j++) { if (dp[k - 1][j]) dp[k][j + arr[i]] = 1; } } } int max_value = -INF, min_value = INF; for (int i = 0; i < MAX * MAX + 1; i++) { // checking if a particular sum // can be reachable by choosing // n numbers if (dp[n][i]) { // getting the actual sum as // we shifted the numbers by /// 50 to avoid negative indexing // in array int temp = i - 50 * n; max_value = max(max_value, temp * (sum - temp)); min_value = min(min_value, temp * (sum - temp)); } } cout << "Maximum Value: " << max_value << "\n" << "Minimum Value: " << min_value << endl;} // Driver Codeint main(){ int n = 2, m = 2; int arr[] = { 1, 2, 3, 4 }; minMaxValues(arr, n, m); return 0;} // Java program to find the maximum// and minimum values of an Algebraic// expression of given formimport java.io.*;import java.lang.*; public class GFG { static double INF = 1e9; static int MAX = 50; static void minMaxValues(int []arr, int n, int m) { // Finding sum of array elements int sum = 0; for (int i = 0; i < (n + m); i++) { sum += arr[i]; // shifting the integers by 50 // so that they become positive arr[i] += 50; } // dp[i][j] represents true if sum // j can be reachable by choosing // i numbers boolean dp[][] = new boolean[MAX+1][MAX * MAX + 1]; dp[0][0] = true; // if dp[i][j] is true, that means // it is possible to select i numbers // from (n + m) numbers to sum upto j for (int i = 0; i < (n + m); i++) { // k can be at max n because the // left expression has n numbers for (int k = Math.min(n, i + 1); k >= 1; k--) { for (int j = 0; j < MAX * MAX + 1; j++) { if (dp[k - 1][j]) dp[k][j + arr[i]] = true; } } } double max_value = -1 * INF, min_value = INF; for (int i = 0; i < MAX * MAX + 1; i++) { // checking if a particular sum // can be reachable by choosing // n numbers if (dp[n][i]) { // getting the actual sum as // we shifted the numbers by /// 50 to avoid negative indexing // in array int temp = i - 50 * n; max_value = Math.max(max_value, temp * (sum - temp)); min_value = Math.min(min_value, temp * (sum - temp)); } } System.out.print("Maximum Value: " + (int)max_value + "\n" + "Minimum Value: " + (int)min_value + "\n"); } // Driver Code public static void main(String args[]) { int n = 2, m = 2; int []arr = { 1, 2, 3, 4 }; minMaxValues(arr, n, m); }} // This code is contributed by Manish Shaw// (manishshaw1) # Python3 program to find the # maximum and minimum values # of an Algebraic expression # of given formdef minMaxValues(arr, n, m) : # Finding sum of # array elements sum = 0 INF = 1000000000 MAX = 50 for i in range(0, (n + m)) : sum += arr[i] # shifting the integers by 50 # so that they become positive arr[i] += 50 # dp[i][j] represents true # if sum j can be reachable # by choosing i numbers dp = [[0 for x in range(MAX * MAX + 1)] for y in range( MAX + 1)] dp[0][0] = 1 # if dp[i][j] is true, that # means it is possible to # select i numbers from (n + m) # numbers to sum upto j for i in range(0, (n + m)) : # k can be at max n because the # left expression has n numbers for k in range(min(n, i + 1), 0, -1) : for j in range(0, MAX * MAX + 1) : if (dp[k - 1][j]) : dp[k][j + arr[i]] = 1 max_value = -1 * INF min_value = INF for i in range(0, MAX * MAX + 1) : # checking if a particular # sum can be reachable by # choosing n numbers if (dp[n][i]) : # getting the actual sum # as we shifted the numbers # by 50 to avoid negative # indexing in array temp = i - 50 * n max_value = max(max_value, temp * (sum - temp)) min_value = min(min_value, temp * (sum - temp)) print ("Maximum Value: {}\nMinimum Value: {}" .format(max_value, min_value)) # Driver Coden = 2m = 2arr = [ 1, 2, 3, 4 ] minMaxValues(arr, n, m) # This code is contributed by # Manish Shaw(manishshaw1) // C# program to find the maximum// and minimum values of an Algebraic// expression of given formusing System;using System.Collections.Generic; class GFG { static double INF = 1e9; static int MAX = 50; static void minMaxValues(int []arr, int n, int m) { // Finding sum of array elements int sum = 0; for (int i = 0; i < (n + m); i++) { sum += arr[i]; // shifting the integers by 50 // so that they become positive arr[i] += 50; } // dp[i][j] represents true if sum // j can be reachable by choosing // i numbers bool[,] dp = new bool[MAX+1, MAX * MAX + 1]; dp[0,0] = true; // if dp[i][j] is true, that means // it is possible to select i numbers // from (n + m) numbers to sum upto j for (int i = 0; i < (n + m); i++) { // k can be at max n because the // left expression has n numbers for (int k = Math.Min(n, i + 1); k >= 1; k--) { for (int j = 0; j < MAX * MAX + 1; j++) { if (dp[k - 1,j]) dp[k,j + arr[i]] = true; } } } double max_value = -1 * INF, min_value = INF; for (int i = 0; i < MAX * MAX + 1; i++) { // checking if a particular sum // can be reachable by choosing // n numbers if (dp[n,i]) { // getting the actual sum as // we shifted the numbers by /// 50 to avoid negative indexing // in array int temp = i - 50 * n; max_value = Math.Max(max_value, temp * (sum - temp)); min_value = Math.Min(min_value, temp * (sum - temp)); } } Console.WriteLine("Maximum Value: " + max_value + "\n" + "Minimum Value: " + min_value + "\n"); } // Driver Code public static void Main() { int n = 2, m = 2; int []arr = { 1, 2, 3, 4 }; minMaxValues(arr, n, m); }} // This code is contributed by Manish Shaw// (manishshaw1) <?php// PHP program to find the // maximum and minimum values // of an Algebraic expression // of given formfunction minMaxValues($arr, $n, $m){ // Finding sum of // array elements $sum = 0; $INF = 1000000000; $MAX = 50; for ($i = 0; $i < ($n + $m); $i++) { $sum += $arr[$i]; // shifting the integers by 50 // so that they become positive $arr[$i] += 50; } // dp[i][j] represents true // if sum j can be reachable // by choosing i numbers $dp = array(); // new bool[MAX+1, MAX * MAX + 1]; for($i = 0; $i < $MAX + 1; $i++) { for($j = 0; $j < $MAX * $MAX + 1; $j++) $dp[$i][$j] = 0; } $dp[0][0] = 1; // if dp[i][j] is true, that // means it is possible to // select i numbers from (n + m) // numbers to sum upto j for ($i = 0; $i < ($n + $m); $i++) { // k can be at max n because the // left expression has n numbers for ($k = min($n, $i + 1); $k >= 1; $k--) { for ($j = 0; $j < $MAX * $MAX + 1; $j++) { if ($dp[$k - 1][$j]) $dp[$k][$j + $arr[$i]] = 1; } } } $max_value = -1 * $INF; $min_value = $INF; for ($i = 0; $i < $MAX * $MAX + 1; $i++) { // checking if a particular // sum can be reachable by // choosing n numbers if ($dp[$n][$i]) { // getting the actual sum // as we shifted the numbers // by 50 to avoid negative // indexing in array $temp = $i - 50 * $n; $max_value = max($max_value, $temp * ($sum - $temp)); $min_value = min($min_value, $temp * ($sum - $temp)); } } echo ("Maximum Value: ". $max_value. "\n". "Minimum Value: ". $min_value. "\n");} // Driver Code$n = 2;$m = 2;$arr = [ 1, 2, 3, 4 ]; minMaxValues($arr, $n, $m); // This code is contributed by // Manish Shaw(manishshaw1)?> <script> // Javascript program to find the maximum// and minimum values of an Algebraic// expression of given form var INF = 1000000000var MAX = 50 function minMaxValues(arr, n, m){ // Finding sum of array elements var sum = 0; for (var i = 0; i < (n + m); i++) { sum += arr[i]; // shifting the integers by 50 // so that they become positive arr[i] += 50; } // dp[i][j] represents true if sum// j can be reachable by choosing// i numbersvar dp = Array.from(Array(MAX+1), ()=> Array(MAX*MAX + 1).fill(0)); dp[0][0] = 1; // if dp[i][j] is true, that means // it is possible to select i numbers // from (n + m) numbers to sum upto j for (var i = 0; i < (n + m); i++) { // k can be at max n because the // left expression has n numbers for (var k = Math.min(n, i + 1); k >= 1; k--) { for (var j = 0; j < MAX * MAX + 1; j++) { if (dp[k - 1][j]) dp[k][j + arr[i]] = 1; } } } var max_value = -INF, min_value = INF; for (var i = 0; i < MAX * MAX + 1; i++) { // checking if a particular sum // can be reachable by choosing // n numbers if (dp[n][i]) { // getting the actual sum as // we shifted the numbers by /// 50 to avoid negative indexing // in array var temp = i - 50 * n; max_value = Math.max(max_value, temp * (sum - temp)); min_value = Math.min(min_value, temp * (sum - temp)); } } document.write( "Maximum Value: " + max_value + "<br>" + "Minimum Value: " + min_value );} // Driver Codevar n = 2, m = 2;var arr =[1, 2, 3, 4];minMaxValues(arr, n, m); </script> Maximum Value: 25 Minimum Value: 21 This approach will have a runtime complexity of O(MAX * MAX * (n+m)2). manishshaw1 itsok surindertarika1234 Dynamic Programming Mathematical Matrix Technical Scripter Dynamic Programming Mathematical Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16 Longest Palindromic Substring | Set 1 Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Edit Distance | DP-5 Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples
[ { "code": null, "e": 26411, "s": 26383, "text": "\n11 Oct, 2021" }, { "code": null, "e": 26609, "s": 26411, "text": "Given an algebraic expression of the form (x1 + x2 + x3 + . . . + xn) * (y1 + y2 + . . . + ym) and (n + m) integers. Find the maximum and minimum value of the expression using the given integers. " }, { "code": null, "e": 26665, "s": 26609, "text": "Constraint : n <= 50 m <= 50 -50 <= x1, x2, .. xn <= 50" }, { "code": null, "e": 26678, "s": 26665, "text": "Examples : " }, { "code": null, "e": 27046, "s": 26678, "text": "Input : n = 2, m = 2\n arr[] = {1, 2, 3, 4}\nOutput : Maximum : 25 \n Minimum : 21\nThe expression is (x1 + x2) * (y1 + y2) and\nthe given integers are 1, 2, 3 and 4. Then\nmaximum value is (1 + 4) * (2 + 3) = 25 \nwhereas minimum value is (4 + 3) * (2 + 1) \n= 21.\n\nInput : n = 3, m = 1\n arr[] = {1, 2, 3, 4}\nOutput : Maximum : 24 \n Minimum : 9" }, { "code": null, "e": 28521, "s": 27048, "text": "A simple solution is to consider all possible combinations of n numbers and remaining m numbers and calculating their values, from which maximum value and minimum value can be derived.Below is an efficient solution. The idea is based on limited values of n, m, x1, x2, .. y1, y2, .. Let suppose S be the sum of all the (n + m) numbers in the expression and X be the sum of the n numbers on the left of expression. Obviously, the sum of the m numbers on the right of expression will be represented as (S – X). There can be many possible values of X from the given (n + m) numbers and hence the problem gets reduced to simply iterate through all values of X and keeping track of the minimum and maximum value of X * (S – X). Now, the problem is equivalent to finding all possible values of X. Since the given numbers are in the range of -50 to 50 and the maximum value of (n + m) is 100, X will lie in between -2500 and 2500 which results into overall 5000 values of X. We will use dynamic programming approach to solve this problem. Consider a dp[i][j] array which can value either 1 or 0, where 1 means X can be equal to j by choosing i numbers from the (n + m) numbers and 0 otherwise. Then for each number k, if dp[i][j] is 1 then dp[i + 1][j + k] is also 1 where k belongs to given (n + m) numbers. Thus, by iterating through all k, we can determine whether a value of X is reachable by choosing a total of n numbers Below is the implementation of the above approach. " }, { "code": null, "e": 28525, "s": 28521, "text": "C++" }, { "code": null, "e": 28530, "s": 28525, "text": "Java" }, { "code": null, "e": 28538, "s": 28530, "text": "Python3" }, { "code": null, "e": 28541, "s": 28538, "text": "C#" }, { "code": null, "e": 28545, "s": 28541, "text": "PHP" }, { "code": null, "e": 28556, "s": 28545, "text": "Javascript" }, { "code": "// CPP program to find the maximum// and minimum values of an Algebraic// expression of given form#include <bits/stdc++.h>using namespace std; #define INF 1e9#define MAX 50 int minMaxValues(int arr[], int n, int m){ // Finding sum of array elements int sum = 0; for (int i = 0; i < (n + m); i++) { sum += arr[i]; // shifting the integers by 50 // so that they become positive arr[i] += 50; } // dp[i][j] represents true if sum// j can be reachable by choosing// i numbersbool dp[MAX+1][MAX * MAX + 1]; // initialize the dp array to 01 memset(dp, 0, sizeof(dp)); dp[0][0] = 1; // if dp[i][j] is true, that means // it is possible to select i numbers // from (n + m) numbers to sum upto j for (int i = 0; i < (n + m); i++) { // k can be at max n because the // left expression has n numbers for (int k = min(n, i + 1); k >= 1; k--) { for (int j = 0; j < MAX * MAX + 1; j++) { if (dp[k - 1][j]) dp[k][j + arr[i]] = 1; } } } int max_value = -INF, min_value = INF; for (int i = 0; i < MAX * MAX + 1; i++) { // checking if a particular sum // can be reachable by choosing // n numbers if (dp[n][i]) { // getting the actual sum as // we shifted the numbers by /// 50 to avoid negative indexing // in array int temp = i - 50 * n; max_value = max(max_value, temp * (sum - temp)); min_value = min(min_value, temp * (sum - temp)); } } cout << \"Maximum Value: \" << max_value << \"\\n\" << \"Minimum Value: \" << min_value << endl;} // Driver Codeint main(){ int n = 2, m = 2; int arr[] = { 1, 2, 3, 4 }; minMaxValues(arr, n, m); return 0;}", "e": 30409, "s": 28556, "text": null }, { "code": "// Java program to find the maximum// and minimum values of an Algebraic// expression of given formimport java.io.*;import java.lang.*; public class GFG { static double INF = 1e9; static int MAX = 50; static void minMaxValues(int []arr, int n, int m) { // Finding sum of array elements int sum = 0; for (int i = 0; i < (n + m); i++) { sum += arr[i]; // shifting the integers by 50 // so that they become positive arr[i] += 50; } // dp[i][j] represents true if sum // j can be reachable by choosing // i numbers boolean dp[][] = new boolean[MAX+1][MAX * MAX + 1]; dp[0][0] = true; // if dp[i][j] is true, that means // it is possible to select i numbers // from (n + m) numbers to sum upto j for (int i = 0; i < (n + m); i++) { // k can be at max n because the // left expression has n numbers for (int k = Math.min(n, i + 1); k >= 1; k--) { for (int j = 0; j < MAX * MAX + 1; j++) { if (dp[k - 1][j]) dp[k][j + arr[i]] = true; } } } double max_value = -1 * INF, min_value = INF; for (int i = 0; i < MAX * MAX + 1; i++) { // checking if a particular sum // can be reachable by choosing // n numbers if (dp[n][i]) { // getting the actual sum as // we shifted the numbers by /// 50 to avoid negative indexing // in array int temp = i - 50 * n; max_value = Math.max(max_value, temp * (sum - temp)); min_value = Math.min(min_value, temp * (sum - temp)); } } System.out.print(\"Maximum Value: \" + (int)max_value + \"\\n\" + \"Minimum Value: \" + (int)min_value + \"\\n\"); } // Driver Code public static void main(String args[]) { int n = 2, m = 2; int []arr = { 1, 2, 3, 4 }; minMaxValues(arr, n, m); }} // This code is contributed by Manish Shaw// (manishshaw1)", "e": 32878, "s": 30409, "text": null }, { "code": "# Python3 program to find the # maximum and minimum values # of an Algebraic expression # of given formdef minMaxValues(arr, n, m) : # Finding sum of # array elements sum = 0 INF = 1000000000 MAX = 50 for i in range(0, (n + m)) : sum += arr[i] # shifting the integers by 50 # so that they become positive arr[i] += 50 # dp[i][j] represents true # if sum j can be reachable # by choosing i numbers dp = [[0 for x in range(MAX * MAX + 1)] for y in range( MAX + 1)] dp[0][0] = 1 # if dp[i][j] is true, that # means it is possible to # select i numbers from (n + m) # numbers to sum upto j for i in range(0, (n + m)) : # k can be at max n because the # left expression has n numbers for k in range(min(n, i + 1), 0, -1) : for j in range(0, MAX * MAX + 1) : if (dp[k - 1][j]) : dp[k][j + arr[i]] = 1 max_value = -1 * INF min_value = INF for i in range(0, MAX * MAX + 1) : # checking if a particular # sum can be reachable by # choosing n numbers if (dp[n][i]) : # getting the actual sum # as we shifted the numbers # by 50 to avoid negative # indexing in array temp = i - 50 * n max_value = max(max_value, temp * (sum - temp)) min_value = min(min_value, temp * (sum - temp)) print (\"Maximum Value: {}\\nMinimum Value: {}\" .format(max_value, min_value)) # Driver Coden = 2m = 2arr = [ 1, 2, 3, 4 ] minMaxValues(arr, n, m) # This code is contributed by # Manish Shaw(manishshaw1)", "e": 34688, "s": 32878, "text": null }, { "code": "// C# program to find the maximum// and minimum values of an Algebraic// expression of given formusing System;using System.Collections.Generic; class GFG { static double INF = 1e9; static int MAX = 50; static void minMaxValues(int []arr, int n, int m) { // Finding sum of array elements int sum = 0; for (int i = 0; i < (n + m); i++) { sum += arr[i]; // shifting the integers by 50 // so that they become positive arr[i] += 50; } // dp[i][j] represents true if sum // j can be reachable by choosing // i numbers bool[,] dp = new bool[MAX+1, MAX * MAX + 1]; dp[0,0] = true; // if dp[i][j] is true, that means // it is possible to select i numbers // from (n + m) numbers to sum upto j for (int i = 0; i < (n + m); i++) { // k can be at max n because the // left expression has n numbers for (int k = Math.Min(n, i + 1); k >= 1; k--) { for (int j = 0; j < MAX * MAX + 1; j++) { if (dp[k - 1,j]) dp[k,j + arr[i]] = true; } } } double max_value = -1 * INF, min_value = INF; for (int i = 0; i < MAX * MAX + 1; i++) { // checking if a particular sum // can be reachable by choosing // n numbers if (dp[n,i]) { // getting the actual sum as // we shifted the numbers by /// 50 to avoid negative indexing // in array int temp = i - 50 * n; max_value = Math.Max(max_value, temp * (sum - temp)); min_value = Math.Min(min_value, temp * (sum - temp)); } } Console.WriteLine(\"Maximum Value: \" + max_value + \"\\n\" + \"Minimum Value: \" + min_value + \"\\n\"); } // Driver Code public static void Main() { int n = 2, m = 2; int []arr = { 1, 2, 3, 4 }; minMaxValues(arr, n, m); }} // This code is contributed by Manish Shaw// (manishshaw1)", "e": 37049, "s": 34688, "text": null }, { "code": "<?php// PHP program to find the // maximum and minimum values // of an Algebraic expression // of given formfunction minMaxValues($arr, $n, $m){ // Finding sum of // array elements $sum = 0; $INF = 1000000000; $MAX = 50; for ($i = 0; $i < ($n + $m); $i++) { $sum += $arr[$i]; // shifting the integers by 50 // so that they become positive $arr[$i] += 50; } // dp[i][j] represents true // if sum j can be reachable // by choosing i numbers $dp = array(); // new bool[MAX+1, MAX * MAX + 1]; for($i = 0; $i < $MAX + 1; $i++) { for($j = 0; $j < $MAX * $MAX + 1; $j++) $dp[$i][$j] = 0; } $dp[0][0] = 1; // if dp[i][j] is true, that // means it is possible to // select i numbers from (n + m) // numbers to sum upto j for ($i = 0; $i < ($n + $m); $i++) { // k can be at max n because the // left expression has n numbers for ($k = min($n, $i + 1); $k >= 1; $k--) { for ($j = 0; $j < $MAX * $MAX + 1; $j++) { if ($dp[$k - 1][$j]) $dp[$k][$j + $arr[$i]] = 1; } } } $max_value = -1 * $INF; $min_value = $INF; for ($i = 0; $i < $MAX * $MAX + 1; $i++) { // checking if a particular // sum can be reachable by // choosing n numbers if ($dp[$n][$i]) { // getting the actual sum // as we shifted the numbers // by 50 to avoid negative // indexing in array $temp = $i - 50 * $n; $max_value = max($max_value, $temp * ($sum - $temp)); $min_value = min($min_value, $temp * ($sum - $temp)); } } echo (\"Maximum Value: \". $max_value. \"\\n\". \"Minimum Value: \". $min_value. \"\\n\");} // Driver Code$n = 2;$m = 2;$arr = [ 1, 2, 3, 4 ]; minMaxValues($arr, $n, $m); // This code is contributed by // Manish Shaw(manishshaw1)?>", "e": 39231, "s": 37049, "text": null }, { "code": "<script> // Javascript program to find the maximum// and minimum values of an Algebraic// expression of given form var INF = 1000000000var MAX = 50 function minMaxValues(arr, n, m){ // Finding sum of array elements var sum = 0; for (var i = 0; i < (n + m); i++) { sum += arr[i]; // shifting the integers by 50 // so that they become positive arr[i] += 50; } // dp[i][j] represents true if sum// j can be reachable by choosing// i numbersvar dp = Array.from(Array(MAX+1), ()=> Array(MAX*MAX + 1).fill(0)); dp[0][0] = 1; // if dp[i][j] is true, that means // it is possible to select i numbers // from (n + m) numbers to sum upto j for (var i = 0; i < (n + m); i++) { // k can be at max n because the // left expression has n numbers for (var k = Math.min(n, i + 1); k >= 1; k--) { for (var j = 0; j < MAX * MAX + 1; j++) { if (dp[k - 1][j]) dp[k][j + arr[i]] = 1; } } } var max_value = -INF, min_value = INF; for (var i = 0; i < MAX * MAX + 1; i++) { // checking if a particular sum // can be reachable by choosing // n numbers if (dp[n][i]) { // getting the actual sum as // we shifted the numbers by /// 50 to avoid negative indexing // in array var temp = i - 50 * n; max_value = Math.max(max_value, temp * (sum - temp)); min_value = Math.min(min_value, temp * (sum - temp)); } } document.write( \"Maximum Value: \" + max_value + \"<br>\" + \"Minimum Value: \" + min_value );} // Driver Codevar n = 2, m = 2;var arr =[1, 2, 3, 4];minMaxValues(arr, n, m); </script>", "e": 41005, "s": 39231, "text": null }, { "code": null, "e": 41041, "s": 41005, "text": "Maximum Value: 25\nMinimum Value: 21" }, { "code": null, "e": 41115, "s": 41043, "text": "This approach will have a runtime complexity of O(MAX * MAX * (n+m)2). " }, { "code": null, "e": 41127, "s": 41115, "text": "manishshaw1" }, { "code": null, "e": 41133, "s": 41127, "text": "itsok" }, { "code": null, "e": 41152, "s": 41133, "text": "surindertarika1234" }, { "code": null, "e": 41172, "s": 41152, "text": "Dynamic Programming" }, { "code": null, "e": 41185, "s": 41172, "text": "Mathematical" }, { "code": null, "e": 41192, "s": 41185, "text": "Matrix" }, { "code": null, "e": 41211, "s": 41192, "text": "Technical Scripter" }, { "code": null, "e": 41231, "s": 41211, "text": "Dynamic Programming" }, { "code": null, "e": 41244, "s": 41231, "text": "Mathematical" }, { "code": null, "e": 41251, "s": 41244, "text": "Matrix" }, { "code": null, "e": 41349, "s": 41251, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 41380, "s": 41349, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 41413, "s": 41380, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 41451, "s": 41413, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 41519, "s": 41451, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 41540, "s": 41519, "text": "Edit Distance | DP-5" }, { "code": null, "e": 41600, "s": 41540, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 41615, "s": 41600, "text": "C++ Data Types" }, { "code": null, "e": 41658, "s": 41615, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 41682, "s": 41658, "text": "Merge two sorted arrays" } ]
How to Update Two Tables in One Statement in SQL Server? - GeeksforGeeks
16 Dec, 2021 In SQL, there is a requirement of a single query/statement to simultaneously perform 2 tasks at the same time. For instance, updating 2 different tables together in a single query/statement. This involves the use of the BEGIN TRANSACTION clause and the COMMIT clause. The individual UPDATE clauses are written in between the former ones to execute both the updates simultaneously. The same is depicted in the below article. For this article, we will be using the Microsoft SQL Server as our database. Step 1: Create a Database. For this use the below command to create a database named GeeksForGeeks. Query: CREATE DATABASE GeeksForGeeks Output: Step 2: Use the GeeksForGeeks database. For this use the below command. Query: USE GeeksForGeeks Output: Step 3: Create a table ECONOMICS_MARKS inside the database GeeksForGeeks. This table has 3 columns namely ID, S_NAME and ECO_MARKS containing the roll number and name of the students and the marks scored by the students in economics subject. Query: CREATE TABLE ECONOMICS_MARKS( ID INT, S_NAME VARCHAR(10), ECO_MARKS INT); Output: Step 4: Describe the structure of the table ECONOMICS_MARKS. Query: EXEC SP_COLUMNS ECONOMICS_MARKS; Output: Step 5: Create a table COMMERCE_MARKS inside the database GeeksForGeeks. This table has 3 columns namely ID, S_NAME and COM_MARKS containing the roll number and name of the students and the marks scored by the students in commerce subject. Query: CREATE TABLE COMMERCE_MARKS( ID INT, S_NAME VARCHAR(10), COM_MARKS INT); Output: Step 6: Describe the structure of the table COMMERCE_MARKS. Query: EXEC SP_COLUMNS COMMERCE_MARKS; Output: Step 7: Insert 5 rows into the ECONOMICS_MARKS table. Query: INSERT INTO ECONOMICS_MARKS VALUES(1,'SAM',70); INSERT INTO ECONOMICS_MARKS VALUES(2,'AMY',68); INSERT INTO ECONOMICS_MARKS VALUES(3,'EMMA',69); INSERT INTO ECONOMICS_MARKS VALUES(4,'ROB',57); INSERT INTO ECONOMICS_MARKS VALUES(5,'KEVIN',65); Output: Step 8: Display all the rows of the ECONOMICS_MARKS table. Query: SELECT * FROM ECONOMICS_MARKS; Output: Step 9: Insert 5 rows into the COMMERCE_MARKS table. Query: INSERT INTO COMMERCE_MARKS VALUES(1,'SAM',80); INSERT INTO COMMERCE_MARKS VALUES(2,'AMY',88); INSERT INTO COMMERCE_MARKS VALUES(3,'EMMA',90); INSERT INTO COMMERCE_MARKS VALUES(4,'ROB',75); INSERT INTO COMMERCE_MARKS VALUES(5,'KEVIN',56); Output: Step 10: Display all the rows of the COMMERCE_MARKS table. Query: SELECT * FROM COMMERCE_MARKS; Output: Step 11: Update the economics and commerce marks of student having id=1 to 80 and 75 respectively using a single query. This involves 2 steps. First, perform JOIN of ECONOMICS_MARKS table and COMMERCE_MARKS table. Then using ALIASES of the tables which are E and C respectively, compare the ID of students(to ensure same ID is picked from both tables) AND finally compare the student ID to 1(given value). When both these conditions fulfill, UPDATE the corresponding marks to 80 and 75. This whole thing must be enclosed between BEGIN TRANSACTION and COMMIT to treat it a single ATOMIC operation. This query involves updating of records belonging to the same student IDs. Syntax: BEGIN TRANSACTION; UPDATE TABLE_1 SET TABLE_1.TABLE_1_COLUMN = VALUE_1 FROM TABLE_1 T1, TABLE_2 T2 WHERE T1.ID = T2.ID AND T1.ID = ID_VALUE_1; UPDATE TABLE_2 SET TABLE_2.TABLE_2_COLUMN = VALUE_2 FROM TABLE_1 T1, TABLE_2 T2 WHERE T1.ID = T2.ID AND T2.ID = ID_VALUE_2; COMMIT; Query: BEGIN TRANSACTION; UPDATE ECONOMICS_MARKS SET ECONOMICS_MARKS.ECO_MARKS = 80 FROM ECONOMICS_MARKS E, COMMERCE_MARKS C WHERE E.ID = C.ID AND E.ID = 1; UPDATE COMMERCE_MARKS SET COMMERCE_MARKS.COM_MARKS = 75 FROM ECONOMICS_MARKS E, COMMERCE_MARKS C WHERE E.ID = C.ID AND C.ID = 1; COMMIT; Output: Step 12: Display all the rows of the updated ECONOMICS_MARKS table. Query: SELECT * FROM ECONOMICS_MARKS; Note – The value of the column ECO_MARKS for the ID 1 is updated to 80. Output: Step 13: Display all the rows of the updated COMMERCE_MARKS table. Query: SELECT * FROM COMMERCE_MARKS; Note:The value of the column COM_MARKS for the ID 1 is updated to 75. Output: Step 14: Update the economics marks of student having id=2 to 86 and commerce marks of student having id=3 to 99 using a single query. This query involves updating of records belonging to the different student IDs. Query: BEGIN TRANSACTION; UPDATE ECONOMICS_MARKS SET ECONOMICS_MARKS.ECO_MARKS = 86 FROM ECONOMICS_MARKS E, COMMERCE_MARKS C WHERE E.ID = C.ID AND E.ID = 2; UPDATE COMMERCE_MARKS SET COMMERCE_MARKS.COM_MARKS = 99 FROM ECONOMICS_MARKS E, COMMERCE_MARKS C WHERE E.ID = C.ID AND C.ID = 3; COMMIT; Output: Step 15: Display all the rows of the updated ECONOMICS_MARKS table. Query: SELECT * FROM ECONOMICS_MARKS; Note – The value of the column ECO_MARKS for the ID 2 is updated to 86. Output: Step 16: Display all the rows of the updated COMMERCE_MARKS table. Query: SELECT * FROM COMMERCE_MARKS; Note – The value of the column COM_MARKS for the ID 3 is updated to 99. Output: Picked SQL-Query SQL-Server SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Update Multiple Columns in Single Update Statement in SQL? SQL | Subquery How to Create a Table With Multiple Foreign Keys in SQL? What is Temporary Table in SQL? SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter SQL using Python SQL Query to Convert VARCHAR to INT How to Write a SQL Query For a Specific Date Range and Date Time? How to Select Data Between Two Dates and Times in SQL Server? SQL Query to Compare Two Dates
[ { "code": null, "e": 25513, "s": 25485, "text": "\n16 Dec, 2021" }, { "code": null, "e": 26014, "s": 25513, "text": "In SQL, there is a requirement of a single query/statement to simultaneously perform 2 tasks at the same time. For instance, updating 2 different tables together in a single query/statement. This involves the use of the BEGIN TRANSACTION clause and the COMMIT clause. The individual UPDATE clauses are written in between the former ones to execute both the updates simultaneously. The same is depicted in the below article. For this article, we will be using the Microsoft SQL Server as our database." }, { "code": null, "e": 26114, "s": 26014, "text": "Step 1: Create a Database. For this use the below command to create a database named GeeksForGeeks." }, { "code": null, "e": 26121, "s": 26114, "text": "Query:" }, { "code": null, "e": 26151, "s": 26121, "text": "CREATE DATABASE GeeksForGeeks" }, { "code": null, "e": 26159, "s": 26151, "text": "Output:" }, { "code": null, "e": 26231, "s": 26159, "text": "Step 2: Use the GeeksForGeeks database. For this use the below command." }, { "code": null, "e": 26238, "s": 26231, "text": "Query:" }, { "code": null, "e": 26256, "s": 26238, "text": "USE GeeksForGeeks" }, { "code": null, "e": 26264, "s": 26256, "text": "Output:" }, { "code": null, "e": 26506, "s": 26264, "text": "Step 3: Create a table ECONOMICS_MARKS inside the database GeeksForGeeks. This table has 3 columns namely ID, S_NAME and ECO_MARKS containing the roll number and name of the students and the marks scored by the students in economics subject." }, { "code": null, "e": 26513, "s": 26506, "text": "Query:" }, { "code": null, "e": 26587, "s": 26513, "text": "CREATE TABLE ECONOMICS_MARKS(\nID INT,\nS_NAME VARCHAR(10),\nECO_MARKS INT);" }, { "code": null, "e": 26595, "s": 26587, "text": "Output:" }, { "code": null, "e": 26656, "s": 26595, "text": "Step 4: Describe the structure of the table ECONOMICS_MARKS." }, { "code": null, "e": 26663, "s": 26656, "text": "Query:" }, { "code": null, "e": 26696, "s": 26663, "text": "EXEC SP_COLUMNS ECONOMICS_MARKS;" }, { "code": null, "e": 26704, "s": 26696, "text": "Output:" }, { "code": null, "e": 26944, "s": 26704, "text": "Step 5: Create a table COMMERCE_MARKS inside the database GeeksForGeeks. This table has 3 columns namely ID, S_NAME and COM_MARKS containing the roll number and name of the students and the marks scored by the students in commerce subject." }, { "code": null, "e": 26951, "s": 26944, "text": "Query:" }, { "code": null, "e": 27024, "s": 26951, "text": "CREATE TABLE COMMERCE_MARKS(\nID INT,\nS_NAME VARCHAR(10),\nCOM_MARKS INT);" }, { "code": null, "e": 27032, "s": 27024, "text": "Output:" }, { "code": null, "e": 27092, "s": 27032, "text": "Step 6: Describe the structure of the table COMMERCE_MARKS." }, { "code": null, "e": 27099, "s": 27092, "text": "Query:" }, { "code": null, "e": 27131, "s": 27099, "text": "EXEC SP_COLUMNS COMMERCE_MARKS;" }, { "code": null, "e": 27139, "s": 27131, "text": "Output:" }, { "code": null, "e": 27193, "s": 27139, "text": "Step 7: Insert 5 rows into the ECONOMICS_MARKS table." }, { "code": null, "e": 27200, "s": 27193, "text": "Query:" }, { "code": null, "e": 27443, "s": 27200, "text": "INSERT INTO ECONOMICS_MARKS VALUES(1,'SAM',70);\nINSERT INTO ECONOMICS_MARKS VALUES(2,'AMY',68);\nINSERT INTO ECONOMICS_MARKS VALUES(3,'EMMA',69);\nINSERT INTO ECONOMICS_MARKS VALUES(4,'ROB',57);\nINSERT INTO ECONOMICS_MARKS VALUES(5,'KEVIN',65);" }, { "code": null, "e": 27451, "s": 27443, "text": "Output:" }, { "code": null, "e": 27510, "s": 27451, "text": "Step 8: Display all the rows of the ECONOMICS_MARKS table." }, { "code": null, "e": 27517, "s": 27510, "text": "Query:" }, { "code": null, "e": 27548, "s": 27517, "text": "SELECT * FROM ECONOMICS_MARKS;" }, { "code": null, "e": 27556, "s": 27548, "text": "Output:" }, { "code": null, "e": 27609, "s": 27556, "text": "Step 9: Insert 5 rows into the COMMERCE_MARKS table." }, { "code": null, "e": 27616, "s": 27609, "text": "Query:" }, { "code": null, "e": 27854, "s": 27616, "text": "INSERT INTO COMMERCE_MARKS VALUES(1,'SAM',80);\nINSERT INTO COMMERCE_MARKS VALUES(2,'AMY',88);\nINSERT INTO COMMERCE_MARKS VALUES(3,'EMMA',90);\nINSERT INTO COMMERCE_MARKS VALUES(4,'ROB',75);\nINSERT INTO COMMERCE_MARKS VALUES(5,'KEVIN',56);" }, { "code": null, "e": 27862, "s": 27854, "text": "Output:" }, { "code": null, "e": 27921, "s": 27862, "text": "Step 10: Display all the rows of the COMMERCE_MARKS table." }, { "code": null, "e": 27928, "s": 27921, "text": "Query:" }, { "code": null, "e": 27958, "s": 27928, "text": "SELECT * FROM COMMERCE_MARKS;" }, { "code": null, "e": 27966, "s": 27958, "text": "Output:" }, { "code": null, "e": 28638, "s": 27966, "text": "Step 11: Update the economics and commerce marks of student having id=1 to 80 and 75 respectively using a single query. This involves 2 steps. First, perform JOIN of ECONOMICS_MARKS table and COMMERCE_MARKS table. Then using ALIASES of the tables which are E and C respectively, compare the ID of students(to ensure same ID is picked from both tables) AND finally compare the student ID to 1(given value). When both these conditions fulfill, UPDATE the corresponding marks to 80 and 75. This whole thing must be enclosed between BEGIN TRANSACTION and COMMIT to treat it a single ATOMIC operation. This query involves updating of records belonging to the same student IDs." }, { "code": null, "e": 28646, "s": 28638, "text": "Syntax:" }, { "code": null, "e": 28921, "s": 28646, "text": "BEGIN TRANSACTION;\nUPDATE TABLE_1\nSET TABLE_1.TABLE_1_COLUMN = VALUE_1\nFROM TABLE_1 T1, TABLE_2 T2\nWHERE T1.ID = T2.ID\nAND T1.ID = ID_VALUE_1;\nUPDATE TABLE_2\nSET TABLE_2.TABLE_2_COLUMN = VALUE_2\nFROM TABLE_1 T1, TABLE_2 T2\nWHERE T1.ID = T2.ID\nAND T2.ID = ID_VALUE_2;\nCOMMIT;" }, { "code": null, "e": 28928, "s": 28921, "text": "Query:" }, { "code": null, "e": 29215, "s": 28928, "text": "BEGIN TRANSACTION;\nUPDATE ECONOMICS_MARKS\nSET ECONOMICS_MARKS.ECO_MARKS = 80\nFROM ECONOMICS_MARKS E, COMMERCE_MARKS C\nWHERE E.ID = C.ID\nAND E.ID = 1;\nUPDATE COMMERCE_MARKS\nSET COMMERCE_MARKS.COM_MARKS = 75\nFROM ECONOMICS_MARKS E, COMMERCE_MARKS C\nWHERE E.ID = C.ID\nAND C.ID = 1;\nCOMMIT;" }, { "code": null, "e": 29223, "s": 29215, "text": "Output:" }, { "code": null, "e": 29291, "s": 29223, "text": "Step 12: Display all the rows of the updated ECONOMICS_MARKS table." }, { "code": null, "e": 29298, "s": 29291, "text": "Query:" }, { "code": null, "e": 29329, "s": 29298, "text": "SELECT * FROM ECONOMICS_MARKS;" }, { "code": null, "e": 29401, "s": 29329, "text": "Note – The value of the column ECO_MARKS for the ID 1 is updated to 80." }, { "code": null, "e": 29409, "s": 29401, "text": "Output:" }, { "code": null, "e": 29476, "s": 29409, "text": "Step 13: Display all the rows of the updated COMMERCE_MARKS table." }, { "code": null, "e": 29483, "s": 29476, "text": "Query:" }, { "code": null, "e": 29513, "s": 29483, "text": "SELECT * FROM COMMERCE_MARKS;" }, { "code": null, "e": 29583, "s": 29513, "text": "Note:The value of the column COM_MARKS for the ID 1 is updated to 75." }, { "code": null, "e": 29591, "s": 29583, "text": "Output:" }, { "code": null, "e": 29806, "s": 29591, "text": "Step 14: Update the economics marks of student having id=2 to 86 and commerce marks of student having id=3 to 99 using a single query. This query involves updating of records belonging to the different student IDs." }, { "code": null, "e": 29813, "s": 29806, "text": "Query:" }, { "code": null, "e": 30100, "s": 29813, "text": "BEGIN TRANSACTION;\nUPDATE ECONOMICS_MARKS\nSET ECONOMICS_MARKS.ECO_MARKS = 86\nFROM ECONOMICS_MARKS E, COMMERCE_MARKS C\nWHERE E.ID = C.ID\nAND E.ID = 2;\nUPDATE COMMERCE_MARKS\nSET COMMERCE_MARKS.COM_MARKS = 99\nFROM ECONOMICS_MARKS E, COMMERCE_MARKS C\nWHERE E.ID = C.ID\nAND C.ID = 3;\nCOMMIT;" }, { "code": null, "e": 30108, "s": 30100, "text": "Output:" }, { "code": null, "e": 30176, "s": 30108, "text": "Step 15: Display all the rows of the updated ECONOMICS_MARKS table." }, { "code": null, "e": 30183, "s": 30176, "text": "Query:" }, { "code": null, "e": 30214, "s": 30183, "text": "SELECT * FROM ECONOMICS_MARKS;" }, { "code": null, "e": 30286, "s": 30214, "text": "Note – The value of the column ECO_MARKS for the ID 2 is updated to 86." }, { "code": null, "e": 30294, "s": 30286, "text": "Output:" }, { "code": null, "e": 30361, "s": 30294, "text": "Step 16: Display all the rows of the updated COMMERCE_MARKS table." }, { "code": null, "e": 30368, "s": 30361, "text": "Query:" }, { "code": null, "e": 30398, "s": 30368, "text": "SELECT * FROM COMMERCE_MARKS;" }, { "code": null, "e": 30470, "s": 30398, "text": "Note – The value of the column COM_MARKS for the ID 3 is updated to 99." }, { "code": null, "e": 30478, "s": 30470, "text": "Output:" }, { "code": null, "e": 30485, "s": 30478, "text": "Picked" }, { "code": null, "e": 30495, "s": 30485, "text": "SQL-Query" }, { "code": null, "e": 30506, "s": 30495, "text": "SQL-Server" }, { "code": null, "e": 30510, "s": 30506, "text": "SQL" }, { "code": null, "e": 30514, "s": 30510, "text": "SQL" }, { "code": null, "e": 30612, "s": 30514, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30678, "s": 30612, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 30693, "s": 30678, "text": "SQL | Subquery" }, { "code": null, "e": 30750, "s": 30693, "text": "How to Create a Table With Multiple Foreign Keys in SQL?" }, { "code": null, "e": 30782, "s": 30750, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 30860, "s": 30782, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 30877, "s": 30860, "text": "SQL using Python" }, { "code": null, "e": 30913, "s": 30877, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 30979, "s": 30913, "text": "How to Write a SQL Query For a Specific Date Range and Date Time?" }, { "code": null, "e": 31041, "s": 30979, "text": "How to Select Data Between Two Dates and Times in SQL Server?" } ]
GATE 2017 Mock - GeeksforGeeks
28 Jun, 2021 Time Remaining :: In the present-day world, no individual or organization even think to plough a lonely furrow. The plane _______ by the time we arrive at the airport in this slow traffic. Call the doctor at once. A B C D (fix pen 2 in A) 2 1 4 3 2 4 1 3 2 3 4 1 - 3 cases Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Best Time to Buy and Sell Stock Must Do Coding Questions for Product Based Companies How to Replace Values in Column Based on Condition in Pandas? C Program to read contents of Whole File Insert Image in a Jupyter Notebook How to Replace Values in a List in Python? How to Read Text Files with Pandas? How to Compare Two Columns in Pandas? Python Data Structures and Algorithms Data Science With Python Tutorial
[ { "code": null, "e": 28855, "s": 28827, "text": "\n28 Jun, 2021" }, { "code": null, "e": 28873, "s": 28855, "text": "Time Remaining ::" }, { "code": null, "e": 28969, "s": 28873, "text": " In the present-day world, no individual or organization even \nthink to plough a lonely furrow." }, { "code": null, "e": 29046, "s": 28969, "text": "The plane _______ by the time we arrive at the airport in this slow traffic." }, { "code": null, "e": 29071, "s": 29046, "text": "Call the doctor at once." }, { "code": null, "e": 29167, "s": 29071, "text": "A B C D (fix pen 2 in A)\n2 1 4 3\n2 4 1 3\n2 3 4 1 - 3 cases\n" }, { "code": null, "e": 29265, "s": 29167, "text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here." }, { "code": null, "e": 29297, "s": 29265, "text": "Best Time to Buy and Sell Stock" }, { "code": null, "e": 29350, "s": 29297, "text": "Must Do Coding Questions for Product Based Companies" }, { "code": null, "e": 29412, "s": 29350, "text": "How to Replace Values in Column Based on Condition in Pandas?" }, { "code": null, "e": 29453, "s": 29412, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 29488, "s": 29453, "text": "Insert Image in a Jupyter Notebook" }, { "code": null, "e": 29531, "s": 29488, "text": "How to Replace Values in a List in Python?" }, { "code": null, "e": 29567, "s": 29531, "text": "How to Read Text Files with Pandas?" }, { "code": null, "e": 29605, "s": 29567, "text": "How to Compare Two Columns in Pandas?" }, { "code": null, "e": 29643, "s": 29605, "text": "Python Data Structures and Algorithms" } ]
Count of Equilateral Triangles of unit length possible from a given Hexagon - GeeksforGeeks
10 May, 2021 Given an array S[] consisting of the lengths of the 6 sides of a Hexagon, the task is to calculate the number of equilateral triangles of unit length that can be made from the given hexagon. Examples: Input: S = {1, 1, 1, 1, 1, 1} Output: 6 Explanation: Input: S = {2, 2, 1, 3, 1, 2} Output: 19 Explanation: Approach: The following observations need to be made to solve the given problem: Consider an equilateral triangle of ‘X’ side length. It has been divided into smaller triangles of unit length each, by drawing lines parallel to its sides. Below are the images of three such equilateral triangles: Example 1: X = 2 Example 2: X = 3 Example 3: X = 5 In each of the above three examples, the count of unit length equilateral triangles possible are: X = 2: 4 equilateral triangles of 1 unit length side.X = 3: 9 equilateral triangles of 1 unit length side.X = 5: 25 equilateral triangles of 1 unit length side. X = 2: 4 equilateral triangles of 1 unit length side. X = 3: 9 equilateral triangles of 1 unit length side. X = 5: 25 equilateral triangles of 1 unit length side. By observation, it is clear that, for an equilateral triangle of side length X, X2 equilateral triangles of unit length are possible. Extending this observation to Hexagons, inscribe Hexagons inside the equilateral triangles, as shown below: A regular Hexagon inscribed from equilateral triangle of side X = 3, has 6 mini triangles inside it. An irregular Hexagon inscribed from the equilateral triangle of side X = 5, has 19 mini triangles inside it. It can be observed that by removing a certain number of mini triangles from the bigger triangle, the hexagon with given dimensions can be found. The formula for counting the number of triangles of unit length can be generalized for a Hexagon having six sides S1 , S2 , S3 , S4 , S5 , S6 as: Number of triangles that can be formed = ( S1 + S2 + S3 )2 – S12 – S32 – S52 Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to calculate the// the number of Triangles possibleint calculateTriangles(int sides[]){ double count = pow(sides[0] + sides[1] + sides[2], 2); count -= pow(sides[0], 2); count -= pow(sides[2], 2); count -= pow(sides[4], 2); return (int)(count);} // Driver Codeint main(){ // Regular Hexagon int sides[] = { 1, 1, 1, 1, 1, 1 }; cout << (calculateTriangles(sides)) << endl; // Irregular Hexagon int sides1[] = { 2, 2, 1, 3, 1, 2 }; cout << (calculateTriangles(sides1)) << endl; return 0;} // This code is contributed by 29AjayKumar // Java program to implement// the above approachimport java.util.*; class GFG{ // Function to calculate the// the number of Triangles possiblestatic int calculateTriangles(int sides[]){ double count = Math.pow(sides[0] + sides[1] + sides[2], 2); count -= Math.pow(sides[0], 2); count -= Math.pow(sides[2], 2); count -= Math.pow(sides[4], 2); return (int)(count);} // Driver Codepublic static void main(String[] args){ // Regular Hexagon int sides[] = { 1, 1, 1, 1, 1, 1 }; System.out.print((calculateTriangles(sides)) + "\n"); // Irregular Hexagon int sides1[] = { 2, 2, 1, 3, 1, 2 }; System.out.print((calculateTriangles(sides1)) + "\n");}} // This code is contributed by amal kumar choubey # Python3 Program to implement# the above approach # Function to calculate the# the number of Triangles possibledef calculateTriangles(sides): count = pow( sides[0] + sides[1] + sides[2], 2) count -= pow( sides[0], 2) count -= pow( sides[2], 2) count -= pow( sides[4], 2) return int(count) # Driver Code # Regular Hexagonsides = [1, 1, 1, 1, 1, 1]print(calculateTriangles(sides)) # Irregular Hexagonsides = [2, 2, 1, 3, 1, 2]print(calculateTriangles(sides)) // C# program to implement// the above approachusing System; class GFG{ // Function to calculate the// the number of Triangles possiblestatic int calculateTriangles(int []sides){ double count = Math.Pow(sides[0] + sides[1] + sides[2], 2); count -= Math.Pow(sides[0], 2); count -= Math.Pow(sides[2], 2); count -= Math.Pow(sides[4], 2); return (int)(count);} // Driver Codepublic static void Main(String[] args){ // Regular Hexagon int []sides = { 1, 1, 1, 1, 1, 1 }; Console.Write((calculateTriangles(sides)) + "\n"); // Irregular Hexagon int []sides1 = { 2, 2, 1, 3, 1, 2 }; Console.Write((calculateTriangles(sides1)) + "\n");}} // This code is contributed by amal kumar choubey <script> // JavaScript program to implement// the above approach // Function to calculate the// the number of Triangles possiblefunction calculateTriangles(sides){ let count = Math.pow(sides[0] + sides[1] + sides[2], 2); count -= Math.pow(sides[0], 2); count -= Math.pow(sides[2], 2); count -= Math.pow(sides[4], 2); return (count);} // Driver Code // Regular Hexagon let sides = [ 1, 1, 1, 1, 1, 1 ]; document.write((calculateTriangles(sides)) + "<br/>"); // Irregular Hexagon let sides1 = [ 2, 2, 1, 3, 1, 2 ]; document.write((calculateTriangles(sides1)) + "<br/>"); </script> 6 19 Time Complexity: O(1) Auxiliary Space: O(1) 29AjayKumar Amal Kumar Choubey sanjoy_62 triangle Aptitude CAT Quiz Geometric Mathematical Puzzles Mathematical Geometric Puzzles Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Puzzle | How much money did the man have before entering the bank? Aptitude | GATE CS 1998 | Question 49 Aptitude | Arithmetic Aptitude 4 | Question 3 Order and Ranking Questions & Answers 7 Best Tips to Prepare for Aptitude Test For Campus Placements Length of race track based on the final distance between participants
[ { "code": null, "e": 26547, "s": 26519, "text": "\n10 May, 2021" }, { "code": null, "e": 26738, "s": 26547, "text": "Given an array S[] consisting of the lengths of the 6 sides of a Hexagon, the task is to calculate the number of equilateral triangles of unit length that can be made from the given hexagon." }, { "code": null, "e": 26748, "s": 26738, "text": "Examples:" }, { "code": null, "e": 26803, "s": 26748, "text": "Input: S = {1, 1, 1, 1, 1, 1} Output: 6 Explanation: " }, { "code": null, "e": 26861, "s": 26805, "text": "Input: S = {2, 2, 1, 3, 1, 2} Output: 19 Explanation: " }, { "code": null, "e": 26946, "s": 26863, "text": "Approach: The following observations need to be made to solve the given problem: " }, { "code": null, "e": 27103, "s": 26946, "text": "Consider an equilateral triangle of ‘X’ side length. It has been divided into smaller triangles of unit length each, by drawing lines parallel to its sides." }, { "code": null, "e": 27163, "s": 27103, "text": "Below are the images of three such equilateral triangles: " }, { "code": null, "e": 27180, "s": 27163, "text": "Example 1: X = 2" }, { "code": null, "e": 27199, "s": 27182, "text": "Example 2: X = 3" }, { "code": null, "e": 27218, "s": 27201, "text": "Example 3: X = 5" }, { "code": null, "e": 27318, "s": 27218, "text": "In each of the above three examples, the count of unit length equilateral triangles possible are: " }, { "code": null, "e": 27480, "s": 27318, "text": "X = 2: 4 equilateral triangles of 1 unit length side.X = 3: 9 equilateral triangles of 1 unit length side.X = 5: 25 equilateral triangles of 1 unit length side. " }, { "code": null, "e": 27534, "s": 27480, "text": "X = 2: 4 equilateral triangles of 1 unit length side." }, { "code": null, "e": 27588, "s": 27534, "text": "X = 3: 9 equilateral triangles of 1 unit length side." }, { "code": null, "e": 27644, "s": 27588, "text": "X = 5: 25 equilateral triangles of 1 unit length side. " }, { "code": null, "e": 27778, "s": 27644, "text": "By observation, it is clear that, for an equilateral triangle of side length X, X2 equilateral triangles of unit length are possible." }, { "code": null, "e": 27886, "s": 27778, "text": "Extending this observation to Hexagons, inscribe Hexagons inside the equilateral triangles, as shown below:" }, { "code": null, "e": 27987, "s": 27886, "text": "A regular Hexagon inscribed from equilateral triangle of side X = 3, has 6 mini triangles inside it." }, { "code": null, "e": 28098, "s": 27989, "text": "An irregular Hexagon inscribed from the equilateral triangle of side X = 5, has 19 mini triangles inside it." }, { "code": null, "e": 28243, "s": 28098, "text": "It can be observed that by removing a certain number of mini triangles from the bigger triangle, the hexagon with given dimensions can be found." }, { "code": null, "e": 28389, "s": 28243, "text": "The formula for counting the number of triangles of unit length can be generalized for a Hexagon having six sides S1 , S2 , S3 , S4 , S5 , S6 as:" }, { "code": null, "e": 28466, "s": 28389, "text": "Number of triangles that can be formed = ( S1 + S2 + S3 )2 – S12 – S32 – S52" }, { "code": null, "e": 28517, "s": 28466, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 28521, "s": 28517, "text": "C++" }, { "code": null, "e": 28526, "s": 28521, "text": "Java" }, { "code": null, "e": 28534, "s": 28526, "text": "Python3" }, { "code": null, "e": 28537, "s": 28534, "text": "C#" }, { "code": null, "e": 28548, "s": 28537, "text": "Javascript" }, { "code": "// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to calculate the// the number of Triangles possibleint calculateTriangles(int sides[]){ double count = pow(sides[0] + sides[1] + sides[2], 2); count -= pow(sides[0], 2); count -= pow(sides[2], 2); count -= pow(sides[4], 2); return (int)(count);} // Driver Codeint main(){ // Regular Hexagon int sides[] = { 1, 1, 1, 1, 1, 1 }; cout << (calculateTriangles(sides)) << endl; // Irregular Hexagon int sides1[] = { 2, 2, 1, 3, 1, 2 }; cout << (calculateTriangles(sides1)) << endl; return 0;} // This code is contributed by 29AjayKumar", "e": 29257, "s": 28548, "text": null }, { "code": "// Java program to implement// the above approachimport java.util.*; class GFG{ // Function to calculate the// the number of Triangles possiblestatic int calculateTriangles(int sides[]){ double count = Math.pow(sides[0] + sides[1] + sides[2], 2); count -= Math.pow(sides[0], 2); count -= Math.pow(sides[2], 2); count -= Math.pow(sides[4], 2); return (int)(count);} // Driver Codepublic static void main(String[] args){ // Regular Hexagon int sides[] = { 1, 1, 1, 1, 1, 1 }; System.out.print((calculateTriangles(sides)) + \"\\n\"); // Irregular Hexagon int sides1[] = { 2, 2, 1, 3, 1, 2 }; System.out.print((calculateTriangles(sides1)) + \"\\n\");}} // This code is contributed by amal kumar choubey", "e": 30021, "s": 29257, "text": null }, { "code": "# Python3 Program to implement# the above approach # Function to calculate the# the number of Triangles possibledef calculateTriangles(sides): count = pow( sides[0] + sides[1] + sides[2], 2) count -= pow( sides[0], 2) count -= pow( sides[2], 2) count -= pow( sides[4], 2) return int(count) # Driver Code # Regular Hexagonsides = [1, 1, 1, 1, 1, 1]print(calculateTriangles(sides)) # Irregular Hexagonsides = [2, 2, 1, 3, 1, 2]print(calculateTriangles(sides))", "e": 30499, "s": 30021, "text": null }, { "code": "// C# program to implement// the above approachusing System; class GFG{ // Function to calculate the// the number of Triangles possiblestatic int calculateTriangles(int []sides){ double count = Math.Pow(sides[0] + sides[1] + sides[2], 2); count -= Math.Pow(sides[0], 2); count -= Math.Pow(sides[2], 2); count -= Math.Pow(sides[4], 2); return (int)(count);} // Driver Codepublic static void Main(String[] args){ // Regular Hexagon int []sides = { 1, 1, 1, 1, 1, 1 }; Console.Write((calculateTriangles(sides)) + \"\\n\"); // Irregular Hexagon int []sides1 = { 2, 2, 1, 3, 1, 2 }; Console.Write((calculateTriangles(sides1)) + \"\\n\");}} // This code is contributed by amal kumar choubey", "e": 31249, "s": 30499, "text": null }, { "code": "<script> // JavaScript program to implement// the above approach // Function to calculate the// the number of Triangles possiblefunction calculateTriangles(sides){ let count = Math.pow(sides[0] + sides[1] + sides[2], 2); count -= Math.pow(sides[0], 2); count -= Math.pow(sides[2], 2); count -= Math.pow(sides[4], 2); return (count);} // Driver Code // Regular Hexagon let sides = [ 1, 1, 1, 1, 1, 1 ]; document.write((calculateTriangles(sides)) + \"<br/>\"); // Irregular Hexagon let sides1 = [ 2, 2, 1, 3, 1, 2 ]; document.write((calculateTriangles(sides1)) + \"<br/>\"); </script>", "e": 31915, "s": 31249, "text": null }, { "code": null, "e": 31920, "s": 31915, "text": "6\n19" }, { "code": null, "e": 31966, "s": 31922, "text": "Time Complexity: O(1) Auxiliary Space: O(1)" }, { "code": null, "e": 31978, "s": 31966, "text": "29AjayKumar" }, { "code": null, "e": 31997, "s": 31978, "text": "Amal Kumar Choubey" }, { "code": null, "e": 32007, "s": 31997, "text": "sanjoy_62" }, { "code": null, "e": 32016, "s": 32007, "text": "triangle" }, { "code": null, "e": 32025, "s": 32016, "text": "Aptitude" }, { "code": null, "e": 32034, "s": 32025, "text": "CAT Quiz" }, { "code": null, "e": 32044, "s": 32034, "text": "Geometric" }, { "code": null, "e": 32057, "s": 32044, "text": "Mathematical" }, { "code": null, "e": 32065, "s": 32057, "text": "Puzzles" }, { "code": null, "e": 32078, "s": 32065, "text": "Mathematical" }, { "code": null, "e": 32088, "s": 32078, "text": "Geometric" }, { "code": null, "e": 32096, "s": 32088, "text": "Puzzles" }, { "code": null, "e": 32194, "s": 32096, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32261, "s": 32194, "text": "Puzzle | How much money did the man have before entering the bank?" }, { "code": null, "e": 32299, "s": 32261, "text": "Aptitude | GATE CS 1998 | Question 49" }, { "code": null, "e": 32345, "s": 32299, "text": "Aptitude | Arithmetic Aptitude 4 | Question 3" }, { "code": null, "e": 32383, "s": 32345, "text": "Order and Ranking Questions & Answers" }, { "code": null, "e": 32446, "s": 32383, "text": "7 Best Tips to Prepare for Aptitude Test For Campus Placements" } ]
Socialphish- Phishing Tool in Kali Linux - GeeksforGeeks
28 Apr, 2021 Socialphish is a powerful open source tool Phishing Tool. Socialphish is becoming very popular nowadays that is used to do phishing attacks on Target. Socialphish is easy then Social Engineering Toolkit. Socialphish contain some templates generated by another tool called Socialphish. Socialphish offers phishing templates web pages for 33 popular sites such as Facebook, Instagram ,Google, Snapchat, Github, Yahoo, Protonmail, Spotify, Netflix, Linkedin, WordPress, Origin, Steam, Microsoft, etc. Socialphish also provides option to use a custom template if someone wants. This tool makes easy to perform phishing attack. There is a lot of creativity that they can put into making the email look as legitimate as possible Socialphish Socialphish is open source tool. Socialphish is used in Phishing attacks. Socialphish tool is very simple and easy tool. Socialphish is written in bash language. Socialphish tool is lightweight tool. This does not take extra space. Socialphish creates phishing pages of more than 30 websites. Socialphish creates phishing pages of popular sites such as Facebook, Instagram, Google, Snapchat, Github, Yahoo, Protonmail, Spotify, Netflix, Linkedin, WordPress, Origin, Steam, Microsoft, etc Step 1: Open your Kali Linux operating system. Move to desktop. Here you have to create a directory called Socialphish. In this directory you have to install the tool. cd Desktop Step 2: Now you are on desktop. Here you have to create directory called Socialphish. To create Maskphish directory use following command. mkdir Socialphish Step 3: You have created directory. Now use following command to move into that directory. cd Socialphish ‘ Step 4: Now you are in Socialphish directory. In this directory you have to download the tool means you have to clone the tool from GitHub. Use following command to clone the tool from GitHub. git clone https://github.com/xHak9x/SocialPhish.git Step 5: The tool has been downloaded in the directory Socialphish. Now to list out the contents of the tool that has been downloaded use following command. ls Step 6: When you listed out the contents of the tool you can see that a new directory has been generated by the tool that is SocialPhish. You have to move in this directory to view the contents of the tool. To move in this directory use following command. cd SocialPhish Step 7: To list out the contents of this directory use following command. ls Step 8. Now you have to give the permission to the tool using following command. chmod +x socialphish.sh Step 9: Now you can run the tool using following command. This command will open help menu of the tool. ./socialphish.sh The tool is running successfully. Now you have to give the option number to the tool for which you have to create the phishing page. Suppose you want to create the phishing page for instagram then you have to choose option 1. If you want phishing page of facebook choose option 2. Similarly, you can choose for all 33 websites in the tool. Use Socialphish and create a phishing page for instagram. 01 02 Type 01 and then for port forwarding 02 You can see the link has been generated by the tool that is instagram phishing webpage. Send this link to victim. once he/she open the link he/she will get an original look alike web page of instagram and once he/she fill the details in the webpage . It will be highlighted in the Socialphish terminal. You can see here we have filled the login form we have given username as geeky and password as geekygeeky now once victim click on login all the details will be shown in socialphish terminal. You can see credentials has been found. Even you can perform this attack using yourself on to your target. This was all about Socialphish. Socialphish is a powerful open source tool Phishing Tool. Socialphish is becoming very popular nowadays that is used to do phishing attacks on Target. Socialphish is easy then Social Engineering Toolkit. Socialphish contain some templates generated by another tool called Socialphish. Socialphish offers phishing templates web pages for 33 popular sites such as Facebook, Instagram, Google ,Snapchat, Github, Yahoo, Protonmail, Spotify, Netflix, Linkedin, WordPress, Origin, Steam, Microsoft, etc. Cyber-security Kali-Linux Linux-Tools Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ZIP command in Linux with examples TCP Server-Client implementation in C SORT command in Linux/Unix with examples tar command in Linux with examples curl command in Linux with Examples Conditional Statements | Shell Script 'crontab' in Linux with Examples diff command in Linux with examples Tail command in Linux with examples UDP Server-Client implementation in C
[ { "code": null, "e": 25851, "s": 25823, "text": "\n28 Apr, 2021" }, { "code": null, "e": 26575, "s": 25851, "text": "Socialphish is a powerful open source tool Phishing Tool. Socialphish is becoming very popular nowadays that is used to do phishing attacks on Target. Socialphish is easy then Social Engineering Toolkit. Socialphish contain some templates generated by another tool called Socialphish. Socialphish offers phishing templates web pages for 33 popular sites such as Facebook, Instagram ,Google, Snapchat, Github, Yahoo, Protonmail, Spotify, Netflix, Linkedin, WordPress, Origin, Steam, Microsoft, etc. Socialphish also provides option to use a custom template if someone wants. This tool makes easy to perform phishing attack. There is a lot of creativity that they can put into making the email look as legitimate as possible" }, { "code": null, "e": 26587, "s": 26575, "text": "Socialphish" }, { "code": null, "e": 26620, "s": 26587, "text": "Socialphish is open source tool." }, { "code": null, "e": 26661, "s": 26620, "text": "Socialphish is used in Phishing attacks." }, { "code": null, "e": 26749, "s": 26661, "text": "Socialphish tool is very simple and easy tool. Socialphish is written in bash language." }, { "code": null, "e": 26819, "s": 26749, "text": "Socialphish tool is lightweight tool. This does not take extra space." }, { "code": null, "e": 26880, "s": 26819, "text": "Socialphish creates phishing pages of more than 30 websites." }, { "code": null, "e": 27075, "s": 26880, "text": "Socialphish creates phishing pages of popular sites such as Facebook, Instagram, Google, Snapchat, Github, Yahoo, Protonmail, Spotify, Netflix, Linkedin, WordPress, Origin, Steam, Microsoft, etc" }, { "code": null, "e": 27243, "s": 27075, "text": "Step 1: Open your Kali Linux operating system. Move to desktop. Here you have to create a directory called Socialphish. In this directory you have to install the tool." }, { "code": null, "e": 27254, "s": 27243, "text": "cd Desktop" }, { "code": null, "e": 27393, "s": 27254, "text": "Step 2: Now you are on desktop. Here you have to create directory called Socialphish. To create Maskphish directory use following command." }, { "code": null, "e": 27411, "s": 27393, "text": "mkdir Socialphish" }, { "code": null, "e": 27502, "s": 27411, "text": "Step 3: You have created directory. Now use following command to move into that directory." }, { "code": null, "e": 27517, "s": 27502, "text": "cd Socialphish" }, { "code": null, "e": 27519, "s": 27517, "text": "‘" }, { "code": null, "e": 27712, "s": 27519, "text": "Step 4: Now you are in Socialphish directory. In this directory you have to download the tool means you have to clone the tool from GitHub. Use following command to clone the tool from GitHub." }, { "code": null, "e": 27764, "s": 27712, "text": "git clone https://github.com/xHak9x/SocialPhish.git" }, { "code": null, "e": 27920, "s": 27764, "text": "Step 5: The tool has been downloaded in the directory Socialphish. Now to list out the contents of the tool that has been downloaded use following command." }, { "code": null, "e": 27923, "s": 27920, "text": "ls" }, { "code": null, "e": 28179, "s": 27923, "text": "Step 6: When you listed out the contents of the tool you can see that a new directory has been generated by the tool that is SocialPhish. You have to move in this directory to view the contents of the tool. To move in this directory use following command." }, { "code": null, "e": 28194, "s": 28179, "text": "cd SocialPhish" }, { "code": null, "e": 28268, "s": 28194, "text": "Step 7: To list out the contents of this directory use following command." }, { "code": null, "e": 28271, "s": 28268, "text": "ls" }, { "code": null, "e": 28353, "s": 28271, "text": "Step 8. Now you have to give the permission to the tool using following command." }, { "code": null, "e": 28377, "s": 28353, "text": "chmod +x socialphish.sh" }, { "code": null, "e": 28482, "s": 28377, "text": "Step 9: Now you can run the tool using following command. This command will open help menu of the tool." }, { "code": null, "e": 28499, "s": 28482, "text": "./socialphish.sh" }, { "code": null, "e": 28839, "s": 28499, "text": "The tool is running successfully. Now you have to give the option number to the tool for which you have to create the phishing page. Suppose you want to create the phishing page for instagram then you have to choose option 1. If you want phishing page of facebook choose option 2. Similarly, you can choose for all 33 websites in the tool." }, { "code": null, "e": 28897, "s": 28839, "text": "Use Socialphish and create a phishing page for instagram." }, { "code": null, "e": 28903, "s": 28897, "text": "01\n02" }, { "code": null, "e": 28943, "s": 28903, "text": "Type 01 and then for port forwarding 02" }, { "code": null, "e": 29246, "s": 28943, "text": "You can see the link has been generated by the tool that is instagram phishing webpage. Send this link to victim. once he/she open the link he/she will get an original look alike web page of instagram and once he/she fill the details in the webpage . It will be highlighted in the Socialphish terminal." }, { "code": null, "e": 29438, "s": 29246, "text": "You can see here we have filled the login form we have given username as geeky and password as geekygeeky now once victim click on login all the details will be shown in socialphish terminal." }, { "code": null, "e": 30076, "s": 29438, "text": "You can see credentials has been found. Even you can perform this attack using yourself on to your target. This was all about Socialphish. Socialphish is a powerful open source tool Phishing Tool. Socialphish is becoming very popular nowadays that is used to do phishing attacks on Target. Socialphish is easy then Social Engineering Toolkit. Socialphish contain some templates generated by another tool called Socialphish. Socialphish offers phishing templates web pages for 33 popular sites such as Facebook, Instagram, Google ,Snapchat, Github, Yahoo, Protonmail, Spotify, Netflix, Linkedin, WordPress, Origin, Steam, Microsoft, etc." }, { "code": null, "e": 30091, "s": 30076, "text": "Cyber-security" }, { "code": null, "e": 30102, "s": 30091, "text": "Kali-Linux" }, { "code": null, "e": 30114, "s": 30102, "text": "Linux-Tools" }, { "code": null, "e": 30125, "s": 30114, "text": "Linux-Unix" }, { "code": null, "e": 30223, "s": 30125, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30258, "s": 30223, "text": "ZIP command in Linux with examples" }, { "code": null, "e": 30296, "s": 30258, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 30337, "s": 30296, "text": "SORT command in Linux/Unix with examples" }, { "code": null, "e": 30372, "s": 30337, "text": "tar command in Linux with examples" }, { "code": null, "e": 30408, "s": 30372, "text": "curl command in Linux with Examples" }, { "code": null, "e": 30446, "s": 30408, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 30479, "s": 30446, "text": "'crontab' in Linux with Examples" }, { "code": null, "e": 30515, "s": 30479, "text": "diff command in Linux with examples" }, { "code": null, "e": 30551, "s": 30515, "text": "Tail command in Linux with examples" } ]
D3.js transform.toString() Function - GeeksforGeeks
02 Sep, 2020 The transform.toString() Function in D3.js is used to get a string representing the SVG transform corresponding to this transform. Syntax: transform.toString() Parameters: This function does not accept any parameter. Return Value: This function returns a string value that can be used to set zoom behavior. Below programs illustrate the transform.toString() function in D3.js. Example 1: HTML <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src= "https://d3js.org/d3.v4.min.js"> </script> </head> <body> <center> <h1 style="color: green;"> Geeksforgeeks </h1> <h3>D3.js | transform.toString() Function</h3> <svg width="400" height="250"></svg> <script> var svg = d3.select("svg"), width = +svg.attr("width"), height = +svg.attr("height"); var radius = 30; var circle = {x: 200, y: height /2 } ; var circle = svg.append("circle") .attr("cx", circle.x) .attr("cy", circle.y) .attr("r", radius) .attr("fill", "green"); // Defining zoom behaviour var zoom_handler = d3.zoom() .on("zoom", zoom_actions); zoom_handler(circle); function zoom_actions(){ var transform = d3.event.transform; // Setting attribute using this method this.setAttribute("transform", transform.toString()); } </script> </center></body> </html> Output: Example 2: HTML <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src= "https://d3js.org/d3.v4.min.js"> </script> <style> circle { opacity: 0.7; fill: #9a05a3; } </style></head> <body> <center> <h1 style="color: green;"> Geeksforgeeks </h1> <h3>D3.js | transform.toString() Function</h3> <svg></svg> <script> var transform = d3.zoomIdentity .translate(100, 0).scale(1); var zoom = d3.zoom().on("zoom", handleZoom); var svg = d3.select("svg") .attr('width', 300) .attr('height', 250) .style("background", "#31c460") .call(zoom) .call(zoom.transform, transform); var zoomable = svg .append("g") .attr("class", "zoomable") .attr("transform", transform); var circles = zoomable.append('circle') .attr("id", "circles") .attr("cx", 50) .attr("cy", 125) .attr('r', 30); function handleZoom(){ if (zoomable) { // Setting attribute using this method zoomable.attr("transform", d3.event.transform.toString()); } }; </script> </center></body> </html> Output: D3.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request JavaScript | Promises How to get character array from string in JavaScript? Remove elements from a JavaScript Array Installation of Node.js on Linux 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": 26545, "s": 26517, "text": "\n02 Sep, 2020" }, { "code": null, "e": 26676, "s": 26545, "text": "The transform.toString() Function in D3.js is used to get a string representing the SVG transform corresponding to this transform." }, { "code": null, "e": 26684, "s": 26676, "text": "Syntax:" }, { "code": null, "e": 26706, "s": 26684, "text": "transform.toString()\n" }, { "code": null, "e": 26763, "s": 26706, "text": "Parameters: This function does not accept any parameter." }, { "code": null, "e": 26853, "s": 26763, "text": "Return Value: This function returns a string value that can be used to set zoom behavior." }, { "code": null, "e": 26923, "s": 26853, "text": "Below programs illustrate the transform.toString() function in D3.js." }, { "code": null, "e": 26934, "s": 26923, "text": "Example 1:" }, { "code": null, "e": 26939, "s": 26934, "text": "HTML" }, { "code": "<!DOCTYPE html> <html> <head> <meta charset=\"utf-8\"> <script src= \"https://d3js.org/d3.v4.min.js\"> </script> </head> <body> <center> <h1 style=\"color: green;\"> Geeksforgeeks </h1> <h3>D3.js | transform.toString() Function</h3> <svg width=\"400\" height=\"250\"></svg> <script> var svg = d3.select(\"svg\"), width = +svg.attr(\"width\"), height = +svg.attr(\"height\"); var radius = 30; var circle = {x: 200, y: height /2 } ; var circle = svg.append(\"circle\") .attr(\"cx\", circle.x) .attr(\"cy\", circle.y) .attr(\"r\", radius) .attr(\"fill\", \"green\"); // Defining zoom behaviour var zoom_handler = d3.zoom() .on(\"zoom\", zoom_actions); zoom_handler(circle); function zoom_actions(){ var transform = d3.event.transform; // Setting attribute using this method this.setAttribute(\"transform\", transform.toString()); } </script> </center></body> </html>", "e": 28274, "s": 26939, "text": null }, { "code": null, "e": 28282, "s": 28274, "text": "Output:" }, { "code": null, "e": 28293, "s": 28282, "text": "Example 2:" }, { "code": null, "e": 28298, "s": 28293, "text": "HTML" }, { "code": "<!DOCTYPE html> <html> <head> <meta charset=\"utf-8\"> <script src= \"https://d3js.org/d3.v4.min.js\"> </script> <style> circle { opacity: 0.7; fill: #9a05a3; } </style></head> <body> <center> <h1 style=\"color: green;\"> Geeksforgeeks </h1> <h3>D3.js | transform.toString() Function</h3> <svg></svg> <script> var transform = d3.zoomIdentity .translate(100, 0).scale(1); var zoom = d3.zoom().on(\"zoom\", handleZoom); var svg = d3.select(\"svg\") .attr('width', 300) .attr('height', 250) .style(\"background\", \"#31c460\") .call(zoom) .call(zoom.transform, transform); var zoomable = svg .append(\"g\") .attr(\"class\", \"zoomable\") .attr(\"transform\", transform); var circles = zoomable.append('circle') .attr(\"id\", \"circles\") .attr(\"cx\", 50) .attr(\"cy\", 125) .attr('r', 30); function handleZoom(){ if (zoomable) { // Setting attribute using this method zoomable.attr(\"transform\", d3.event.transform.toString()); } }; </script> </center></body> </html>", "e": 29824, "s": 28298, "text": null }, { "code": null, "e": 29832, "s": 29824, "text": "Output:" }, { "code": null, "e": 29838, "s": 29832, "text": "D3.js" }, { "code": null, "e": 29849, "s": 29838, "text": "JavaScript" }, { "code": null, "e": 29866, "s": 29849, "text": "Web Technologies" }, { "code": null, "e": 29964, "s": 29866, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30004, "s": 29964, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30065, "s": 30004, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 30106, "s": 30065, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 30128, "s": 30106, "text": "JavaScript | Promises" }, { "code": null, "e": 30182, "s": 30128, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 30222, "s": 30182, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30255, "s": 30222, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30298, "s": 30255, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 30348, "s": 30298, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Python – tensorflow.math.multiply()
10 Jun, 2020 TensorFlow is open-source python library designed by Google to develop Machine Learning models and deep learning neural networks. multiply() is used to find element wise x*y. It supports broadcasting. Syntax: tf.math.multiply(x, y, name) Parameter: x: It’s the input tensor. Allowed dtype for this tensor are bfloat16, half, float32, float64, uint8, int8, uint16, int16, int32, int64, complex64, complex128. y: It’s the input tensor of same dtype as x. name(optional): It’s defines the name for the operation. Returns:It returns a tensor of same dtype as x. Example 1: Python3 # Importing the libraryimport tensorflow as tf # Initializing the input tensora = tf.constant([.2, .5, .7, 1], dtype = tf.float64)b = tf.constant([.1, .3, 1, 5], dtype = tf.float64) # Printing the input tensorprint('a: ', a)print('b: ', b) # Calculating resultres = tf.math.multiply(x = a, y = b) # Printing the resultprint('Result: ', res) Output: a: tf.Tensor([0.2 0.5 0.7 1. ], shape=(4, ), dtype=float64) b: tf.Tensor([0.1 0.3 1. 5. ], shape=(4, ), dtype=float64) Result: tf.Tensor([0.02 0.15 0.7 5. ], shape=(4, ), dtype=float64) Example 2: Complex number multiplication Python3 # importing the libraryimport tensorflow as tf # Initializing the input tensora = tf.constant([-2 + 3j, -5 + 4j, 7 + 2j, 1 + 7j], dtype = tf.complex128)b = tf.constant([-1 + 2j, -6 + 8j, 8 + 2j, 0 + 1j], dtype = tf.complex128) # Printing the input tensorprint('a: ', a)print('b: ', b) # Calculating resultres = tf.math.multiply(x = a, y = b) # Printing the resultprint('Result: ', res) Output: a: tf.Tensor([-2.+3.j -5.+4.j 7.+2.j 1.+7.j], shape=(4, ), dtype=complex128) b: tf.Tensor([-1.+2.j -6.+8.j 8.+2.j 0.+1.j], shape=(4, ), dtype=complex128) Result: tf.Tensor([-4. -7.j -2.-64.j 52.+30.j -7. +1.j], shape=(4, ), dtype=complex128) Python Tensorflow-math-functions Python-Tensorflow Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Iterate over a list in Python Python Classes and Objects Convert integer to string in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Jun, 2020" }, { "code": null, "e": 230, "s": 28, "text": "TensorFlow is open-source python library designed by Google to develop Machine Learning models and deep learning neural networks. multiply() is used to find element wise x*y. It supports broadcasting." }, { "code": null, "e": 267, "s": 230, "text": "Syntax: tf.math.multiply(x, y, name)" }, { "code": null, "e": 278, "s": 267, "text": "Parameter:" }, { "code": null, "e": 437, "s": 278, "text": "x: It’s the input tensor. Allowed dtype for this tensor are bfloat16, half, float32, float64, uint8, int8, uint16, int16, int32, int64, complex64, complex128." }, { "code": null, "e": 482, "s": 437, "text": "y: It’s the input tensor of same dtype as x." }, { "code": null, "e": 539, "s": 482, "text": "name(optional): It’s defines the name for the operation." }, { "code": null, "e": 587, "s": 539, "text": "Returns:It returns a tensor of same dtype as x." }, { "code": null, "e": 598, "s": 587, "text": "Example 1:" }, { "code": null, "e": 606, "s": 598, "text": "Python3" }, { "code": "# Importing the libraryimport tensorflow as tf # Initializing the input tensora = tf.constant([.2, .5, .7, 1], dtype = tf.float64)b = tf.constant([.1, .3, 1, 5], dtype = tf.float64) # Printing the input tensorprint('a: ', a)print('b: ', b) # Calculating resultres = tf.math.multiply(x = a, y = b) # Printing the resultprint('Result: ', res)", "e": 951, "s": 606, "text": null }, { "code": null, "e": 959, "s": 951, "text": "Output:" }, { "code": null, "e": 1154, "s": 959, "text": "a: tf.Tensor([0.2 0.5 0.7 1. ], shape=(4, ), dtype=float64)\nb: tf.Tensor([0.1 0.3 1. 5. ], shape=(4, ), dtype=float64)\nResult: tf.Tensor([0.02 0.15 0.7 5. ], shape=(4, ), dtype=float64)\n\n\n" }, { "code": null, "e": 1195, "s": 1154, "text": "Example 2: Complex number multiplication" }, { "code": null, "e": 1203, "s": 1195, "text": "Python3" }, { "code": "# importing the libraryimport tensorflow as tf # Initializing the input tensora = tf.constant([-2 + 3j, -5 + 4j, 7 + 2j, 1 + 7j], dtype = tf.complex128)b = tf.constant([-1 + 2j, -6 + 8j, 8 + 2j, 0 + 1j], dtype = tf.complex128) # Printing the input tensorprint('a: ', a)print('b: ', b) # Calculating resultres = tf.math.multiply(x = a, y = b) # Printing the resultprint('Result: ', res)", "e": 1593, "s": 1203, "text": null }, { "code": null, "e": 1601, "s": 1593, "text": "Output:" }, { "code": null, "e": 1851, "s": 1601, "text": "a: tf.Tensor([-2.+3.j -5.+4.j 7.+2.j 1.+7.j], shape=(4, ), dtype=complex128)\nb: tf.Tensor([-1.+2.j -6.+8.j 8.+2.j 0.+1.j], shape=(4, ), dtype=complex128)\nResult: tf.Tensor([-4. -7.j -2.-64.j 52.+30.j -7. +1.j], shape=(4, ), dtype=complex128)\n" }, { "code": null, "e": 1884, "s": 1851, "text": "Python Tensorflow-math-functions" }, { "code": null, "e": 1902, "s": 1884, "text": "Python-Tensorflow" }, { "code": null, "e": 1909, "s": 1902, "text": "Python" }, { "code": null, "e": 2007, "s": 1909, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2025, "s": 2007, "text": "Python Dictionary" }, { "code": null, "e": 2067, "s": 2025, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2089, "s": 2067, "text": "Enumerate() in Python" }, { "code": null, "e": 2124, "s": 2089, "text": "Read a file line by line in Python" }, { "code": null, "e": 2150, "s": 2124, "text": "Python String | replace()" }, { "code": null, "e": 2182, "s": 2150, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2211, "s": 2182, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2241, "s": 2211, "text": "Iterate over a list in Python" }, { "code": null, "e": 2268, "s": 2241, "text": "Python Classes and Objects" } ]
Python regex to find sequences of one upper case letter followed by lower case letters
29 Dec, 2020 Write a Python Program to find sequences of one upper case letter followed by lower case letters. If found, print ‘Yes’, otherwise ‘No’. Examples: Input : Geeks Output : Yes Input : geeksforgeeks Output : No Approach: Using re.search() To check if the sequence of one upper case letter followed by lower case letters we use regular expression ‘[A-Z]+[a-z]+$‘. # Python3 code to find sequences of one upper# case letter followed by lower case lettersimport re # Function to match the stringdef match(text): # regex pattern = '[A-Z]+[a-z]+$' # searching pattern if re.search(pattern, text): return('Yes') else: return('No') # Driver Functionprint(match("Geeks"))print(match("geeksforGeeks"))print(match("geeks")) Output: Yes Yes No Python Regex-programs python-regex Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Rotate axis tick labels in Seaborn and Matplotlib Enumerate() in Python Deque in Python Stack in Python Python Dictionary Defaultdict in Python Python | Split string into list of characters Python | Get dictionary keys as a list Iterate over characters of a string in Python Python | Convert set into a list
[ { "code": null, "e": 52, "s": 24, "text": "\n29 Dec, 2020" }, { "code": null, "e": 189, "s": 52, "text": "Write a Python Program to find sequences of one upper case letter followed by lower case letters. If found, print ‘Yes’, otherwise ‘No’." }, { "code": null, "e": 199, "s": 189, "text": "Examples:" }, { "code": null, "e": 262, "s": 199, "text": "Input : Geeks\nOutput : Yes\n\nInput : geeksforgeeks\nOutput : No\n" }, { "code": null, "e": 292, "s": 264, "text": "Approach: Using re.search()" }, { "code": null, "e": 416, "s": 292, "text": "To check if the sequence of one upper case letter followed by lower case letters we use regular expression ‘[A-Z]+[a-z]+$‘." }, { "code": "# Python3 code to find sequences of one upper# case letter followed by lower case lettersimport re # Function to match the stringdef match(text): # regex pattern = '[A-Z]+[a-z]+$' # searching pattern if re.search(pattern, text): return('Yes') else: return('No') # Driver Functionprint(match(\"Geeks\"))print(match(\"geeksforGeeks\"))print(match(\"geeks\"))", "e": 854, "s": 416, "text": null }, { "code": null, "e": 862, "s": 854, "text": "Output:" }, { "code": null, "e": 873, "s": 862, "text": "Yes\nYes\nNo" }, { "code": null, "e": 895, "s": 873, "text": "Python Regex-programs" }, { "code": null, "e": 908, "s": 895, "text": "python-regex" }, { "code": null, "e": 915, "s": 908, "text": "Python" }, { "code": null, "e": 931, "s": 915, "text": "Python Programs" }, { "code": null, "e": 1029, "s": 931, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1079, "s": 1029, "text": "Rotate axis tick labels in Seaborn and Matplotlib" }, { "code": null, "e": 1101, "s": 1079, "text": "Enumerate() in Python" }, { "code": null, "e": 1117, "s": 1101, "text": "Deque in Python" }, { "code": null, "e": 1133, "s": 1117, "text": "Stack in Python" }, { "code": null, "e": 1151, "s": 1133, "text": "Python Dictionary" }, { "code": null, "e": 1173, "s": 1151, "text": "Defaultdict in Python" }, { "code": null, "e": 1219, "s": 1173, "text": "Python | Split string into list of characters" }, { "code": null, "e": 1258, "s": 1219, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 1304, "s": 1258, "text": "Iterate over characters of a string in Python" } ]
How to Solve ConcurrentModificationException in Java?
02 Mar, 2022 An unaccepted, unwanted event that disturbed the normal flow of a program is called an Exception. Most of the time exception is caused by our program and these are recoverable. Example: If our program requirement is to read data from the remote file locating in the U.S.A. At runtime, if a remote file is not available then we will get RuntimeException saying FileNotFoundException. If FileNotFoundException occurs we can provide the local file to the program to read and continue the rest of the program normally. There are mainly two types of exception in java as follows: Checked Exceptions are the exceptions that are checked by the compiler for the smooth execution of the program at runtime is called a checked exception. In our program, if there is a chance of rising checked exceptions then compulsory we should handle that checked exception (either by try-catch or throws keyword) otherwise we will get a compile-time error.Unchecked Exceptions are the exceptions that are not checked by the compiler, whether programmer handling or not such types of exceptions are called unchecked exceptions. Examples of unchecked Exceptions are ArithmeticException, ArrayStoreException, etc. Checked Exceptions are the exceptions that are checked by the compiler for the smooth execution of the program at runtime is called a checked exception. In our program, if there is a chance of rising checked exceptions then compulsory we should handle that checked exception (either by try-catch or throws keyword) otherwise we will get a compile-time error. Unchecked Exceptions are the exceptions that are not checked by the compiler, whether programmer handling or not such types of exceptions are called unchecked exceptions. Examples of unchecked Exceptions are ArithmeticException, ArrayStoreException, etc. Note: Whether the exception is checked or unchecked every exception occurs at run time only if there is no chance of occurring any exception at compile time. Implementation: ConcurrentModificationException is the child class of RuntimeException and hence it is an unchecked exception. This exception rises when an object is tried to be modified concurrently when it is not permissible i.e when one thread is iterating over some collection class object and if some other thread tried to modify or try to make some changes on that collection object then we will get ConcurrentModificationException. This exception usually occurs when we are working with Java collections classes. Example Java // Java program to illustrate// ConcurrentModificationException // Importing all classes from java.util package// Importing input output classesimport java.io.*;import java.util.*; // Main Classclass GFG { // Main driver method public static void main(String[] args) { // Creating an object of ArrayList // Declaring object of Integer type ArrayList<Integer> list = new ArrayList<>(); // Adding element to ArrayList object created above // using the add() method // Custom input elements list.add(1); list.add(2); list.add(3); list.add(4); list.add(5); // Display all the elements of ArrayList object System.out.println("List Value Before Iteration:" + list); // Creating an iterator object to // iterate over the ArrayList Iterator<Integer> it = list.iterator(); // Condition check // It holds true till there is single element // remaining in the List while (it.hasNext()) { Integer value = it.next(); // Here we are trying to remove the one entry of // ArrayList base on the if condition and hence // We will get Concurrent ModificationException if (value.equals(3)) list.remove(value); } // Print and display the value of ArrayList object System.out.println("List Value After Iteration:" + list); }} Output: Output explanation: The above program is a single-threaded program and here we can avoid ConcurrentModificationException by using iterator’s remove( ) function, we can remove an object from an underlying collection object without getting any exception. Example 2 Java // Java Program to illustrate// ConcurrentModificationException // Importing the required packagesimport java.io.*;import java.util.*;import java.util.Iterator; // Main Classclass GFG { // Main driver method public static void main(String[] args) { // Creating an collection class object // Declaring object of integer type ArrayList<Integer> list = new ArrayList<>(); // Adding element to ArrayList // using add() method // Custom integer input entries list.add(1); list.add(2); list.add(3); list.add(4); list.add(5); // Display the value of ArrayList System.out.println("List Value Before Iteration:" + list); // Creating an iterator object // to iterate over the ArrayList Iterator<Integer> itr = list.iterator(); // Condition check // it holds true till there is single element // remaining in the List while (itr.hasNext()) { // next() method() looks out for next element in // the List Integer value = itr.next(); // Here we are trying to remove the one entry of // ArrayList base on the given if condition and // hence // We will get Concurrent ModificationException if (value.equals(3)) itr.remove(); } // Display the value of ArrayList System.out.println("List Value After iteration:" + list); }} List Value Before Iteration:[1, 2, 3, 4, 5] List Value After iteration:[1, 2, 4, 5] Note: In multi-threaded program we can avoid ConcurrentModificaionException by using ConcurrentHashMap and CopyOnWriteArrayList classes. These classes help us in avoiding ConcurrentModificaionException. anikaseth98 clintra sagar0719kumar akshaysingh98088 anikakapoor avtarkumar719 Java-Exceptions How To Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to download and install Python Latest Version on Android How to Add External JAR File to an IntelliJ IDEA Project? How to Fix “passwd: Authentication token manipulation error” in Linux Spring Boot | How to publish JSON messages on Apache Kafka How to install Python on Windows? Arrays.sort() in Java with examples For-each loop in Java Arrays in Java Multidimensional Arrays in Java Split() String method in Java with examples
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Mar, 2022" }, { "code": null, "e": 544, "s": 28, "text": "An unaccepted, unwanted event that disturbed the normal flow of a program is called an Exception. Most of the time exception is caused by our program and these are recoverable. Example: If our program requirement is to read data from the remote file locating in the U.S.A. At runtime, if a remote file is not available then we will get RuntimeException saying FileNotFoundException. If FileNotFoundException occurs we can provide the local file to the program to read and continue the rest of the program normally." }, { "code": null, "e": 605, "s": 544, "text": "There are mainly two types of exception in java as follows:" }, { "code": null, "e": 1218, "s": 605, "text": "Checked Exceptions are the exceptions that are checked by the compiler for the smooth execution of the program at runtime is called a checked exception. In our program, if there is a chance of rising checked exceptions then compulsory we should handle that checked exception (either by try-catch or throws keyword) otherwise we will get a compile-time error.Unchecked Exceptions are the exceptions that are not checked by the compiler, whether programmer handling or not such types of exceptions are called unchecked exceptions. Examples of unchecked Exceptions are ArithmeticException, ArrayStoreException, etc." }, { "code": null, "e": 1577, "s": 1218, "text": "Checked Exceptions are the exceptions that are checked by the compiler for the smooth execution of the program at runtime is called a checked exception. In our program, if there is a chance of rising checked exceptions then compulsory we should handle that checked exception (either by try-catch or throws keyword) otherwise we will get a compile-time error." }, { "code": null, "e": 1832, "s": 1577, "text": "Unchecked Exceptions are the exceptions that are not checked by the compiler, whether programmer handling or not such types of exceptions are called unchecked exceptions. Examples of unchecked Exceptions are ArithmeticException, ArrayStoreException, etc." }, { "code": null, "e": 1990, "s": 1832, "text": "Note: Whether the exception is checked or unchecked every exception occurs at run time only if there is no chance of occurring any exception at compile time." }, { "code": null, "e": 2007, "s": 1990, "text": " Implementation:" }, { "code": null, "e": 2511, "s": 2007, "text": "ConcurrentModificationException is the child class of RuntimeException and hence it is an unchecked exception. This exception rises when an object is tried to be modified concurrently when it is not permissible i.e when one thread is iterating over some collection class object and if some other thread tried to modify or try to make some changes on that collection object then we will get ConcurrentModificationException. This exception usually occurs when we are working with Java collections classes." }, { "code": null, "e": 2519, "s": 2511, "text": "Example" }, { "code": null, "e": 2524, "s": 2519, "text": "Java" }, { "code": "// Java program to illustrate// ConcurrentModificationException // Importing all classes from java.util package// Importing input output classesimport java.io.*;import java.util.*; // Main Classclass GFG { // Main driver method public static void main(String[] args) { // Creating an object of ArrayList // Declaring object of Integer type ArrayList<Integer> list = new ArrayList<>(); // Adding element to ArrayList object created above // using the add() method // Custom input elements list.add(1); list.add(2); list.add(3); list.add(4); list.add(5); // Display all the elements of ArrayList object System.out.println(\"List Value Before Iteration:\" + list); // Creating an iterator object to // iterate over the ArrayList Iterator<Integer> it = list.iterator(); // Condition check // It holds true till there is single element // remaining in the List while (it.hasNext()) { Integer value = it.next(); // Here we are trying to remove the one entry of // ArrayList base on the if condition and hence // We will get Concurrent ModificationException if (value.equals(3)) list.remove(value); } // Print and display the value of ArrayList object System.out.println(\"List Value After Iteration:\" + list); }}", "e": 4032, "s": 2524, "text": null }, { "code": null, "e": 4040, "s": 4032, "text": "Output:" }, { "code": null, "e": 4060, "s": 4040, "text": "Output explanation:" }, { "code": null, "e": 4294, "s": 4060, "text": "The above program is a single-threaded program and here we can avoid ConcurrentModificationException by using iterator’s remove( ) function, we can remove an object from an underlying collection object without getting any exception." }, { "code": null, "e": 4306, "s": 4294, "text": "Example 2 " }, { "code": null, "e": 4311, "s": 4306, "text": "Java" }, { "code": "// Java Program to illustrate// ConcurrentModificationException // Importing the required packagesimport java.io.*;import java.util.*;import java.util.Iterator; // Main Classclass GFG { // Main driver method public static void main(String[] args) { // Creating an collection class object // Declaring object of integer type ArrayList<Integer> list = new ArrayList<>(); // Adding element to ArrayList // using add() method // Custom integer input entries list.add(1); list.add(2); list.add(3); list.add(4); list.add(5); // Display the value of ArrayList System.out.println(\"List Value Before Iteration:\" + list); // Creating an iterator object // to iterate over the ArrayList Iterator<Integer> itr = list.iterator(); // Condition check // it holds true till there is single element // remaining in the List while (itr.hasNext()) { // next() method() looks out for next element in // the List Integer value = itr.next(); // Here we are trying to remove the one entry of // ArrayList base on the given if condition and // hence // We will get Concurrent ModificationException if (value.equals(3)) itr.remove(); } // Display the value of ArrayList System.out.println(\"List Value After iteration:\" + list); }}", "e": 5855, "s": 4311, "text": null }, { "code": null, "e": 5939, "s": 5855, "text": "List Value Before Iteration:[1, 2, 3, 4, 5]\nList Value After iteration:[1, 2, 4, 5]" }, { "code": null, "e": 6143, "s": 5939, "text": "Note: In multi-threaded program we can avoid ConcurrentModificaionException by using ConcurrentHashMap and CopyOnWriteArrayList classes. These classes help us in avoiding ConcurrentModificaionException." }, { "code": null, "e": 6157, "s": 6145, "text": "anikaseth98" }, { "code": null, "e": 6165, "s": 6157, "text": "clintra" }, { "code": null, "e": 6180, "s": 6165, "text": "sagar0719kumar" }, { "code": null, "e": 6197, "s": 6180, "text": "akshaysingh98088" }, { "code": null, "e": 6209, "s": 6197, "text": "anikakapoor" }, { "code": null, "e": 6223, "s": 6209, "text": "avtarkumar719" }, { "code": null, "e": 6239, "s": 6223, "text": "Java-Exceptions" }, { "code": null, "e": 6246, "s": 6239, "text": "How To" }, { "code": null, "e": 6251, "s": 6246, "text": "Java" }, { "code": null, "e": 6256, "s": 6251, "text": "Java" }, { "code": null, "e": 6354, "s": 6256, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6415, "s": 6354, "text": "How to download and install Python Latest Version on Android" }, { "code": null, "e": 6473, "s": 6415, "text": "How to Add External JAR File to an IntelliJ IDEA Project?" }, { "code": null, "e": 6543, "s": 6473, "text": "How to Fix “passwd: Authentication token manipulation error” in Linux" }, { "code": null, "e": 6602, "s": 6543, "text": "Spring Boot | How to publish JSON messages on Apache Kafka" }, { "code": null, "e": 6636, "s": 6602, "text": "How to install Python on Windows?" }, { "code": null, "e": 6672, "s": 6636, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 6694, "s": 6672, "text": "For-each loop in Java" }, { "code": null, "e": 6709, "s": 6694, "text": "Arrays in Java" }, { "code": null, "e": 6741, "s": 6709, "text": "Multidimensional Arrays in Java" } ]
Design Smiley Face Eyes that follow Mouse Cursor using CSS and JS
26 Apr, 2021 An animated face by using HTML and CSS and JavaScript. Where the face will follow the cursor. It is one of the simple CSS and JavaScript effects. For a beginner, it is one of the best examples to learn the concept of pseudo-elements. Approach: The Basic idea of a face is comes from CSS.Here the whole animation will be made by CSS and a little bit of Javascript. Mainly by using CSS, we will make the cartoon face and by Javascript, we will help to flow the eyeball of the face. The main idea is that the eyeballs of the faces will move towards the mouse pointer and when the mouse comes on the face it closes the mouth, other than it opens its mouth and smiles. HTML code: Using HTML we will make the basic structure of the face. We will take some divs, and give them some class name as we can decorate it in future. html <div class="face"> <div class="eyes"> <div class="eye"></div> <div class="eye"></div> </div></div><div class="face"> <div class="eyes"> <div class="eye"></div> <div class="eye"></div> </div></div> CSS Code: By using CSS we will define the area of the particular divs,then will add some CSS attribute like border-radius, background color to make the area like round and a face of cartoon. also, we must have to use some hover effect to make this faces more attractive and alive, like when the mouse pointer comes on the face it closes it’s mouth. css <style type="text/css"> * { margin: 0; padding: 0; box-sizing: border-box; } body { /* Here mainly the body background color, height, width, position, size of fonts etc fixed*/ display: flex; justify-content: center; align-items: center; min-height: 100vh; height: 100%; width: 100%; background-repeat: unset; font-size: 50px; } /*In this part we will make the round shape of the face,and the basic structure of face like add some color of face,height,width etc*/ .face { position: relative; width: 200px; height: 200px; border-radius: 50%; background: green; display: flex; justify-content: center; align-items: center; } .face::before { /*In this part we will make the mouth of the face*/ content: ""; position: absolute; top: 120px; width: 150px; height: 70px; background: yellow; border-bottom-left-radius: 70px; border-bottom-right-radius: 70px; transition: 0.5s; } .face:hover::before { /*Here we will add the hover effects. Like when the cursor will came on the mouth the mouth will closed that means is radius will be decreased*/ top: 120px; width: 150px; height: 20px; background: yellow; border-bottom-left-radius: 0px; border-bottom-right-radius: 0px; } /*In this part we will make the eyes of the face*/ .eyes { position: relative; top: -30px; display: flex; } .eyes .eye { position: relative; width: 60px; height: 60px; display: block; background: #fff; margin: 0 15px; border-radius: 50%; } .eyes .eye::before { content: ""; position: absolute; top: 50%; left: 25%; transform: translate(-50%, -50%); width: 40px; height: 40px; background: #000; border-radius: 50%; }</style> JavaScript: Here we also use a little bit of JavaScript as the eyeball can move towards the mouse pointer. First of all, we will create a function named eyeball. and then declare variables. In this code we have nothing to print, so we wouldn’t use document.write, But we have to rotate the eyeball, so we use the class name ‘eye’ to rotate and use style.transform function as “rotate(“+rot+”deg)”. And finally, our eye will be ready to move. javascript <script> document.querySelector( "body").addEventListener("mousemove", eyeball); function eyeball() { var eye = document.querySelectorAll(".eye"); eye.forEach(function (eye) { let x = eye.getBoundingClientRect().left + eye.clientWidth / 2; let y = eye.getBoundingClientRect().top + eye.clientHeight / 2; let radian = Math.atan2(event.pageX - x, event.pageY - y); let rot = radian * (180 / Math.PI) * -1 + 270; eye.style.transform = "rotate(" + rot + "deg)"; }); }</script> Example: Here is the full code of HTML CSS and JavaScript html <!DOCTYPE html><html> <head> <meta charset="utf-8" /> <time></time> <style type="text/css"> * { margin: 0; padding: 0; box-sizing: border-box; } body { /* Here mainly the body background color, height, width, position, size of fonts etc fixed*/ display: flex; justify-content: center; align-items: center; min-height: 100vh; height: 100%; width: 100%; background-repeat: unset; font-size: 50px; } /*In this part we will make the round shape of the face,and the basic structure of face like add some color of face,height,width etc*/ .face { position: relative; width: 200px; height: 200px; border-radius: 50%; background: green; display: flex; justify-content: center; align-items: center; } .face::before { /*In this part we will make the mouth of the face*/ content: ""; position: absolute; top: 120px; width: 150px; height: 70px; background: yellow; border-bottom-left-radius: 70px; border-bottom-right-radius: 70px; transition: 0.5s; } .face:hover::before { /*Here we will add the hover effects. Like when the cursor will came on the mouth the mouth will closed that means is radius will be decreased*/ top: 120px; width: 150px; height: 20px; background: yellow; border-bottom-left-radius: 0px; border-bottom-right-radius: 0px; } /*In this part we will make the eyes of the face*/ .eyes { position: relative; top: -30px; display: flex; } .eyes .eye { position: relative; width: 60px; height: 60px; display: block; background: #fff; margin: 0 15px; border-radius: 50%; } .eyes .eye::before { content: ""; position: absolute; top: 50%; left: 25%; transform: translate(-50%, -50%); width: 40px; height: 40px; background: #000; border-radius: 50%; } </style> </head> <body> <!-- In this divs take separate classes named eye, face which will help to make the animation, because the whole animation will be made by using css--> <div class="face"> <div class="eyes"> <div class="eye"></div> <div class="eye"></div> </div> </div> <div class="face"> <div class="eyes"> <div class="eye"></div> <div class="eye"></div> </div> </div> <!-- Here the div ends.That means the face part ends--> <script> document.querySelector( "body").addEventListener("mousemove", eyeball); function eyeball() { var eye = document.querySelectorAll(".eye"); eye.forEach(function (eye) { let x = eye.getBoundingClientRect().left + eye.clientWidth / 2; let y = eye.getBoundingClientRect().top + eye.clientHeight / 2; let radian = Math.atan2(event.pageX - x, event.pageY - y); let rot = radian * (180 / Math.PI) * -1 + 270; eye.style.transform = "rotate(" + rot + "deg)"; }); } </script> </body></html> Output: arorakashish0911 CSS-Misc HTML-Misc CSS HTML JavaScript Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Apr, 2021" }, { "code": null, "e": 262, "s": 28, "text": "An animated face by using HTML and CSS and JavaScript. Where the face will follow the cursor. It is one of the simple CSS and JavaScript effects. For a beginner, it is one of the best examples to learn the concept of pseudo-elements." }, { "code": null, "e": 692, "s": 262, "text": "Approach: The Basic idea of a face is comes from CSS.Here the whole animation will be made by CSS and a little bit of Javascript. Mainly by using CSS, we will make the cartoon face and by Javascript, we will help to flow the eyeball of the face. The main idea is that the eyeballs of the faces will move towards the mouse pointer and when the mouse comes on the face it closes the mouth, other than it opens its mouth and smiles." }, { "code": null, "e": 847, "s": 692, "text": "HTML code: Using HTML we will make the basic structure of the face. We will take some divs, and give them some class name as we can decorate it in future." }, { "code": null, "e": 854, "s": 849, "text": "html" }, { "code": "<div class=\"face\"> <div class=\"eyes\"> <div class=\"eye\"></div> <div class=\"eye\"></div> </div></div><div class=\"face\"> <div class=\"eyes\"> <div class=\"eye\"></div> <div class=\"eye\"></div> </div></div>", "e": 1091, "s": 854, "text": null }, { "code": null, "e": 1440, "s": 1091, "text": "CSS Code: By using CSS we will define the area of the particular divs,then will add some CSS attribute like border-radius, background color to make the area like round and a face of cartoon. also, we must have to use some hover effect to make this faces more attractive and alive, like when the mouse pointer comes on the face it closes it’s mouth." }, { "code": null, "e": 1446, "s": 1442, "text": "css" }, { "code": "<style type=\"text/css\"> * { margin: 0; padding: 0; box-sizing: border-box; } body { /* Here mainly the body background color, height, width, position, size of fonts etc fixed*/ display: flex; justify-content: center; align-items: center; min-height: 100vh; height: 100%; width: 100%; background-repeat: unset; font-size: 50px; } /*In this part we will make the round shape of the face,and the basic structure of face like add some color of face,height,width etc*/ .face { position: relative; width: 200px; height: 200px; border-radius: 50%; background: green; display: flex; justify-content: center; align-items: center; } .face::before { /*In this part we will make the mouth of the face*/ content: \"\"; position: absolute; top: 120px; width: 150px; height: 70px; background: yellow; border-bottom-left-radius: 70px; border-bottom-right-radius: 70px; transition: 0.5s; } .face:hover::before { /*Here we will add the hover effects. Like when the cursor will came on the mouth the mouth will closed that means is radius will be decreased*/ top: 120px; width: 150px; height: 20px; background: yellow; border-bottom-left-radius: 0px; border-bottom-right-radius: 0px; } /*In this part we will make the eyes of the face*/ .eyes { position: relative; top: -30px; display: flex; } .eyes .eye { position: relative; width: 60px; height: 60px; display: block; background: #fff; margin: 0 15px; border-radius: 50%; } .eyes .eye::before { content: \"\"; position: absolute; top: 50%; left: 25%; transform: translate(-50%, -50%); width: 40px; height: 40px; background: #000; border-radius: 50%; }</style>", "e": 3572, "s": 1446, "text": null }, { "code": null, "e": 4014, "s": 3572, "text": "JavaScript: Here we also use a little bit of JavaScript as the eyeball can move towards the mouse pointer. First of all, we will create a function named eyeball. and then declare variables. In this code we have nothing to print, so we wouldn’t use document.write, But we have to rotate the eyeball, so we use the class name ‘eye’ to rotate and use style.transform function as “rotate(“+rot+”deg)”. And finally, our eye will be ready to move." }, { "code": null, "e": 4027, "s": 4016, "text": "javascript" }, { "code": "<script> document.querySelector( \"body\").addEventListener(\"mousemove\", eyeball); function eyeball() { var eye = document.querySelectorAll(\".eye\"); eye.forEach(function (eye) { let x = eye.getBoundingClientRect().left + eye.clientWidth / 2; let y = eye.getBoundingClientRect().top + eye.clientHeight / 2; let radian = Math.atan2(event.pageX - x, event.pageY - y); let rot = radian * (180 / Math.PI) * -1 + 270; eye.style.transform = \"rotate(\" + rot + \"deg)\"; }); }</script>", "e": 4685, "s": 4027, "text": null }, { "code": null, "e": 4743, "s": 4685, "text": "Example: Here is the full code of HTML CSS and JavaScript" }, { "code": null, "e": 4748, "s": 4743, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <meta charset=\"utf-8\" /> <time></time> <style type=\"text/css\"> * { margin: 0; padding: 0; box-sizing: border-box; } body { /* Here mainly the body background color, height, width, position, size of fonts etc fixed*/ display: flex; justify-content: center; align-items: center; min-height: 100vh; height: 100%; width: 100%; background-repeat: unset; font-size: 50px; } /*In this part we will make the round shape of the face,and the basic structure of face like add some color of face,height,width etc*/ .face { position: relative; width: 200px; height: 200px; border-radius: 50%; background: green; display: flex; justify-content: center; align-items: center; } .face::before { /*In this part we will make the mouth of the face*/ content: \"\"; position: absolute; top: 120px; width: 150px; height: 70px; background: yellow; border-bottom-left-radius: 70px; border-bottom-right-radius: 70px; transition: 0.5s; } .face:hover::before { /*Here we will add the hover effects. Like when the cursor will came on the mouth the mouth will closed that means is radius will be decreased*/ top: 120px; width: 150px; height: 20px; background: yellow; border-bottom-left-radius: 0px; border-bottom-right-radius: 0px; } /*In this part we will make the eyes of the face*/ .eyes { position: relative; top: -30px; display: flex; } .eyes .eye { position: relative; width: 60px; height: 60px; display: block; background: #fff; margin: 0 15px; border-radius: 50%; } .eyes .eye::before { content: \"\"; position: absolute; top: 50%; left: 25%; transform: translate(-50%, -50%); width: 40px; height: 40px; background: #000; border-radius: 50%; } </style> </head> <body> <!-- In this divs take separate classes named eye, face which will help to make the animation, because the whole animation will be made by using css--> <div class=\"face\"> <div class=\"eyes\"> <div class=\"eye\"></div> <div class=\"eye\"></div> </div> </div> <div class=\"face\"> <div class=\"eyes\"> <div class=\"eye\"></div> <div class=\"eye\"></div> </div> </div> <!-- Here the div ends.That means the face part ends--> <script> document.querySelector( \"body\").addEventListener(\"mousemove\", eyeball); function eyeball() { var eye = document.querySelectorAll(\".eye\"); eye.forEach(function (eye) { let x = eye.getBoundingClientRect().left + eye.clientWidth / 2; let y = eye.getBoundingClientRect().top + eye.clientHeight / 2; let radian = Math.atan2(event.pageX - x, event.pageY - y); let rot = radian * (180 / Math.PI) * -1 + 270; eye.style.transform = \"rotate(\" + rot + \"deg)\"; }); } </script> </body></html>", "e": 8934, "s": 4748, "text": null }, { "code": null, "e": 8944, "s": 8934, "text": "Output: " }, { "code": null, "e": 8963, "s": 8946, "text": "arorakashish0911" }, { "code": null, "e": 8972, "s": 8963, "text": "CSS-Misc" }, { "code": null, "e": 8982, "s": 8972, "text": "HTML-Misc" }, { "code": null, "e": 8986, "s": 8982, "text": "CSS" }, { "code": null, "e": 8991, "s": 8986, "text": "HTML" }, { "code": null, "e": 9002, "s": 8991, "text": "JavaScript" }, { "code": null, "e": 9019, "s": 9002, "text": "Web Technologies" }, { "code": null, "e": 9024, "s": 9019, "text": "HTML" } ]
Python min() Function
13 Aug, 2020 Python min() function returns the smallest of the value or smallest item in an iterable passed as its parameter. There are two types of min function – min() functions with objects min() functions with an iterable Unlike the min() function of C/C++, the min() function in Python can take any type of object and returns the smallest among them. In the case of strings, it returns the lexicographically smallest value. Syntax: min(a, b, c, ..., key=func) Parameters: a, b, c, .. : similar type of data. key: A function to customize the sort order Example: Python3 # Python code to demonstrate the # working of min() # printing the minimum of# 4, 12, 43.3, 19, 100print(min(4, 12, 43.3, 19, 100)) # printing the minimum of # a, b, c, d, eprint(min('a', 'b', 'c', 'd', 'e')) Output: 4 a To customize the sort order key parameter is passed in the min() function. Example: Python3 # Python code to demonstrate the # working of min() # find the string with minimum # lengths = min("GfG", "Geeks", "GeeksWorld", key = len)print(s) Output: GfG min() functions throw TypeError when conflicting data types are compared. Example: Python3 # Python code to demonstrate the# Exception of min() # printing the minimum of 4, 12, 43.3, 19, # "GeeksforGeeks" Throws Exception print(min(4, 12, 43.3, 19, "GeeksforGeeks")) Output: TypeError: unorderable types: str() < int() When an iterable is passed to the min function it returns the smallest item of the iterable. Syntax: min(iterable, default = obj, key = func) Parameters: iterable: An iterable like list, tuple, string default: Default value that is returned when the iterable is empty key: A function to customize the sort order Example: Python3 # Python code to demonstrate the# working of min() # printing the minimum of [4, 12, 43.3, 19]print(min([4, 12, 43.3, 19])) # printing the minimum of "GeeksforGeeks"print(min("GeeksforGeeks")) # printing the minimum of ("A", "b", "C")print(min(("A", "a", "C"))) Output: 4 G A As seen above, to customize the sort order key parameter is passed in the min() function. Example: Python3 # Python code to demonstrate the# working of min() d = {1: "c", 2: "b", 3: "a"} # printing the minimum key of# dictionaryprint(min(d)) # printing the key with minimum # value in dictionaryprint(min(d, key = lambda k: d[k])) Output: 1 3 ValueError is raised when an empty iterable is passed without the default argument Example: Python3 # Python code to demonstrate the# Exception of min() L = [] # printing the minimum empty listprint(min(L)) Output: ValueError: min() arg is an empty sequence Python-Built-in-functions Python-Functions Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Aug, 2020" }, { "code": null, "e": 179, "s": 28, "text": "Python min() function returns the smallest of the value or smallest item in an iterable passed as its parameter. There are two types of min function –" }, { "code": null, "e": 208, "s": 179, "text": "min() functions with objects" }, { "code": null, "e": 241, "s": 208, "text": "min() functions with an iterable" }, { "code": null, "e": 444, "s": 241, "text": "Unlike the min() function of C/C++, the min() function in Python can take any type of object and returns the smallest among them. In the case of strings, it returns the lexicographically smallest value." }, { "code": null, "e": 480, "s": 444, "text": "Syntax: min(a, b, c, ..., key=func)" }, { "code": null, "e": 492, "s": 480, "text": "Parameters:" }, { "code": null, "e": 528, "s": 492, "text": "a, b, c, .. : similar type of data." }, { "code": null, "e": 572, "s": 528, "text": "key: A function to customize the sort order" }, { "code": null, "e": 581, "s": 572, "text": "Example:" }, { "code": null, "e": 589, "s": 581, "text": "Python3" }, { "code": "# Python code to demonstrate the # working of min() # printing the minimum of# 4, 12, 43.3, 19, 100print(min(4, 12, 43.3, 19, 100)) # printing the minimum of # a, b, c, d, eprint(min('a', 'b', 'c', 'd', 'e'))", "e": 800, "s": 589, "text": null }, { "code": null, "e": 808, "s": 800, "text": "Output:" }, { "code": null, "e": 813, "s": 808, "text": "4\na\n" }, { "code": null, "e": 889, "s": 813, "text": "To customize the sort order key parameter is passed in the min() function. " }, { "code": null, "e": 898, "s": 889, "text": "Example:" }, { "code": null, "e": 906, "s": 898, "text": "Python3" }, { "code": "# Python code to demonstrate the # working of min() # find the string with minimum # lengths = min(\"GfG\", \"Geeks\", \"GeeksWorld\", key = len)print(s)", "e": 1059, "s": 906, "text": null }, { "code": null, "e": 1067, "s": 1059, "text": "Output:" }, { "code": null, "e": 1072, "s": 1067, "text": "GfG\n" }, { "code": null, "e": 1146, "s": 1072, "text": "min() functions throw TypeError when conflicting data types are compared." }, { "code": null, "e": 1155, "s": 1146, "text": "Example:" }, { "code": null, "e": 1163, "s": 1155, "text": "Python3" }, { "code": "# Python code to demonstrate the# Exception of min() # printing the minimum of 4, 12, 43.3, 19, # \"GeeksforGeeks\" Throws Exception print(min(4, 12, 43.3, 19, \"GeeksforGeeks\"))", "e": 1343, "s": 1163, "text": null }, { "code": null, "e": 1351, "s": 1343, "text": "Output:" }, { "code": null, "e": 1396, "s": 1351, "text": "TypeError: unorderable types: str() < int()\n" }, { "code": null, "e": 1489, "s": 1396, "text": "When an iterable is passed to the min function it returns the smallest item of the iterable." }, { "code": null, "e": 1538, "s": 1489, "text": "Syntax: min(iterable, default = obj, key = func)" }, { "code": null, "e": 1550, "s": 1538, "text": "Parameters:" }, { "code": null, "e": 1597, "s": 1550, "text": "iterable: An iterable like list, tuple, string" }, { "code": null, "e": 1664, "s": 1597, "text": "default: Default value that is returned when the iterable is empty" }, { "code": null, "e": 1708, "s": 1664, "text": "key: A function to customize the sort order" }, { "code": null, "e": 1717, "s": 1708, "text": "Example:" }, { "code": null, "e": 1725, "s": 1717, "text": "Python3" }, { "code": "# Python code to demonstrate the# working of min() # printing the minimum of [4, 12, 43.3, 19]print(min([4, 12, 43.3, 19])) # printing the minimum of \"GeeksforGeeks\"print(min(\"GeeksforGeeks\")) # printing the minimum of (\"A\", \"b\", \"C\")print(min((\"A\", \"a\", \"C\")))", "e": 1993, "s": 1725, "text": null }, { "code": null, "e": 2001, "s": 1993, "text": "Output:" }, { "code": null, "e": 2008, "s": 2001, "text": "4\nG\nA\n" }, { "code": null, "e": 2099, "s": 2008, "text": "As seen above, to customize the sort order key parameter is passed in the min() function. " }, { "code": null, "e": 2108, "s": 2099, "text": "Example:" }, { "code": null, "e": 2116, "s": 2108, "text": "Python3" }, { "code": "# Python code to demonstrate the# working of min() d = {1: \"c\", 2: \"b\", 3: \"a\"} # printing the minimum key of# dictionaryprint(min(d)) # printing the key with minimum # value in dictionaryprint(min(d, key = lambda k: d[k]))", "e": 2352, "s": 2116, "text": null }, { "code": null, "e": 2360, "s": 2352, "text": "Output:" }, { "code": null, "e": 2365, "s": 2360, "text": "1\n3\n" }, { "code": null, "e": 2448, "s": 2365, "text": "ValueError is raised when an empty iterable is passed without the default argument" }, { "code": null, "e": 2457, "s": 2448, "text": "Example:" }, { "code": null, "e": 2465, "s": 2457, "text": "Python3" }, { "code": "# Python code to demonstrate the# Exception of min() L = [] # printing the minimum empty listprint(min(L))", "e": 2577, "s": 2465, "text": null }, { "code": null, "e": 2585, "s": 2577, "text": "Output:" }, { "code": null, "e": 2629, "s": 2585, "text": "ValueError: min() arg is an empty sequence\n" }, { "code": null, "e": 2655, "s": 2629, "text": "Python-Built-in-functions" }, { "code": null, "e": 2672, "s": 2655, "text": "Python-Functions" }, { "code": null, "e": 2679, "s": 2672, "text": "Python" } ]
How to Update Current Timestamp in MySQL?
30 Nov, 2021 MySQL is an easy-to-use RDBMS. Many organizations prefer to use it because of its easy maintainability, easier to prepare schemas, stored procedures, triggers, and database maintenance. In this article, let us see how to update to Current Timestamp in MySQL. Step 1: Database creation Firstly we create the database.Here GEEKSFORGEEKS is the db name. Query: CREATE DATABASE GEEKSFORGEEKS; Step 2: Make the database active Query: USE GEEKSFORGEEKS; Step 3: Create a table employee with empLoginTime field as Timestamp. Query: CREATE TABLE employee ( empId int NOT NULL, empName VARCHAR(20), empLoginTime TIMESTAMP ); Output: Step 4: We can set the time zone as follows Query: SET TIME_ZONE = '+00:00'; If we want to change the time Zone that also can be done. Step 5: Now, let us insert the records Query: INSERT INTO employee ( empId, empName, empLoginTime ) VALUES (1, 'XXX', '2021-01-01 00:00:01'), (2, 'YYY', '2021-01-01 00:00:01'), (3, 'ZZZ', '2021-01-01 00:00:01'), (4, 'XYZ', '2021-01-01 00:00:01'); Step 6: Display the records Query: SELECT * FROM employee; Output: Here, the ”empLoginTime’ column indicates the value in the mentioned timezone pattern. Step 7: There are possibilities of viewing data from different timezones. During those times, we can set the timezone as we like Query: SET time_zone ='+03:00'; SELECT * FROM employee; Output: In MySQL, there is a facility to keep the default current timestamp value for a column. i.e. empLoginTime should automatically get the timestamp value whenever the employee login into the system. It is equivalent to updating the column to a current timestamp value. Query: ALTER TABLE employee MODIFY COLUMN empLoginTime TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP; Let us check the structure of the table now Query: DESC employee; With both DEFAULT CURRENT_TIMESTAMP and ON UPDATE CURRENT_TIMESTAMP, the “empLoginTime” column has the current timestamp for its default value and is automatically updated to the current timestamp. Now let us insert the records in the table. Since we have the default current_timestamp and on update also to current_timestamp, we no need to give the values for ’empLoginTime’. Below is the query to do that. Query: **Since empLoginTime has the current timestamp value, we no need to add the value explicitly to that column** INSERT INTO employee (empId, empName) VALUES (5, 'ABC'),(6,'CDE'); Display the records Query: SELECT * FROM employee; It is always better to have the ‘login’ and ‘logout’ columns and also similar kinds of columns to have to default current_timestamp values. If it is not set, we can update the column values easily. In MySQL workbench, we have to do the following : Steps to update the data Navigate to Edit –> Preferences. Then click the “SQL Editor” tab and uncheck the “Safe Updates” check box. Then click on Query –> Reconnect to Server. Now execute your SQL query Query: UPDATE employee set empLoginTime = CURRENT_TIMESTAMP WHERE empId < 4; Display the records Query: SELECT * FROM employee; Usually, we should have “created time” and “modified time” in a table to have the updated values. That will help for the auditing purpose. The default constraint is helpful to set the current timestamp value. During table creation itself, the default value can be set, or else by using ALTER command, we can set the default constraint. The other way is by using the ‘UPDATE’ command and which is seen in the above example. mysql Picked SQL-basics SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Update Multiple Columns in Single Update Statement in SQL? Window functions in SQL What is Temporary Table in SQL? SQL using Python SQL | Sub queries in From Clause SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter RANK() Function in SQL Server SQL Query to Convert VARCHAR to INT SQL Query to Compare Two Dates SQL | DROP, TRUNCATE
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Nov, 2021" }, { "code": null, "e": 287, "s": 28, "text": "MySQL is an easy-to-use RDBMS. Many organizations prefer to use it because of its easy maintainability, easier to prepare schemas, stored procedures, triggers, and database maintenance. In this article, let us see how to update to Current Timestamp in MySQL." }, { "code": null, "e": 314, "s": 287, "text": "Step 1: Database creation " }, { "code": null, "e": 380, "s": 314, "text": "Firstly we create the database.Here GEEKSFORGEEKS is the db name." }, { "code": null, "e": 387, "s": 380, "text": "Query:" }, { "code": null, "e": 418, "s": 387, "text": "CREATE DATABASE GEEKSFORGEEKS;" }, { "code": null, "e": 451, "s": 418, "text": "Step 2: Make the database active" }, { "code": null, "e": 458, "s": 451, "text": "Query:" }, { "code": null, "e": 477, "s": 458, "text": "USE GEEKSFORGEEKS;" }, { "code": null, "e": 547, "s": 477, "text": "Step 3: Create a table employee with empLoginTime field as Timestamp." }, { "code": null, "e": 554, "s": 547, "text": "Query:" }, { "code": null, "e": 672, "s": 554, "text": "CREATE TABLE employee\n (\n empId int NOT NULL,\n empName VARCHAR(20),\n empLoginTime TIMESTAMP\n );" }, { "code": null, "e": 680, "s": 672, "text": "Output:" }, { "code": null, "e": 724, "s": 680, "text": "Step 4: We can set the time zone as follows" }, { "code": null, "e": 731, "s": 724, "text": "Query:" }, { "code": null, "e": 757, "s": 731, "text": "SET TIME_ZONE = '+00:00';" }, { "code": null, "e": 815, "s": 757, "text": "If we want to change the time Zone that also can be done." }, { "code": null, "e": 854, "s": 815, "text": "Step 5: Now, let us insert the records" }, { "code": null, "e": 861, "s": 854, "text": "Query:" }, { "code": null, "e": 1094, "s": 861, "text": "INSERT INTO employee\n (\n empId, empName, empLoginTime\n )\nVALUES\n (1, 'XXX', '2021-01-01 00:00:01'),\n (2, 'YYY', '2021-01-01 00:00:01'),\n (3, 'ZZZ', '2021-01-01 00:00:01'),\n (4, 'XYZ', '2021-01-01 00:00:01');" }, { "code": null, "e": 1122, "s": 1094, "text": "Step 6: Display the records" }, { "code": null, "e": 1129, "s": 1122, "text": "Query:" }, { "code": null, "e": 1153, "s": 1129, "text": "SELECT * FROM employee;" }, { "code": null, "e": 1161, "s": 1153, "text": "Output:" }, { "code": null, "e": 1248, "s": 1161, "text": "Here, the ”empLoginTime’ column indicates the value in the mentioned timezone pattern." }, { "code": null, "e": 1377, "s": 1248, "text": "Step 7: There are possibilities of viewing data from different timezones. During those times, we can set the timezone as we like" }, { "code": null, "e": 1384, "s": 1377, "text": "Query:" }, { "code": null, "e": 1433, "s": 1384, "text": "SET time_zone ='+03:00';\nSELECT * FROM employee;" }, { "code": null, "e": 1441, "s": 1433, "text": "Output:" }, { "code": null, "e": 1708, "s": 1441, "text": "In MySQL, there is a facility to keep the default current timestamp value for a column. i.e. empLoginTime should automatically get the timestamp value whenever the employee login into the system. It is equivalent to updating the column to a current timestamp value." }, { "code": null, "e": 1715, "s": 1708, "text": "Query:" }, { "code": null, "e": 1834, "s": 1715, "text": "ALTER TABLE employee MODIFY \nCOLUMN empLoginTime \nTIMESTAMP DEFAULT CURRENT_TIMESTAMP\nON UPDATE CURRENT_TIMESTAMP; " }, { "code": null, "e": 1878, "s": 1834, "text": "Let us check the structure of the table now" }, { "code": null, "e": 1885, "s": 1878, "text": "Query:" }, { "code": null, "e": 1900, "s": 1885, "text": "DESC employee;" }, { "code": null, "e": 2098, "s": 1900, "text": "With both DEFAULT CURRENT_TIMESTAMP and ON UPDATE CURRENT_TIMESTAMP, the “empLoginTime” column has the current timestamp for its default value and is automatically updated to the current timestamp." }, { "code": null, "e": 2308, "s": 2098, "text": "Now let us insert the records in the table. Since we have the default current_timestamp and on update also to current_timestamp, we no need to give the values for ’empLoginTime’. Below is the query to do that." }, { "code": null, "e": 2315, "s": 2308, "text": "Query:" }, { "code": null, "e": 2494, "s": 2315, "text": "**Since empLoginTime has the current \ntimestamp value, we no need to add the value\n explicitly to that column**\nINSERT INTO employee (empId, empName) VALUES\n(5, 'ABC'),(6,'CDE');" }, { "code": null, "e": 2514, "s": 2494, "text": "Display the records" }, { "code": null, "e": 2521, "s": 2514, "text": "Query:" }, { "code": null, "e": 2545, "s": 2521, "text": "SELECT * FROM employee;" }, { "code": null, "e": 2745, "s": 2545, "text": "It is always better to have the ‘login’ and ‘logout’ columns and also similar kinds of columns to have to default current_timestamp values. If it is not set, we can update the column values easily. " }, { "code": null, "e": 2795, "s": 2745, "text": "In MySQL workbench, we have to do the following :" }, { "code": null, "e": 2820, "s": 2795, "text": "Steps to update the data" }, { "code": null, "e": 2853, "s": 2820, "text": "Navigate to Edit –> Preferences." }, { "code": null, "e": 2927, "s": 2853, "text": "Then click the “SQL Editor” tab and uncheck the “Safe Updates” check box." }, { "code": null, "e": 2971, "s": 2927, "text": "Then click on Query –> Reconnect to Server." }, { "code": null, "e": 2998, "s": 2971, "text": "Now execute your SQL query" }, { "code": null, "e": 3005, "s": 2998, "text": "Query:" }, { "code": null, "e": 3075, "s": 3005, "text": "UPDATE employee set empLoginTime = CURRENT_TIMESTAMP\nWHERE empId < 4;" }, { "code": null, "e": 3096, "s": 3075, "text": "Display the records " }, { "code": null, "e": 3103, "s": 3096, "text": "Query:" }, { "code": null, "e": 3127, "s": 3103, "text": "SELECT * FROM employee;" }, { "code": null, "e": 3551, "s": 3127, "text": "Usually, we should have “created time” and “modified time” in a table to have the updated values. That will help for the auditing purpose. The default constraint is helpful to set the current timestamp value. During table creation itself, the default value can be set, or else by using ALTER command, we can set the default constraint. The other way is by using the ‘UPDATE’ command and which is seen in the above example." }, { "code": null, "e": 3557, "s": 3551, "text": "mysql" }, { "code": null, "e": 3564, "s": 3557, "text": "Picked" }, { "code": null, "e": 3575, "s": 3564, "text": "SQL-basics" }, { "code": null, "e": 3579, "s": 3575, "text": "SQL" }, { "code": null, "e": 3583, "s": 3579, "text": "SQL" }, { "code": null, "e": 3681, "s": 3583, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3747, "s": 3681, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 3771, "s": 3747, "text": "Window functions in SQL" }, { "code": null, "e": 3803, "s": 3771, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 3820, "s": 3803, "text": "SQL using Python" }, { "code": null, "e": 3853, "s": 3820, "text": "SQL | Sub queries in From Clause" }, { "code": null, "e": 3931, "s": 3853, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 3961, "s": 3931, "text": "RANK() Function in SQL Server" }, { "code": null, "e": 3997, "s": 3961, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 4028, "s": 3997, "text": "SQL Query to Compare Two Dates" } ]
unordered_map operator[] in C++ STL
14 Dec, 2018 The std::unordered_map::operator[] is a built in function in C++ STL which returns the reference of value if key matches in the container. If no key is found then it inserts that key into container.Syntax: mapped_type& operator[](key_type&& k); Parameter: It takes parameter as key whose mapped value is accessed.Return type: Returns a reference associated to that key. Example 1 // C++ code to illustrate the method// unordered_map operator[]#include <bits/stdc++.h>using namespace std; int main(){ unordered_map<int, int> sample; // Map initialization sample = { { 1, 2 }, { 3, 4 }, { 5, 6 } }; // print element before doing // any operations for (auto& it : sample) cout << it.first << " : " << it.second << endl; // existing element is read int m = sample[1]; // existing element is written sample[3] = m; // existing elements are accessed sample[5] = sample[1]; // non existing element // new element 25 will be inserted m = sample[25]; // new element 10 will be inserted sample[5] = sample[10]; // print element after doing // operations for (auto& it : sample) cout << it.first << " : " << it.second << endl; return 0;} 5 : 6 3 : 4 1 : 2 10 : 0 1 : 2 5 : 0 3 : 2 25 : 0 Example 2 // C++ code to illustrate the method// unordered_map operator[]#include <bits/stdc++.h> using namespace std; int main(){ unordered_map<char, int> sample; // Map initialization sample = { { 'a', 2 }, { 'b', 4 }, { 'c', 6 } }; // print element before doing // any operations for (auto& it : sample) cout << it.first << " : " << it.second << endl; // existing element is read int m = sample['a']; // existing element is written sample['b'] = m; // existing elements are accessed sample['c'] = sample['a']; // non existing element // new element 'd' will be inserted m = sample['d']; // new element 'f' will be inserted sample['c'] = sample['f']; // print element after doing // operations for (auto& it : sample) cout << it.first << " : " << it.second << endl; return 0;} c : 6 b : 4 a : 2 f : 0 a : 2 b : 2 c : 0 d : 0 Time Complexity O(n) in worst case. cpp-unordered_map cpp-unordered_map-functions C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Sorting a vector in C++ Polymorphism in C++ Friend class and function in C++ Pair in C++ Standard Template Library (STL) std::string class in C++ Queue in C++ Standard Template Library (STL) Unordered Sets in C++ Standard Template Library std::find in C++ List in C++ Standard Template Library (STL) Inline Functions in C++
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Dec, 2018" }, { "code": null, "e": 234, "s": 28, "text": "The std::unordered_map::operator[] is a built in function in C++ STL which returns the reference of value if key matches in the container. If no key is found then it inserts that key into container.Syntax:" }, { "code": null, "e": 274, "s": 234, "text": "mapped_type& operator[](key_type&& k);\n" }, { "code": null, "e": 399, "s": 274, "text": "Parameter: It takes parameter as key whose mapped value is accessed.Return type: Returns a reference associated to that key." }, { "code": null, "e": 409, "s": 399, "text": "Example 1" }, { "code": "// C++ code to illustrate the method// unordered_map operator[]#include <bits/stdc++.h>using namespace std; int main(){ unordered_map<int, int> sample; // Map initialization sample = { { 1, 2 }, { 3, 4 }, { 5, 6 } }; // print element before doing // any operations for (auto& it : sample) cout << it.first << \" : \" << it.second << endl; // existing element is read int m = sample[1]; // existing element is written sample[3] = m; // existing elements are accessed sample[5] = sample[1]; // non existing element // new element 25 will be inserted m = sample[25]; // new element 10 will be inserted sample[5] = sample[10]; // print element after doing // operations for (auto& it : sample) cout << it.first << \" : \" << it.second << endl; return 0;}", "e": 1250, "s": 409, "text": null }, { "code": null, "e": 1301, "s": 1250, "text": "5 : 6\n3 : 4\n1 : 2\n10 : 0\n1 : 2\n5 : 0\n3 : 2\n25 : 0\n" }, { "code": null, "e": 1311, "s": 1301, "text": "Example 2" }, { "code": "// C++ code to illustrate the method// unordered_map operator[]#include <bits/stdc++.h> using namespace std; int main(){ unordered_map<char, int> sample; // Map initialization sample = { { 'a', 2 }, { 'b', 4 }, { 'c', 6 } }; // print element before doing // any operations for (auto& it : sample) cout << it.first << \" : \" << it.second << endl; // existing element is read int m = sample['a']; // existing element is written sample['b'] = m; // existing elements are accessed sample['c'] = sample['a']; // non existing element // new element 'd' will be inserted m = sample['d']; // new element 'f' will be inserted sample['c'] = sample['f']; // print element after doing // operations for (auto& it : sample) cout << it.first << \" : \" << it.second << endl; return 0;}", "e": 2175, "s": 1311, "text": null }, { "code": null, "e": 2224, "s": 2175, "text": "c : 6\nb : 4\na : 2\nf : 0\na : 2\nb : 2\nc : 0\nd : 0\n" }, { "code": null, "e": 2260, "s": 2224, "text": "Time Complexity O(n) in worst case." }, { "code": null, "e": 2278, "s": 2260, "text": "cpp-unordered_map" }, { "code": null, "e": 2306, "s": 2278, "text": "cpp-unordered_map-functions" }, { "code": null, "e": 2310, "s": 2306, "text": "C++" }, { "code": null, "e": 2314, "s": 2310, "text": "CPP" }, { "code": null, "e": 2412, "s": 2314, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2436, "s": 2412, "text": "Sorting a vector in C++" }, { "code": null, "e": 2456, "s": 2436, "text": "Polymorphism in C++" }, { "code": null, "e": 2489, "s": 2456, "text": "Friend class and function in C++" }, { "code": null, "e": 2533, "s": 2489, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 2558, "s": 2533, "text": "std::string class in C++" }, { "code": null, "e": 2603, "s": 2558, "text": "Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 2651, "s": 2603, "text": "Unordered Sets in C++ Standard Template Library" }, { "code": null, "e": 2668, "s": 2651, "text": "std::find in C++" }, { "code": null, "e": 2712, "s": 2668, "text": "List in C++ Standard Template Library (STL)" } ]
JavaScript | Date Objects
08 Jul, 2019 The Date object is an inbuilt datatype of JavaScript language. It is used to work with dates and times. The Date object is created by using new keyword, i.e. new Date(). The Date object can be used date and time in terms of millisecond precision within 100 million days before or after 1/1/1970. But using another methods we can only get and set the year, month, day, hour, minute, second, and millisecond fields using local or UTC or GMT time. So we can represent date and time till the year 275755 using Date object.There are four different way to declare a date, the basic things is that the date objects are created by the new Date() operator.Syntax: new Date() new Date(milliseconds) new Date(dataString) new Date(year, month, date, hour, minute, second, millisecond) Example: new Date():Parameters: The Date() constructor creates a Date object which sets the current date and time depend on the browser’s time zone. It does not accepts any value.Example:<script> // "geeks" is Date objectvar geeks = new Date(); document.write(geeks);// Prints todays date </script> Output: I will return the current Day Month Date Year Standard Time.Wed Jul 03 2019 19:01:35 GMT+0530 (India Standard Time) <script> // "geeks" is Date objectvar geeks = new Date(); document.write(geeks);// Prints todays date </script> Output: I will return the current Day Month Date Year Standard Time. Wed Jul 03 2019 19:01:35 GMT+0530 (India Standard Time) new Date(milliseconds):Parameters: This method accepts single parameter milliseconds which indicates any numeric value. This argument is taken as the internal numeric representation of the date in milliseconds.Example:<script> // "geeks" is Date objectvar geeks = new Date(4500); document.write("Todays date : " + geeks);</script> Output:Todays date : Thu Jan 01 1970 05:30:04 GMT+0530 (India Standard Time) <script> // "geeks" is Date objectvar geeks = new Date(4500); document.write("Todays date : " + geeks);</script> Output: Todays date : Thu Jan 01 1970 05:30:04 GMT+0530 (India Standard Time) new Date(datastring):Parameters: This method accepts single parameter dataString which indicates any string value. It is a string representation of a date and return the datastring with the day.Example:<script> // "geeks" is Date objectvar geeks = new Date("October 13, 2013 11:13:00"); document.write("Datastring with day : " + geeks);</script> Output:Datastring with day : Sun Oct 13 2013 11:13:00 GMT+0530 (India Standard Time) <script> // "geeks" is Date objectvar geeks = new Date("October 13, 2013 11:13:00"); document.write("Datastring with day : " + geeks);</script> Output: Datastring with day : Sun Oct 13 2013 11:13:00 GMT+0530 (India Standard Time) l new Date(year, month, date, hour, minute, second, millisecond):Parameters: This method accepts seven parameters as mentioned above and described below:year: Integer value which represents the year. This should always specify the year in full, i.e. use 2018, instead of use 18.month: Integer value which represents the month. The integer values are starts from 0 for January to 11 for December.date: Integer value which represents the date.hour: Integer value which represents the hour in 24-hours scale.minute: Integer value which represents the minute.second: Integer value which represents the second.millisecond: Integer value which represents the millisecond.Example:<script> // "geeks" is Date objectvar geeks = new Date(2014, 10, 24, 10, 33, 30, 0); document.write(geeks);</script> Output:Mon Nov 24 2014 10:33:30 GMT+0530 (India Standard Time) year: Integer value which represents the year. This should always specify the year in full, i.e. use 2018, instead of use 18. month: Integer value which represents the month. The integer values are starts from 0 for January to 11 for December. date: Integer value which represents the date. hour: Integer value which represents the hour in 24-hours scale. minute: Integer value which represents the minute. second: Integer value which represents the second. millisecond: Integer value which represents the millisecond. Example: <script> // "geeks" is Date objectvar geeks = new Date(2014, 10, 24, 10, 33, 30, 0); document.write(geeks);</script> Output: Mon Nov 24 2014 10:33:30 GMT+0530 (India Standard Time) Properties of Date object: Prototype: Prototype allows us to add properties and methods to an object. Date constructor: It defines the function that creates an Date object’s prototype. Some Methods of Date object: Here are some methods that define the usage of a Date object, These are non-static methods. Below methods are returns all the values according to local time: There are many more methods: Below methods are returns all the values according to universal time: javascript-date Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Difference Between PUT and PATCH Request How to append HTML code to a div using JavaScript ? Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Jul, 2019" }, { "code": null, "e": 683, "s": 28, "text": "The Date object is an inbuilt datatype of JavaScript language. It is used to work with dates and times. The Date object is created by using new keyword, i.e. new Date(). The Date object can be used date and time in terms of millisecond precision within 100 million days before or after 1/1/1970. But using another methods we can only get and set the year, month, day, hour, minute, second, and millisecond fields using local or UTC or GMT time. So we can represent date and time till the year 275755 using Date object.There are four different way to declare a date, the basic things is that the date objects are created by the new Date() operator.Syntax:" }, { "code": null, "e": 802, "s": 683, "text": "new Date()\nnew Date(milliseconds)\nnew Date(dataString)\nnew Date(year, month, date, hour, minute, second, millisecond)\n" }, { "code": null, "e": 811, "s": 802, "text": "Example:" }, { "code": null, "e": 1231, "s": 811, "text": "new Date():Parameters: The Date() constructor creates a Date object which sets the current date and time depend on the browser’s time zone. It does not accepts any value.Example:<script> // \"geeks\" is Date objectvar geeks = new Date(); document.write(geeks);// Prints todays date </script> Output: I will return the current Day Month Date Year Standard Time.Wed Jul 03 2019 19:01:35 GMT+0530 (India Standard Time)\n" }, { "code": "<script> // \"geeks\" is Date objectvar geeks = new Date(); document.write(geeks);// Prints todays date </script> ", "e": 1349, "s": 1231, "text": null }, { "code": null, "e": 1418, "s": 1349, "text": "Output: I will return the current Day Month Date Year Standard Time." }, { "code": null, "e": 1475, "s": 1418, "text": "Wed Jul 03 2019 19:01:35 GMT+0530 (India Standard Time)\n" }, { "code": null, "e": 1889, "s": 1475, "text": "new Date(milliseconds):Parameters: This method accepts single parameter milliseconds which indicates any numeric value. This argument is taken as the internal numeric representation of the date in milliseconds.Example:<script> // \"geeks\" is Date objectvar geeks = new Date(4500); document.write(\"Todays date : \" + geeks);</script> Output:Todays date : Thu Jan 01 1970 05:30:04 GMT+0530 (India Standard Time)\n" }, { "code": "<script> // \"geeks\" is Date objectvar geeks = new Date(4500); document.write(\"Todays date : \" + geeks);</script> ", "e": 2008, "s": 1889, "text": null }, { "code": null, "e": 2016, "s": 2008, "text": "Output:" }, { "code": null, "e": 2087, "s": 2016, "text": "Todays date : Thu Jan 01 1970 05:30:04 GMT+0530 (India Standard Time)\n" }, { "code": null, "e": 2524, "s": 2087, "text": "new Date(datastring):Parameters: This method accepts single parameter dataString which indicates any string value. It is a string representation of a date and return the datastring with the day.Example:<script> // \"geeks\" is Date objectvar geeks = new Date(\"October 13, 2013 11:13:00\"); document.write(\"Datastring with day : \" + geeks);</script> Output:Datastring with day : Sun Oct 13 2013 11:13:00 GMT+0530 (India Standard Time)\n" }, { "code": "<script> // \"geeks\" is Date objectvar geeks = new Date(\"October 13, 2013 11:13:00\"); document.write(\"Datastring with day : \" + geeks);</script> ", "e": 2674, "s": 2524, "text": null }, { "code": null, "e": 2682, "s": 2674, "text": "Output:" }, { "code": null, "e": 2761, "s": 2682, "text": "Datastring with day : Sun Oct 13 2013 11:13:00 GMT+0530 (India Standard Time)\n" }, { "code": null, "e": 2763, "s": 2761, "text": "l" }, { "code": null, "e": 3636, "s": 2763, "text": "new Date(year, month, date, hour, minute, second, millisecond):Parameters: This method accepts seven parameters as mentioned above and described below:year: Integer value which represents the year. This should always specify the year in full, i.e. use 2018, instead of use 18.month: Integer value which represents the month. The integer values are starts from 0 for January to 11 for December.date: Integer value which represents the date.hour: Integer value which represents the hour in 24-hours scale.minute: Integer value which represents the minute.second: Integer value which represents the second.millisecond: Integer value which represents the millisecond.Example:<script> // \"geeks\" is Date objectvar geeks = new Date(2014, 10, 24, 10, 33, 30, 0); document.write(geeks);</script> Output:Mon Nov 24 2014 10:33:30 GMT+0530 (India Standard Time)\n" }, { "code": null, "e": 3762, "s": 3636, "text": "year: Integer value which represents the year. This should always specify the year in full, i.e. use 2018, instead of use 18." }, { "code": null, "e": 3880, "s": 3762, "text": "month: Integer value which represents the month. The integer values are starts from 0 for January to 11 for December." }, { "code": null, "e": 3927, "s": 3880, "text": "date: Integer value which represents the date." }, { "code": null, "e": 3992, "s": 3927, "text": "hour: Integer value which represents the hour in 24-hours scale." }, { "code": null, "e": 4043, "s": 3992, "text": "minute: Integer value which represents the minute." }, { "code": null, "e": 4094, "s": 4043, "text": "second: Integer value which represents the second." }, { "code": null, "e": 4155, "s": 4094, "text": "millisecond: Integer value which represents the millisecond." }, { "code": null, "e": 4164, "s": 4155, "text": "Example:" }, { "code": "<script> // \"geeks\" is Date objectvar geeks = new Date(2014, 10, 24, 10, 33, 30, 0); document.write(geeks);</script> ", "e": 4303, "s": 4164, "text": null }, { "code": null, "e": 4311, "s": 4303, "text": "Output:" }, { "code": null, "e": 4368, "s": 4311, "text": "Mon Nov 24 2014 10:33:30 GMT+0530 (India Standard Time)\n" }, { "code": null, "e": 4395, "s": 4368, "text": "Properties of Date object:" }, { "code": null, "e": 4470, "s": 4395, "text": "Prototype: Prototype allows us to add properties and methods to an object." }, { "code": null, "e": 4553, "s": 4470, "text": "Date constructor: It defines the function that creates an Date object’s prototype." }, { "code": null, "e": 4674, "s": 4553, "text": "Some Methods of Date object: Here are some methods that define the usage of a Date object, These are non-static methods." }, { "code": null, "e": 4740, "s": 4674, "text": "Below methods are returns all the values according to local time:" }, { "code": null, "e": 4769, "s": 4740, "text": "There are many more methods:" }, { "code": null, "e": 4839, "s": 4769, "text": "Below methods are returns all the values according to universal time:" }, { "code": null, "e": 4855, "s": 4839, "text": "javascript-date" }, { "code": null, "e": 4862, "s": 4855, "text": "Picked" }, { "code": null, "e": 4873, "s": 4862, "text": "JavaScript" }, { "code": null, "e": 4890, "s": 4873, "text": "Web Technologies" }, { "code": null, "e": 4988, "s": 4890, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5049, "s": 4988, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 5121, "s": 5049, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 5161, "s": 5121, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 5202, "s": 5161, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 5254, "s": 5202, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 5287, "s": 5254, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 5349, "s": 5287, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 5410, "s": 5349, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 5460, "s": 5410, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Given an example of C pointer addition and subtraction
Pointers have many but easy concepts and they are very important to C programming. Two of the arithmetic pointer concepts are explained below, which are C pointer addition and subtraction respectively. C pointer addition refers to adding a value to the pointer variable. The formula is as follows − new_address= current_address + (number * size_of(data type)) Following is the C program for C pointer addition − Live Demo #include<stdio.h> int main(){ int num=500; int *ptr;//pointer to int ptr=#//stores the address of number variable printf("add of ptr is %u \n",ptr); ptr=ptr+7; //adding 7 to pointer variable printf("after adding add of ptr is %u \n",ptr); return 0; } When the above program is executed, it produces the following result − add of ptr is 6422036 after adding add of ptr is 6422064 It subtracts a value from the pointer variable. Subtracting any number from a pointer variable will give an address. The formula is as follows − new_address= current_address - (number * size_of(data type)) Following is the C program for C pointer subtraction − Live Demo #include<stdio.h> int main(){ int num=500; int *ptr;//pointer to int ptr=#//stores the address of number variable printf("addr of ptr is %u \n",ptr); ptr=ptr-5; //subtract 5 to pointer variable printf("after sub Addr of ptr is %u \n",ptr); return 0; } When the above program is executed, it produces the following result − addr of ptr is 6422036 after sub Addr of ptr is 6422016
[ { "code": null, "e": 1270, "s": 1187, "text": "Pointers have many but easy concepts and they are very important to C programming." }, { "code": null, "e": 1389, "s": 1270, "text": "Two of the arithmetic pointer concepts are explained below, which are C pointer addition and subtraction respectively." }, { "code": null, "e": 1458, "s": 1389, "text": "C pointer addition refers to adding a value to the pointer variable." }, { "code": null, "e": 1486, "s": 1458, "text": "The formula is as follows −" }, { "code": null, "e": 1547, "s": 1486, "text": "new_address= current_address + (number * size_of(data type))" }, { "code": null, "e": 1599, "s": 1547, "text": "Following is the C program for C pointer addition −" }, { "code": null, "e": 1610, "s": 1599, "text": " Live Demo" }, { "code": null, "e": 1882, "s": 1610, "text": "#include<stdio.h>\nint main(){\n int num=500;\n int *ptr;//pointer to int\n ptr=#//stores the address of number variable\n printf(\"add of ptr is %u \\n\",ptr);\n ptr=ptr+7; //adding 7 to pointer variable\n printf(\"after adding add of ptr is %u \\n\",ptr);\n return 0;\n}" }, { "code": null, "e": 1953, "s": 1882, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 2010, "s": 1953, "text": "add of ptr is 6422036\nafter adding add of ptr is 6422064" }, { "code": null, "e": 2127, "s": 2010, "text": "It subtracts a value from the pointer variable. Subtracting any number from a pointer variable will give an address." }, { "code": null, "e": 2155, "s": 2127, "text": "The formula is as follows −" }, { "code": null, "e": 2216, "s": 2155, "text": "new_address= current_address - (number * size_of(data type))" }, { "code": null, "e": 2271, "s": 2216, "text": "Following is the C program for C pointer subtraction −" }, { "code": null, "e": 2282, "s": 2271, "text": " Live Demo" }, { "code": null, "e": 2555, "s": 2282, "text": "#include<stdio.h>\nint main(){\n int num=500;\n int *ptr;//pointer to int\n ptr=#//stores the address of number variable\n printf(\"addr of ptr is %u \\n\",ptr);\n ptr=ptr-5; //subtract 5 to pointer variable\n printf(\"after sub Addr of ptr is %u \\n\",ptr);\n return 0;\n}" }, { "code": null, "e": 2626, "s": 2555, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 2682, "s": 2626, "text": "addr of ptr is 6422036\nafter sub Addr of ptr is 6422016" } ]
Form minimum number from given sequence
29 Jun, 2022 Given a pattern containing only I’s and D’s. I for increasing and D for decreasing. Device an algorithm to print the minimum number following that pattern. Digits from 1-9 and digits can’t repeat. Examples: Input: D Output: 21 Input: I Output: 12 Input: DD Output: 321 Input: II Output: 123 Input: DIDI Output: 21435 Input: IIDDD Output: 126543 Input: DDIDDIID Output: 321654798 Source: Amazon Interview Question Below are some important observations Since digits can’t repeat, there can be at most 9 digits in output. Also, number of digits in output is one more than number of characters in input. Note that the first character of input corresponds to two digits in output. Idea is to iterate over input array and keep track of last printed digit and maximum digit printed so far. Below is the implementation of above idea. C++ Java Python3 C# PHP Javascript // C++ program to print minimum number that can be formed// from a given sequence of Is and Ds#include <bits/stdc++.h>using namespace std; // Prints the minimum number that can be formed from// input sequence of I's and D'svoid PrintMinNumberForPattern(string arr){ // Initialize current_max (to make sure that // we don't use repeated character int curr_max = 0; // Initialize last_entry (Keeps track for // last printed digit) int last_entry = 0; int j; // Iterate over input array for (int i=0; i<arr.length(); i++) { // Initialize 'noOfNextD' to get count of // next D's available int noOfNextD = 0; switch(arr[i]) { case 'I': // If letter is 'I' // Calculate number of next consecutive D's // available j = i+1; while (arr[j] == 'D' && j < arr.length()) { noOfNextD++; j++; } if (i==0) { curr_max = noOfNextD + 2; // If 'I' is first letter, print incremented // sequence from 1 cout << " " << ++last_entry; cout << " " << curr_max; // Set max digit reached last_entry = curr_max; } else { // If not first letter // Get next digit to print curr_max = curr_max + noOfNextD + 1; // Print digit for I last_entry = curr_max; cout << " " << last_entry; } // For all next consecutive 'D' print // decremented sequence for (int k=0; k<noOfNextD; k++) { cout << " " << --last_entry; i++; } break; // If letter is 'D' case 'D': if (i == 0) { // If 'D' is first letter in sequence // Find number of Next D's available j = i+1; while (arr[j] == 'D' && j < arr.length()) { noOfNextD++; j++; } // Calculate first digit to print based on // number of consecutive D's curr_max = noOfNextD + 2; // Print twice for the first time cout << " " << curr_max << " " << curr_max - 1; // Store last entry last_entry = curr_max - 1; } else { // If current 'D' is not first letter // Decrement last_entry cout << " " << last_entry - 1; last_entry--; } break; } } cout << endl;} // Driver program to test aboveint main(){ PrintMinNumberForPattern("IDID"); PrintMinNumberForPattern("I"); PrintMinNumberForPattern("DD"); PrintMinNumberForPattern("II"); PrintMinNumberForPattern("DIDI"); PrintMinNumberForPattern("IIDDD"); PrintMinNumberForPattern("DDIDDIID"); return 0;} // Java program to print minimum number that can be formed// from a given sequence of Is and Dsclass GFG{ // Prints the minimum number that can be formed from // input sequence of I's and D's static void PrintMinNumberForPattern(String arr) { // Initialize current_max (to make sure that // we don't use repeated character int curr_max = 0; // Initialize last_entry (Keeps track for // last printed digit) int last_entry = 0; int j; // Iterate over input array for (int i = 0; i < arr.length(); i++) { // Initialize 'noOfNextD' to get count of // next D's available int noOfNextD = 0; switch (arr.charAt(i)) { case 'I': // If letter is 'I' // Calculate number of next consecutive D's // available j = i + 1; while (j < arr.length() && arr.charAt(j) == 'D') { noOfNextD++; j++; } if (i == 0) { curr_max = noOfNextD + 2; // If 'I' is first letter, print incremented // sequence from 1 System.out.print(" " + ++last_entry); System.out.print(" " + curr_max); // Set max digit reached last_entry = curr_max; } else { // If not first letter // Get next digit to print curr_max = curr_max + noOfNextD + 1; // Print digit for I last_entry = curr_max; System.out.print(" " + last_entry); } // For all next consecutive 'D' print // decremented sequence for (int k = 0; k < noOfNextD; k++) { System.out.print(" " + --last_entry); i++; } break; // If letter is 'D' case 'D': if (i == 0) { // If 'D' is first letter in sequence // Find number of Next D's available j = i + 1; while (j < arr.length()&&arr.charAt(j) == 'D') { noOfNextD++; j++; } // Calculate first digit to print based on // number of consecutive D's curr_max = noOfNextD + 2; // Print twice for the first time System.out.print(" " + curr_max + " " + (curr_max - 1)); // Store last entry last_entry = curr_max - 1; } else { // If current 'D' is not first letter // Decrement last_entry System.out.print(" " + (last_entry - 1)); last_entry--; } break; } } System.out.println(); } // Driver code public static void main(String[] args) { PrintMinNumberForPattern("IDID"); PrintMinNumberForPattern("I"); PrintMinNumberForPattern("DD"); PrintMinNumberForPattern("II"); PrintMinNumberForPattern("DIDI"); PrintMinNumberForPattern("IIDDD"); PrintMinNumberForPattern("DDIDDIID"); }} // This code is contributed by Princi Singh # Python3 program to print minimum number that# can be formed from a given sequence of Is and Ds # Prints the minimum number that can be formed from# input sequence of I's and D'sdef PrintMinNumberForPattern(arr): # Initialize current_max (to make sure that # we don't use repeated character curr_max = 0 # Initialize last_entry (Keeps track for # last printed digit) last_entry = 0 i = 0 # Iterate over input array while i < len(arr): # Initialize 'noOfNextD' to get count of # next D's available noOfNextD = 0 if arr[i] == "I": # If letter is 'I' # Calculate number of next consecutive D's # available j = i + 1 while j < len(arr) and arr[j] == "D": noOfNextD += 1 j += 1 if i == 0: curr_max = noOfNextD + 2 last_entry += 1 # If 'I' is first letter, print incremented # sequence from 1 print("", last_entry, end = "") print("", curr_max, end = "") # Set max digit reached last_entry = curr_max else: # If not first letter # Get next digit to print curr_max += noOfNextD + 1 # Print digit for I last_entry = curr_max print("", last_entry, end = "") # For all next consecutive 'D' print # decremented sequence for k in range(noOfNextD): last_entry -= 1 print("", last_entry, end = "") i += 1 # If letter is 'D' elif arr[i] == "D": if i == 0: # If 'D' is first letter in sequence # Find number of Next D's available j = i + 1 while j < len(arr) and arr[j] == "D": noOfNextD += 1 j += 1 # Calculate first digit to print based on # number of consecutive D's curr_max = noOfNextD + 2 # Print twice for the first time print("", curr_max, curr_max - 1, end = "") # Store last entry last_entry = curr_max - 1 else: # If current 'D' is not first letter # Decrement last_entry print("", last_entry - 1, end = "") last_entry -= 1 i += 1 print() # Driver codeif __name__ == "__main__": PrintMinNumberForPattern("IDID") PrintMinNumberForPattern("I") PrintMinNumberForPattern("DD") PrintMinNumberForPattern("II") PrintMinNumberForPattern("DIDI") PrintMinNumberForPattern("IIDDD") PrintMinNumberForPattern("DDIDDIID") # This code is contributed by# sanjeev2552 // C# program to print minimum number that can be formed// from a given sequence of Is and Dsusing System; class GFG{ // Prints the minimum number that can be formed from // input sequence of I's and D's static void PrintMinNumberForPattern(String arr) { // Initialize current_max (to make sure that // we don't use repeated character int curr_max = 0; // Initialize last_entry (Keeps track for // last printed digit) int last_entry = 0; int j; // Iterate over input array for (int i = 0; i < arr.Length; i++) { // Initialize 'noOfNextD' to get count of // next D's available int noOfNextD = 0; switch (arr[i]) { case 'I': // If letter is 'I' // Calculate number of next consecutive D's // available j = i + 1; while (j < arr.Length && arr[j] == 'D') { noOfNextD++; j++; } if (i == 0) { curr_max = noOfNextD + 2; // If 'I' is first letter, print incremented // sequence from 1 Console.Write(" " + ++last_entry); Console.Write(" " + curr_max); // Set max digit reached last_entry = curr_max; } else { // If not first letter // Get next digit to print curr_max = curr_max + noOfNextD + 1; // Print digit for I last_entry = curr_max; Console.Write(" " + last_entry); } // For all next consecutive 'D' print // decremented sequence for (int k = 0; k < noOfNextD; k++) { Console.Write(" " + --last_entry); i++; } break; // If letter is 'D' case 'D': if (i == 0) { // If 'D' is first letter in sequence // Find number of Next D's available j = i + 1; while (j < arr.Length&&arr[j] == 'D') { noOfNextD++; j++; } // Calculate first digit to print based on // number of consecutive D's curr_max = noOfNextD + 2; // Print twice for the first time Console.Write(" " + curr_max + " " + (curr_max - 1)); // Store last entry last_entry = curr_max - 1; } else { // If current 'D' is not first letter // Decrement last_entry Console.Write(" " + (last_entry - 1)); last_entry--; } break; } } Console.WriteLine(); } // Driver code public static void Main(String[] args) { PrintMinNumberForPattern("IDID"); PrintMinNumberForPattern("I"); PrintMinNumberForPattern("DD"); PrintMinNumberForPattern("II"); PrintMinNumberForPattern("DIDI"); PrintMinNumberForPattern("IIDDD"); PrintMinNumberForPattern("DDIDDIID"); }} // This code is contributed by Princi Singh <?php// PHP program to print minimum// number that can be formed// from a given sequence of// Is and Ds // Prints the minimum number// that can be formed from// input sequence of I's and D'sfunction PrintMinNumberForPattern($arr){ // Initialize current_max // (to make sure that // we don't use repeated // character $curr_max = 0; // Initialize last_entry // (Keeps track for // last printed digit) $last_entry = 0; $j; // Iterate over // input array for ($i = 0; $i < strlen($arr); $i++) { // Initialize 'noOfNextD' // to get count of // next D's available $noOfNextD = 0; switch($arr[$i]) { case 'I': // If letter is 'I' // Calculate number of // next consecutive D's // available $j = $i + 1; while ($arr[$j] == 'D' && $j < strlen($arr)) { $noOfNextD++; $j++; } if ($i == 0) { $curr_max = $noOfNextD + 2; // If 'I' is first letter, // print incremented // sequence from 1 echo " " , ++$last_entry; echo " " , $curr_max; // Set max // digit reached $last_entry = $curr_max; } else { // If not first letter // Get next digit // to print $curr_max = $curr_max + $noOfNextD + 1; // Print digit for I $last_entry = $curr_max; echo " " , $last_entry; } // For all next consecutive 'D' // print decremented sequence for ($k = 0; $k < $noOfNextD; $k++) { echo " " , --$last_entry; $i++; } break; // If letter is 'D' case 'D': if ($i == 0) { // If 'D' is first letter // in sequence. Find number // of Next D's available $j = $i+1; while (($arr[$j] == 'D') && ($j < strlen($arr))) { $noOfNextD++; $j++; } // Calculate first digit // to print based on // number of consecutive D's $curr_max = $noOfNextD + 2; // Print twice for // the first time echo " " , $curr_max , " " ,$curr_max - 1; // Store last entry $last_entry = $curr_max - 1; } else { // If current 'D' // is not first letter // Decrement last_entry echo " " , $last_entry - 1; $last_entry--; } break; } } echo "\n";} // Driver CodePrintMinNumberForPattern("IDID");PrintMinNumberForPattern("I");PrintMinNumberForPattern("DD");PrintMinNumberForPattern("II");PrintMinNumberForPattern("DIDI");PrintMinNumberForPattern("IIDDD");PrintMinNumberForPattern("DDIDDIID"); // This code is contributed by aj_36?> <script>// Javascript program to print minimum number that can be formed// from a given sequence of Is and Ds // Prints the minimum number that can be formed from // input sequence of I's and D'sfunction PrintMinNumberForPattern(arr){ // Initialize current_max (to make sure that // we don't use repeated character let curr_max = 0; // Initialize last_entry (Keeps track for // last printed digit) let last_entry = 0; let j; // Iterate over input array for (let i = 0; i < arr.length; i++) { // Initialize 'noOfNextD' to get count of // next D's available let noOfNextD = 0; switch (arr[i]) { case 'I': // If letter is 'I' // Calculate number of next consecutive D's // available j = i + 1; while (j < arr.length && arr[j] == 'D') { noOfNextD++; j++; } if (i == 0) { curr_max = noOfNextD + 2; // If 'I' is first letter, print incremented // sequence from 1 document.write(" " + ++last_entry); document.write(" " + curr_max); // Set max digit reached last_entry = curr_max; } else { // If not first letter // Get next digit to print curr_max = curr_max + noOfNextD + 1; // Print digit for I last_entry = curr_max; document.write(" " + last_entry); } // For all next consecutive 'D' print // decremented sequence for (let k = 0; k < noOfNextD; k++) { document.write(" " + --last_entry); i++; } break; // If letter is 'D' case 'D': if (i == 0) { // If 'D' is first letter in sequence // Find number of Next D's available j = i + 1; while (j < arr.length && arr[j] == 'D') { noOfNextD++; j++; } // Calculate first digit to print based on // number of consecutive D's curr_max = noOfNextD + 2; // Print twice for the first time document.write(" " + curr_max + " " + (curr_max - 1)); // Store last entry last_entry = curr_max - 1; } else { // If current 'D' is not first letter // Decrement last_entry document.write(" " + (last_entry - 1)); last_entry--; } break; } } document.write("<br>");} // Driver codePrintMinNumberForPattern("IDID");PrintMinNumberForPattern("I");PrintMinNumberForPattern("DD");PrintMinNumberForPattern("II");PrintMinNumberForPattern("DIDI");PrintMinNumberForPattern("IIDDD");PrintMinNumberForPattern("DDIDDIID"); // This code is contributed by ab2127</script> 1 3 2 5 4 1 2 3 2 1 1 2 3 2 1 4 3 5 1 2 6 5 4 3 3 2 1 6 5 4 7 9 8 This solution is suggested by Swapnil Trambake. Alternate Solution: Let’s observe a few facts in case of minimum number: The digits can’t repeat hence there can be 9 digits at most in output. To form a minimum number , at every index of the output, we are interested in the minimum number which can be placed at that index. The idea is to iterate over the entire input array , keeping track of the minimum number (1-9) which can be placed at that position of the output. The tricky part of course occurs when ‘D’ is encountered at index other than 0. In such a case we have to track the nearest ‘I’ to the left of ‘D’ and increment each number in the output vector by 1 in between ‘I’ and ‘D’. We cover the base case as follows: If the first character of input is ‘I’ then we append 1 and 2 in the output vector and the minimum available number is set to 3 .The index of most recent ‘I’ is set to 1. If the first character of input is ‘D’ then we append 2 and 1 in the output vector and the minimum available number is set to 3, and the index of most recent ‘I’ is set to 0. Now we iterate the input string from index 1 till its end and: If the character scanned is ‘I’ , a minimum value that has not been used yet is appended to the output vector .We increment the value of minimum no. available and index of most recent ‘I’ is also updated. If the character scanned is ‘D’ at index i of input array, we append the ith element from output vector in the output and track the nearest ‘I’ to the left of ‘D’ and increment each number in the output vector by 1 in between ‘I’ and ‘D’. Following is the program for the same: C++ Java Python3 C# Javascript // C++ program to print minimum number that can be formed// from a given sequence of Is and Ds#include<bits/stdc++.h>using namespace std; void printLeast(string arr){ // min_avail represents the minimum number which is // still available for inserting in the output vector. // pos_of_I keeps track of the most recent index // where 'I' was encountered w.r.t the output vector int min_avail = 1, pos_of_I = 0; //vector to store the output vector<int>v; // cover the base cases if (arr[0]=='I') { v.push_back(1); v.push_back(2); min_avail = 3; pos_of_I = 1; } else { v.push_back(2); v.push_back(1); min_avail = 3; pos_of_I = 0; } // Traverse rest of the input for (int i=1; i<arr.length(); i++) { if (arr[i]=='I') { v.push_back(min_avail); min_avail++; pos_of_I = i+1; } else { v.push_back(v[i]); for (int j=pos_of_I; j<=i; j++) v[j]++; min_avail++; } } // print the number for (int i=0; i<v.size(); i++) cout << v[i] << " "; cout << endl;} // Driver program to check the above functionint main(){ printLeast("IDID"); printLeast("I"); printLeast("DD"); printLeast("II"); printLeast("DIDI"); printLeast("IIDDD"); printLeast("DDIDDIID"); return 0;} // Java program to print minimum number that can be formed// from a given sequence of Is and Dsimport java.io.*;import java.util.*;public class GFG { static void printLeast(String arr) { // min_avail represents the minimum number which is // still available for inserting in the output vector. // pos_of_I keeps track of the most recent index // where 'I' was encountered w.r.t the output vector int min_avail = 1, pos_of_I = 0; //vector to store the output ArrayList<Integer> al = new ArrayList<>(); // cover the base cases if (arr.charAt(0) == 'I') { al.add(1); al.add(2); min_avail = 3; pos_of_I = 1; } else { al.add(2); al.add(1); min_avail = 3; pos_of_I = 0; } // Traverse rest of the input for (int i = 1; i < arr.length(); i++) { if (arr.charAt(i) == 'I') { al.add(min_avail); min_avail++; pos_of_I = i + 1; } else { al.add(al.get(i)); for (int j = pos_of_I; j <= i; j++) al.set(j, al.get(j) + 1); min_avail++; } } // print the number for (int i = 0; i < al.size(); i++) System.out.print(al.get(i) + " "); System.out.println(); } // Driver code public static void main(String args[]) { printLeast("IDID"); printLeast("I"); printLeast("DD"); printLeast("II"); printLeast("DIDI"); printLeast("IIDDD"); printLeast("DDIDDIID"); }}// This code is contributed by rachana soma # Python3 program to print minimum number# that can be formed from a given sequence# of Is and Dsdef printLeast(arr): # min_avail represents the minimum # number which is still available # for inserting in the output vector. # pos_of_I keeps track of the most # recent index where 'I' was # encountered w.r.t the output vector min_avail = 1 pos_of_I = 0 # Vector to store the output v = [] # Cover the base cases if (arr[0] == 'I'): v.append(1) v.append(2) min_avail = 3 pos_of_I = 1 else: v.append(2) v.append(1) min_avail = 3 pos_of_I = 0 # Traverse rest of the input for i in range(1, len(arr)): if (arr[i] == 'I'): v.append(min_avail) min_avail += 1 pos_of_I = i + 1 else: v.append(v[i]) for j in range(pos_of_I, i + 1): v[j] += 1 min_avail += 1 # Print the number print(*v, sep = ' ') # Driver codeprintLeast("IDID")printLeast("I")printLeast("DD")printLeast("II")printLeast("DIDI")printLeast("IIDDD")printLeast("DDIDDIID") # This code is contributed by avanitrachhadiya2155 // C# program to print minimum number that can be formed// from a given sequence of Is and Dsusing System;using System.Collections.Generic; class GFG{ static void printLeast(String arr){ // min_avail represents the minimum number which is // still available for inserting in the output vector. // pos_of_I keeps track of the most recent index // where 'I' was encountered w.r.t the output vector int min_avail = 1, pos_of_I = 0; //vector to store the output List<int> al = new List<int>(); // cover the base cases if (arr[0] == 'I') { al.Add(1); al.Add(2); min_avail = 3; pos_of_I = 1; } else { al.Add(2); al.Add(1); min_avail = 3; pos_of_I = 0; } // Traverse rest of the input for (int i = 1; i < arr.Length; i++) { if (arr[i] == 'I') { al.Add(min_avail); min_avail++; pos_of_I = i + 1; } else { al.Add(al[i]); for (int j = pos_of_I; j <= i; j++) al[j] = al[j] + 1; min_avail++; } } // print the number for (int i = 0; i < al.Count; i++) Console.Write(al[i] + " "); Console.WriteLine();} // Driver codepublic static void Main(String []args){ printLeast("IDID"); printLeast("I"); printLeast("DD"); printLeast("II"); printLeast("DIDI"); printLeast("IIDDD"); printLeast("DDIDDIID");}} // This code is contributed by Rajput-Ji <script> // Javascript program to print // minimum number that can be formed // from a given sequence of Is and Ds function printLeast(arr) { // min_avail represents the // minimum number which is // still available for inserting // in the output vector. // pos_of_I keeps track of the // most recent index // where 'I' was encountered // w.r.t the output vector let min_avail = 1, pos_of_I = 0; //vector to store the output let al = []; // cover the base cases if (arr[0] == 'I') { al.push(1); al.push(2); min_avail = 3; pos_of_I = 1; } else { al.push(2); al.push(1); min_avail = 3; pos_of_I = 0; } // Traverse rest of the input for (let i = 1; i < arr.length; i++) { if (arr[i] == 'I') { al.push(min_avail); min_avail++; pos_of_I = i + 1; } else { al.push(al[i]); for (let j = pos_of_I; j <= i; j++) al[j] = al[j] + 1; min_avail++; } } // print the number for (let i = 0; i < al.length; i++) document.write(al[i] + " "); document.write("</br>"); } printLeast("IDID"); printLeast("I"); printLeast("DD"); printLeast("II"); printLeast("DIDI"); printLeast("IIDDD"); printLeast("DDIDDIID"); </script> 1 3 2 5 4 1 2 3 2 1 1 2 3 2 1 4 3 5 1 2 6 5 4 3 3 2 1 6 5 4 7 9 8 This solution is suggested by Ashutosh Kumar. Method 3 We can that when we encounter I, we got numbers in increasing order but if we encounter ‘D’, we want to have numbers in decreasing order. Length of the output string is always one more than the input string. So the loop is from 0 to the length of the string. We have to take numbers from 1-9 so we always push (i+1) to our stack. Then we check what is the resulting character at the specified index.So, there will be two cases which are as follows:- Case 1: If we have encountered I or we are at the last character of input string, then pop from the stack and add it to the end of the output string until the stack gets empty. Case 2: If we have encountered D, then we want the numbers in decreasing order. so we just push (i+1) to our stack. C++ Java Python3 C# Javascript // C++ program to print minimum number that can be formed// from a given sequence of Is and Ds#include <bits/stdc++.h>using namespace std; // Function to decode the given sequence to construct// minimum number without repeated digitsvoid PrintMinNumberForPattern(string seq){ // result store output string string result; // create an empty stack of integers stack<int> stk; // run n+1 times where n is length of input sequence for (int i = 0; i <= seq.length(); i++) { // push number i+1 into the stack stk.push(i + 1); // if all characters of the input sequence are // processed or current character is 'I' // (increasing) if (i == seq.length() || seq[i] == 'I') { // run till stack is empty while (!stk.empty()) { // remove top element from the stack and // add it to solution result += to_string(stk.top()); result += " "; stk.pop(); } } } cout << result << endl;} // main functionint main(){ PrintMinNumberForPattern("IDID"); PrintMinNumberForPattern("I"); PrintMinNumberForPattern("DD"); PrintMinNumberForPattern("II"); PrintMinNumberForPattern("DIDI"); PrintMinNumberForPattern("IIDDD"); PrintMinNumberForPattern("DDIDDIID"); return 0;} import java.util.Stack; // Java program to print minimum number that can be formed// from a given sequence of Is and Dsclass GFG { // Function to decode the given sequence to construct// minimum number without repeated digits static void PrintMinNumberForPattern(String seq) { // result store output string String result = ""; // create an empty stack of integers Stack<Integer> stk = new Stack<Integer>(); // run n+1 times where n is length of input sequence for (int i = 0; i <= seq.length(); i++) { // push number i+1 into the stack stk.push(i + 1); // if all characters of the input sequence are // processed or current character is 'I' // (increasing) if (i == seq.length() || seq.charAt(i) == 'I') { // run till stack is empty while (!stk.empty()) { // remove top element from the stack and // add it to solution result += String.valueOf(stk.peek()); result += " "; stk.pop(); } } } System.out.println(result); } // main function public static void main(String[] args) { PrintMinNumberForPattern("IDID"); PrintMinNumberForPattern("I"); PrintMinNumberForPattern("DD"); PrintMinNumberForPattern("II"); PrintMinNumberForPattern("DIDI"); PrintMinNumberForPattern("IIDDD"); PrintMinNumberForPattern("DDIDDIID"); }}// This code is contributed by PrinciRaj1992 # Python3 program to print minimum# number that can be formed from a# given sequence of Is and Dsdef PrintMinNumberForPattern(Strr): # Take a List to work as Stack stack = [] # String for storing result res = '' # run n+1 times where n is length # of input sequence, As length of # result string is always 1 greater for i in range(len(Strr) + 1): # Push number i+1 into the stack stack.append(i + 1) # If all characters of the input # sequence are processed or current # character is 'I if (i == len(Strr) or Strr[i] == 'I'): # Run While Loop Until stack is empty while len(stack) > 0: # pop the element on top of stack # And store it in result String res += str(stack.pop()) res += ' ' # Print the result print(res) # Driver CodePrintMinNumberForPattern("IDID")PrintMinNumberForPattern("I")PrintMinNumberForPattern("DD")PrintMinNumberForPattern("II")PrintMinNumberForPattern("DIDI")PrintMinNumberForPattern("IIDDD")PrintMinNumberForPattern("DDIDDIID") # This code is contributed by AyushManglani // C# program to print minimum number that can be formed// from a given sequence of Is and Dsusing System;using System.Collections;public class GFG { // Function to decode the given sequence to construct// minimum number without repeated digits static void PrintMinNumberForPattern(String seq) { // result store output string String result = ""; // create an empty stack of integers Stack stk = new Stack(); // run n+1 times where n is length of input sequence for (int i = 0; i <= seq.Length; i++) { // push number i+1 into the stack stk.Push(i + 1); // if all characters of the input sequence are // processed or current character is 'I' // (increasing) if (i == seq.Length || seq[i] == 'I') { // run till stack is empty while (stk.Count!=0) { // remove top element from the stack and // add it to solution result += String.Join("",stk.Peek()); result += " "; stk.Pop(); } } } Console.WriteLine(result); } // main function public static void Main() { PrintMinNumberForPattern("IDID"); PrintMinNumberForPattern("I"); PrintMinNumberForPattern("DD"); PrintMinNumberForPattern("II"); PrintMinNumberForPattern("DIDI"); PrintMinNumberForPattern("IIDDD"); PrintMinNumberForPattern("DDIDDIID"); }}// This code is contributed by 29AjayKumar <script> // Javascript program to print // minimum number that can be formed // from a given sequence of Is and Ds // Function to decode the given // sequence to construct // minimum number without repeated digits function PrintMinNumberForPattern(seq) { // result store output string let result = ""; // create an empty stack of integers let stk = []; // run n+1 times where n is length // of input sequence for (let i = 0; i <= seq.length; i++) { // push number i+1 into the stack stk.push(i + 1); // if all characters of the input // sequence are // processed or current character is 'I' // (increasing) if (i == seq.length || seq[i] == 'I') { // run till stack is empty while (stk.length!=0) { // remove top element from // the stack and // add it to solution result += (stk[stk.length - 1]).toString(); result += " "; stk.pop(); } } } document.write(result + "</br>"); } PrintMinNumberForPattern("IDID"); PrintMinNumberForPattern("I"); PrintMinNumberForPattern("DD"); PrintMinNumberForPattern("II"); PrintMinNumberForPattern("DIDI"); PrintMinNumberForPattern("IIDDD"); PrintMinNumberForPattern("DDIDDIID"); </script> 1 3 2 5 4 1 2 3 2 1 1 2 3 2 1 4 3 5 1 2 6 5 4 3 3 2 1 6 5 4 7 9 8 Time Complexity: O(n) Auxiliary Space: O(n)This method is contributed by Roshni Agarwal. Method 4 (Using two pointers) Observation Since we have to find a minimum number without repeating digits, maximum length of output can be 9 (using each 1-9 digits once)Length of the output will be exactly one greater than input length.The idea is to iterate over the string and do the following if current character is ‘I’ or string is ended. Assign count in increasing order to each element from current-1 to the next left index of ‘I’ (or starting index is reached).Increase the count by 1. Since we have to find a minimum number without repeating digits, maximum length of output can be 9 (using each 1-9 digits once) Length of the output will be exactly one greater than input length. The idea is to iterate over the string and do the following if current character is ‘I’ or string is ended. Assign count in increasing order to each element from current-1 to the next left index of ‘I’ (or starting index is reached).Increase the count by 1. Assign count in increasing order to each element from current-1 to the next left index of ‘I’ (or starting index is reached).Increase the count by 1. Assign count in increasing order to each element from current-1 to the next left index of ‘I’ (or starting index is reached). Increase the count by 1. Input : IDID Output : 13254 Input : I Output : 12 Input : DD Output : 321 Input : II Output : 123 Input : DIDI Output : 21435 Input : IIDDD Output : 126543 Input : DDIDDIID Output : 321654798 Below is the implementation of above approach: C++ Java Python3 C# Javascript // C++ program of above approach#include <bits/stdc++.h>using namespace std; // Returns minimum number made from given sequence without repeating digitsstring getMinNumberForPattern(string seq){ int n = seq.length(); if (n >= 9) return "-1"; string result(n+1, ' '); int count = 1; // The loop runs for each input character as well as // one additional time for assigning rank to remaining characters for (int i = 0; i <= n; i++) { if (i == n || seq[i] == 'I') { for (int j = i - 1 ; j >= -1 ; j--) { result[j + 1] = '0' + count++; if(j >= 0 && seq[j] == 'I') break; } } } return result;} // main functionint main(){ string inputs[] = {"IDID", "I", "DD", "II", "DIDI", "IIDDD", "DDIDDIID"}; for (string input : inputs) { cout << getMinNumberForPattern(input) << "\n"; } return 0;} // Java program of above approachimport java.io.IOException; public class Test{ // Returns minimum number made from given sequence without repeating digits static String getMinNumberForPattern(String seq) { int n = seq.length(); if (n >= 9) return "-1"; char result[] = new char[n + 1]; int count = 1; // The loop runs for each input character as well as // one additional time for assigning rank to each remaining characters for (int i = 0; i <= n; i++) { if (i == n || seq.charAt(i) == 'I') { for (int j = i - 1; j >= -1; j--) { result[j + 1] = (char) ((int) '0' + count++); if (j >= 0 && seq.charAt(j) == 'I') break; } } } return new String(result); } public static void main(String[] args) throws IOException { String inputs[] = { "IDID", "I", "DD", "II", "DIDI", "IIDDD", "DDIDDIID" }; for(String input : inputs) { System.out.println(getMinNumberForPattern(input)); } }} # Python3 program of above approach # Returns minimum number made from# given sequence without repeating digitsdef getMinNumberForPattern(seq): n = len(seq) if (n >= 9): return "-1" result = [None] * (n + 1) count = 1 # The loop runs for each input character # as well as one additional time for # assigning rank to remaining characters for i in range(n + 1): if (i == n or seq[i] == 'I'): for j in range(i - 1, -2, -1): result[j + 1] = int('0' + str(count)) count += 1 if(j >= 0 and seq[j] == 'I'): break return result # Driver Codeif __name__ == '__main__': inputs = ["IDID", "I", "DD", "II", "DIDI", "IIDDD", "DDIDDIID"] for Input in inputs: print(*(getMinNumberForPattern(Input))) # This code is contributed by PranchalK // C# program of above approachusing System;class GFG{ // Returns minimum number made from given// sequence without repeating digitsstatic String getMinNumberForPattern(String seq){ int n = seq.Length; if (n >= 9) return "-1"; char []result = new char[n + 1]; int count = 1; // The loop runs for each input character // as well as one additional time for // assigning rank to each remaining characters for (int i = 0; i <= n; i++) { if (i == n || seq[i] == 'I') { for (int j = i - 1; j >= -1; j--) { result[j + 1] = (char) ((int) '0' + count++); if (j >= 0 && seq[j] == 'I') break; } } } return new String(result);} // Driver Codepublic static void Main(){ String []inputs = { "IDID", "I", "DD", "II", "DIDI", "IIDDD", "DDIDDIID" }; foreach(String input in inputs) { Console.WriteLine(getMinNumberForPattern(input)); }}} // This code is contributed by Rajput-Ji <script> // Javascript program of above approach // Returns minimum number made from given // sequence without repeating digits function getMinNumberForPattern(seq) { let n = seq.length; if (n >= 9) return "-1"; let result = new Array(n + 1); let count = 1; // The loop runs for each input character // as well as one additional time for // assigning rank to each remaining characters for (let i = 0; i <= n; i++) { if (i == n || seq[i] == 'I') { for (let j = i - 1; j >= -1; j--) { result[j + 1] = String.fromCharCode('0'.charCodeAt() + count++); if (j >= 0 && seq[j] == 'I') break; } } } return result.join(""); } let inputs = [ "IDID", "I", "DD", "II", "DIDI", "IIDDD", "DDIDDIID" ]; for(let input = 0; input < inputs.length; input++) { document.write( getMinNumberForPattern(inputs[input]) + "</br>"); } </script> 13254 12 321 123 21435 126543 321654798 Time Complexity: O(N) Auxiliary Space: O(N)This solution is suggested by Brij Desai.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Method 5 (Start with the Smallest) Start with the smallest number as the answer and keep shifting the digits when we encounter a D. There is no need to traverse back for the index.Follow the below steps, Start with the smallest number for len(s)+1 (say for DI, start with “123”)Now, starting with the second digit (index 1) and first character (D), iterate until end of the digits list, keeping track of the first D in a sequence of DsWhen we encounter a Dmove the digit at current index to the first D in the sequenceWhen we encounter an Ireset the last known location of D. Nothing to move as the digit is correctly placed (as of now...) Start with the smallest number for len(s)+1 (say for DI, start with “123”) Now, starting with the second digit (index 1) and first character (D), iterate until end of the digits list, keeping track of the first D in a sequence of DsWhen we encounter a Dmove the digit at current index to the first D in the sequenceWhen we encounter an Ireset the last known location of D. Nothing to move as the digit is correctly placed (as of now...) When we encounter a Dmove the digit at current index to the first D in the sequenceWhen we encounter an Ireset the last known location of D. Nothing to move as the digit is correctly placed (as of now...) When we encounter a Dmove the digit at current index to the first D in the sequence When we encounter an Ireset the last known location of D. Nothing to move as the digit is correctly placed (as of now...) Below is the implementation of the above approach: C++ Java Python3 // c++ program to generate required sequence#include <iostream>#include <stdlib.h>#include <string>#include <vector>using namespace std; //:param s: a seq consisting only of 'D' and 'I' chars. D is//for decreasing and I for increasing :return: digits from//1-9 that fit the str. The number they repr should the min//such numbervector<string> didi_seq_gen(string s){ if (s.size() == 0) return {}; vector<string> base_list = { "1" }; for (int i = 2; i < s.size() + 2; i++) base_list.push_back(to_string(i)); int last_D = -1; for (int i = 1; i < base_list.size(); i++) { if (s[i - 1] == 'D') { if (last_D < 0) last_D = i - 1; string v = base_list[i]; base_list.erase(base_list.begin() + i); base_list.insert(base_list.begin() + last_D, v); } else last_D = -1; } return base_list;} int main(){ vector<string> inputs = { "IDID", "I", "DD", "II", "DIDI", "IIDDD", "DDIDDIID" }; for (auto x : inputs) { vector<string> ans = didi_seq_gen(x); for (auto i : ans) { cout << i; } cout << endl; } return 0;} // Java program to generate required sequenceimport java.util.*; public class Main { public static void main(String[] args) { String[] inputs = { "IDID", "I", "DD", "II", "DIDI", "IIDDD", "DDIDDIID" }; for (String x : inputs) { List<String> ans = didi_seq_gen(x); for (String i : ans) { System.out.print(i); } System.out.println(); } } //:param s: a seq consisting only of 'D' and 'I' chars. //D is for decreasing and I for increasing :return: // digits from 1-9 that fit the str. The number they repr // should the min such number public static List<String> didi_seq_gen(String s) { if (s.length() == 0) return new ArrayList<>(); List<String> base_list = new ArrayList<>(Arrays.asList("1")); for (int i = 2; i < s.length() + 2; i++) base_list.add(Integer.toString(i)); int last_D = -1; for (int i = 1; i < base_list.size(); i++) { if (s.charAt(i - 1) == 'D') { if (last_D < 0) last_D = i - 1; String v = base_list.get(i); base_list.remove(i); base_list.add(last_D, v); } else { last_D = -1; } } return base_list; }} // This code is contributed by Tapesh (tapeshdua420) # Python implementation of the above approach def didi_seq_gen(s: str): ''' :param s: a seq consisting only of 'D' and 'I' chars. D is for decreasing and I for increasing :return: digits from 1-9 that fit the str. The number they repr should the min such number :rtype: str example : for seq DII -> 2134 ''' if not s or len(s) <= 0: return "" base_list = ["1"] for i in range(1, len(s) + 1): base_list.append(f'{i + 1}') last_D = -1 for i in range(1, len(base_list)): if s[i - 1] == 'D': if last_D < 0: last_D = i - 1 v = base_list[i] del base_list[i] base_list.insert(last_D, v) else: last_D = -1 return base_list # Driver Code# Function callprint(didi_seq_gen("IDID"))print(didi_seq_gen("I"))print(didi_seq_gen("DD"))print(didi_seq_gen("II"))print(didi_seq_gen("DIDI"))print(didi_seq_gen("IIDDD"))print(didi_seq_gen("DDIDDIID" )) ['1', '3', '2', '5', '4'] ['1', '2'] ['3', '2', '1'] ['1', '2', '3'] ['2', '1', '4', '3', '5'] ['1', '2', '6', '5', '4', '3'] ['3', '2', '1', '6', '5', '4', '7', '9', '8'] Time Complexity: O(N) Auxiliary Space: O(N) Input: "DDDD" Output: "432156" For input 1, pattern is like, D -> D -> D -> D 5 4 3 2 1 Input: "DDDII" Output: "432156" For input 2, pattern is like, D -> D -> D -> I -> I 4 3 2 1 5 6 Input: "IIDIDIII" Output: "124365789" For input 3, pattern is like, I -> I -> D -> I -> D -> I -> I -> I 1 2 4 3 6 5 7 8 9 Think if the string contains only characters ‘I’ increasing, then there isn’t any problem you can just print and keep incrementing. Now think if the string contains only characters ‘D’ increasing, then you somehow have to get the number ‘D’ characters present from initial point, so that you can start from total count of ‘D’ and print by decrementing. The problem is when you encounter character ‘D’ after character ‘I’. Here somehow you have to get count of ‘D’ to get the next possible decremental start for ‘D’ and then print by decrementing until you have encountered all of ‘D’. Here in this approach the code has been made more modular compared to method 1 of space optimized version. C++ Java Python3 C# Javascript // This code illustrates to find minimum number following// pattern with optimized space and modular code.#include <bits/stdc++.h>using namespace std; // This function returns minimum number following// pattern of increasing or decreasing sequence.string findMinNumberPattern(string str){ string ans = ""; // Minimum number following pattern int i = 0; int cur = 1; // cur val following pattern int dCount = 0; // Count of char 'D' while (i < str.length()) { char ch = str[i]; // If 1st ch == 'I', incr and add to ans if (i == 0 && ch == 'I') { ans += to_string(cur); cur++; } // If cur char == 'D', // incr dCount as well, since we always // start counting for dCount from i+1 if (ch == 'D') { dCount++; } int j = i + 1; // Count 'D' from i+1 index while (j < str.length() && str[j] == 'D') { dCount++; j++; } int k = dCount; // Store dCount while (dCount >= 0) { ans += to_string(cur + dCount); dCount--; } cur += (k + 1); // Manages next cur val dCount = 0; i = j; } return ans;} int main(){ cout << (findMinNumberPattern("DIDID")) << endl; cout << (findMinNumberPattern("DIDIII")) << endl; cout << (findMinNumberPattern("DDDIIDI")) << endl; cout << (findMinNumberPattern("IDIDIID")) << endl; cout << (findMinNumberPattern("DIIDIDD")) << endl; cout << (findMinNumberPattern("IIDIDDD")) << endl; return 0;} // This code is contributed by suresh07. /*package whatever //do not write package name here */ // This code illustrates to find minimum number following// pattern with optimized space and modular code. import java.io.*; class GFG { // This function returns minimum number following // pattern of increasing or decreasing sequence. public static String findMinNumberPattern(String str) { String ans = ""; // Minimum number following pattern int i = 0; int cur = 1; // cur val following pattern int dCount = 0; // Count of char 'D' while (i < str.length()) { char ch = str.charAt(i); // If 1st ch == 'I', incr and add to ans if (i == 0 && ch == 'I') { ans += cur; cur++; } // If cur char == 'D', // incr dCount as well, since we always // start counting for dCount from i+1 if (ch == 'D') { dCount++; } int j = i + 1; // Count 'D' from i+1 index while (j < str.length() && str.charAt(j) == 'D') { dCount++; j++; } int k = dCount; // Store dCount while (dCount >= 0) { ans += (cur + dCount); dCount--; } cur += (k + 1); // Manages next cur val dCount = 0; i = j; } return ans; } public static void main(String[] args) { System.out.println(findMinNumberPattern("DIDID")); System.out.println(findMinNumberPattern("DIDIII")); System.out.println(findMinNumberPattern("DDDIIDI")); System.out.println(findMinNumberPattern("IDIDIID")); System.out.println(findMinNumberPattern("DIIDIDD")); System.out.println(findMinNumberPattern("IIDIDDD")); }} // This code is contributed by Arun M # This code illustrates to find minimum number following# pattern with optimized space and modular code. # This function returns minimum number following# pattern of increasing or decreasing sequence.def findMinNumberPattern(Str): ans = "" # Minimum number following pattern i = 0 cur = 1 # cur val following pattern dCount = 0 # Count of char 'D' while (i < len(Str)) : ch = Str[i] # If 1st ch == 'I', incr and add to ans if (i == 0 and ch == 'I') : ans += str(cur) cur+=1 # If cur char == 'D', # incr dCount as well, since we always # start counting for dCount from i+1 if (ch == 'D') : dCount+=1 j = i + 1 # Count 'D' from i+1 index while (j < len(Str) and Str[j] == 'D') : dCount+=1 j+=1 k = dCount # Store dCount while (dCount >= 0) : ans += str(cur + dCount) dCount-=1 cur += (k + 1) # Manages next cur val dCount = 0 i = j return ans print(findMinNumberPattern("DIDID"))print(findMinNumberPattern("DIDIII"))print(findMinNumberPattern("DDDIIDI"))print(findMinNumberPattern("IDIDIID"))print(findMinNumberPattern("DIIDIDD"))print(findMinNumberPattern("IIDIDDD")) # This code is contributed by mukesh07. // This code illustrates to find minimum number following// pattern with optimized space and modular code.using System;class GFG { // This function returns minimum number following // pattern of increasing or decreasing sequence. public static string findMinNumberPattern(string str) { string ans = ""; // Minimum number following pattern int i = 0; int cur = 1; // cur val following pattern int dCount = 0; // Count of char 'D' while (i < str.Length) { char ch = str[i]; // If 1st ch == 'I', incr and add to ans if (i == 0 && ch == 'I') { ans += cur; cur++; } // If cur char == 'D', // incr dCount as well, since we always // start counting for dCount from i+1 if (ch == 'D') { dCount++; } int j = i + 1; // Count 'D' from i+1 index while (j < str.Length && str[j] == 'D') { dCount++; j++; } int k = dCount; // Store dCount while (dCount >= 0) { ans += (cur + dCount); dCount--; } cur += (k + 1); // Manages next cur val dCount = 0; i = j; } return ans; } static void Main() { Console.WriteLine(findMinNumberPattern("DIDID")); Console.WriteLine(findMinNumberPattern("DIDIII")); Console.WriteLine(findMinNumberPattern("DDDIIDI")); Console.WriteLine(findMinNumberPattern("IDIDIID")); Console.WriteLine(findMinNumberPattern("DIIDIDD")); Console.WriteLine(findMinNumberPattern("IIDIDDD")); }} // This code is contributed by mukesh07. <script>// This code illustrates to find minimum number following// pattern with optimized space and modular code. // This function returns minimum number following // pattern of increasing or decreasing sequence.function findMinNumberPattern(str){ let ans = ""; // Minimum number following pattern let i = 0; let cur = 1; // cur val following pattern let dCount = 0; // Count of char 'D' while (i < str.length) { let ch = str[i]; // If 1st ch == 'I', incr and add to ans if (i == 0 && ch == 'I') { ans += cur; cur++; } // If cur char == 'D', // incr dCount as well, since we always // start counting for dCount from i+1 if (ch == 'D') { dCount++; } let j = i + 1; // Count 'D' from i+1 index while (j < str.length && str[j] == 'D') { dCount++; j++; } let k = dCount; // Store dCount while (dCount >= 0) { ans += (cur + dCount); dCount--; } cur += (k + 1); // Manages next cur val dCount = 0; i = j; } return ans;} document.write(findMinNumberPattern("DIDID")+"<br>");document.write(findMinNumberPattern("DIDIII")+"<br>");document.write(findMinNumberPattern("DDDIIDI")+"<br>");document.write(findMinNumberPattern("IDIDIID")+"<br>");document.write(findMinNumberPattern("DIIDIDD")+"<br>");document.write(findMinNumberPattern("IIDIDDD")+"<br>"); // This code is contributed by unknown2108</script> 214365 2143567 43215768 13254687 21354876 12438765 jit_t brijdesai6 princiraj1992 Rajput-Ji 29AjayKumar PranchalKatiyar rachana soma princi singh sanjeev2552 ayushmanglani1 avanitrachhadiya2155 harvinder bholowasia rameshtravel07 divyeshrabadiya07 decode2207 arun8778451315 ab2127 unknown2108 ruhelaa48 suresh07 mukesh07 arorakashish0911 repakaeswaripriya tapeshdua420 Amazon Goldman Sachs Arrays Stack Strings Amazon Goldman Sachs Arrays Strings Stack Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n29 Jun, 2022" }, { "code": null, "e": 249, "s": 52, "text": "Given a pattern containing only I’s and D’s. I for increasing and D for decreasing. Device an algorithm to print the minimum number following that pattern. Digits from 1-9 and digits can’t repeat." }, { "code": null, "e": 260, "s": 249, "text": "Examples: " }, { "code": null, "e": 486, "s": 260, "text": " Input: D Output: 21\n Input: I Output: 12\n Input: DD Output: 321\n Input: II Output: 123\n Input: DIDI Output: 21435\n Input: IIDDD Output: 126543\n Input: DDIDDIID Output: 321654798" }, { "code": null, "e": 520, "s": 486, "text": "Source: Amazon Interview Question" }, { "code": null, "e": 558, "s": 520, "text": "Below are some important observations" }, { "code": null, "e": 627, "s": 558, "text": "Since digits can’t repeat, there can be at most 9 digits in output. " }, { "code": null, "e": 784, "s": 627, "text": "Also, number of digits in output is one more than number of characters in input. Note that the first character of input corresponds to two digits in output." }, { "code": null, "e": 934, "s": 784, "text": "Idea is to iterate over input array and keep track of last printed digit and maximum digit printed so far. Below is the implementation of above idea." }, { "code": null, "e": 938, "s": 934, "text": "C++" }, { "code": null, "e": 943, "s": 938, "text": "Java" }, { "code": null, "e": 951, "s": 943, "text": "Python3" }, { "code": null, "e": 954, "s": 951, "text": "C#" }, { "code": null, "e": 958, "s": 954, "text": "PHP" }, { "code": null, "e": 969, "s": 958, "text": "Javascript" }, { "code": "// C++ program to print minimum number that can be formed// from a given sequence of Is and Ds#include <bits/stdc++.h>using namespace std; // Prints the minimum number that can be formed from// input sequence of I's and D'svoid PrintMinNumberForPattern(string arr){ // Initialize current_max (to make sure that // we don't use repeated character int curr_max = 0; // Initialize last_entry (Keeps track for // last printed digit) int last_entry = 0; int j; // Iterate over input array for (int i=0; i<arr.length(); i++) { // Initialize 'noOfNextD' to get count of // next D's available int noOfNextD = 0; switch(arr[i]) { case 'I': // If letter is 'I' // Calculate number of next consecutive D's // available j = i+1; while (arr[j] == 'D' && j < arr.length()) { noOfNextD++; j++; } if (i==0) { curr_max = noOfNextD + 2; // If 'I' is first letter, print incremented // sequence from 1 cout << \" \" << ++last_entry; cout << \" \" << curr_max; // Set max digit reached last_entry = curr_max; } else { // If not first letter // Get next digit to print curr_max = curr_max + noOfNextD + 1; // Print digit for I last_entry = curr_max; cout << \" \" << last_entry; } // For all next consecutive 'D' print // decremented sequence for (int k=0; k<noOfNextD; k++) { cout << \" \" << --last_entry; i++; } break; // If letter is 'D' case 'D': if (i == 0) { // If 'D' is first letter in sequence // Find number of Next D's available j = i+1; while (arr[j] == 'D' && j < arr.length()) { noOfNextD++; j++; } // Calculate first digit to print based on // number of consecutive D's curr_max = noOfNextD + 2; // Print twice for the first time cout << \" \" << curr_max << \" \" << curr_max - 1; // Store last entry last_entry = curr_max - 1; } else { // If current 'D' is not first letter // Decrement last_entry cout << \" \" << last_entry - 1; last_entry--; } break; } } cout << endl;} // Driver program to test aboveint main(){ PrintMinNumberForPattern(\"IDID\"); PrintMinNumberForPattern(\"I\"); PrintMinNumberForPattern(\"DD\"); PrintMinNumberForPattern(\"II\"); PrintMinNumberForPattern(\"DIDI\"); PrintMinNumberForPattern(\"IIDDD\"); PrintMinNumberForPattern(\"DDIDDIID\"); return 0;}", "e": 4102, "s": 969, "text": null }, { "code": "// Java program to print minimum number that can be formed// from a given sequence of Is and Dsclass GFG{ // Prints the minimum number that can be formed from // input sequence of I's and D's static void PrintMinNumberForPattern(String arr) { // Initialize current_max (to make sure that // we don't use repeated character int curr_max = 0; // Initialize last_entry (Keeps track for // last printed digit) int last_entry = 0; int j; // Iterate over input array for (int i = 0; i < arr.length(); i++) { // Initialize 'noOfNextD' to get count of // next D's available int noOfNextD = 0; switch (arr.charAt(i)) { case 'I': // If letter is 'I' // Calculate number of next consecutive D's // available j = i + 1; while (j < arr.length() && arr.charAt(j) == 'D') { noOfNextD++; j++; } if (i == 0) { curr_max = noOfNextD + 2; // If 'I' is first letter, print incremented // sequence from 1 System.out.print(\" \" + ++last_entry); System.out.print(\" \" + curr_max); // Set max digit reached last_entry = curr_max; } else { // If not first letter // Get next digit to print curr_max = curr_max + noOfNextD + 1; // Print digit for I last_entry = curr_max; System.out.print(\" \" + last_entry); } // For all next consecutive 'D' print // decremented sequence for (int k = 0; k < noOfNextD; k++) { System.out.print(\" \" + --last_entry); i++; } break; // If letter is 'D' case 'D': if (i == 0) { // If 'D' is first letter in sequence // Find number of Next D's available j = i + 1; while (j < arr.length()&&arr.charAt(j) == 'D') { noOfNextD++; j++; } // Calculate first digit to print based on // number of consecutive D's curr_max = noOfNextD + 2; // Print twice for the first time System.out.print(\" \" + curr_max + \" \" + (curr_max - 1)); // Store last entry last_entry = curr_max - 1; } else { // If current 'D' is not first letter // Decrement last_entry System.out.print(\" \" + (last_entry - 1)); last_entry--; } break; } } System.out.println(); } // Driver code public static void main(String[] args) { PrintMinNumberForPattern(\"IDID\"); PrintMinNumberForPattern(\"I\"); PrintMinNumberForPattern(\"DD\"); PrintMinNumberForPattern(\"II\"); PrintMinNumberForPattern(\"DIDI\"); PrintMinNumberForPattern(\"IIDDD\"); PrintMinNumberForPattern(\"DDIDDIID\"); }} // This code is contributed by Princi Singh", "e": 7996, "s": 4102, "text": null }, { "code": "# Python3 program to print minimum number that# can be formed from a given sequence of Is and Ds # Prints the minimum number that can be formed from# input sequence of I's and D'sdef PrintMinNumberForPattern(arr): # Initialize current_max (to make sure that # we don't use repeated character curr_max = 0 # Initialize last_entry (Keeps track for # last printed digit) last_entry = 0 i = 0 # Iterate over input array while i < len(arr): # Initialize 'noOfNextD' to get count of # next D's available noOfNextD = 0 if arr[i] == \"I\": # If letter is 'I' # Calculate number of next consecutive D's # available j = i + 1 while j < len(arr) and arr[j] == \"D\": noOfNextD += 1 j += 1 if i == 0: curr_max = noOfNextD + 2 last_entry += 1 # If 'I' is first letter, print incremented # sequence from 1 print(\"\", last_entry, end = \"\") print(\"\", curr_max, end = \"\") # Set max digit reached last_entry = curr_max else: # If not first letter # Get next digit to print curr_max += noOfNextD + 1 # Print digit for I last_entry = curr_max print(\"\", last_entry, end = \"\") # For all next consecutive 'D' print # decremented sequence for k in range(noOfNextD): last_entry -= 1 print(\"\", last_entry, end = \"\") i += 1 # If letter is 'D' elif arr[i] == \"D\": if i == 0: # If 'D' is first letter in sequence # Find number of Next D's available j = i + 1 while j < len(arr) and arr[j] == \"D\": noOfNextD += 1 j += 1 # Calculate first digit to print based on # number of consecutive D's curr_max = noOfNextD + 2 # Print twice for the first time print(\"\", curr_max, curr_max - 1, end = \"\") # Store last entry last_entry = curr_max - 1 else: # If current 'D' is not first letter # Decrement last_entry print(\"\", last_entry - 1, end = \"\") last_entry -= 1 i += 1 print() # Driver codeif __name__ == \"__main__\": PrintMinNumberForPattern(\"IDID\") PrintMinNumberForPattern(\"I\") PrintMinNumberForPattern(\"DD\") PrintMinNumberForPattern(\"II\") PrintMinNumberForPattern(\"DIDI\") PrintMinNumberForPattern(\"IIDDD\") PrintMinNumberForPattern(\"DDIDDIID\") # This code is contributed by# sanjeev2552", "e": 10842, "s": 7996, "text": null }, { "code": "// C# program to print minimum number that can be formed// from a given sequence of Is and Dsusing System; class GFG{ // Prints the minimum number that can be formed from // input sequence of I's and D's static void PrintMinNumberForPattern(String arr) { // Initialize current_max (to make sure that // we don't use repeated character int curr_max = 0; // Initialize last_entry (Keeps track for // last printed digit) int last_entry = 0; int j; // Iterate over input array for (int i = 0; i < arr.Length; i++) { // Initialize 'noOfNextD' to get count of // next D's available int noOfNextD = 0; switch (arr[i]) { case 'I': // If letter is 'I' // Calculate number of next consecutive D's // available j = i + 1; while (j < arr.Length && arr[j] == 'D') { noOfNextD++; j++; } if (i == 0) { curr_max = noOfNextD + 2; // If 'I' is first letter, print incremented // sequence from 1 Console.Write(\" \" + ++last_entry); Console.Write(\" \" + curr_max); // Set max digit reached last_entry = curr_max; } else { // If not first letter // Get next digit to print curr_max = curr_max + noOfNextD + 1; // Print digit for I last_entry = curr_max; Console.Write(\" \" + last_entry); } // For all next consecutive 'D' print // decremented sequence for (int k = 0; k < noOfNextD; k++) { Console.Write(\" \" + --last_entry); i++; } break; // If letter is 'D' case 'D': if (i == 0) { // If 'D' is first letter in sequence // Find number of Next D's available j = i + 1; while (j < arr.Length&&arr[j] == 'D') { noOfNextD++; j++; } // Calculate first digit to print based on // number of consecutive D's curr_max = noOfNextD + 2; // Print twice for the first time Console.Write(\" \" + curr_max + \" \" + (curr_max - 1)); // Store last entry last_entry = curr_max - 1; } else { // If current 'D' is not first letter // Decrement last_entry Console.Write(\" \" + (last_entry - 1)); last_entry--; } break; } } Console.WriteLine(); } // Driver code public static void Main(String[] args) { PrintMinNumberForPattern(\"IDID\"); PrintMinNumberForPattern(\"I\"); PrintMinNumberForPattern(\"DD\"); PrintMinNumberForPattern(\"II\"); PrintMinNumberForPattern(\"DIDI\"); PrintMinNumberForPattern(\"IIDDD\"); PrintMinNumberForPattern(\"DDIDDIID\"); }} // This code is contributed by Princi Singh", "e": 14706, "s": 10842, "text": null }, { "code": "<?php// PHP program to print minimum// number that can be formed// from a given sequence of// Is and Ds // Prints the minimum number// that can be formed from// input sequence of I's and D'sfunction PrintMinNumberForPattern($arr){ // Initialize current_max // (to make sure that // we don't use repeated // character $curr_max = 0; // Initialize last_entry // (Keeps track for // last printed digit) $last_entry = 0; $j; // Iterate over // input array for ($i = 0; $i < strlen($arr); $i++) { // Initialize 'noOfNextD' // to get count of // next D's available $noOfNextD = 0; switch($arr[$i]) { case 'I': // If letter is 'I' // Calculate number of // next consecutive D's // available $j = $i + 1; while ($arr[$j] == 'D' && $j < strlen($arr)) { $noOfNextD++; $j++; } if ($i == 0) { $curr_max = $noOfNextD + 2; // If 'I' is first letter, // print incremented // sequence from 1 echo \" \" , ++$last_entry; echo \" \" , $curr_max; // Set max // digit reached $last_entry = $curr_max; } else { // If not first letter // Get next digit // to print $curr_max = $curr_max + $noOfNextD + 1; // Print digit for I $last_entry = $curr_max; echo \" \" , $last_entry; } // For all next consecutive 'D' // print decremented sequence for ($k = 0; $k < $noOfNextD; $k++) { echo \" \" , --$last_entry; $i++; } break; // If letter is 'D' case 'D': if ($i == 0) { // If 'D' is first letter // in sequence. Find number // of Next D's available $j = $i+1; while (($arr[$j] == 'D') && ($j < strlen($arr))) { $noOfNextD++; $j++; } // Calculate first digit // to print based on // number of consecutive D's $curr_max = $noOfNextD + 2; // Print twice for // the first time echo \" \" , $curr_max , \" \" ,$curr_max - 1; // Store last entry $last_entry = $curr_max - 1; } else { // If current 'D' // is not first letter // Decrement last_entry echo \" \" , $last_entry - 1; $last_entry--; } break; } } echo \"\\n\";} // Driver CodePrintMinNumberForPattern(\"IDID\");PrintMinNumberForPattern(\"I\");PrintMinNumberForPattern(\"DD\");PrintMinNumberForPattern(\"II\");PrintMinNumberForPattern(\"DIDI\");PrintMinNumberForPattern(\"IIDDD\");PrintMinNumberForPattern(\"DDIDDIID\"); // This code is contributed by aj_36?>", "e": 18047, "s": 14706, "text": null }, { "code": "<script>// Javascript program to print minimum number that can be formed// from a given sequence of Is and Ds // Prints the minimum number that can be formed from // input sequence of I's and D'sfunction PrintMinNumberForPattern(arr){ // Initialize current_max (to make sure that // we don't use repeated character let curr_max = 0; // Initialize last_entry (Keeps track for // last printed digit) let last_entry = 0; let j; // Iterate over input array for (let i = 0; i < arr.length; i++) { // Initialize 'noOfNextD' to get count of // next D's available let noOfNextD = 0; switch (arr[i]) { case 'I': // If letter is 'I' // Calculate number of next consecutive D's // available j = i + 1; while (j < arr.length && arr[j] == 'D') { noOfNextD++; j++; } if (i == 0) { curr_max = noOfNextD + 2; // If 'I' is first letter, print incremented // sequence from 1 document.write(\" \" + ++last_entry); document.write(\" \" + curr_max); // Set max digit reached last_entry = curr_max; } else { // If not first letter // Get next digit to print curr_max = curr_max + noOfNextD + 1; // Print digit for I last_entry = curr_max; document.write(\" \" + last_entry); } // For all next consecutive 'D' print // decremented sequence for (let k = 0; k < noOfNextD; k++) { document.write(\" \" + --last_entry); i++; } break; // If letter is 'D' case 'D': if (i == 0) { // If 'D' is first letter in sequence // Find number of Next D's available j = i + 1; while (j < arr.length && arr[j] == 'D') { noOfNextD++; j++; } // Calculate first digit to print based on // number of consecutive D's curr_max = noOfNextD + 2; // Print twice for the first time document.write(\" \" + curr_max + \" \" + (curr_max - 1)); // Store last entry last_entry = curr_max - 1; } else { // If current 'D' is not first letter // Decrement last_entry document.write(\" \" + (last_entry - 1)); last_entry--; } break; } } document.write(\"<br>\");} // Driver codePrintMinNumberForPattern(\"IDID\");PrintMinNumberForPattern(\"I\");PrintMinNumberForPattern(\"DD\");PrintMinNumberForPattern(\"II\");PrintMinNumberForPattern(\"DIDI\");PrintMinNumberForPattern(\"IIDDD\");PrintMinNumberForPattern(\"DDIDDIID\"); // This code is contributed by ab2127</script>", "e": 21782, "s": 18047, "text": null }, { "code": null, "e": 21855, "s": 21782, "text": " 1 3 2 5 4\n 1 2\n 3 2 1\n 1 2 3\n 2 1 4 3 5\n 1 2 6 5 4 3\n 3 2 1 6 5 4 7 9 8" }, { "code": null, "e": 21903, "s": 21855, "text": "This solution is suggested by Swapnil Trambake." }, { "code": null, "e": 21977, "s": 21903, "text": "Alternate Solution: Let’s observe a few facts in case of minimum number: " }, { "code": null, "e": 22048, "s": 21977, "text": "The digits can’t repeat hence there can be 9 digits at most in output." }, { "code": null, "e": 22180, "s": 22048, "text": "To form a minimum number , at every index of the output, we are interested in the minimum number which can be placed at that index." }, { "code": null, "e": 22327, "s": 22180, "text": "The idea is to iterate over the entire input array , keeping track of the minimum number (1-9) which can be placed at that position of the output." }, { "code": null, "e": 22586, "s": 22327, "text": "The tricky part of course occurs when ‘D’ is encountered at index other than 0. In such a case we have to track the nearest ‘I’ to the left of ‘D’ and increment each number in the output vector by 1 in between ‘I’ and ‘D’. We cover the base case as follows: " }, { "code": null, "e": 22757, "s": 22586, "text": "If the first character of input is ‘I’ then we append 1 and 2 in the output vector and the minimum available number is set to 3 .The index of most recent ‘I’ is set to 1." }, { "code": null, "e": 22932, "s": 22757, "text": "If the first character of input is ‘D’ then we append 2 and 1 in the output vector and the minimum available number is set to 3, and the index of most recent ‘I’ is set to 0." }, { "code": null, "e": 22996, "s": 22932, "text": "Now we iterate the input string from index 1 till its end and: " }, { "code": null, "e": 23201, "s": 22996, "text": "If the character scanned is ‘I’ , a minimum value that has not been used yet is appended to the output vector .We increment the value of minimum no. available and index of most recent ‘I’ is also updated." }, { "code": null, "e": 23440, "s": 23201, "text": "If the character scanned is ‘D’ at index i of input array, we append the ith element from output vector in the output and track the nearest ‘I’ to the left of ‘D’ and increment each number in the output vector by 1 in between ‘I’ and ‘D’." }, { "code": null, "e": 23480, "s": 23440, "text": "Following is the program for the same: " }, { "code": null, "e": 23484, "s": 23480, "text": "C++" }, { "code": null, "e": 23489, "s": 23484, "text": "Java" }, { "code": null, "e": 23497, "s": 23489, "text": "Python3" }, { "code": null, "e": 23500, "s": 23497, "text": "C#" }, { "code": null, "e": 23511, "s": 23500, "text": "Javascript" }, { "code": "// C++ program to print minimum number that can be formed// from a given sequence of Is and Ds#include<bits/stdc++.h>using namespace std; void printLeast(string arr){ // min_avail represents the minimum number which is // still available for inserting in the output vector. // pos_of_I keeps track of the most recent index // where 'I' was encountered w.r.t the output vector int min_avail = 1, pos_of_I = 0; //vector to store the output vector<int>v; // cover the base cases if (arr[0]=='I') { v.push_back(1); v.push_back(2); min_avail = 3; pos_of_I = 1; } else { v.push_back(2); v.push_back(1); min_avail = 3; pos_of_I = 0; } // Traverse rest of the input for (int i=1; i<arr.length(); i++) { if (arr[i]=='I') { v.push_back(min_avail); min_avail++; pos_of_I = i+1; } else { v.push_back(v[i]); for (int j=pos_of_I; j<=i; j++) v[j]++; min_avail++; } } // print the number for (int i=0; i<v.size(); i++) cout << v[i] << \" \"; cout << endl;} // Driver program to check the above functionint main(){ printLeast(\"IDID\"); printLeast(\"I\"); printLeast(\"DD\"); printLeast(\"II\"); printLeast(\"DIDI\"); printLeast(\"IIDDD\"); printLeast(\"DDIDDIID\"); return 0;}", "e": 24934, "s": 23511, "text": null }, { "code": "// Java program to print minimum number that can be formed// from a given sequence of Is and Dsimport java.io.*;import java.util.*;public class GFG { static void printLeast(String arr) { // min_avail represents the minimum number which is // still available for inserting in the output vector. // pos_of_I keeps track of the most recent index // where 'I' was encountered w.r.t the output vector int min_avail = 1, pos_of_I = 0; //vector to store the output ArrayList<Integer> al = new ArrayList<>(); // cover the base cases if (arr.charAt(0) == 'I') { al.add(1); al.add(2); min_avail = 3; pos_of_I = 1; } else { al.add(2); al.add(1); min_avail = 3; pos_of_I = 0; } // Traverse rest of the input for (int i = 1; i < arr.length(); i++) { if (arr.charAt(i) == 'I') { al.add(min_avail); min_avail++; pos_of_I = i + 1; } else { al.add(al.get(i)); for (int j = pos_of_I; j <= i; j++) al.set(j, al.get(j) + 1); min_avail++; } } // print the number for (int i = 0; i < al.size(); i++) System.out.print(al.get(i) + \" \"); System.out.println(); } // Driver code public static void main(String args[]) { printLeast(\"IDID\"); printLeast(\"I\"); printLeast(\"DD\"); printLeast(\"II\"); printLeast(\"DIDI\"); printLeast(\"IIDDD\"); printLeast(\"DDIDDIID\"); }}// This code is contributed by rachana soma", "e": 27061, "s": 24934, "text": null }, { "code": "# Python3 program to print minimum number# that can be formed from a given sequence# of Is and Dsdef printLeast(arr): # min_avail represents the minimum # number which is still available # for inserting in the output vector. # pos_of_I keeps track of the most # recent index where 'I' was # encountered w.r.t the output vector min_avail = 1 pos_of_I = 0 # Vector to store the output v = [] # Cover the base cases if (arr[0] == 'I'): v.append(1) v.append(2) min_avail = 3 pos_of_I = 1 else: v.append(2) v.append(1) min_avail = 3 pos_of_I = 0 # Traverse rest of the input for i in range(1, len(arr)): if (arr[i] == 'I'): v.append(min_avail) min_avail += 1 pos_of_I = i + 1 else: v.append(v[i]) for j in range(pos_of_I, i + 1): v[j] += 1 min_avail += 1 # Print the number print(*v, sep = ' ') # Driver codeprintLeast(\"IDID\")printLeast(\"I\")printLeast(\"DD\")printLeast(\"II\")printLeast(\"DIDI\")printLeast(\"IIDDD\")printLeast(\"DDIDDIID\") # This code is contributed by avanitrachhadiya2155", "e": 28277, "s": 27061, "text": null }, { "code": "// C# program to print minimum number that can be formed// from a given sequence of Is and Dsusing System;using System.Collections.Generic; class GFG{ static void printLeast(String arr){ // min_avail represents the minimum number which is // still available for inserting in the output vector. // pos_of_I keeps track of the most recent index // where 'I' was encountered w.r.t the output vector int min_avail = 1, pos_of_I = 0; //vector to store the output List<int> al = new List<int>(); // cover the base cases if (arr[0] == 'I') { al.Add(1); al.Add(2); min_avail = 3; pos_of_I = 1; } else { al.Add(2); al.Add(1); min_avail = 3; pos_of_I = 0; } // Traverse rest of the input for (int i = 1; i < arr.Length; i++) { if (arr[i] == 'I') { al.Add(min_avail); min_avail++; pos_of_I = i + 1; } else { al.Add(al[i]); for (int j = pos_of_I; j <= i; j++) al[j] = al[j] + 1; min_avail++; } } // print the number for (int i = 0; i < al.Count; i++) Console.Write(al[i] + \" \"); Console.WriteLine();} // Driver codepublic static void Main(String []args){ printLeast(\"IDID\"); printLeast(\"I\"); printLeast(\"DD\"); printLeast(\"II\"); printLeast(\"DIDI\"); printLeast(\"IIDDD\"); printLeast(\"DDIDDIID\");}} // This code is contributed by Rajput-Ji", "e": 29790, "s": 28277, "text": null }, { "code": "<script> // Javascript program to print // minimum number that can be formed // from a given sequence of Is and Ds function printLeast(arr) { // min_avail represents the // minimum number which is // still available for inserting // in the output vector. // pos_of_I keeps track of the // most recent index // where 'I' was encountered // w.r.t the output vector let min_avail = 1, pos_of_I = 0; //vector to store the output let al = []; // cover the base cases if (arr[0] == 'I') { al.push(1); al.push(2); min_avail = 3; pos_of_I = 1; } else { al.push(2); al.push(1); min_avail = 3; pos_of_I = 0; } // Traverse rest of the input for (let i = 1; i < arr.length; i++) { if (arr[i] == 'I') { al.push(min_avail); min_avail++; pos_of_I = i + 1; } else { al.push(al[i]); for (let j = pos_of_I; j <= i; j++) al[j] = al[j] + 1; min_avail++; } } // print the number for (let i = 0; i < al.length; i++) document.write(al[i] + \" \"); document.write(\"</br>\"); } printLeast(\"IDID\"); printLeast(\"I\"); printLeast(\"DD\"); printLeast(\"II\"); printLeast(\"DIDI\"); printLeast(\"IIDDD\"); printLeast(\"DDIDDIID\"); </script>", "e": 31397, "s": 29790, "text": null }, { "code": null, "e": 31470, "s": 31397, "text": "1 3 2 5 4 \n1 2 \n3 2 1 \n1 2 3 \n2 1 4 3 5 \n1 2 6 5 4 3 \n3 2 1 6 5 4 7 9 8 " }, { "code": null, "e": 31976, "s": 31470, "text": "This solution is suggested by Ashutosh Kumar. Method 3 We can that when we encounter I, we got numbers in increasing order but if we encounter ‘D’, we want to have numbers in decreasing order. Length of the output string is always one more than the input string. So the loop is from 0 to the length of the string. We have to take numbers from 1-9 so we always push (i+1) to our stack. Then we check what is the resulting character at the specified index.So, there will be two cases which are as follows:- " }, { "code": null, "e": 32154, "s": 31976, "text": "Case 1: If we have encountered I or we are at the last character of input string, then pop from the stack and add it to the end of the output string until the stack gets empty. " }, { "code": null, "e": 32270, "s": 32154, "text": "Case 2: If we have encountered D, then we want the numbers in decreasing order. so we just push (i+1) to our stack." }, { "code": null, "e": 32274, "s": 32270, "text": "C++" }, { "code": null, "e": 32279, "s": 32274, "text": "Java" }, { "code": null, "e": 32287, "s": 32279, "text": "Python3" }, { "code": null, "e": 32290, "s": 32287, "text": "C#" }, { "code": null, "e": 32301, "s": 32290, "text": "Javascript" }, { "code": "// C++ program to print minimum number that can be formed// from a given sequence of Is and Ds#include <bits/stdc++.h>using namespace std; // Function to decode the given sequence to construct// minimum number without repeated digitsvoid PrintMinNumberForPattern(string seq){ // result store output string string result; // create an empty stack of integers stack<int> stk; // run n+1 times where n is length of input sequence for (int i = 0; i <= seq.length(); i++) { // push number i+1 into the stack stk.push(i + 1); // if all characters of the input sequence are // processed or current character is 'I' // (increasing) if (i == seq.length() || seq[i] == 'I') { // run till stack is empty while (!stk.empty()) { // remove top element from the stack and // add it to solution result += to_string(stk.top()); result += \" \"; stk.pop(); } } } cout << result << endl;} // main functionint main(){ PrintMinNumberForPattern(\"IDID\"); PrintMinNumberForPattern(\"I\"); PrintMinNumberForPattern(\"DD\"); PrintMinNumberForPattern(\"II\"); PrintMinNumberForPattern(\"DIDI\"); PrintMinNumberForPattern(\"IIDDD\"); PrintMinNumberForPattern(\"DDIDDIID\"); return 0;}", "e": 33674, "s": 32301, "text": null }, { "code": "import java.util.Stack; // Java program to print minimum number that can be formed// from a given sequence of Is and Dsclass GFG { // Function to decode the given sequence to construct// minimum number without repeated digits static void PrintMinNumberForPattern(String seq) { // result store output string String result = \"\"; // create an empty stack of integers Stack<Integer> stk = new Stack<Integer>(); // run n+1 times where n is length of input sequence for (int i = 0; i <= seq.length(); i++) { // push number i+1 into the stack stk.push(i + 1); // if all characters of the input sequence are // processed or current character is 'I' // (increasing) if (i == seq.length() || seq.charAt(i) == 'I') { // run till stack is empty while (!stk.empty()) { // remove top element from the stack and // add it to solution result += String.valueOf(stk.peek()); result += \" \"; stk.pop(); } } } System.out.println(result); } // main function public static void main(String[] args) { PrintMinNumberForPattern(\"IDID\"); PrintMinNumberForPattern(\"I\"); PrintMinNumberForPattern(\"DD\"); PrintMinNumberForPattern(\"II\"); PrintMinNumberForPattern(\"DIDI\"); PrintMinNumberForPattern(\"IIDDD\"); PrintMinNumberForPattern(\"DDIDDIID\"); }}// This code is contributed by PrinciRaj1992", "e": 35272, "s": 33674, "text": null }, { "code": "# Python3 program to print minimum# number that can be formed from a# given sequence of Is and Dsdef PrintMinNumberForPattern(Strr): # Take a List to work as Stack stack = [] # String for storing result res = '' # run n+1 times where n is length # of input sequence, As length of # result string is always 1 greater for i in range(len(Strr) + 1): # Push number i+1 into the stack stack.append(i + 1) # If all characters of the input # sequence are processed or current # character is 'I if (i == len(Strr) or Strr[i] == 'I'): # Run While Loop Until stack is empty while len(stack) > 0: # pop the element on top of stack # And store it in result String res += str(stack.pop()) res += ' ' # Print the result print(res) # Driver CodePrintMinNumberForPattern(\"IDID\")PrintMinNumberForPattern(\"I\")PrintMinNumberForPattern(\"DD\")PrintMinNumberForPattern(\"II\")PrintMinNumberForPattern(\"DIDI\")PrintMinNumberForPattern(\"IIDDD\")PrintMinNumberForPattern(\"DDIDDIID\") # This code is contributed by AyushManglani", "e": 36467, "s": 35272, "text": null }, { "code": "// C# program to print minimum number that can be formed// from a given sequence of Is and Dsusing System;using System.Collections;public class GFG { // Function to decode the given sequence to construct// minimum number without repeated digits static void PrintMinNumberForPattern(String seq) { // result store output string String result = \"\"; // create an empty stack of integers Stack stk = new Stack(); // run n+1 times where n is length of input sequence for (int i = 0; i <= seq.Length; i++) { // push number i+1 into the stack stk.Push(i + 1); // if all characters of the input sequence are // processed or current character is 'I' // (increasing) if (i == seq.Length || seq[i] == 'I') { // run till stack is empty while (stk.Count!=0) { // remove top element from the stack and // add it to solution result += String.Join(\"\",stk.Peek()); result += \" \"; stk.Pop(); } } } Console.WriteLine(result); } // main function public static void Main() { PrintMinNumberForPattern(\"IDID\"); PrintMinNumberForPattern(\"I\"); PrintMinNumberForPattern(\"DD\"); PrintMinNumberForPattern(\"II\"); PrintMinNumberForPattern(\"DIDI\"); PrintMinNumberForPattern(\"IIDDD\"); PrintMinNumberForPattern(\"DDIDDIID\"); }}// This code is contributed by 29AjayKumar", "e": 38045, "s": 36467, "text": null }, { "code": "<script> // Javascript program to print // minimum number that can be formed // from a given sequence of Is and Ds // Function to decode the given // sequence to construct // minimum number without repeated digits function PrintMinNumberForPattern(seq) { // result store output string let result = \"\"; // create an empty stack of integers let stk = []; // run n+1 times where n is length // of input sequence for (let i = 0; i <= seq.length; i++) { // push number i+1 into the stack stk.push(i + 1); // if all characters of the input // sequence are // processed or current character is 'I' // (increasing) if (i == seq.length || seq[i] == 'I') { // run till stack is empty while (stk.length!=0) { // remove top element from // the stack and // add it to solution result += (stk[stk.length - 1]).toString(); result += \" \"; stk.pop(); } } } document.write(result + \"</br>\"); } PrintMinNumberForPattern(\"IDID\"); PrintMinNumberForPattern(\"I\"); PrintMinNumberForPattern(\"DD\"); PrintMinNumberForPattern(\"II\"); PrintMinNumberForPattern(\"DIDI\"); PrintMinNumberForPattern(\"IIDDD\"); PrintMinNumberForPattern(\"DDIDDIID\"); </script>", "e": 39562, "s": 38045, "text": null }, { "code": null, "e": 39635, "s": 39562, "text": "1 3 2 5 4 \n1 2 \n3 2 1 \n1 2 3 \n2 1 4 3 5 \n1 2 6 5 4 3 \n3 2 1 6 5 4 7 9 8 " }, { "code": null, "e": 39725, "s": 39635, "text": "Time Complexity: O(n) Auxiliary Space: O(n)This method is contributed by Roshni Agarwal. " }, { "code": null, "e": 39768, "s": 39725, "text": "Method 4 (Using two pointers) Observation " }, { "code": null, "e": 40220, "s": 39768, "text": "Since we have to find a minimum number without repeating digits, maximum length of output can be 9 (using each 1-9 digits once)Length of the output will be exactly one greater than input length.The idea is to iterate over the string and do the following if current character is ‘I’ or string is ended. Assign count in increasing order to each element from current-1 to the next left index of ‘I’ (or starting index is reached).Increase the count by 1." }, { "code": null, "e": 40348, "s": 40220, "text": "Since we have to find a minimum number without repeating digits, maximum length of output can be 9 (using each 1-9 digits once)" }, { "code": null, "e": 40416, "s": 40348, "text": "Length of the output will be exactly one greater than input length." }, { "code": null, "e": 40674, "s": 40416, "text": "The idea is to iterate over the string and do the following if current character is ‘I’ or string is ended. Assign count in increasing order to each element from current-1 to the next left index of ‘I’ (or starting index is reached).Increase the count by 1." }, { "code": null, "e": 40824, "s": 40674, "text": "Assign count in increasing order to each element from current-1 to the next left index of ‘I’ (or starting index is reached).Increase the count by 1." }, { "code": null, "e": 40950, "s": 40824, "text": "Assign count in increasing order to each element from current-1 to the next left index of ‘I’ (or starting index is reached)." }, { "code": null, "e": 40975, "s": 40950, "text": "Increase the count by 1." }, { "code": null, "e": 41187, "s": 40975, "text": "Input : IDID\nOutput : 13254\n\nInput : I\nOutput : 12\n\nInput : DD\nOutput : 321\n\nInput : II\nOutput : 123\n\nInput : DIDI\nOutput : 21435\n\nInput : IIDDD\nOutput : 126543\n\nInput : DDIDDIID\nOutput : 321654798" }, { "code": null, "e": 41234, "s": 41187, "text": "Below is the implementation of above approach:" }, { "code": null, "e": 41238, "s": 41234, "text": "C++" }, { "code": null, "e": 41243, "s": 41238, "text": "Java" }, { "code": null, "e": 41251, "s": 41243, "text": "Python3" }, { "code": null, "e": 41254, "s": 41251, "text": "C#" }, { "code": null, "e": 41265, "s": 41254, "text": "Javascript" }, { "code": "// C++ program of above approach#include <bits/stdc++.h>using namespace std; // Returns minimum number made from given sequence without repeating digitsstring getMinNumberForPattern(string seq){ int n = seq.length(); if (n >= 9) return \"-1\"; string result(n+1, ' '); int count = 1; // The loop runs for each input character as well as // one additional time for assigning rank to remaining characters for (int i = 0; i <= n; i++) { if (i == n || seq[i] == 'I') { for (int j = i - 1 ; j >= -1 ; j--) { result[j + 1] = '0' + count++; if(j >= 0 && seq[j] == 'I') break; } } } return result;} // main functionint main(){ string inputs[] = {\"IDID\", \"I\", \"DD\", \"II\", \"DIDI\", \"IIDDD\", \"DDIDDIID\"}; for (string input : inputs) { cout << getMinNumberForPattern(input) << \"\\n\"; } return 0;}", "e": 42218, "s": 41265, "text": null }, { "code": "// Java program of above approachimport java.io.IOException; public class Test{ // Returns minimum number made from given sequence without repeating digits static String getMinNumberForPattern(String seq) { int n = seq.length(); if (n >= 9) return \"-1\"; char result[] = new char[n + 1]; int count = 1; // The loop runs for each input character as well as // one additional time for assigning rank to each remaining characters for (int i = 0; i <= n; i++) { if (i == n || seq.charAt(i) == 'I') { for (int j = i - 1; j >= -1; j--) { result[j + 1] = (char) ((int) '0' + count++); if (j >= 0 && seq.charAt(j) == 'I') break; } } } return new String(result); } public static void main(String[] args) throws IOException { String inputs[] = { \"IDID\", \"I\", \"DD\", \"II\", \"DIDI\", \"IIDDD\", \"DDIDDIID\" }; for(String input : inputs) { System.out.println(getMinNumberForPattern(input)); } }}", "e": 43384, "s": 42218, "text": null }, { "code": "# Python3 program of above approach # Returns minimum number made from# given sequence without repeating digitsdef getMinNumberForPattern(seq): n = len(seq) if (n >= 9): return \"-1\" result = [None] * (n + 1) count = 1 # The loop runs for each input character # as well as one additional time for # assigning rank to remaining characters for i in range(n + 1): if (i == n or seq[i] == 'I'): for j in range(i - 1, -2, -1): result[j + 1] = int('0' + str(count)) count += 1 if(j >= 0 and seq[j] == 'I'): break return result # Driver Codeif __name__ == '__main__': inputs = [\"IDID\", \"I\", \"DD\", \"II\", \"DIDI\", \"IIDDD\", \"DDIDDIID\"] for Input in inputs: print(*(getMinNumberForPattern(Input))) # This code is contributed by PranchalK", "e": 44263, "s": 43384, "text": null }, { "code": "// C# program of above approachusing System;class GFG{ // Returns minimum number made from given// sequence without repeating digitsstatic String getMinNumberForPattern(String seq){ int n = seq.Length; if (n >= 9) return \"-1\"; char []result = new char[n + 1]; int count = 1; // The loop runs for each input character // as well as one additional time for // assigning rank to each remaining characters for (int i = 0; i <= n; i++) { if (i == n || seq[i] == 'I') { for (int j = i - 1; j >= -1; j--) { result[j + 1] = (char) ((int) '0' + count++); if (j >= 0 && seq[j] == 'I') break; } } } return new String(result);} // Driver Codepublic static void Main(){ String []inputs = { \"IDID\", \"I\", \"DD\", \"II\", \"DIDI\", \"IIDDD\", \"DDIDDIID\" }; foreach(String input in inputs) { Console.WriteLine(getMinNumberForPattern(input)); }}} // This code is contributed by Rajput-Ji", "e": 45319, "s": 44263, "text": null }, { "code": "<script> // Javascript program of above approach // Returns minimum number made from given // sequence without repeating digits function getMinNumberForPattern(seq) { let n = seq.length; if (n >= 9) return \"-1\"; let result = new Array(n + 1); let count = 1; // The loop runs for each input character // as well as one additional time for // assigning rank to each remaining characters for (let i = 0; i <= n; i++) { if (i == n || seq[i] == 'I') { for (let j = i - 1; j >= -1; j--) { result[j + 1] = String.fromCharCode('0'.charCodeAt() + count++); if (j >= 0 && seq[j] == 'I') break; } } } return result.join(\"\"); } let inputs = [ \"IDID\", \"I\", \"DD\", \"II\", \"DIDI\", \"IIDDD\", \"DDIDDIID\" ]; for(let input = 0; input < inputs.length; input++) { document.write( getMinNumberForPattern(inputs[input]) + \"</br>\"); } </script>", "e": 46466, "s": 45319, "text": null }, { "code": null, "e": 46506, "s": 46466, "text": "13254\n12\n321\n123\n21435\n126543\n321654798" }, { "code": null, "e": 46714, "s": 46506, "text": "Time Complexity: O(N) Auxiliary Space: O(N)This solution is suggested by Brij Desai.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 46749, "s": 46714, "text": "Method 5 (Start with the Smallest)" }, { "code": null, "e": 46918, "s": 46749, "text": "Start with the smallest number as the answer and keep shifting the digits when we encounter a D. There is no need to traverse back for the index.Follow the below steps," }, { "code": null, "e": 47354, "s": 46918, "text": "Start with the smallest number for len(s)+1 (say for DI, start with “123”)Now, starting with the second digit (index 1) and first character (D), iterate until end of the digits list, keeping track of the first D in a sequence of DsWhen we encounter a Dmove the digit at current index to the first D in the sequenceWhen we encounter an Ireset the last known location of D. Nothing to move as the digit is correctly placed (as of now...)" }, { "code": null, "e": 47429, "s": 47354, "text": "Start with the smallest number for len(s)+1 (say for DI, start with “123”)" }, { "code": null, "e": 47791, "s": 47429, "text": "Now, starting with the second digit (index 1) and first character (D), iterate until end of the digits list, keeping track of the first D in a sequence of DsWhen we encounter a Dmove the digit at current index to the first D in the sequenceWhen we encounter an Ireset the last known location of D. Nothing to move as the digit is correctly placed (as of now...)" }, { "code": null, "e": 47996, "s": 47791, "text": "When we encounter a Dmove the digit at current index to the first D in the sequenceWhen we encounter an Ireset the last known location of D. Nothing to move as the digit is correctly placed (as of now...)" }, { "code": null, "e": 48080, "s": 47996, "text": "When we encounter a Dmove the digit at current index to the first D in the sequence" }, { "code": null, "e": 48202, "s": 48080, "text": "When we encounter an Ireset the last known location of D. Nothing to move as the digit is correctly placed (as of now...)" }, { "code": null, "e": 48253, "s": 48202, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 48257, "s": 48253, "text": "C++" }, { "code": null, "e": 48262, "s": 48257, "text": "Java" }, { "code": null, "e": 48270, "s": 48262, "text": "Python3" }, { "code": "// c++ program to generate required sequence#include <iostream>#include <stdlib.h>#include <string>#include <vector>using namespace std; //:param s: a seq consisting only of 'D' and 'I' chars. D is//for decreasing and I for increasing :return: digits from//1-9 that fit the str. The number they repr should the min//such numbervector<string> didi_seq_gen(string s){ if (s.size() == 0) return {}; vector<string> base_list = { \"1\" }; for (int i = 2; i < s.size() + 2; i++) base_list.push_back(to_string(i)); int last_D = -1; for (int i = 1; i < base_list.size(); i++) { if (s[i - 1] == 'D') { if (last_D < 0) last_D = i - 1; string v = base_list[i]; base_list.erase(base_list.begin() + i); base_list.insert(base_list.begin() + last_D, v); } else last_D = -1; } return base_list;} int main(){ vector<string> inputs = { \"IDID\", \"I\", \"DD\", \"II\", \"DIDI\", \"IIDDD\", \"DDIDDIID\" }; for (auto x : inputs) { vector<string> ans = didi_seq_gen(x); for (auto i : ans) { cout << i; } cout << endl; } return 0;}", "e": 49469, "s": 48270, "text": null }, { "code": "// Java program to generate required sequenceimport java.util.*; public class Main { public static void main(String[] args) { String[] inputs = { \"IDID\", \"I\", \"DD\", \"II\", \"DIDI\", \"IIDDD\", \"DDIDDIID\" }; for (String x : inputs) { List<String> ans = didi_seq_gen(x); for (String i : ans) { System.out.print(i); } System.out.println(); } } //:param s: a seq consisting only of 'D' and 'I' chars. //D is for decreasing and I for increasing :return: // digits from 1-9 that fit the str. The number they repr // should the min such number public static List<String> didi_seq_gen(String s) { if (s.length() == 0) return new ArrayList<>(); List<String> base_list = new ArrayList<>(Arrays.asList(\"1\")); for (int i = 2; i < s.length() + 2; i++) base_list.add(Integer.toString(i)); int last_D = -1; for (int i = 1; i < base_list.size(); i++) { if (s.charAt(i - 1) == 'D') { if (last_D < 0) last_D = i - 1; String v = base_list.get(i); base_list.remove(i); base_list.add(last_D, v); } else { last_D = -1; } } return base_list; }} // This code is contributed by Tapesh (tapeshdua420)", "e": 50904, "s": 49469, "text": null }, { "code": "# Python implementation of the above approach def didi_seq_gen(s: str): ''' :param s: a seq consisting only of 'D' and 'I' chars. D is for decreasing and I for increasing :return: digits from 1-9 that fit the str. The number they repr should the min such number :rtype: str example : for seq DII -> 2134 ''' if not s or len(s) <= 0: return \"\" base_list = [\"1\"] for i in range(1, len(s) + 1): base_list.append(f'{i + 1}') last_D = -1 for i in range(1, len(base_list)): if s[i - 1] == 'D': if last_D < 0: last_D = i - 1 v = base_list[i] del base_list[i] base_list.insert(last_D, v) else: last_D = -1 return base_list # Driver Code# Function callprint(didi_seq_gen(\"IDID\"))print(didi_seq_gen(\"I\"))print(didi_seq_gen(\"DD\"))print(didi_seq_gen(\"II\"))print(didi_seq_gen(\"DIDI\"))print(didi_seq_gen(\"IIDDD\"))print(didi_seq_gen(\"DDIDDIID\" ))", "e": 51884, "s": 50904, "text": null }, { "code": null, "e": 52056, "s": 51884, "text": "['1', '3', '2', '5', '4']\n['1', '2']\n['3', '2', '1']\n['1', '2', '3']\n['2', '1', '4', '3', '5']\n['1', '2', '6', '5', '4', '3']\n['3', '2', '1', '6', '5', '4', '7', '9', '8']" }, { "code": null, "e": 52100, "s": 52056, "text": "Time Complexity: O(N) Auxiliary Space: O(N)" }, { "code": null, "e": 52607, "s": 52100, "text": "Input: \"DDDD\"\nOutput: \"432156\"\n\nFor input 1, pattern is like, D -> D -> D -> D\n 5 4 3 2 1\n \nInput: \"DDDII\"\nOutput: \"432156\"\n\nFor input 2, pattern is like, D -> D -> D -> I -> I\n 4 3 2 1 5 6\n\n\nInput: \"IIDIDIII\"\nOutput: \"124365789\"\n\nFor input 3, pattern is like, I -> I -> D -> I -> D -> I -> I -> I\n 1 2 4 3 6 5 7 8 9 " }, { "code": null, "e": 52739, "s": 52607, "text": "Think if the string contains only characters ‘I’ increasing, then there isn’t any problem you can just print and keep incrementing." }, { "code": null, "e": 52960, "s": 52739, "text": "Now think if the string contains only characters ‘D’ increasing, then you somehow have to get the number ‘D’ characters present from initial point, so that you can start from total count of ‘D’ and print by decrementing." }, { "code": null, "e": 53192, "s": 52960, "text": "The problem is when you encounter character ‘D’ after character ‘I’. Here somehow you have to get count of ‘D’ to get the next possible decremental start for ‘D’ and then print by decrementing until you have encountered all of ‘D’." }, { "code": null, "e": 53299, "s": 53192, "text": "Here in this approach the code has been made more modular compared to method 1 of space optimized version." }, { "code": null, "e": 53303, "s": 53299, "text": "C++" }, { "code": null, "e": 53308, "s": 53303, "text": "Java" }, { "code": null, "e": 53316, "s": 53308, "text": "Python3" }, { "code": null, "e": 53319, "s": 53316, "text": "C#" }, { "code": null, "e": 53330, "s": 53319, "text": "Javascript" }, { "code": "// This code illustrates to find minimum number following// pattern with optimized space and modular code.#include <bits/stdc++.h>using namespace std; // This function returns minimum number following// pattern of increasing or decreasing sequence.string findMinNumberPattern(string str){ string ans = \"\"; // Minimum number following pattern int i = 0; int cur = 1; // cur val following pattern int dCount = 0; // Count of char 'D' while (i < str.length()) { char ch = str[i]; // If 1st ch == 'I', incr and add to ans if (i == 0 && ch == 'I') { ans += to_string(cur); cur++; } // If cur char == 'D', // incr dCount as well, since we always // start counting for dCount from i+1 if (ch == 'D') { dCount++; } int j = i + 1; // Count 'D' from i+1 index while (j < str.length() && str[j] == 'D') { dCount++; j++; } int k = dCount; // Store dCount while (dCount >= 0) { ans += to_string(cur + dCount); dCount--; } cur += (k + 1); // Manages next cur val dCount = 0; i = j; } return ans;} int main(){ cout << (findMinNumberPattern(\"DIDID\")) << endl; cout << (findMinNumberPattern(\"DIDIII\")) << endl; cout << (findMinNumberPattern(\"DDDIIDI\")) << endl; cout << (findMinNumberPattern(\"IDIDIID\")) << endl; cout << (findMinNumberPattern(\"DIIDIDD\")) << endl; cout << (findMinNumberPattern(\"IIDIDDD\")) << endl; return 0;} // This code is contributed by suresh07.", "e": 54954, "s": 53330, "text": null }, { "code": "/*package whatever //do not write package name here */ // This code illustrates to find minimum number following// pattern with optimized space and modular code. import java.io.*; class GFG { // This function returns minimum number following // pattern of increasing or decreasing sequence. public static String findMinNumberPattern(String str) { String ans = \"\"; // Minimum number following pattern int i = 0; int cur = 1; // cur val following pattern int dCount = 0; // Count of char 'D' while (i < str.length()) { char ch = str.charAt(i); // If 1st ch == 'I', incr and add to ans if (i == 0 && ch == 'I') { ans += cur; cur++; } // If cur char == 'D', // incr dCount as well, since we always // start counting for dCount from i+1 if (ch == 'D') { dCount++; } int j = i + 1; // Count 'D' from i+1 index while (j < str.length() && str.charAt(j) == 'D') { dCount++; j++; } int k = dCount; // Store dCount while (dCount >= 0) { ans += (cur + dCount); dCount--; } cur += (k + 1); // Manages next cur val dCount = 0; i = j; } return ans; } public static void main(String[] args) { System.out.println(findMinNumberPattern(\"DIDID\")); System.out.println(findMinNumberPattern(\"DIDIII\")); System.out.println(findMinNumberPattern(\"DDDIIDI\")); System.out.println(findMinNumberPattern(\"IDIDIID\")); System.out.println(findMinNumberPattern(\"DIIDIDD\")); System.out.println(findMinNumberPattern(\"IIDIDDD\")); }} // This code is contributed by Arun M", "e": 56833, "s": 54954, "text": null }, { "code": "# This code illustrates to find minimum number following# pattern with optimized space and modular code. # This function returns minimum number following# pattern of increasing or decreasing sequence.def findMinNumberPattern(Str): ans = \"\" # Minimum number following pattern i = 0 cur = 1 # cur val following pattern dCount = 0 # Count of char 'D' while (i < len(Str)) : ch = Str[i] # If 1st ch == 'I', incr and add to ans if (i == 0 and ch == 'I') : ans += str(cur) cur+=1 # If cur char == 'D', # incr dCount as well, since we always # start counting for dCount from i+1 if (ch == 'D') : dCount+=1 j = i + 1 # Count 'D' from i+1 index while (j < len(Str) and Str[j] == 'D') : dCount+=1 j+=1 k = dCount # Store dCount while (dCount >= 0) : ans += str(cur + dCount) dCount-=1 cur += (k + 1) # Manages next cur val dCount = 0 i = j return ans print(findMinNumberPattern(\"DIDID\"))print(findMinNumberPattern(\"DIDIII\"))print(findMinNumberPattern(\"DDDIIDI\"))print(findMinNumberPattern(\"IDIDIID\"))print(findMinNumberPattern(\"DIIDIDD\"))print(findMinNumberPattern(\"IIDIDDD\")) # This code is contributed by mukesh07.", "e": 58174, "s": 56833, "text": null }, { "code": "// This code illustrates to find minimum number following// pattern with optimized space and modular code.using System;class GFG { // This function returns minimum number following // pattern of increasing or decreasing sequence. public static string findMinNumberPattern(string str) { string ans = \"\"; // Minimum number following pattern int i = 0; int cur = 1; // cur val following pattern int dCount = 0; // Count of char 'D' while (i < str.Length) { char ch = str[i]; // If 1st ch == 'I', incr and add to ans if (i == 0 && ch == 'I') { ans += cur; cur++; } // If cur char == 'D', // incr dCount as well, since we always // start counting for dCount from i+1 if (ch == 'D') { dCount++; } int j = i + 1; // Count 'D' from i+1 index while (j < str.Length && str[j] == 'D') { dCount++; j++; } int k = dCount; // Store dCount while (dCount >= 0) { ans += (cur + dCount); dCount--; } cur += (k + 1); // Manages next cur val dCount = 0; i = j; } return ans; } static void Main() { Console.WriteLine(findMinNumberPattern(\"DIDID\")); Console.WriteLine(findMinNumberPattern(\"DIDIII\")); Console.WriteLine(findMinNumberPattern(\"DDDIIDI\")); Console.WriteLine(findMinNumberPattern(\"IDIDIID\")); Console.WriteLine(findMinNumberPattern(\"DIIDIDD\")); Console.WriteLine(findMinNumberPattern(\"IIDIDDD\")); }} // This code is contributed by mukesh07.", "e": 59937, "s": 58174, "text": null }, { "code": "<script>// This code illustrates to find minimum number following// pattern with optimized space and modular code. // This function returns minimum number following // pattern of increasing or decreasing sequence.function findMinNumberPattern(str){ let ans = \"\"; // Minimum number following pattern let i = 0; let cur = 1; // cur val following pattern let dCount = 0; // Count of char 'D' while (i < str.length) { let ch = str[i]; // If 1st ch == 'I', incr and add to ans if (i == 0 && ch == 'I') { ans += cur; cur++; } // If cur char == 'D', // incr dCount as well, since we always // start counting for dCount from i+1 if (ch == 'D') { dCount++; } let j = i + 1; // Count 'D' from i+1 index while (j < str.length && str[j] == 'D') { dCount++; j++; } let k = dCount; // Store dCount while (dCount >= 0) { ans += (cur + dCount); dCount--; } cur += (k + 1); // Manages next cur val dCount = 0; i = j; } return ans;} document.write(findMinNumberPattern(\"DIDID\")+\"<br>\");document.write(findMinNumberPattern(\"DIDIII\")+\"<br>\");document.write(findMinNumberPattern(\"DDDIIDI\")+\"<br>\");document.write(findMinNumberPattern(\"IDIDIID\")+\"<br>\");document.write(findMinNumberPattern(\"DIIDIDD\")+\"<br>\");document.write(findMinNumberPattern(\"IIDIDDD\")+\"<br>\"); // This code is contributed by unknown2108</script>", "e": 61619, "s": 59937, "text": null }, { "code": null, "e": 61670, "s": 61619, "text": "214365\n2143567\n43215768\n13254687\n21354876\n12438765" }, { "code": null, "e": 61676, "s": 61670, "text": "jit_t" }, { "code": null, "e": 61687, "s": 61676, "text": "brijdesai6" }, { "code": null, "e": 61701, "s": 61687, "text": "princiraj1992" }, { "code": null, "e": 61711, "s": 61701, "text": "Rajput-Ji" }, { "code": null, "e": 61723, "s": 61711, "text": "29AjayKumar" }, { "code": null, "e": 61739, "s": 61723, "text": "PranchalKatiyar" }, { "code": null, "e": 61752, "s": 61739, "text": "rachana soma" }, { "code": null, "e": 61765, "s": 61752, "text": "princi singh" }, { "code": null, "e": 61777, "s": 61765, "text": "sanjeev2552" }, { "code": null, "e": 61792, "s": 61777, "text": "ayushmanglani1" }, { "code": null, "e": 61813, "s": 61792, "text": "avanitrachhadiya2155" }, { "code": null, "e": 61834, "s": 61813, "text": "harvinder bholowasia" }, { "code": null, "e": 61849, "s": 61834, "text": "rameshtravel07" }, { "code": null, "e": 61867, "s": 61849, "text": "divyeshrabadiya07" }, { "code": null, "e": 61878, "s": 61867, "text": "decode2207" }, { "code": null, "e": 61893, "s": 61878, "text": "arun8778451315" }, { "code": null, "e": 61900, "s": 61893, "text": "ab2127" }, { "code": null, "e": 61912, "s": 61900, "text": "unknown2108" }, { "code": null, "e": 61922, "s": 61912, "text": "ruhelaa48" }, { "code": null, "e": 61931, "s": 61922, "text": "suresh07" }, { "code": null, "e": 61940, "s": 61931, "text": "mukesh07" }, { "code": null, "e": 61957, "s": 61940, "text": "arorakashish0911" }, { "code": null, "e": 61975, "s": 61957, "text": "repakaeswaripriya" }, { "code": null, "e": 61988, "s": 61975, "text": "tapeshdua420" }, { "code": null, "e": 61995, "s": 61988, "text": "Amazon" }, { "code": null, "e": 62009, "s": 61995, "text": "Goldman Sachs" }, { "code": null, "e": 62016, "s": 62009, "text": "Arrays" }, { "code": null, "e": 62022, "s": 62016, "text": "Stack" }, { "code": null, "e": 62030, "s": 62022, "text": "Strings" }, { "code": null, "e": 62037, "s": 62030, "text": "Amazon" }, { "code": null, "e": 62051, "s": 62037, "text": "Goldman Sachs" }, { "code": null, "e": 62058, "s": 62051, "text": "Arrays" }, { "code": null, "e": 62066, "s": 62058, "text": "Strings" }, { "code": null, "e": 62072, "s": 62066, "text": "Stack" } ]
Hive – Alter Table
24 Nov, 2020 Hive provides us the functionality to perform Alteration on the Tables and Databases. ALTER TABLE command can be used to perform alterations on the tables. We can modify multiple numbers of properties associated with the table schema in the Hive. Alteration on table modify’s or changes its metadata and does not affect the actual data available inside the table. In general when we made some mistakes while creating the table structure then we use ALTER TABLE to change the characteristics of the schema. We can perform multiple operations with table schema like renaming the table name, add the column, change or replace the column name, etc. To perform the below operation make sure your hive is running. Below are the steps to launch a hive on your local system. Step 1: Start all your Hadoop Daemon start-dfs.sh # this will start namenode, datanode and secondary namenode start-yarn.sh # this will start node manager and resource manager jps # To check running daemons Step 2: Launch hive from terminal hive Let’s make a table demo with one attribute demo_name of type string in the hive (By default hive makes tables in its default database if not specified). CREATE TABLE IF NOT EXISTS demo ( demo_name STRING ) ROW FORMAT DELIMITED FIELDS TERMINATED BY ','; Let’s perform each of the operations we can perform with ALTER TABLE one by one. 1. Renaming Table Name ALTER TABLE with RENAME is used to change the name of an already existing table in the hive. Syntax: ALTER TABLE <current_table_name> RENAME TO <new_table_name>; Command: Let’s rename our table name from the demo to the customer. ALTER TABLE demo RENAME TO customer; In the above, the image we can observe that our table name has changed to customer. 2. ADD Columns Syntax: ALTER TABLE <table_name> ADD COLUMNS (<col-name> <data-type> COMMENT ”, <col-name> <data-type> COMMENT ”, ..... ) Command: Let’s add a column contact to the customer table that we have obtained after renaming the demo. ALTER TABLE customer ADD COLUMNS ( contact BIGINT COMMENT ‘Store the customer contact number’); We can describe the table to see its properties with the below command. DESCRIBE customer; We have successfully added the contact column to the customer table. 3. CHANGE Column CHANGE in ALTER TABLE is used to change the name or data type of an existing column or attribute. Syntax: ALTER TABLE <table_name> CHANGE <column_name> <new_column_name> <new_data_type>; Command: Let’s change the demo_name attribute to customer_name. ALTER TABLE customer CHANGE demo_name customer_name STRING; 4. REPLACE Column The REPLACE with ALTER TABLE is used to remove all the existing columns from the table in Hive. The attributes or columns which are added in the ALTER TABLE REPLACE statement will be replaced with the older columns. Syntax: ALTER TABLE <table_name> REPLACE COLUMNS ( <attribute_name> <data_type>, <attribute_name> <data_type>, . . . ); For example in our customer table, we have 2 attributes customer_name and contact. If we want to remove the contact attribute the query should be like as shown below. Command: ALTER TABLE customer REPLACE COLUMNS ( customer_name STRING ); We should mention the column we want. In the above image, we can observe that we have successfully dropped the column contact. Hive does not have any DROP statement to drop columns inside the table. We have to use REPLACE if we want to drop a particular column. Apache-Hive Hadoop Hadoop Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference Between Hadoop and Spark Hadoop Streaming Using Python - Word Count Problem Architecture of HBase Architecture and Working of Hive What is Big Data? Hadoop - Different Modes of Operation Applications of Big Data How to Create Table in Hive? Introduction to Apache Pig Anatomy of File Read and Write in HDFS
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Nov, 2020" }, { "code": null, "e": 674, "s": 28, "text": "Hive provides us the functionality to perform Alteration on the Tables and Databases. ALTER TABLE command can be used to perform alterations on the tables. We can modify multiple numbers of properties associated with the table schema in the Hive. Alteration on table modify’s or changes its metadata and does not affect the actual data available inside the table. In general when we made some mistakes while creating the table structure then we use ALTER TABLE to change the characteristics of the schema. We can perform multiple operations with table schema like renaming the table name, add the column, change or replace the column name, etc. " }, { "code": null, "e": 796, "s": 674, "text": "To perform the below operation make sure your hive is running. Below are the steps to launch a hive on your local system." }, { "code": null, "e": 833, "s": 796, "text": "Step 1: Start all your Hadoop Daemon" }, { "code": null, "e": 1071, "s": 833, "text": "start-dfs.sh # this will start namenode, datanode and secondary namenode\nstart-yarn.sh # this will start node manager and resource manager \njps # To check running daemons\n" }, { "code": null, "e": 1105, "s": 1071, "text": "Step 2: Launch hive from terminal" }, { "code": null, "e": 1111, "s": 1105, "text": "hive\n" }, { "code": null, "e": 1264, "s": 1111, "text": "Let’s make a table demo with one attribute demo_name of type string in the hive (By default hive makes tables in its default database if not specified)." }, { "code": null, "e": 1366, "s": 1264, "text": "CREATE TABLE IF NOT EXISTS demo (\ndemo_name STRING\n)\nROW FORMAT DELIMITED\nFIELDS TERMINATED BY ','; \n" }, { "code": null, "e": 1447, "s": 1366, "text": "Let’s perform each of the operations we can perform with ALTER TABLE one by one." }, { "code": null, "e": 1470, "s": 1447, "text": "1. Renaming Table Name" }, { "code": null, "e": 1563, "s": 1470, "text": "ALTER TABLE with RENAME is used to change the name of an already existing table in the hive." }, { "code": null, "e": 1571, "s": 1563, "text": "Syntax:" }, { "code": null, "e": 1633, "s": 1571, "text": "ALTER TABLE <current_table_name> RENAME TO <new_table_name>;\n" }, { "code": null, "e": 1642, "s": 1633, "text": "Command:" }, { "code": null, "e": 1701, "s": 1642, "text": "Let’s rename our table name from the demo to the customer." }, { "code": null, "e": 1739, "s": 1701, "text": "ALTER TABLE demo RENAME TO customer;\n" }, { "code": null, "e": 1824, "s": 1739, "text": "In the above, the image we can observe that our table name has changed to customer. " }, { "code": null, "e": 1839, "s": 1824, "text": "2. ADD Columns" }, { "code": null, "e": 1847, "s": 1839, "text": "Syntax:" }, { "code": null, "e": 1965, "s": 1847, "text": "ALTER TABLE <table_name> ADD COLUMNS (<col-name> <data-type> COMMENT ”, <col-name> <data-type> COMMENT ”, ..... )" }, { "code": null, "e": 1974, "s": 1965, "text": "Command:" }, { "code": null, "e": 2071, "s": 1974, "text": "Let’s add a column contact to the customer table that we have obtained after renaming the demo. " }, { "code": null, "e": 2167, "s": 2071, "text": "ALTER TABLE customer ADD COLUMNS ( contact BIGINT COMMENT ‘Store the customer contact number’);" }, { "code": null, "e": 2239, "s": 2167, "text": "We can describe the table to see its properties with the below command." }, { "code": null, "e": 2259, "s": 2239, "text": "DESCRIBE customer;\n" }, { "code": null, "e": 2328, "s": 2259, "text": "We have successfully added the contact column to the customer table." }, { "code": null, "e": 2345, "s": 2328, "text": "3. CHANGE Column" }, { "code": null, "e": 2443, "s": 2345, "text": "CHANGE in ALTER TABLE is used to change the name or data type of an existing column or attribute." }, { "code": null, "e": 2452, "s": 2443, "text": "Syntax: " }, { "code": null, "e": 2534, "s": 2452, "text": "ALTER TABLE <table_name> CHANGE <column_name> <new_column_name> <new_data_type>;\n" }, { "code": null, "e": 2544, "s": 2534, "text": "Command: " }, { "code": null, "e": 2599, "s": 2544, "text": "Let’s change the demo_name attribute to customer_name." }, { "code": null, "e": 2661, "s": 2599, "text": "ALTER TABLE customer CHANGE demo_name customer_name STRING; \n" }, { "code": null, "e": 2679, "s": 2661, "text": "4. REPLACE Column" }, { "code": null, "e": 2895, "s": 2679, "text": "The REPLACE with ALTER TABLE is used to remove all the existing columns from the table in Hive. The attributes or columns which are added in the ALTER TABLE REPLACE statement will be replaced with the older columns." }, { "code": null, "e": 2903, "s": 2895, "text": "Syntax:" }, { "code": null, "e": 3016, "s": 2903, "text": "ALTER TABLE <table_name> REPLACE COLUMNS (\n<attribute_name> <data_type>,\n<attribute_name> <data_type>,\n.\n.\n.\n);\n" }, { "code": null, "e": 3183, "s": 3016, "text": "For example in our customer table, we have 2 attributes customer_name and contact. If we want to remove the contact attribute the query should be like as shown below." }, { "code": null, "e": 3192, "s": 3183, "text": "Command:" }, { "code": null, "e": 3256, "s": 3192, "text": "ALTER TABLE customer REPLACE COLUMNS (\ncustomer_name STRING\n);\n" }, { "code": null, "e": 3294, "s": 3256, "text": "We should mention the column we want." }, { "code": null, "e": 3518, "s": 3294, "text": "In the above image, we can observe that we have successfully dropped the column contact. Hive does not have any DROP statement to drop columns inside the table. We have to use REPLACE if we want to drop a particular column." }, { "code": null, "e": 3530, "s": 3518, "text": "Apache-Hive" }, { "code": null, "e": 3537, "s": 3530, "text": "Hadoop" }, { "code": null, "e": 3544, "s": 3537, "text": "Hadoop" }, { "code": null, "e": 3642, "s": 3544, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3678, "s": 3642, "text": "Difference Between Hadoop and Spark" }, { "code": null, "e": 3729, "s": 3678, "text": "Hadoop Streaming Using Python - Word Count Problem" }, { "code": null, "e": 3751, "s": 3729, "text": "Architecture of HBase" }, { "code": null, "e": 3784, "s": 3751, "text": "Architecture and Working of Hive" }, { "code": null, "e": 3802, "s": 3784, "text": "What is Big Data?" }, { "code": null, "e": 3840, "s": 3802, "text": "Hadoop - Different Modes of Operation" }, { "code": null, "e": 3865, "s": 3840, "text": "Applications of Big Data" }, { "code": null, "e": 3894, "s": 3865, "text": "How to Create Table in Hive?" }, { "code": null, "e": 3921, "s": 3894, "text": "Introduction to Apache Pig" } ]
Insecure Direct Object Reference (IDOR) Vulnerability
12 Sep, 2021 One of the most crucial Vulnerabilities listed in top 10 of OWASP is Insecure Direct Object Reference Vulnerability (IDOR Vulnerability). In this article we will discuss IDOR Vulnerability. Before moving ahead, let us first discuss Authentication. Authentication means to verify the identity of a person and allow that person to access specific requests if the user is authenticated (verified). But if a user is not authenticated and can be able to view files i.e. open files in a wrong way like the Hackers/Attackers do?, it is called Broken Authentication. This article will focus on the way an attacker uses Broken Authentication Vulnerabilities that may lead to IDOR. What is an IDOR Vulnerability? In a web application, whenever a user generates, sends or receives a request from a server, there are some HTTP parameters such as “id”, “uid”, “pid” etc that have some unique values which the user has been assigned. An attacker can see such parameter values in cookies, headers, or wifi Packet captures. Via this, an attacker might be able to tamper these values and this tampering may lead to IDOR. Some of the examples that demonstrate the untrusted data which can be manipulated using IDOR: www.xyz.com/myaccount/uid=12 www.xyz.com/myaccount/uid=14 www.xyz.com/myaccount/uid=15 www.xyz.com/myaccount/uid=19 Here we can see that the uid in the URL seems to be vulnerable and can be tampered by an attacker to break the authentication. How IDOR Vulnerabilities get executed? Let us first discuss the back-end working of a Web application that uses the unauthenticated medium in SQL, which leads to accessing user account information. String query = "SELECT * FROM accts WHERE account = ?"; PreparedStatement pstmt = connection.prepareStatement(query, ... ); pstmt.setString(1, request.getParameter("acct")); ResultSet results = pstmt.executeQuery( ); In the above code, the attacker will modify the “accts” parameter in the web application and can enter multiple account numbers to retrieve the information. Steps involved in execution of IDOR attack: Burp Suite Tool is widely used by attackers to execute such type of Attacks. Following are the steps being followed: Capture the Request: First of all, an attacker will decide a target website to which he wants to execute an IDOR attack. Then the website is added to the scope and spider the website to get all the URLs with specific parameters in it. Filter the parameters Request: After the first step, we will filter our captured request with the parameter filters. An attacker will only choose that parameter or Injection points where they can execute the attacks. Forward request to Repeater: Now, if an attacker will find some of the injection point where they can execute IDOR, they will forward the request to the repeater. The vulnerable URL might look something like this: www.xyz.com/myaccount/uid=19. Here the “UID” seems to be vulnerable. Tampering of Parameters: Now as the attacker has the vulnerable injection point, they will now try to execute the IDOR attack with the help of Social engineering or the pattern as written in injection point. Example: an attacker may change uid from 19 to 20 which will open account of another user who has been assigned id number 20. Impacts of IDOR Vulnerability: Exposure of Confidential Information: When the attacker will have control over your account via this vulnerability, it is obvious that an attacker will be able to come across your personal information. Authentication Bypass: As the attacker can have access to millions of account with this vulnerability, it will be a type of Authentication bypass mechanism. Alteration of Data: An attacker may have privileges to access your data and alter it. By this, an attacker may have permission to make changes to your data, which may lead to manipulation of records. Account Takeover: While an attacker may have multiple access to user accounts just by changing the “UID” values, this will lead to account takeover vulnerability. When one vulnerability leads to another vulnerability(like in this case), It is known as Chaining of BUGS. Remediation of IDOR Vulnerability: Developers should avoid displaying private object references such as keys or file names. Validation of Parameters should be properly implemented. Verification of all the Referenced objects should be done. Tokens should be generated in such a way that it should only be mapped to the user and should not be public. sweetyty Technical Scripter 2019 Technical Scripter Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ? Installation of Node.js on Linux How to insert spaces/tabs in text using HTML/CSS? Remove elements from a JavaScript Array How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ?
[ { "code": null, "e": 52, "s": 24, "text": "\n12 Sep, 2021" }, { "code": null, "e": 725, "s": 52, "text": "One of the most crucial Vulnerabilities listed in top 10 of OWASP is Insecure Direct Object Reference Vulnerability (IDOR Vulnerability). In this article we will discuss IDOR Vulnerability. Before moving ahead, let us first discuss Authentication. Authentication means to verify the identity of a person and allow that person to access specific requests if the user is authenticated (verified). But if a user is not authenticated and can be able to view files i.e. open files in a wrong way like the Hackers/Attackers do?, it is called Broken Authentication. This article will focus on the way an attacker uses Broken Authentication Vulnerabilities that may lead to IDOR. " }, { "code": null, "e": 1158, "s": 725, "text": "What is an IDOR Vulnerability? In a web application, whenever a user generates, sends or receives a request from a server, there are some HTTP parameters such as “id”, “uid”, “pid” etc that have some unique values which the user has been assigned. An attacker can see such parameter values in cookies, headers, or wifi Packet captures. Via this, an attacker might be able to tamper these values and this tampering may lead to IDOR. " }, { "code": null, "e": 1254, "s": 1158, "text": "Some of the examples that demonstrate the untrusted data which can be manipulated using IDOR: " }, { "code": null, "e": 1283, "s": 1254, "text": "www.xyz.com/myaccount/uid=12" }, { "code": null, "e": 1312, "s": 1283, "text": "www.xyz.com/myaccount/uid=14" }, { "code": null, "e": 1341, "s": 1312, "text": "www.xyz.com/myaccount/uid=15" }, { "code": null, "e": 1370, "s": 1341, "text": "www.xyz.com/myaccount/uid=19" }, { "code": null, "e": 1498, "s": 1370, "text": "Here we can see that the uid in the URL seems to be vulnerable and can be tampered by an attacker to break the authentication. " }, { "code": null, "e": 1698, "s": 1498, "text": "How IDOR Vulnerabilities get executed? Let us first discuss the back-end working of a Web application that uses the unauthenticated medium in SQL, which leads to accessing user account information. " }, { "code": null, "e": 1915, "s": 1698, "text": "String query = \"SELECT * FROM accts WHERE account = ?\";\nPreparedStatement pstmt = connection.prepareStatement(query, ... );\npstmt.setString(1, request.getParameter(\"acct\"));\nResultSet results = pstmt.executeQuery( );" }, { "code": null, "e": 2073, "s": 1915, "text": "In the above code, the attacker will modify the “accts” parameter in the web application and can enter multiple account numbers to retrieve the information. " }, { "code": null, "e": 2236, "s": 2073, "text": "Steps involved in execution of IDOR attack: Burp Suite Tool is widely used by attackers to execute such type of Attacks. Following are the steps being followed: " }, { "code": null, "e": 2471, "s": 2236, "text": "Capture the Request: First of all, an attacker will decide a target website to which he wants to execute an IDOR attack. Then the website is added to the scope and spider the website to get all the URLs with specific parameters in it." }, { "code": null, "e": 2688, "s": 2471, "text": "Filter the parameters Request: After the first step, we will filter our captured request with the parameter filters. An attacker will only choose that parameter or Injection points where they can execute the attacks." }, { "code": null, "e": 2971, "s": 2688, "text": "Forward request to Repeater: Now, if an attacker will find some of the injection point where they can execute IDOR, they will forward the request to the repeater. The vulnerable URL might look something like this: www.xyz.com/myaccount/uid=19. Here the “UID” seems to be vulnerable." }, { "code": null, "e": 3305, "s": 2971, "text": "Tampering of Parameters: Now as the attacker has the vulnerable injection point, they will now try to execute the IDOR attack with the help of Social engineering or the pattern as written in injection point. Example: an attacker may change uid from 19 to 20 which will open account of another user who has been assigned id number 20." }, { "code": null, "e": 3338, "s": 3305, "text": "Impacts of IDOR Vulnerability: " }, { "code": null, "e": 3540, "s": 3338, "text": "Exposure of Confidential Information: When the attacker will have control over your account via this vulnerability, it is obvious that an attacker will be able to come across your personal information." }, { "code": null, "e": 3697, "s": 3540, "text": "Authentication Bypass: As the attacker can have access to millions of account with this vulnerability, it will be a type of Authentication bypass mechanism." }, { "code": null, "e": 3897, "s": 3697, "text": "Alteration of Data: An attacker may have privileges to access your data and alter it. By this, an attacker may have permission to make changes to your data, which may lead to manipulation of records." }, { "code": null, "e": 4167, "s": 3897, "text": "Account Takeover: While an attacker may have multiple access to user accounts just by changing the “UID” values, this will lead to account takeover vulnerability. When one vulnerability leads to another vulnerability(like in this case), It is known as Chaining of BUGS." }, { "code": null, "e": 4204, "s": 4167, "text": "Remediation of IDOR Vulnerability: " }, { "code": null, "e": 4293, "s": 4204, "text": "Developers should avoid displaying private object references such as keys or file names." }, { "code": null, "e": 4350, "s": 4293, "text": "Validation of Parameters should be properly implemented." }, { "code": null, "e": 4409, "s": 4350, "text": "Verification of all the Referenced objects should be done." }, { "code": null, "e": 4518, "s": 4409, "text": "Tokens should be generated in such a way that it should only be mapped to the user and should not be public." }, { "code": null, "e": 4529, "s": 4520, "text": "sweetyty" }, { "code": null, "e": 4553, "s": 4529, "text": "Technical Scripter 2019" }, { "code": null, "e": 4572, "s": 4553, "text": "Technical Scripter" }, { "code": null, "e": 4589, "s": 4572, "text": "Web Technologies" }, { "code": null, "e": 4616, "s": 4589, "text": "Web technologies Questions" }, { "code": null, "e": 4714, "s": 4616, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4747, "s": 4714, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 4809, "s": 4747, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 4870, "s": 4809, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4920, "s": 4870, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 4963, "s": 4920, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 4996, "s": 4963, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 5046, "s": 4996, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 5086, "s": 5046, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 5146, "s": 5086, "text": "How to set the default value for an HTML <select> element ?" } ]
How to communicate between Activity and Service in Android using Kotlin?
This example demonstrates how to communicate between Activity and Service in Android using Kotlin. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/relativeLayout" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:id="@+id/text2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="70dp" android:background="#008080" android:padding="5dp" android:text="TutorialsPoint" android:textColor="#fff" android:textSize="24sp" android:textStyle="bold" /> <Button android:id="@+id/buttonStart" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/text2" android:layout_centerInParent="true" android:layout_marginTop="74dp" android:text="Start Service" /> <Button android:id="@+id/buttonStop" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:text="Stop Service" /> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.kt import android.app.Service import android.content.Intent import android.media.MediaPlayer import android.os.Bundle import android.os.IBinder import android.view.View import android.widget.Button import android.widget.Toast import androidx.annotation.Nullable import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity(), View.OnClickListener { private lateinit var buttonStart: Button private lateinit var buttonStop: Button override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) title = "KotlinApp" buttonStart = findViewById(R.id.buttonStart) buttonStop = findViewById(R.id.buttonStop) buttonStart.setOnClickListener(this) buttonStop.setOnClickListener(this) } override fun onClick(src: View?) { when (src?.id) { R.id.buttonStart -> startService(Intent(this, MyService::class.java)) R.id.buttonStop -> stopService(Intent(this, MyService::class.java)) } } class MyService : Service() { private lateinit var myPlayer: MediaPlayer @Nullable override fun onBind(intent: Intent?): IBinder? { return null } override fun onCreate() { Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show() myPlayer = MediaPlayer.create(this, R.raw.song) myPlayer.isLooping = false } override fun onStart(intent: Intent?, startId: Int) { Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show() myPlayer.start() } override fun onDestroy() { Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show() myPlayer.stop() } } } Step 4 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.q11"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <service android:name=".MainActivity$MyService" /> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen.
[ { "code": null, "e": 1286, "s": 1187, "text": "This example demonstrates how to communicate between Activity and Service in Android using Kotlin." }, { "code": null, "e": 1415, "s": 1286, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1480, "s": 1415, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2763, "s": 1480, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:id=\"@+id/relativeLayout\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <TextView\n android:id=\"@+id/text2\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"70dp\"\n android:background=\"#008080\"\n android:padding=\"5dp\"\n android:text=\"TutorialsPoint\"\n android:textColor=\"#fff\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\" />\n <Button\n android:id=\"@+id/buttonStart\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@+id/text2\"\n android:layout_centerInParent=\"true\"\n android:layout_marginTop=\"74dp\"\n android:text=\"Start Service\" />\n <Button\n android:id=\"@+id/buttonStop\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_centerVertical=\"true\"\n android:text=\"Stop Service\" />\n</RelativeLayout>" }, { "code": null, "e": 2818, "s": 2763, "text": "Step 3 − Add the following code to src/MainActivity.kt" }, { "code": null, "e": 4599, "s": 2818, "text": "import android.app.Service\nimport android.content.Intent\nimport android.media.MediaPlayer\nimport android.os.Bundle\nimport android.os.IBinder\nimport android.view.View\nimport android.widget.Button\nimport android.widget.Toast\nimport androidx.annotation.Nullable\nimport androidx.appcompat.app.AppCompatActivity\nclass MainActivity : AppCompatActivity(), View.OnClickListener {\n private lateinit var buttonStart: Button\n private lateinit var buttonStop: Button\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n buttonStart = findViewById(R.id.buttonStart)\n buttonStop = findViewById(R.id.buttonStop)\n buttonStart.setOnClickListener(this)\n buttonStop.setOnClickListener(this)\n }\n override fun onClick(src: View?) {\n when (src?.id) {\n R.id.buttonStart -> startService(Intent(this, MyService::class.java))\n R.id.buttonStop -> stopService(Intent(this, MyService::class.java))\n }\n }\n class MyService : Service() {\n private lateinit var myPlayer: MediaPlayer\n @Nullable\n override fun onBind(intent: Intent?): IBinder? {\n return null\n }\n override fun onCreate() {\n Toast.makeText(this, \"Service Created\",\n Toast.LENGTH_LONG).show()\n myPlayer = MediaPlayer.create(this, R.raw.song)\n myPlayer.isLooping = false\n }\n override fun onStart(intent: Intent?, startId: Int) {\n Toast.makeText(this, \"Service Started\",\n Toast.LENGTH_LONG).show()\n myPlayer.start()\n }\n override fun onDestroy() {\n Toast.makeText(this, \"Service Stopped\",\n Toast.LENGTH_LONG).show()\n myPlayer.stop()\n }\n }\n}" }, { "code": null, "e": 4654, "s": 4599, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 5385, "s": 4654, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.q11\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n <service android:name=\".MainActivity$MyService\" />\n </application>\n</manifest>" }, { "code": null, "e": 5734, "s": 5385, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen." } ]
XSD - Element
Simple Element is an XML element which can only have text. It can not contain any attribute. <xs:element name = "element-name" type = "element-type"/> <xs:element name = "firstname" type = "xs:string"/> defines following element <firstname></firstname> <xs:element name = "firstname" type = "xs:string"/> <firstname>Dinkar</firstname> Consider the following XML Elements <name>Dinkar</name> <marks>90</marks> <birthdate>1985-05-23</birthdate> XSD declarations for above XML elements will be as follows − <xs:element name = "name" type = "xs:string"/> <xs:element name = "marks" type = "xs:integer"/> <xs:element name = "birthdate" type = "xs:date"/> A Simple Element can have a default value assigned. Default values are used in case an element does not have any text. <xs:element name = "grade" type = "xs:string" default = "NA" /> Simple Element can have fix value assigend. In case, fixed value is assigned element can not have any text. <xs:element name = "class" type = "xs:string" fixed = "1" />
[ { "code": null, "e": 1931, "s": 1838, "text": "Simple Element is an XML element which can only have text. It can not contain any attribute." }, { "code": null, "e": 1990, "s": 1931, "text": "<xs:element name = \"element-name\" type = \"element-type\"/>\n" }, { "code": null, "e": 2044, "s": 1990, "text": "<xs:element name = \"firstname\" type = \"xs:string\"/> \n" }, { "code": null, "e": 2070, "s": 2044, "text": "defines following element" }, { "code": null, "e": 2095, "s": 2070, "text": "<firstname></firstname>\n" }, { "code": null, "e": 2149, "s": 2095, "text": "<xs:element name = \"firstname\" type = \"xs:string\"/> \n" }, { "code": null, "e": 2180, "s": 2149, "text": "<firstname>Dinkar</firstname>\n" }, { "code": null, "e": 2216, "s": 2180, "text": "Consider the following XML Elements" }, { "code": null, "e": 2289, "s": 2216, "text": "<name>Dinkar</name>\n<marks>90</marks>\n<birthdate>1985-05-23</birthdate>\n" }, { "code": null, "e": 2351, "s": 2289, "text": "XSD declarations for above XML elements will be as follows − " }, { "code": null, "e": 2498, "s": 2351, "text": "<xs:element name = \"name\" type = \"xs:string\"/>\n<xs:element name = \"marks\" type = \"xs:integer\"/>\n<xs:element name = \"birthdate\" type = \"xs:date\"/>\n" }, { "code": null, "e": 2617, "s": 2498, "text": "A Simple Element can have a default value assigned. Default values are used in case an element does not have any text." }, { "code": null, "e": 2683, "s": 2617, "text": "<xs:element name = \"grade\" type = \"xs:string\" default = \"NA\" /> \n" }, { "code": null, "e": 2791, "s": 2683, "text": "Simple Element can have fix value assigend. In case, fixed value is assigned element can not have any text." } ]
execute_async_script driver method – Selenium Python
15 May, 2020 Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies. Selenium WebDriver offers various useful methods to control the session, or in other words, browser. For example, adding a cookie, pressing back button, navigating among tabs, etc. This article revolves around execute_async_script driver method in Selenium. execute_async_script method asynchronously Executes JavaScript in the current window/frame. This is a big feature of selenium, because javascript can do everything with a website from hitting APIs to playing with live code. Syntax – execute_async_script(script, *args) Args – script: The JavaScript to execute. *args: Any applicable arguments for your JavaScript. Example –Now one can use execute_async_script method as a driver method as below – diver.get("https://www.geeksforgeeks.org/") driver.execute_async_script("alert("alert via selenium")") To demonstrate, execute_async_script method of WebDriver in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on driver object. Program – # import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # write scriptscript = "alert('Alert via selenium')" # generate a alert via javascriptdriver.execute_async_script(script) Output –Browser generates alert as verified below – Python-selenium selenium Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n15 May, 2020" }, { "code": null, "e": 767, "s": 28, "text": "Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies. Selenium WebDriver offers various useful methods to control the session, or in other words, browser. For example, adding a cookie, pressing back button, navigating among tabs, etc." }, { "code": null, "e": 1068, "s": 767, "text": "This article revolves around execute_async_script driver method in Selenium. execute_async_script method asynchronously Executes JavaScript in the current window/frame. This is a big feature of selenium, because javascript can do everything with a website from hitting APIs to playing with live code." }, { "code": null, "e": 1077, "s": 1068, "text": "Syntax –" }, { "code": null, "e": 1113, "s": 1077, "text": "execute_async_script(script, *args)" }, { "code": null, "e": 1120, "s": 1113, "text": "Args –" }, { "code": null, "e": 1155, "s": 1120, "text": "script: The JavaScript to execute." }, { "code": null, "e": 1208, "s": 1155, "text": "*args: Any applicable arguments for your JavaScript." }, { "code": null, "e": 1291, "s": 1208, "text": "Example –Now one can use execute_async_script method as a driver method as below –" }, { "code": null, "e": 1395, "s": 1291, "text": "diver.get(\"https://www.geeksforgeeks.org/\")\ndriver.execute_async_script(\"alert(\"alert via selenium\")\")\n" }, { "code": null, "e": 1546, "s": 1395, "text": "To demonstrate, execute_async_script method of WebDriver in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on driver object." }, { "code": null, "e": 1556, "s": 1546, "text": "Program –" }, { "code": "# import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get(\"https://www.geeksforgeeks.org/\") # write scriptscript = \"alert('Alert via selenium')\" # generate a alert via javascriptdriver.execute_async_script(script)", "e": 1853, "s": 1556, "text": null }, { "code": null, "e": 1905, "s": 1853, "text": "Output –Browser generates alert as verified below –" }, { "code": null, "e": 1921, "s": 1905, "text": "Python-selenium" }, { "code": null, "e": 1930, "s": 1921, "text": "selenium" }, { "code": null, "e": 1937, "s": 1930, "text": "Python" } ]
Sum Of Two Numbers in PL/SQL
29 Dec, 2020 Prerequisite – PL/SQL introductionIn PL/SQL code groups of commands are arranged within a block. A block group related declarations or statements. In declare part, we declare variables and between begin and end part, we perform the operations. Here, first, we take three variables x, y, and z and assign the value in x and y and after addition of both the numbers, we assign the resultant value to z and print z. Examples: Input : 15 25 Output : 40 Input : 250 400 Output : 650 Below is the required implementation: SQL declare -- declare variable x, y-- and z of datatype numberx number(5); y number(5); z number(7); begin -- Here we Assigning 10 into xx:=10; -- Assigning 20 into xy:=20; -- Assigning sum of x and y into zz:=x+y; -- Print the Resultdbms_output.put_line('Sum is '||z);end;/ -- Program End Output : Sum is 30 viswajit4u SQL-PL/SQL DBMS SQL DBMS SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. CTE in SQL Difference between Clustered and Non-clustered index SQL Interview Questions SQL | Views Difference between DELETE, DROP and TRUNCATE SQL | DDL, DQL, DML, DCL and TCL Commands How to find Nth highest salary from a table CTE in SQL SQL | ALTER (RENAME) How to Update Multiple Columns in Single Update Statement in SQL?
[ { "code": null, "e": 53, "s": 25, "text": "\n29 Dec, 2020" }, { "code": null, "e": 201, "s": 53, "text": "Prerequisite – PL/SQL introductionIn PL/SQL code groups of commands are arranged within a block. A block group related declarations or statements. " }, { "code": null, "e": 298, "s": 201, "text": "In declare part, we declare variables and between begin and end part, we perform the operations." }, { "code": null, "e": 467, "s": 298, "text": "Here, first, we take three variables x, y, and z and assign the value in x and y and after addition of both the numbers, we assign the resultant value to z and print z." }, { "code": null, "e": 479, "s": 467, "text": "Examples: " }, { "code": null, "e": 505, "s": 479, "text": "Input : 15 25\nOutput : 40" }, { "code": null, "e": 534, "s": 505, "text": "Input : 250 400\nOutput : 650" }, { "code": null, "e": 573, "s": 534, "text": "Below is the required implementation: " }, { "code": null, "e": 577, "s": 573, "text": "SQL" }, { "code": "declare -- declare variable x, y-- and z of datatype numberx number(5); y number(5); z number(7); begin -- Here we Assigning 10 into xx:=10; -- Assigning 20 into xy:=20; -- Assigning sum of x and y into zz:=x+y; -- Print the Resultdbms_output.put_line('Sum is '||z);end;/ -- Program End", "e": 963, "s": 577, "text": null }, { "code": null, "e": 973, "s": 963, "text": "Output : " }, { "code": null, "e": 983, "s": 973, "text": "Sum is 30" }, { "code": null, "e": 996, "s": 985, "text": "viswajit4u" }, { "code": null, "e": 1007, "s": 996, "text": "SQL-PL/SQL" }, { "code": null, "e": 1012, "s": 1007, "text": "DBMS" }, { "code": null, "e": 1016, "s": 1012, "text": "SQL" }, { "code": null, "e": 1021, "s": 1016, "text": "DBMS" }, { "code": null, "e": 1025, "s": 1021, "text": "SQL" }, { "code": null, "e": 1123, "s": 1025, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1134, "s": 1123, "text": "CTE in SQL" }, { "code": null, "e": 1187, "s": 1134, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 1211, "s": 1187, "text": "SQL Interview Questions" }, { "code": null, "e": 1223, "s": 1211, "text": "SQL | Views" }, { "code": null, "e": 1268, "s": 1223, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 1310, "s": 1268, "text": "SQL | DDL, DQL, DML, DCL and TCL Commands" }, { "code": null, "e": 1354, "s": 1310, "text": "How to find Nth highest salary from a table" }, { "code": null, "e": 1365, "s": 1354, "text": "CTE in SQL" }, { "code": null, "e": 1386, "s": 1365, "text": "SQL | ALTER (RENAME)" } ]
Kali Linux – Terminal and Shell
30 Jun, 2020 Generally, operating systems have 2 interfaces GUI(Graphical User Interface) and CLI(Command Line Interface) and the same is the case with Linux Based Operating Systems. Linux Operating Systems are generally packed with terminal emulator packages for CLI based functioning and Desktop environment packages for GUI based functioning. Some common ones are listed below: Terminals: Qterminal gnome-terminal MATE terminal xterm Terminator konsole Desktop Environments: Xfce/Xfce server Desktop GNOME3 KDE plasma 5 cinnamon Desktop MATE Desktop So being one of the Linux based Operating Systems Kali comes packed with a few of these terminals and Desktop environments. By default, the terminal of Kali 2020.2 Linux is Qterminal and the Desktop environment is Xfce/Xfce server. Now most of us think that when we have Graphical User Interface what is the need for Command Line Interface. Our hardware understands instructions in the form of bits(0 or 1), which are to be processed by the kernel in the form of system calls and those system calls are to be made by some code or some commands. So in order to work with them, it is necessary to have a good hands-on Command Line interface. And when we host a server over Linux, there we only have Command Line Interface without any GUI based environment. So in order to work there, we should have a good command on Linux commands which could be done with the help of Linux Terminals. Though in many cases GUI is better still, if it is the case of Linux then the terminal and Command Line interface plays a vital role as Linux has many tools that are command based and have no GUI interface. So concluding from this, it depends on what is the task which is to be performed. Sometimes a task could be performed easily with GUI while other times it could be performed with feasibility through terminal. Many people confuse between a shell and a terminal emulator. They both are different. Linux based Operating Systems come pre-packed with some shells. In these shells, we need to input the commands, then these shells send these commands to the processor for processing, and then it returns back output to the terminal. Now, Terminal emulator packages allow us to input commands to shell and it reflects the output by the shell. In simple words, the shell is a program that is responsible for the execution of an instruction and returning the output while the terminal is responsible to send instructions to the shell by taking input from the user and displaying the output of the instruction to the user. Examples of shells: bash Borne cshell Korn POSIX 1. Customizing the terminal. In order to customize the kali Linux Terminal. Go to the File menu and select the preferences option. It has a lot of options to customize your terminal, customize the terminal as per your convenience. 2. Executing a command through terminal. To execute a command in the terminal, just enter a command there and provide the appropriate input, the terminal will execute the command through the shell and will return the output. Just type the following lines in the terminal. echo "This is a terminal" pwd 3. Using comments in terminal. To put a comment in the terminal we use “#” character. Following is the example of a comment. #this is a comment. Kali-Linux Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. tar command in Linux with examples curl command in Linux with Examples SORT command in Linux/Unix with examples 'crontab' in Linux with Examples TCP Server-Client implementation in C Tail command in Linux with examples scp command in Linux with Examples Docker - COPY Instruction UDP Server-Client implementation in C Cat command in Linux with examples
[ { "code": null, "e": 52, "s": 24, "text": "\n30 Jun, 2020" }, { "code": null, "e": 420, "s": 52, "text": "Generally, operating systems have 2 interfaces GUI(Graphical User Interface) and CLI(Command Line Interface) and the same is the case with Linux Based Operating Systems. Linux Operating Systems are generally packed with terminal emulator packages for CLI based functioning and Desktop environment packages for GUI based functioning. Some common ones are listed below:" }, { "code": null, "e": 431, "s": 420, "text": "Terminals:" }, { "code": null, "e": 441, "s": 431, "text": "Qterminal" }, { "code": null, "e": 456, "s": 441, "text": "gnome-terminal" }, { "code": null, "e": 470, "s": 456, "text": "MATE terminal" }, { "code": null, "e": 476, "s": 470, "text": "xterm" }, { "code": null, "e": 487, "s": 476, "text": "Terminator" }, { "code": null, "e": 495, "s": 487, "text": "konsole" }, { "code": null, "e": 517, "s": 495, "text": "Desktop Environments:" }, { "code": null, "e": 542, "s": 517, "text": "Xfce/Xfce server Desktop" }, { "code": null, "e": 549, "s": 542, "text": "GNOME3" }, { "code": null, "e": 562, "s": 549, "text": "KDE plasma 5" }, { "code": null, "e": 579, "s": 562, "text": "cinnamon Desktop" }, { "code": null, "e": 592, "s": 579, "text": "MATE Desktop" }, { "code": null, "e": 824, "s": 592, "text": "So being one of the Linux based Operating Systems Kali comes packed with a few of these terminals and Desktop environments. By default, the terminal of Kali 2020.2 Linux is Qterminal and the Desktop environment is Xfce/Xfce server." }, { "code": null, "e": 1476, "s": 824, "text": "Now most of us think that when we have Graphical User Interface what is the need for Command Line Interface. Our hardware understands instructions in the form of bits(0 or 1), which are to be processed by the kernel in the form of system calls and those system calls are to be made by some code or some commands. So in order to work with them, it is necessary to have a good hands-on Command Line interface. And when we host a server over Linux, there we only have Command Line Interface without any GUI based environment. So in order to work there, we should have a good command on Linux commands which could be done with the help of Linux Terminals." }, { "code": null, "e": 1683, "s": 1476, "text": "Though in many cases GUI is better still, if it is the case of Linux then the terminal and Command Line interface plays a vital role as Linux has many tools that are command based and have no GUI interface." }, { "code": null, "e": 1892, "s": 1683, "text": "So concluding from this, it depends on what is the task which is to be performed. Sometimes a task could be performed easily with GUI while other times it could be performed with feasibility through terminal." }, { "code": null, "e": 2319, "s": 1892, "text": "Many people confuse between a shell and a terminal emulator. They both are different. Linux based Operating Systems come pre-packed with some shells. In these shells, we need to input the commands, then these shells send these commands to the processor for processing, and then it returns back output to the terminal. Now, Terminal emulator packages allow us to input commands to shell and it reflects the output by the shell." }, { "code": null, "e": 2596, "s": 2319, "text": "In simple words, the shell is a program that is responsible for the execution of an instruction and returning the output while the terminal is responsible to send instructions to the shell by taking input from the user and displaying the output of the instruction to the user." }, { "code": null, "e": 2616, "s": 2596, "text": "Examples of shells:" }, { "code": null, "e": 2621, "s": 2616, "text": "bash" }, { "code": null, "e": 2627, "s": 2621, "text": "Borne" }, { "code": null, "e": 2634, "s": 2627, "text": "cshell" }, { "code": null, "e": 2639, "s": 2634, "text": "Korn" }, { "code": null, "e": 2645, "s": 2639, "text": "POSIX" }, { "code": null, "e": 2876, "s": 2645, "text": "1. Customizing the terminal. In order to customize the kali Linux Terminal. Go to the File menu and select the preferences option. It has a lot of options to customize your terminal, customize the terminal as per your convenience." }, { "code": null, "e": 3148, "s": 2876, "text": "2. Executing a command through terminal. To execute a command in the terminal, just enter a command there and provide the appropriate input, the terminal will execute the command through the shell and will return the output. Just type the following lines in the terminal." }, { "code": null, "e": 3179, "s": 3148, "text": "echo \"This is a terminal\"\npwd\n" }, { "code": null, "e": 3304, "s": 3179, "text": "3. Using comments in terminal. To put a comment in the terminal we use “#” character. Following is the example of a comment." }, { "code": null, "e": 3325, "s": 3304, "text": "#this is a comment.\n" }, { "code": null, "e": 3336, "s": 3325, "text": "Kali-Linux" }, { "code": null, "e": 3347, "s": 3336, "text": "Linux-Unix" }, { "code": null, "e": 3445, "s": 3347, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3480, "s": 3445, "text": "tar command in Linux with examples" }, { "code": null, "e": 3516, "s": 3480, "text": "curl command in Linux with Examples" }, { "code": null, "e": 3557, "s": 3516, "text": "SORT command in Linux/Unix with examples" }, { "code": null, "e": 3590, "s": 3557, "text": "'crontab' in Linux with Examples" }, { "code": null, "e": 3628, "s": 3590, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 3664, "s": 3628, "text": "Tail command in Linux with examples" }, { "code": null, "e": 3699, "s": 3664, "text": "scp command in Linux with Examples" }, { "code": null, "e": 3725, "s": 3699, "text": "Docker - COPY Instruction" }, { "code": null, "e": 3763, "s": 3725, "text": "UDP Server-Client implementation in C" } ]
Java Examples - Update Table Contents
How to update(delete, insert or update) contents of a table using JDBC connection? Following method uses update, delete & insert SQL commands to edit or delete row contents. import java.sql.*; public class updateTable { public static void main(String[] args) { try { Class.forName("org.apache.derby.jdbc.ClientDriver"); } catch(ClassNotFoundException e) { System.out.println("Class not found "+ e); } try { Connection con = DriverManager.getConnection ( "jdbc:derby://localhost:1527/testDb","username", "password"); Statement stmt = con.createStatement(); String query1 = "update emp set name = 'ravi' where id = 2"; String query2 = "delete from emp where id = 1"; String query3 = "insert into emp values (1,'ronak','manager')"; stmt.execute(query1); stmt.execute(query2); stmt.execute(query3); ResultSet rs = stmt.executeQuery("SELECT * FROM emp"); System.out.println("id name job"); while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); String job = rs.getString("job"); System.out.println(id+" "+name+" "+job); } } catch(SQLException e) { System.out.println("SQL exception occured" + e); } } } The above code sample will produce the following result. The result may vary. id name job 2 ravi trainee 1 ronak manager Print Add Notes Bookmark this page
[ { "code": null, "e": 2151, "s": 2068, "text": "How to update(delete, insert or update) contents of a table using JDBC connection?" }, { "code": null, "e": 2242, "s": 2151, "text": "Following method uses update, delete & insert SQL commands to edit or delete row contents." }, { "code": null, "e": 3480, "s": 2242, "text": "import java.sql.*;\n\npublic class updateTable {\n public static void main(String[] args) {\n try {\n Class.forName(\"org.apache.derby.jdbc.ClientDriver\");\n } catch(ClassNotFoundException e) {\n System.out.println(\"Class not found \"+ e);\n }\n try {\n Connection con = DriverManager.getConnection (\n \"jdbc:derby://localhost:1527/testDb\",\"username\", \"password\");\n \n Statement stmt = con.createStatement();\n String query1 = \"update emp set name = 'ravi' where id = 2\";\n String query2 = \"delete from emp where id = 1\";\n String query3 = \"insert into emp values (1,'ronak','manager')\";\n \n stmt.execute(query1);\n stmt.execute(query2);\n stmt.execute(query3);\n \n ResultSet rs = stmt.executeQuery(\"SELECT * FROM emp\");\n System.out.println(\"id name job\");\n \n while (rs.next()) {\n int id = rs.getInt(\"id\");\n String name = rs.getString(\"name\");\n String job = rs.getString(\"job\");\n System.out.println(id+\" \"+name+\" \"+job);\n }\n } catch(SQLException e) {\n System.out.println(\"SQL exception occured\" + e);\n }\n }\n}" }, { "code": null, "e": 3558, "s": 3480, "text": "The above code sample will produce the following result. The result may vary." }, { "code": null, "e": 3616, "s": 3558, "text": "id name job\n2 ravi trainee\n1 ronak manager\n" }, { "code": null, "e": 3623, "s": 3616, "text": " Print" }, { "code": null, "e": 3634, "s": 3623, "text": " Add Notes" } ]