title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Spring MVC - Hidden Field Example | The following example describes how to use a Hidden Field in forms using the Spring Web MVC framework. To start with, let us have a working Eclipse IDE in place and consider the following steps to develop a Dynamic Form based Web Application using Spring Web Framework.
package com.tutorialspoint;
public class Student {
private Integer age;
private String name;
private Integer id;
public void setAge(Integer age) {
this.age = age;
}
public Integer getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
}
package com.tutorialspoint;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.ui.ModelMap;
@Controller
public class StudentController {
@RequestMapping(value = "/student", method = RequestMethod.GET)
public ModelAndView student() {
return new ModelAndView("student", "command", new Student());
}
@RequestMapping(value = "/addStudent", method = RequestMethod.POST)
public String addStudent(@ModelAttribute("SpringWeb")Student student,
ModelMap model) {
model.addAttribute("name", student.getName());
model.addAttribute("age", student.getAge());
model.addAttribute("id", student.getId());
return "result";
}
}
Here, for the first service method student(), we have passed a blank Studentobject in the ModelAndView object with the name "command", because the spring framework expects an object with the name "command", if you are using <form:form> tags in your JSP file. So, when the student() method is called, it returns the student.jsp view.
The second service method addStudent() will be called against a POST method on the HelloWeb/addStudent URL. You will prepare your model object based on the submitted information. Finally, a "result" view will be returned from the service method, which will result in rendering result.jsp
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>Student Information</h2>
<form:form method = "POST" action = "/HelloWeb/addStudent">
<table>
<tr>
<td><form:label path = "name">Name</form:label></td>
<td><form:input path = "name" /></td>
</tr>
<tr>
<td><form:label path = "age">Age</form:label></td>
<td><form:input path = "age" /></td>
</tr>
<tr>
<td>< </td>
<td><form:hidden path = "id" value = "1" /></td>
</tr>
<tr>
<td colspan = "2">
<input type = "submit" value = "Submit"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
Here, we are using the <form:hidden /> tag to render a HTML hidden field.
For example −
<form:hidden path = "id" value = "1"/>
It will render following HTML content.
<input id = "id" name = "id" type = "hidden" value = "1"/>
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>Submitted Student Information</h2>
<table>
<tr>
<td>Name</td>
<td>${name}</td>
</tr>
<tr>
<td>Age</td>
<td>${age}</td>
</tr>
<tr>
<td>ID</td>
<td>${id}</td>
</tr>
</table>
</body>
</html>
Once you are done with creating source and configuration files, export your application. Right click on your application and use Export → WAR File option and save your HelloWeb.war file in Tomcat's webapps folder.
Now start your Tomcat server and make sure you are able to access other webpages from webapps folder using a standard browser. Try a URL – http://localhost:8080/HelloWeb/student and we will see the following screen, if everything is fine with the Spring Web Application.
After submitting the required information, click on the submit button to submit the form. We will see the following screen, if everything is fine with your Spring Web Application.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 3061,
"s": 2791,
"text": "The following example describes how to use a Hidden Field in forms using the Spring Web MVC framework. To start with, let us have a working Eclipse IDE in place and consider the following steps to develop a Dynamic Form based Web Application using Spring Web Framework."
},
{
"code": null,
"e": 3535,
"s": 3061,
"text": "package com.tutorialspoint;\n\npublic class Student {\n private Integer age;\n private String name;\n private Integer id;\n\n public void setAge(Integer age) {\n this.age = age;\n }\n public Integer getAge() {\n return age;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n public String getName() {\n return name;\n }\n\n public void setId(Integer id) {\n this.id = id;\n }\n public Integer getId() {\n return id;\n }\n}"
},
{
"code": null,
"e": 4480,
"s": 3535,
"text": "package com.tutorialspoint;\n\nimport org.springframework.stereotype.Controller;\nimport org.springframework.web.bind.annotation.ModelAttribute;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestMethod;\nimport org.springframework.web.servlet.ModelAndView;\nimport org.springframework.ui.ModelMap;\n\n@Controller\npublic class StudentController {\n\n @RequestMapping(value = \"/student\", method = RequestMethod.GET)\n public ModelAndView student() {\n return new ModelAndView(\"student\", \"command\", new Student());\n }\n \n @RequestMapping(value = \"/addStudent\", method = RequestMethod.POST)\n public String addStudent(@ModelAttribute(\"SpringWeb\")Student student, \n ModelMap model) {\n model.addAttribute(\"name\", student.getName());\n model.addAttribute(\"age\", student.getAge());\n model.addAttribute(\"id\", student.getId());\n \n return \"result\";\n }\n}"
},
{
"code": null,
"e": 4813,
"s": 4480,
"text": "Here, for the first service method student(), we have passed a blank Studentobject in the ModelAndView object with the name \"command\", because the spring framework expects an object with the name \"command\", if you are using <form:form> tags in your JSP file. So, when the student() method is called, it returns the student.jsp view."
},
{
"code": null,
"e": 5102,
"s": 4813,
"text": "The second service method addStudent() will be called against a POST method on the HelloWeb/addStudent URL. You will prepare your model object based on the submitted information. Finally, a \"result\" view will be returned from the service method, which will result in rendering result.jsp "
},
{
"code": null,
"e": 6017,
"s": 5102,
"text": "<%@taglib uri = \"http://www.springframework.org/tags/form\" prefix = \"form\"%>\n<html>\n <head>\n <title>Spring MVC Form Handling</title>\n </head>\n <body>\n\n <h2>Student Information</h2>\n <form:form method = \"POST\" action = \"/HelloWeb/addStudent\">\n <table>\n <tr>\n <td><form:label path = \"name\">Name</form:label></td>\n <td><form:input path = \"name\" /></td>\n </tr>\n <tr>\n <td><form:label path = \"age\">Age</form:label></td>\n <td><form:input path = \"age\" /></td>\n </tr>\n <tr>\n <td>< </td>\n <td><form:hidden path = \"id\" value = \"1\" /></td>\n </tr>\n <tr>\n <td colspan = \"2\">\n <input type = \"submit\" value = \"Submit\"/>\n </td>\n </tr>\n </table> \n </form:form>\n </body>\n</html>"
},
{
"code": null,
"e": 6091,
"s": 6017,
"text": "Here, we are using the <form:hidden /> tag to render a HTML hidden field."
},
{
"code": null,
"e": 6105,
"s": 6091,
"text": "For example −"
},
{
"code": null,
"e": 6144,
"s": 6105,
"text": "<form:hidden path = \"id\" value = \"1\"/>"
},
{
"code": null,
"e": 6183,
"s": 6144,
"text": "It will render following HTML content."
},
{
"code": null,
"e": 6243,
"s": 6183,
"text": "<input id = \"id\" name = \"id\" type = \"hidden\" value = \"1\"/>\n"
},
{
"code": null,
"e": 6746,
"s": 6243,
"text": "<%@taglib uri = \"http://www.springframework.org/tags/form\" prefix = \"form\"%>\n<html>\n <head>\n <title>Spring MVC Form Handling</title>\n </head>\n <body>\n\n <h2>Submitted Student Information</h2>\n <table>\n <tr>\n <td>Name</td>\n <td>${name}</td>\n </tr>\n <tr>\n <td>Age</td>\n <td>${age}</td>\n </tr>\n <tr>\n <td>ID</td>\n <td>${id}</td>\n </tr>\n </table> \n </body>\n</html>"
},
{
"code": null,
"e": 6960,
"s": 6746,
"text": "Once you are done with creating source and configuration files, export your application. Right click on your application and use Export → WAR File option and save your HelloWeb.war file in Tomcat's webapps folder."
},
{
"code": null,
"e": 7231,
"s": 6960,
"text": "Now start your Tomcat server and make sure you are able to access other webpages from webapps folder using a standard browser. Try a URL – http://localhost:8080/HelloWeb/student and we will see the following screen, if everything is fine with the Spring Web Application."
},
{
"code": null,
"e": 7411,
"s": 7231,
"text": "After submitting the required information, click on the submit button to submit the form. We will see the following screen, if everything is fine with your Spring Web Application."
},
{
"code": null,
"e": 7418,
"s": 7411,
"text": " Print"
},
{
"code": null,
"e": 7429,
"s": 7418,
"text": " Add Notes"
}
] |
Connecting MongoDB with NodeJS | This method is used to connect the Mongo DB server with our Node application. This is an asynchronous method from MongoDB module.
mongodb.connect(path[, callback])
•path – The server path where the MongoDB server is actually running along with its port.
•path – The server path where the MongoDB server is actually running along with its port.
•callback – This function will give a callback if any error occurs.
•callback – This function will give a callback if any error occurs.
Before proceeding to try connect your application with Nodejs, we need to setup our MongoDB server first.
Use the following query to install mongoDB from npm.
Use the following query to install mongoDB from npm.
npm install mongodb –save
Run the following command to set up your mongoDB on the specific localhost server. This will help in creating connection with the MongoDB.
Run the following command to set up your mongoDB on the specific localhost server. This will help in creating connection with the MongoDB.
mongod --dbpath=data --bind_ip 127.0.0.1
Create a MongodbConnect.js and copy-paste the following code snippet into that file.
Create a MongodbConnect.js and copy-paste the following code snippet into that file.
Now, run the following command to run the code snippet.
Now, run the following command to run the code snippet.
node MongodbConnect.js
// Calling the required MongoDB module.
const MongoClient = require("mongodb");
// Server path
const url = 'mongodb://localhost:27017/';
// Name of the database
const dbname = "Employee";
MongoClient.connect(url, (err,client)=>{
if(!err) {
console.log("successful connection with the server");
}
else
console.log("Error in the connectivity");
})
C:\Users\tutorialsPoint\> node MongodbConnect.js
(node:7016) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
(Use `node --trace-deprecation ...` to show where the warning was created)
successful connection with the server. | [
{
"code": null,
"e": 1192,
"s": 1062,
"text": "This method is used to connect the Mongo DB server with our Node application. This is an asynchronous method from MongoDB module."
},
{
"code": null,
"e": 1226,
"s": 1192,
"text": "mongodb.connect(path[, callback])"
},
{
"code": null,
"e": 1316,
"s": 1226,
"text": "•path – The server path where the MongoDB server is actually running along with its port."
},
{
"code": null,
"e": 1406,
"s": 1316,
"text": "•path – The server path where the MongoDB server is actually running along with its port."
},
{
"code": null,
"e": 1474,
"s": 1406,
"text": "•callback – This function will give a callback if any error occurs."
},
{
"code": null,
"e": 1542,
"s": 1474,
"text": "•callback – This function will give a callback if any error occurs."
},
{
"code": null,
"e": 1648,
"s": 1542,
"text": "Before proceeding to try connect your application with Nodejs, we need to setup our MongoDB server first."
},
{
"code": null,
"e": 1701,
"s": 1648,
"text": "Use the following query to install mongoDB from npm."
},
{
"code": null,
"e": 1754,
"s": 1701,
"text": "Use the following query to install mongoDB from npm."
},
{
"code": null,
"e": 1780,
"s": 1754,
"text": "npm install mongodb –save"
},
{
"code": null,
"e": 1919,
"s": 1780,
"text": "Run the following command to set up your mongoDB on the specific localhost server. This will help in creating connection with the MongoDB."
},
{
"code": null,
"e": 2058,
"s": 1919,
"text": "Run the following command to set up your mongoDB on the specific localhost server. This will help in creating connection with the MongoDB."
},
{
"code": null,
"e": 2099,
"s": 2058,
"text": "mongod --dbpath=data --bind_ip 127.0.0.1"
},
{
"code": null,
"e": 2184,
"s": 2099,
"text": "Create a MongodbConnect.js and copy-paste the following code snippet into that file."
},
{
"code": null,
"e": 2269,
"s": 2184,
"text": "Create a MongodbConnect.js and copy-paste the following code snippet into that file."
},
{
"code": null,
"e": 2325,
"s": 2269,
"text": "Now, run the following command to run the code snippet."
},
{
"code": null,
"e": 2381,
"s": 2325,
"text": "Now, run the following command to run the code snippet."
},
{
"code": null,
"e": 2404,
"s": 2381,
"text": "node MongodbConnect.js"
},
{
"code": null,
"e": 2774,
"s": 2404,
"text": "// Calling the required MongoDB module.\nconst MongoClient = require(\"mongodb\");\n\n// Server path\nconst url = 'mongodb://localhost:27017/';\n\n// Name of the database\nconst dbname = \"Employee\";\n\nMongoClient.connect(url, (err,client)=>{\n if(!err) {\n console.log(\"successful connection with the server\");\n }\n else\n console.log(\"Error in the connectivity\");\n})"
},
{
"code": null,
"e": 3199,
"s": 2774,
"text": "C:\\Users\\tutorialsPoint\\> node MongodbConnect.js\n(node:7016) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.\n(Use `node --trace-deprecation ...` to show where the warning was created)\nsuccessful connection with the server."
}
] |
GWT - ScrollPanel Widget | The ScrollPanel widget represents a simple panel that wraps its contents in a scrollable area.
Following is the declaration for com.google.gwt.user.client.ui.ScrollPanel class −
public class ScrollPanel
extends SimplePanel
implements SourcesScrollEvents, HasScrollHandlers,
RequiresResize, ProvidesResize
ScrollPanel()
Creates an empty scroll panel.
ScrollPanel(Widget child)
Creates a new scroll panel with the given child widget.
HandlerRegistration addScrollHandler(ScrollHandler handler)
Adds a ScrollEvent handler.
void addScrollListener(ScrollListener listener)
Deprecated. Use addScrollHandler(com.google.gwt.event.dom.client.ScrollHandler) instead
void ensureVisible(UIObject item)
Ensures that the specified item is visible, by adjusting the panel's scroll position.
protected Element getContainerElement()
Override this method to specify that an element other than the root element be the container for the panel's child widget.
int getHorizontalScrollPosition()
Gets the horizontal scroll position.
int getScrollPosition()
Gets the vertical scroll position.
void onResize()
This method must be called whenever the implementor's size has been modified.
void removeScrollListener(ScrollListener listener)
Deprecated. Use the HandlerRegistration.removeHandler() method on the object returned by addScrollHandler(com.google.gwt.event.dom.client.ScrollHandler) instead
void scrollToBottom()
Scroll to the bottom of this panel.
void scrollToLeft()
Scroll to the far left of this panel.
void scrollToRight()
Scroll to the far right of this panel.
void scrollToTop()
Scroll to the top of this panel.
void setAlwaysShowScrollBars(boolean alwaysShow)
Sets whether this panel always shows its scroll bars, or only when necessary.
void setHeight(java.lang.String height)
Sets the object's height.
void setHorizontalScrollPosition(int position)
Sets the horizontal scroll position.
void setScrollPosition(int position)
Sets the vertical scroll position.
void setSize(java.lang.String width, java.lang.String height)
Sets the object's size.
void setWidth(java.lang.String width)
Sets the object's width.
This class inherits methods from the following classes −
com.google.gwt.user.client.ui.UIObject
com.google.gwt.user.client.ui.UIObject
com.google.gwt.user.client.ui.Widget
com.google.gwt.user.client.ui.Widget
com.google.gwt.user.client.ui.Panel
com.google.gwt.user.client.ui.Panel
com.google.gwt.user.client.ui.SimplePanel
com.google.gwt.user.client.ui.SimplePanel
java.lang.Object
java.lang.Object
This example will take you through simple steps to show usage of a ScrollPanel Widget in GWT. Follow the following steps to update the GWT application we created in GWT - Create Application chapter −
Following is the content of the modified module descriptor src/com.tutorialspoint/HelloWorld.gwt.xml.
<?xml version = "1.0" encoding = "UTF-8"?>
<module rename-to = 'helloworld'>
<!-- Inherit the core Web Toolkit stuff. -->
<inherits name = 'com.google.gwt.user.User'/>
<!-- Inherit the default GWT style sheet. -->
<inherits name = 'com.google.gwt.user.theme.clean.Clean'/>
<!-- Specify the app entry point class. -->
<entry-point class = 'com.tutorialspoint.client.HelloWorld'/>
<!-- Specify the paths for translatable code -->
<source path = 'client'/>
<source path = 'shared'/>
</module>
Following is the content of the modified Style Sheet file war/HelloWorld.css.
body {
text-align: center;
font-family: verdana, sans-serif;
}
h1 {
font-size: 2em;
font-weight: bold;
color: #777777;
margin: 40px 0px 70px;
text-align: center;
}
Following is the content of the modified HTML host file war/HelloWorld.html.
<html>
<head>
<title>Hello World</title>
<link rel = "stylesheet" href = "HelloWorld.css"/>
<script language = "javascript" src = "helloworld/helloworld.nocache.js">
</script>
</head>
<body>
<h1>ScrollPanel Widget Demonstration</h1>
<div id = "gwtContainer"></div>
</body>
</html>
Let us have following content of Java file src/com.tutorialspoint/HelloWorld.java which will demonstrate use of ScrollPanel widget.
package com.tutorialspoint.client;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.ui.DecoratorPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.ScrollPanel;
public class HelloWorld implements EntryPoint {
public void onModuleLoad() {
// Create scrollable text
HTML contents = new HTML("This is a ScrollPanel."
+" By putting some fairly large contents in the middle"
+" and setting its size explicitly, it becomes a scrollable area"
+" within the page, but without requiring the use of an IFRAME."
+" Here's quite a bit more meaningless text that will serve primarily"
+" to make this thing scroll off the bottom of its visible area."
+" Otherwise, you might have to make it really, really"
+" small in order to see the nifty scroll bars!");
//create scrollpanel with content
ScrollPanel scrollPanel = new ScrollPanel(contents);
scrollPanel.setSize("400px", "100px");
DecoratorPanel decoratorPanel = new DecoratorPanel();
decoratorPanel.add(scrollPanel);
// Add the widgets to the root panel.
RootPanel.get().add(decoratorPanel);
}
}
Once you are ready with all the changes done, let us compile and run the application in development mode as we did in GWT - Create Application chapter. If everything is fine with your application, this will produce following result −
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2118,
"s": 2023,
"text": "The ScrollPanel widget represents a simple panel that wraps its contents in a scrollable area."
},
{
"code": null,
"e": 2201,
"s": 2118,
"text": "Following is the declaration for com.google.gwt.user.client.ui.ScrollPanel class −"
},
{
"code": null,
"e": 2346,
"s": 2201,
"text": "public class ScrollPanel\n extends SimplePanel\n implements SourcesScrollEvents, HasScrollHandlers,\n RequiresResize, ProvidesResize"
},
{
"code": null,
"e": 2360,
"s": 2346,
"text": "ScrollPanel()"
},
{
"code": null,
"e": 2391,
"s": 2360,
"text": "Creates an empty scroll panel."
},
{
"code": null,
"e": 2417,
"s": 2391,
"text": "ScrollPanel(Widget child)"
},
{
"code": null,
"e": 2473,
"s": 2417,
"text": "Creates a new scroll panel with the given child widget."
},
{
"code": null,
"e": 2533,
"s": 2473,
"text": "HandlerRegistration addScrollHandler(ScrollHandler handler)"
},
{
"code": null,
"e": 2561,
"s": 2533,
"text": "Adds a ScrollEvent handler."
},
{
"code": null,
"e": 2609,
"s": 2561,
"text": "void addScrollListener(ScrollListener listener)"
},
{
"code": null,
"e": 2697,
"s": 2609,
"text": "Deprecated. Use addScrollHandler(com.google.gwt.event.dom.client.ScrollHandler) instead"
},
{
"code": null,
"e": 2731,
"s": 2697,
"text": "void ensureVisible(UIObject item)"
},
{
"code": null,
"e": 2817,
"s": 2731,
"text": "Ensures that the specified item is visible, by adjusting the panel's scroll position."
},
{
"code": null,
"e": 2857,
"s": 2817,
"text": "protected Element getContainerElement()"
},
{
"code": null,
"e": 2980,
"s": 2857,
"text": "Override this method to specify that an element other than the root element be the container for the panel's child widget."
},
{
"code": null,
"e": 3014,
"s": 2980,
"text": "int getHorizontalScrollPosition()"
},
{
"code": null,
"e": 3051,
"s": 3014,
"text": "Gets the horizontal scroll position."
},
{
"code": null,
"e": 3075,
"s": 3051,
"text": "int getScrollPosition()"
},
{
"code": null,
"e": 3110,
"s": 3075,
"text": "Gets the vertical scroll position."
},
{
"code": null,
"e": 3126,
"s": 3110,
"text": "void onResize()"
},
{
"code": null,
"e": 3204,
"s": 3126,
"text": "This method must be called whenever the implementor's size has been modified."
},
{
"code": null,
"e": 3255,
"s": 3204,
"text": "void removeScrollListener(ScrollListener listener)"
},
{
"code": null,
"e": 3416,
"s": 3255,
"text": "Deprecated. Use the HandlerRegistration.removeHandler() method on the object returned by addScrollHandler(com.google.gwt.event.dom.client.ScrollHandler) instead"
},
{
"code": null,
"e": 3438,
"s": 3416,
"text": "void scrollToBottom()"
},
{
"code": null,
"e": 3474,
"s": 3438,
"text": "Scroll to the bottom of this panel."
},
{
"code": null,
"e": 3494,
"s": 3474,
"text": "void scrollToLeft()"
},
{
"code": null,
"e": 3532,
"s": 3494,
"text": "Scroll to the far left of this panel."
},
{
"code": null,
"e": 3553,
"s": 3532,
"text": "void scrollToRight()"
},
{
"code": null,
"e": 3592,
"s": 3553,
"text": "Scroll to the far right of this panel."
},
{
"code": null,
"e": 3611,
"s": 3592,
"text": "void scrollToTop()"
},
{
"code": null,
"e": 3644,
"s": 3611,
"text": "Scroll to the top of this panel."
},
{
"code": null,
"e": 3693,
"s": 3644,
"text": "void setAlwaysShowScrollBars(boolean alwaysShow)"
},
{
"code": null,
"e": 3771,
"s": 3693,
"text": "Sets whether this panel always shows its scroll bars, or only when necessary."
},
{
"code": null,
"e": 3811,
"s": 3771,
"text": "void setHeight(java.lang.String height)"
},
{
"code": null,
"e": 3837,
"s": 3811,
"text": "Sets the object's height."
},
{
"code": null,
"e": 3884,
"s": 3837,
"text": "void setHorizontalScrollPosition(int position)"
},
{
"code": null,
"e": 3921,
"s": 3884,
"text": "Sets the horizontal scroll position."
},
{
"code": null,
"e": 3958,
"s": 3921,
"text": "void setScrollPosition(int position)"
},
{
"code": null,
"e": 3993,
"s": 3958,
"text": "Sets the vertical scroll position."
},
{
"code": null,
"e": 4055,
"s": 3993,
"text": "void setSize(java.lang.String width, java.lang.String height)"
},
{
"code": null,
"e": 4079,
"s": 4055,
"text": "Sets the object's size."
},
{
"code": null,
"e": 4117,
"s": 4079,
"text": "void setWidth(java.lang.String width)"
},
{
"code": null,
"e": 4142,
"s": 4117,
"text": "Sets the object's width."
},
{
"code": null,
"e": 4199,
"s": 4142,
"text": "This class inherits methods from the following classes −"
},
{
"code": null,
"e": 4238,
"s": 4199,
"text": "com.google.gwt.user.client.ui.UIObject"
},
{
"code": null,
"e": 4277,
"s": 4238,
"text": "com.google.gwt.user.client.ui.UIObject"
},
{
"code": null,
"e": 4314,
"s": 4277,
"text": "com.google.gwt.user.client.ui.Widget"
},
{
"code": null,
"e": 4351,
"s": 4314,
"text": "com.google.gwt.user.client.ui.Widget"
},
{
"code": null,
"e": 4387,
"s": 4351,
"text": "com.google.gwt.user.client.ui.Panel"
},
{
"code": null,
"e": 4423,
"s": 4387,
"text": "com.google.gwt.user.client.ui.Panel"
},
{
"code": null,
"e": 4465,
"s": 4423,
"text": "com.google.gwt.user.client.ui.SimplePanel"
},
{
"code": null,
"e": 4507,
"s": 4465,
"text": "com.google.gwt.user.client.ui.SimplePanel"
},
{
"code": null,
"e": 4524,
"s": 4507,
"text": "java.lang.Object"
},
{
"code": null,
"e": 4541,
"s": 4524,
"text": "java.lang.Object"
},
{
"code": null,
"e": 4742,
"s": 4541,
"text": "This example will take you through simple steps to show usage of a ScrollPanel Widget in GWT. Follow the following steps to update the GWT application we created in GWT - Create Application chapter −"
},
{
"code": null,
"e": 4844,
"s": 4742,
"text": "Following is the content of the modified module descriptor src/com.tutorialspoint/HelloWorld.gwt.xml."
},
{
"code": null,
"e": 5453,
"s": 4844,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<module rename-to = 'helloworld'>\n <!-- Inherit the core Web Toolkit stuff. -->\n <inherits name = 'com.google.gwt.user.User'/>\n\n <!-- Inherit the default GWT style sheet. -->\n <inherits name = 'com.google.gwt.user.theme.clean.Clean'/>\n\n <!-- Specify the app entry point class. -->\n <entry-point class = 'com.tutorialspoint.client.HelloWorld'/>\n\n <!-- Specify the paths for translatable code -->\n <source path = 'client'/>\n <source path = 'shared'/>\n\n</module>"
},
{
"code": null,
"e": 5531,
"s": 5453,
"text": "Following is the content of the modified Style Sheet file war/HelloWorld.css."
},
{
"code": null,
"e": 5717,
"s": 5531,
"text": "body {\n text-align: center;\n font-family: verdana, sans-serif;\n}\n\nh1 {\n font-size: 2em;\n font-weight: bold;\n color: #777777;\n margin: 40px 0px 70px;\n text-align: center;\n}"
},
{
"code": null,
"e": 5794,
"s": 5717,
"text": "Following is the content of the modified HTML host file war/HelloWorld.html."
},
{
"code": null,
"e": 6124,
"s": 5794,
"text": "<html>\n <head>\n <title>Hello World</title>\n <link rel = \"stylesheet\" href = \"HelloWorld.css\"/>\n <script language = \"javascript\" src = \"helloworld/helloworld.nocache.js\">\n </script>\n </head>\n\n <body>\n <h1>ScrollPanel Widget Demonstration</h1>\n <div id = \"gwtContainer\"></div>\n </body>\n</html>"
},
{
"code": null,
"e": 6256,
"s": 6124,
"text": "Let us have following content of Java file src/com.tutorialspoint/HelloWorld.java which will demonstrate use of ScrollPanel widget."
},
{
"code": null,
"e": 7540,
"s": 6256,
"text": "package com.tutorialspoint.client;\n\nimport com.google.gwt.core.client.EntryPoint;\nimport com.google.gwt.user.client.ui.DecoratorPanel;\nimport com.google.gwt.user.client.ui.HTML;\nimport com.google.gwt.user.client.ui.RootPanel;\nimport com.google.gwt.user.client.ui.ScrollPanel;\n\npublic class HelloWorld implements EntryPoint {\n\n public void onModuleLoad() {\n // Create scrollable text \n HTML contents = new HTML(\"This is a ScrollPanel.\"\n +\" By putting some fairly large contents in the middle\"\n +\" and setting its size explicitly, it becomes a scrollable area\"\n +\" within the page, but without requiring the use of an IFRAME.\"\n +\" Here's quite a bit more meaningless text that will serve primarily\"\n +\" to make this thing scroll off the bottom of its visible area.\"\n +\" Otherwise, you might have to make it really, really\"\n +\" small in order to see the nifty scroll bars!\");\n\n //create scrollpanel with content\n ScrollPanel scrollPanel = new ScrollPanel(contents);\n scrollPanel.setSize(\"400px\", \"100px\");\n\n DecoratorPanel decoratorPanel = new DecoratorPanel();\n\n decoratorPanel.add(scrollPanel);\n\n // Add the widgets to the root panel.\n RootPanel.get().add(decoratorPanel);\n } \n}"
},
{
"code": null,
"e": 7774,
"s": 7540,
"text": "Once you are ready with all the changes done, let us compile and run the application in development mode as we did in GWT - Create Application chapter. If everything is fine with your application, this will produce following result −"
},
{
"code": null,
"e": 7781,
"s": 7774,
"text": " Print"
},
{
"code": null,
"e": 7792,
"s": 7781,
"text": " Add Notes"
}
] |
How to find the longest common substring from more than two strings in Python? | Common dynamic programming implementations for the Longest Common Substring algorithm runs in O(nm) time. The following is an implementation of the longest common substring algorithm:
def longest_common_substring(s1, s2):
m = [[0] * (1 + len(s2)) for i in xrange(1 + len(s1))]
longest, x_longest = 0, 0
for x in xrange(1, 1 + len(s1)):
for y in xrange(1, 1 + len(s2)):
if s1[x - 1] == s2[y - 1]:
m[x][y] = m[x - 1][y - 1] + 1
if m[x][y] > longest:
longest = m[x][y]
x_longest = x
else:
m[x][y] = 0
return s1[x_longest - longest: x_longest]
print(longest_common_substring('wellbeing', 'welcome'))
wel
This is how it works
Initially, we initialized the counter array(m) all 0.
Initially, we initialized the counter array(m) all 0.
Starting from the 1st row, we will compare the first character of a string s1 with all characters in a string s2.
Starting from the 1st row, we will compare the first character of a string s1 with all characters in a string s2.
While we traverse the characters in s2, if it matches with the character in s1, we increment the counter. It will be saved m[i][j] which is at diagonally one lower position.
While we traverse the characters in s2, if it matches with the character in s1, we increment the counter. It will be saved m[i][j] which is at diagonally one lower position.
At the end we return the longest sub-string using indices we calculated in the loops. | [
{
"code": null,
"e": 1246,
"s": 1062,
"text": "Common dynamic programming implementations for the Longest Common Substring algorithm runs in O(nm) time. The following is an implementation of the longest common substring algorithm:"
},
{
"code": null,
"e": 1782,
"s": 1246,
"text": "def longest_common_substring(s1, s2):\n m = [[0] * (1 + len(s2)) for i in xrange(1 + len(s1))]\n longest, x_longest = 0, 0\n for x in xrange(1, 1 + len(s1)):\n for y in xrange(1, 1 + len(s2)):\n if s1[x - 1] == s2[y - 1]:\n m[x][y] = m[x - 1][y - 1] + 1\n if m[x][y] > longest:\n longest = m[x][y]\n x_longest = x\n else:\n m[x][y] = 0\n return s1[x_longest - longest: x_longest]\nprint(longest_common_substring('wellbeing', 'welcome'))"
},
{
"code": null,
"e": 1786,
"s": 1782,
"text": "wel"
},
{
"code": null,
"e": 1807,
"s": 1786,
"text": "This is how it works"
},
{
"code": null,
"e": 1861,
"s": 1807,
"text": "Initially, we initialized the counter array(m) all 0."
},
{
"code": null,
"e": 1915,
"s": 1861,
"text": "Initially, we initialized the counter array(m) all 0."
},
{
"code": null,
"e": 2029,
"s": 1915,
"text": "Starting from the 1st row, we will compare the first character of a string s1 with all characters in a string s2."
},
{
"code": null,
"e": 2143,
"s": 2029,
"text": "Starting from the 1st row, we will compare the first character of a string s1 with all characters in a string s2."
},
{
"code": null,
"e": 2317,
"s": 2143,
"text": "While we traverse the characters in s2, if it matches with the character in s1, we increment the counter. It will be saved m[i][j] which is at diagonally one lower position."
},
{
"code": null,
"e": 2491,
"s": 2317,
"text": "While we traverse the characters in s2, if it matches with the character in s1, we increment the counter. It will be saved m[i][j] which is at diagonally one lower position."
},
{
"code": null,
"e": 2577,
"s": 2491,
"text": "At the end we return the longest sub-string using indices we calculated in the loops."
}
] |
Matcher group() method in Java with Examples | The java.util.regex.Matcher class represents an engine that performs various match operations. There is no constructor for this class, you can create/obtain an object of this class using the matches() method of the class java.util.regex.Pattern.
The group() method of this (Matcher) class returns the matched input subsequence during the last match.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class GroupExample {
public static void main(String[] args) {
String str = "<p>This <b>is</b> an <b>example</b> HTML <b>script</b> "
+ "where <b>every</b> alternative <b>word</b> is <b>bold</b>. "
+ "It <i>also</i> contains <i>italic</i> words</p>";
//Regular expression to match contents of the bold tags
String regex = "<b>(\\S+)</b>|<i>(\\S+)</i>";
//Creating a pattern object
Pattern pattern = Pattern.compile(regex);
//Matching the compiled pattern in the String
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
System.out.println(matcher.group());
}
}
}
<b>is</b>
<b>example</b>
<b>script</b>
<b>every</b>
<b>word</b>
<b>bold</b>
<i>also</i>
<i>italic</i>
Another variant of this method accepts an integer variable representing the group, where the captured groups are indexed starting from 1 (left to right).
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class GroupTest {
public static void main(String[] args) {
String regex = "(.*)(\\d+)(.*)";
String input = "This is a sample Text, 1234, with numbers in between.";
//Creating a pattern object
Pattern pattern = Pattern.compile(regex);
//Matching the compiled pattern in the String
Matcher matcher = pattern.matcher(input);
if(matcher.find()) {
System.out.println("match: "+matcher.group(0));
System.out.println("First group match: "+matcher.group(1));
System.out.println("Second group match: "+matcher.group(2));
System.out.println("Third group match: "+matcher.group(3));
}
}
}
match: This is a sample Text, 1234, with numbers in between.
First group match: This is a sample Text, 123
Second group match: 4
Third group match: , with numbers in between. | [
{
"code": null,
"e": 1308,
"s": 1062,
"text": "The java.util.regex.Matcher class represents an engine that performs various match operations. There is no constructor for this class, you can create/obtain an object of this class using the matches() method of the class java.util.regex.Pattern."
},
{
"code": null,
"e": 1412,
"s": 1308,
"text": "The group() method of this (Matcher) class returns the matched input subsequence during the last match."
},
{
"code": null,
"e": 2146,
"s": 1412,
"text": "import java.util.regex.Matcher;\nimport java.util.regex.Pattern;\npublic class GroupExample {\n public static void main(String[] args) {\n String str = \"<p>This <b>is</b> an <b>example</b> HTML <b>script</b> \"\n + \"where <b>every</b> alternative <b>word</b> is <b>bold</b>. \"\n + \"It <i>also</i> contains <i>italic</i> words</p>\";\n //Regular expression to match contents of the bold tags\n String regex = \"<b>(\\\\S+)</b>|<i>(\\\\S+)</i>\";\n //Creating a pattern object\n Pattern pattern = Pattern.compile(regex);\n //Matching the compiled pattern in the String\n Matcher matcher = pattern.matcher(str);\n while (matcher.find()) {\n System.out.println(matcher.group());\n }\n }\n}"
},
{
"code": null,
"e": 2248,
"s": 2146,
"text": "<b>is</b>\n<b>example</b>\n<b>script</b>\n<b>every</b>\n<b>word</b>\n<b>bold</b>\n<i>also</i>\n<i>italic</i>"
},
{
"code": null,
"e": 2402,
"s": 2248,
"text": "Another variant of this method accepts an integer variable representing the group, where the captured groups are indexed starting from 1 (left to right)."
},
{
"code": null,
"e": 3141,
"s": 2402,
"text": "import java.util.regex.Matcher;\nimport java.util.regex.Pattern;\npublic class GroupTest {\n public static void main(String[] args) {\n String regex = \"(.*)(\\\\d+)(.*)\";\n String input = \"This is a sample Text, 1234, with numbers in between.\";\n //Creating a pattern object\n Pattern pattern = Pattern.compile(regex);\n //Matching the compiled pattern in the String\n Matcher matcher = pattern.matcher(input);\n if(matcher.find()) {\n System.out.println(\"match: \"+matcher.group(0));\n System.out.println(\"First group match: \"+matcher.group(1));\n System.out.println(\"Second group match: \"+matcher.group(2));\n System.out.println(\"Third group match: \"+matcher.group(3));\n }\n }\n}"
},
{
"code": null,
"e": 3316,
"s": 3141,
"text": "match: This is a sample Text, 1234, with numbers in between.\nFirst group match: This is a sample Text, 123\nSecond group match: 4\nThird group match: , with numbers in between."
}
] |
Deleting all rows older than 5 days in MySQL | To delete all rows older than 5 days, you can use the following syntax −
delete from yourTableName
where datediff(now(), yourTableName.yourDateColumnName) > 5;
Note − Let’s say the current date is 2019-03-10.
To understand the concept, let us create a table. The query to create a table is as follows −
mysql> create table deleteRowsOlderThan5Demo
-> (
-> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> Name varchar(100),
-> Post_Date date
-> );
Query OK, 0 rows affected (0.69 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into deleteRowsOlderThan5Demo(Name,Post_Date) values('Larry','2019-03-
11');
Query OK, 1 row affected (0.12 sec)
mysql> insert into deleteRowsOlderThan5Demo(Name,Post_Date) values('Mike','2019-02-
12');
Query OK, 1 row affected (0.17 sec)
mysql> insert into deleteRowsOlderThan5Demo(Name,Post_Date) values('Sam','2019-03-
10');
Query OK, 1 row affected (0.12 sec)
mysql> insert into deleteRowsOlderThan5Demo(Name,Post_Date) values('Carol','2019-03-
01');
Query OK, 1 row affected (0.23 sec)
mysql> insert into deleteRowsOlderThan5Demo(Name,Post_Date) values('David','2019-01-
31');
Query OK, 1 row affected (0.19 sec)
mysql> insert into deleteRowsOlderThan5Demo(Name,Post_Date) values('Maxwell','2019-01-
26');
Query OK, 1 row affected (0.10 sec)
mysql> insert into deleteRowsOlderThan5Demo(Name,Post_Date) values('John','2019-02-
19');
Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from deleteRowsOlderThan5Demo;
Here is the output −
+----+---------+------------+
| Id | Name | Post_Date |
+----+---------+------------+
| 1 | Larry | 2019-03-11 |
| 2 | Mike | 2019-02-12 |
| 3 | Sam | 2019-03-10 |
| 4 | Carol | 2019-03-01 |
| 5 | David | 2019-01-31 |
| 6 | Maxwell | 2019-01-26 |
| 7 | John | 2019-02-19 |
+----+---------+------------+
7 rows in set (0.00 sec)
Here is the query to delete all rows older than 5 days −
mysql> delete from deleteRowsOlderThan5Demo
-> where datediff(now(), deleteRowsOlderThan5Demo.Post_Date) > 5;
Query OK, 5 rows affected (0.14 sec)
Let us check the table records once again. The query is as follows −
mysql> select *from deleteRowsOlderThan5Demo;
Here is the output −
+----+-------+------------+
| Id | Name | Post_Date |
+----+-------+------------+
| 1 | Larry | 2019-03-11 |
| 3 | Sam | 2019-03-10 |
+----+-------+------------+
2 rows in set (0.00 sec) | [
{
"code": null,
"e": 1135,
"s": 1062,
"text": "To delete all rows older than 5 days, you can use the following syntax −"
},
{
"code": null,
"e": 1225,
"s": 1135,
"text": "delete from yourTableName\n where datediff(now(), yourTableName.yourDateColumnName) > 5;"
},
{
"code": null,
"e": 1274,
"s": 1225,
"text": "Note − Let’s say the current date is 2019-03-10."
},
{
"code": null,
"e": 1368,
"s": 1274,
"text": "To understand the concept, let us create a table. The query to create a table is as follows −"
},
{
"code": null,
"e": 1563,
"s": 1368,
"text": "mysql> create table deleteRowsOlderThan5Demo\n -> (\n -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> Name varchar(100),\n -> Post_Date date\n -> );\nQuery OK, 0 rows affected (0.69 sec)"
},
{
"code": null,
"e": 1644,
"s": 1563,
"text": "Insert some records in the table using insert command. The query is as follows −"
},
{
"code": null,
"e": 2531,
"s": 1644,
"text": "mysql> insert into deleteRowsOlderThan5Demo(Name,Post_Date) values('Larry','2019-03-\n11');\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into deleteRowsOlderThan5Demo(Name,Post_Date) values('Mike','2019-02-\n12');\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into deleteRowsOlderThan5Demo(Name,Post_Date) values('Sam','2019-03-\n10');\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into deleteRowsOlderThan5Demo(Name,Post_Date) values('Carol','2019-03-\n01');\nQuery OK, 1 row affected (0.23 sec)\nmysql> insert into deleteRowsOlderThan5Demo(Name,Post_Date) values('David','2019-01-\n31');\nQuery OK, 1 row affected (0.19 sec)\nmysql> insert into deleteRowsOlderThan5Demo(Name,Post_Date) values('Maxwell','2019-01-\n26');\nQuery OK, 1 row affected (0.10 sec)\nmysql> insert into deleteRowsOlderThan5Demo(Name,Post_Date) values('John','2019-02-\n19');\nQuery OK, 1 row affected (0.12 sec)"
},
{
"code": null,
"e": 2616,
"s": 2531,
"text": "Display all records from the table using select statement. The query is as follows −"
},
{
"code": null,
"e": 2662,
"s": 2616,
"text": "mysql> select *from deleteRowsOlderThan5Demo;"
},
{
"code": null,
"e": 2683,
"s": 2662,
"text": "Here is the output −"
},
{
"code": null,
"e": 3038,
"s": 2683,
"text": "+----+---------+------------+\n| Id | Name | Post_Date |\n+----+---------+------------+\n| 1 | Larry | 2019-03-11 |\n| 2 | Mike | 2019-02-12 |\n| 3 | Sam | 2019-03-10 |\n| 4 | Carol | 2019-03-01 |\n| 5 | David | 2019-01-31 |\n| 6 | Maxwell | 2019-01-26 |\n| 7 | John | 2019-02-19 |\n+----+---------+------------+\n7 rows in set (0.00 sec)"
},
{
"code": null,
"e": 3095,
"s": 3038,
"text": "Here is the query to delete all rows older than 5 days −"
},
{
"code": null,
"e": 3245,
"s": 3095,
"text": "mysql> delete from deleteRowsOlderThan5Demo\n -> where datediff(now(), deleteRowsOlderThan5Demo.Post_Date) > 5;\nQuery OK, 5 rows affected (0.14 sec)"
},
{
"code": null,
"e": 3314,
"s": 3245,
"text": "Let us check the table records once again. The query is as follows −"
},
{
"code": null,
"e": 3360,
"s": 3314,
"text": "mysql> select *from deleteRowsOlderThan5Demo;"
},
{
"code": null,
"e": 3381,
"s": 3360,
"text": "Here is the output −"
},
{
"code": null,
"e": 3574,
"s": 3381,
"text": "+----+-------+------------+\n| Id | Name | Post_Date |\n+----+-------+------------+\n| 1 | Larry | 2019-03-11 |\n| 3 | Sam | 2019-03-10 |\n+----+-------+------------+\n2 rows in set (0.00 sec)"
}
] |
Basic Sentiment Analysis using NLTK | by Samira Munir | Towards Data Science | “Your most unhappy customers are your greatest source of learning.” — Bill Gates
So what does the customer say?
In today’s context, it turns out A LOT. Social media has opened the floodgates of customer opinions and it is now free-flowing in mammoth proportions for businesses to analyze. Today, using machine learning companies are able to extract these opinions in the form of text or audio and then analyze the emotions behind them on an unprecedented scale. Sentiment analysis, opinion mining call it what you like, if you have a product/service to sell you need to be on it.
“ When captured electronically, customer sentiment — expressions beyond facts, that convey mood, opinion, and emotion — carries immense business value. We’re talking the voice of the customer, and of the prospect, patient, voter, and opinion leader.” — Seth Grimes
Starting from user reviews in media to analyzing stock prices, sentiment analysis has become a ubiquitous tool in almost all industries. For example, the graph below shows the stock price movement of eBay with a sentiment index created based on an analysis of tweets that mention eBay.
Techopedia defines sentiment analysis as follows:
Sentiment analysis is a type of data mining that measures the inclination of people’s opinions through natural language processing (NLP), computational linguistics and text analysis, which are used to extract and analyze subjective information from the Web — mostly social media and similar sources. The analyzed data quantifies the general public’s sentiments or reactions toward certain products, people or ideas and reveal the contextual polarity of the information. Sentiment analysis is also known as opinion mining.
There are two broad approaches to sentiment analysis.
Pure statistics:
These kinds of algorithms treat texts as Bags of Words (BOW), where the order of words and as such context is ignored. The original text is filtered down to only the words that are thought to carry sentiment. For this blog, I will be attempting this approach. Such models make no use of understanding of a certain language and only uses statistical measures to classify a text.
A mix of statistics and linguistics:
These algorithms attempt to incorporate grammar principles, various natural language processing techniques and statistics to train the machine to truly ‘understand’ the language.
Sentiment analysis can also be broadly categorized into two kinds, based on the type of output the analysis generates.
Categorical/Polarity— Was that bit of text “positive”, “neutral” or “negative?” In this process, you are trying to label a piece of text as either positive or negative or neutral.
Scalar/Degree — Give a score on a predefined scale that ranges from highly positive to highly negative. For example, the figure below shows an analysis of of sentiment based on tweets about various election candidates. In this instance the sentiment is being measured in a scalar form.
During my data science boot camp, I took a crack at building a basic sentiment analysis tool using NLTK library. I found a nifty youtube tutorial and followed the steps listed to learn how to do basic sentiment analysis. While the tutorial focuses on analyzing Twitter sentiments, I wanted to see if I could label movie reviews into either positive or negative. I found a labeled dataset of 25000 IMDB reviews in the form of .txt files separated into two folders for negative and positive reviews.
I imported the following libraries on my Jupyter notebook and read the positive and negative reviews from their respective folders.
Making the Bag of Words (BOW): For our Bag of Words(BOW) we technically could include all unique words. However, it can be computationally expensive and even unnecessary to include all unique words in our analysis. For example, the name of an actress in a review would not give any information about the sentiment of a review. So, we need to be smart and select the most informative words.
For the small scope of the project and also as guided by the tutorial, I selected only adjectives from the features based on the assumption that adjectives are highly informative of positive and negative sentiments. For each review, I removed punctuations, tokenized the string, removed stop words. Please check out my other blog on how to perform these basic preprocessing tasks using NLTK.
Next, to get a list of all adjectives I performed parts of speech (also discussed in my blog mentioned above) tagging and created our BOW or in this case bag of adjectives. I called this list ‘all_words’ and it needs another round of filtering still.
Next, to pick the most informative adjectives I created a frequency distribution of the words in all_words, using nltk.FreqDist() method. I made a list of the top 5000 most frequently appearing adjectives from all_words. At this point, all_words is ready to be used as our final BOW.
Create Features for Each Review: For each review, I created a tuple. The first element of the tuple is a dictionary where the keys are each of the 5000 words from BOW and values for each key is either True if the word appears in the review or False if the word does not. The second element is the label for that tag, ‘pos’ for positive reviews and ‘neg’ for negative reviews.
#example of a tuple feature set for a given review({'great': True, 'excellent': False, 'horrible': False}, 'pos')
I then split the list of tuples (called feature_set from here on) into training set (20, 000) and testing set (5,000)
The fun part: Machine Learning!!!
Now that I had my features and the training and testing set ready, my next step was to try a vanilla base model. For my base model, I used the Naive Bayes classifier module from NLTK. The model had an accuracy of 84.36%. Which was pretty good for a base model and not surprising given the size of the training data. The figure on the right shows both the confusion matrix for the prediction without and with normalization.
The list to above (left) shows 15 of the most informative features from the model. And the ratios associated with them shows how much more often each corresponding word appear in one class of text over others. These ratios are known as likelihood ratios. For example, the word ‘lousy’ is 13 times more likely to occur in a negative review than in a positive review.
To further evaluate the model I calculated the f1_score using sci-kit learn and created a confusion matrix. The f1_score was 84.36%. The normalized confusion matrix shows that the model predicted correctly for 83% of the positive reviews and 85% of the negative reviews.
Next, I tried out training other classifying algorithms on the training set to find the model with the best score. I used, Multinomial Naive Bayes, Bernoulli Naive Bayes, Logistic Regression, Stochastic Gradient Descent and Support Vector Classifier. NLTK has a builtin Scikit Learn module called SklearnClassifier. This SklearnClassifer can inherit the properties of any model that you can import through Scikit Learn. All you have to do is initiate the NLTK SkleanClassifier with the specific Scikit Learn module as a parameter.
The f1 scores for the different models are listed below. They performed more or less similar. However, both of the Naive Bayes models did slightly better.
MNB: 0.845, BNB: 0.8447999, LogReg: 0.835, SGD: 0.8024, SVC: 0.7808
Final Steps: Build an ensemble model
Next, I wanted to see if the predictive power of all these models were combined, so to speak, could we reach a better score? The logical next step was to build an ensemble model. An ensemble model combines the predictions (take votes) from each of the above models for each review and uses the majority vote as the final prediction.
To avoid having to re-train the models (since each one took about 8 to 12 minutes to train), I stored all of the models using pickle. Pickle is a super useful python module that allows you to retain python objects that might have taken a long time to create before closing out your kernel.
To build the ensemble model I constructed the EnsembleClassifier class that is initialized with a list of classifiers. It is important that an odd number of classifiers are used as part of the ensemble to avoid the chance for a tie. The class has two main methods, classify: which returns a predicted label and confidence: which returns the degree of confidence in the prediction. This degree is measured as (Number of winning votes)/Total Votes.
Next, I loaded all the models using pickle, initialized an ensemble model object and fed the list of features from the testing sets to the model. The f1-score of the ensemble model as shown below was 85%. A slight increase from the highest f1-scores of 84.5% that we achieved earlier with our Original Naive Bayes model.
The same class can be used to do a live classification of a single review as well. The function below takes in a single review, creates a feature set for that review and then spits out a prediction using the ensemble method. The output gives you a label and the degree of confidence in that labeling.
To demonstrate, I collected reviews of Captain Marvel from rotten tomatoes. I intentionally took two reviews that were not as polarizing and two that were very polarizing to see how the model performs. And turned out the model is did pretty well! The model was not so sure about the less polarizing reviews text_a and text_c. But identified the polarizing text_b and text_d with a much higher degree of confidence.
That’s it!
You can find the example codes for this project at my GitHub repository and also in the original webpage that I used as a guideline. In my Github, I have included a live_classifier.py file and my trained models as pickled files. Once you clone the repo you can directly run this live_classifier.py file in your terminal and then play with the sentiment() function to classify any review you find on the internet. Even better, make up your own review!
I am now interested to explore detecting sarcasm or satire in a text. Sarcasm is subtle and even humans find it hard to pick up. Just for the sake of it, I tested the ensemble model on a quote by my favorite author Kurt Vonnegut, who is known for his satirical works. It goes like this:
“Everything was beautiful and nothing hurt” — Kurt Vonnegut
If I hadn’t mentioned the nature of his work earlier I am guessing most humans would consider this quote to have positive sentiment. However, given the context of the quote one could argue that this quote had a deeper sentiment of loss. My very simple sentiment analysis model labels the quote as positive with 100% confidence. That is not surprising, because the model was not trained to identify sarcasm in the first place.
I would like to end with the following quote about the nuances of sentiment analysis and its reliability.
Will Sentiment Analysis ever be 100% accurate, or close?
Probably not, but that is not meant to be a bad thing. This will not be because people aren’t smart enough to eventually make computers that really understand language. Instead, this is really just plain impossible, seeing as how it’s rarely the case that 80% of people agree on the sentiment of text. — http://sentdex.com/sentiment-analysis/
Sources:
Quote 1 — http://breakthroughanalysis.com/2012/09/10/typesofsentimentanalysis/
Figure 1— Ebay Stock Prices —http://sentdex.com/how-accurate-is-sentiment-analysis-for-stocks/
Figure 2 — How Twitter Feels about The 2016 Election Candidates— https://moderndata.plot.ly/elections-analysis-in-r-python-and-ggplot2-9-charts-from-4-countries/
Inspiration — https://pythonprogramming.net/sentiment-analysis-module-nltk-tutorial/ | [
{
"code": null,
"e": 253,
"s": 172,
"text": "“Your most unhappy customers are your greatest source of learning.” — Bill Gates"
},
{
"code": null,
"e": 284,
"s": 253,
"text": "So what does the customer say?"
},
{
"code": null,
"e": 752,
"s": 284,
"text": "In today’s context, it turns out A LOT. Social media has opened the floodgates of customer opinions and it is now free-flowing in mammoth proportions for businesses to analyze. Today, using machine learning companies are able to extract these opinions in the form of text or audio and then analyze the emotions behind them on an unprecedented scale. Sentiment analysis, opinion mining call it what you like, if you have a product/service to sell you need to be on it."
},
{
"code": null,
"e": 1017,
"s": 752,
"text": "“ When captured electronically, customer sentiment — expressions beyond facts, that convey mood, opinion, and emotion — carries immense business value. We’re talking the voice of the customer, and of the prospect, patient, voter, and opinion leader.” — Seth Grimes"
},
{
"code": null,
"e": 1303,
"s": 1017,
"text": "Starting from user reviews in media to analyzing stock prices, sentiment analysis has become a ubiquitous tool in almost all industries. For example, the graph below shows the stock price movement of eBay with a sentiment index created based on an analysis of tweets that mention eBay."
},
{
"code": null,
"e": 1353,
"s": 1303,
"text": "Techopedia defines sentiment analysis as follows:"
},
{
"code": null,
"e": 1875,
"s": 1353,
"text": "Sentiment analysis is a type of data mining that measures the inclination of people’s opinions through natural language processing (NLP), computational linguistics and text analysis, which are used to extract and analyze subjective information from the Web — mostly social media and similar sources. The analyzed data quantifies the general public’s sentiments or reactions toward certain products, people or ideas and reveal the contextual polarity of the information. Sentiment analysis is also known as opinion mining."
},
{
"code": null,
"e": 1929,
"s": 1875,
"text": "There are two broad approaches to sentiment analysis."
},
{
"code": null,
"e": 1946,
"s": 1929,
"text": "Pure statistics:"
},
{
"code": null,
"e": 2324,
"s": 1946,
"text": "These kinds of algorithms treat texts as Bags of Words (BOW), where the order of words and as such context is ignored. The original text is filtered down to only the words that are thought to carry sentiment. For this blog, I will be attempting this approach. Such models make no use of understanding of a certain language and only uses statistical measures to classify a text."
},
{
"code": null,
"e": 2361,
"s": 2324,
"text": "A mix of statistics and linguistics:"
},
{
"code": null,
"e": 2540,
"s": 2361,
"text": "These algorithms attempt to incorporate grammar principles, various natural language processing techniques and statistics to train the machine to truly ‘understand’ the language."
},
{
"code": null,
"e": 2659,
"s": 2540,
"text": "Sentiment analysis can also be broadly categorized into two kinds, based on the type of output the analysis generates."
},
{
"code": null,
"e": 2839,
"s": 2659,
"text": "Categorical/Polarity— Was that bit of text “positive”, “neutral” or “negative?” In this process, you are trying to label a piece of text as either positive or negative or neutral."
},
{
"code": null,
"e": 3125,
"s": 2839,
"text": "Scalar/Degree — Give a score on a predefined scale that ranges from highly positive to highly negative. For example, the figure below shows an analysis of of sentiment based on tweets about various election candidates. In this instance the sentiment is being measured in a scalar form."
},
{
"code": null,
"e": 3623,
"s": 3125,
"text": "During my data science boot camp, I took a crack at building a basic sentiment analysis tool using NLTK library. I found a nifty youtube tutorial and followed the steps listed to learn how to do basic sentiment analysis. While the tutorial focuses on analyzing Twitter sentiments, I wanted to see if I could label movie reviews into either positive or negative. I found a labeled dataset of 25000 IMDB reviews in the form of .txt files separated into two folders for negative and positive reviews."
},
{
"code": null,
"e": 3755,
"s": 3623,
"text": "I imported the following libraries on my Jupyter notebook and read the positive and negative reviews from their respective folders."
},
{
"code": null,
"e": 4145,
"s": 3755,
"text": "Making the Bag of Words (BOW): For our Bag of Words(BOW) we technically could include all unique words. However, it can be computationally expensive and even unnecessary to include all unique words in our analysis. For example, the name of an actress in a review would not give any information about the sentiment of a review. So, we need to be smart and select the most informative words."
},
{
"code": null,
"e": 4537,
"s": 4145,
"text": "For the small scope of the project and also as guided by the tutorial, I selected only adjectives from the features based on the assumption that adjectives are highly informative of positive and negative sentiments. For each review, I removed punctuations, tokenized the string, removed stop words. Please check out my other blog on how to perform these basic preprocessing tasks using NLTK."
},
{
"code": null,
"e": 4788,
"s": 4537,
"text": "Next, to get a list of all adjectives I performed parts of speech (also discussed in my blog mentioned above) tagging and created our BOW or in this case bag of adjectives. I called this list ‘all_words’ and it needs another round of filtering still."
},
{
"code": null,
"e": 5072,
"s": 4788,
"text": "Next, to pick the most informative adjectives I created a frequency distribution of the words in all_words, using nltk.FreqDist() method. I made a list of the top 5000 most frequently appearing adjectives from all_words. At this point, all_words is ready to be used as our final BOW."
},
{
"code": null,
"e": 5448,
"s": 5072,
"text": "Create Features for Each Review: For each review, I created a tuple. The first element of the tuple is a dictionary where the keys are each of the 5000 words from BOW and values for each key is either True if the word appears in the review or False if the word does not. The second element is the label for that tag, ‘pos’ for positive reviews and ‘neg’ for negative reviews."
},
{
"code": null,
"e": 5563,
"s": 5448,
"text": "#example of a tuple feature set for a given review({'great': True, 'excellent': False, 'horrible': False}, 'pos') "
},
{
"code": null,
"e": 5681,
"s": 5563,
"text": "I then split the list of tuples (called feature_set from here on) into training set (20, 000) and testing set (5,000)"
},
{
"code": null,
"e": 5715,
"s": 5681,
"text": "The fun part: Machine Learning!!!"
},
{
"code": null,
"e": 6138,
"s": 5715,
"text": "Now that I had my features and the training and testing set ready, my next step was to try a vanilla base model. For my base model, I used the Naive Bayes classifier module from NLTK. The model had an accuracy of 84.36%. Which was pretty good for a base model and not surprising given the size of the training data. The figure on the right shows both the confusion matrix for the prediction without and with normalization."
},
{
"code": null,
"e": 6504,
"s": 6138,
"text": "The list to above (left) shows 15 of the most informative features from the model. And the ratios associated with them shows how much more often each corresponding word appear in one class of text over others. These ratios are known as likelihood ratios. For example, the word ‘lousy’ is 13 times more likely to occur in a negative review than in a positive review."
},
{
"code": null,
"e": 6775,
"s": 6504,
"text": "To further evaluate the model I calculated the f1_score using sci-kit learn and created a confusion matrix. The f1_score was 84.36%. The normalized confusion matrix shows that the model predicted correctly for 83% of the positive reviews and 85% of the negative reviews."
},
{
"code": null,
"e": 7306,
"s": 6775,
"text": "Next, I tried out training other classifying algorithms on the training set to find the model with the best score. I used, Multinomial Naive Bayes, Bernoulli Naive Bayes, Logistic Regression, Stochastic Gradient Descent and Support Vector Classifier. NLTK has a builtin Scikit Learn module called SklearnClassifier. This SklearnClassifer can inherit the properties of any model that you can import through Scikit Learn. All you have to do is initiate the NLTK SkleanClassifier with the specific Scikit Learn module as a parameter."
},
{
"code": null,
"e": 7461,
"s": 7306,
"text": "The f1 scores for the different models are listed below. They performed more or less similar. However, both of the Naive Bayes models did slightly better."
},
{
"code": null,
"e": 7529,
"s": 7461,
"text": "MNB: 0.845, BNB: 0.8447999, LogReg: 0.835, SGD: 0.8024, SVC: 0.7808"
},
{
"code": null,
"e": 7566,
"s": 7529,
"text": "Final Steps: Build an ensemble model"
},
{
"code": null,
"e": 7899,
"s": 7566,
"text": "Next, I wanted to see if the predictive power of all these models were combined, so to speak, could we reach a better score? The logical next step was to build an ensemble model. An ensemble model combines the predictions (take votes) from each of the above models for each review and uses the majority vote as the final prediction."
},
{
"code": null,
"e": 8189,
"s": 7899,
"text": "To avoid having to re-train the models (since each one took about 8 to 12 minutes to train), I stored all of the models using pickle. Pickle is a super useful python module that allows you to retain python objects that might have taken a long time to create before closing out your kernel."
},
{
"code": null,
"e": 8636,
"s": 8189,
"text": "To build the ensemble model I constructed the EnsembleClassifier class that is initialized with a list of classifiers. It is important that an odd number of classifiers are used as part of the ensemble to avoid the chance for a tie. The class has two main methods, classify: which returns a predicted label and confidence: which returns the degree of confidence in the prediction. This degree is measured as (Number of winning votes)/Total Votes."
},
{
"code": null,
"e": 8957,
"s": 8636,
"text": "Next, I loaded all the models using pickle, initialized an ensemble model object and fed the list of features from the testing sets to the model. The f1-score of the ensemble model as shown below was 85%. A slight increase from the highest f1-scores of 84.5% that we achieved earlier with our Original Naive Bayes model."
},
{
"code": null,
"e": 9258,
"s": 8957,
"text": "The same class can be used to do a live classification of a single review as well. The function below takes in a single review, creates a feature set for that review and then spits out a prediction using the ensemble method. The output gives you a label and the degree of confidence in that labeling."
},
{
"code": null,
"e": 9673,
"s": 9258,
"text": "To demonstrate, I collected reviews of Captain Marvel from rotten tomatoes. I intentionally took two reviews that were not as polarizing and two that were very polarizing to see how the model performs. And turned out the model is did pretty well! The model was not so sure about the less polarizing reviews text_a and text_c. But identified the polarizing text_b and text_d with a much higher degree of confidence."
},
{
"code": null,
"e": 9684,
"s": 9673,
"text": "That’s it!"
},
{
"code": null,
"e": 10135,
"s": 9684,
"text": "You can find the example codes for this project at my GitHub repository and also in the original webpage that I used as a guideline. In my Github, I have included a live_classifier.py file and my trained models as pickled files. Once you clone the repo you can directly run this live_classifier.py file in your terminal and then play with the sentiment() function to classify any review you find on the internet. Even better, make up your own review!"
},
{
"code": null,
"e": 10422,
"s": 10135,
"text": "I am now interested to explore detecting sarcasm or satire in a text. Sarcasm is subtle and even humans find it hard to pick up. Just for the sake of it, I tested the ensemble model on a quote by my favorite author Kurt Vonnegut, who is known for his satirical works. It goes like this:"
},
{
"code": null,
"e": 10482,
"s": 10422,
"text": "“Everything was beautiful and nothing hurt” — Kurt Vonnegut"
},
{
"code": null,
"e": 10908,
"s": 10482,
"text": "If I hadn’t mentioned the nature of his work earlier I am guessing most humans would consider this quote to have positive sentiment. However, given the context of the quote one could argue that this quote had a deeper sentiment of loss. My very simple sentiment analysis model labels the quote as positive with 100% confidence. That is not surprising, because the model was not trained to identify sarcasm in the first place."
},
{
"code": null,
"e": 11014,
"s": 10908,
"text": "I would like to end with the following quote about the nuances of sentiment analysis and its reliability."
},
{
"code": null,
"e": 11071,
"s": 11014,
"text": "Will Sentiment Analysis ever be 100% accurate, or close?"
},
{
"code": null,
"e": 11414,
"s": 11071,
"text": "Probably not, but that is not meant to be a bad thing. This will not be because people aren’t smart enough to eventually make computers that really understand language. Instead, this is really just plain impossible, seeing as how it’s rarely the case that 80% of people agree on the sentiment of text. — http://sentdex.com/sentiment-analysis/"
},
{
"code": null,
"e": 11423,
"s": 11414,
"text": "Sources:"
},
{
"code": null,
"e": 11502,
"s": 11423,
"text": "Quote 1 — http://breakthroughanalysis.com/2012/09/10/typesofsentimentanalysis/"
},
{
"code": null,
"e": 11597,
"s": 11502,
"text": "Figure 1— Ebay Stock Prices —http://sentdex.com/how-accurate-is-sentiment-analysis-for-stocks/"
},
{
"code": null,
"e": 11759,
"s": 11597,
"text": "Figure 2 — How Twitter Feels about The 2016 Election Candidates— https://moderndata.plot.ly/elections-analysis-in-r-python-and-ggplot2-9-charts-from-4-countries/"
}
] |
Bootstrap - Environment Setup | It is very easy to setup and start using Bootstrap. This chapter will explain how to download and setup Bootstrap. We will also discuss the Bootstrap file structure, and demonstrate its usage with an example.
You can download the latest version of Bootstrap from https://getbootstrap.com/. When you click on this link, you will get to see a screen as below −
Here you can see two buttons −
Download Bootstrap − Clicking this, you can download the precompiled and minified versions of Bootstrap CSS, JavaScript, and fonts. No documentation or original source code files are included.
Download Bootstrap − Clicking this, you can download the precompiled and minified versions of Bootstrap CSS, JavaScript, and fonts. No documentation or original source code files are included.
Download Source − Clicking this, you can get the latest Bootstrap LESS and JavaScript source code directly from GitHub.
Download Source − Clicking this, you can get the latest Bootstrap LESS and JavaScript source code directly from GitHub.
For better understanding and ease of use, we shall use precompiled version of Bootstrap throughout the tutorial. As the files are complied and minified you don't have to bother every time including separate files for individual functionality. At the time of writing this tutorial the latest version (Bootstrap 3) was downloaded.
Once the compiled version Bootstrap is downloaded, extract the ZIP file, and you will see the following file/directory structure −
As you can see, there are compiled CSS and JS (bootstrap.*), as well as compiled and minified CSS and JS (bootstrap.min.*). Fonts from Glyphicons are included, as it is the optional Bootstrap theme.
If you have downloaded the Bootstrap source code then the file structure would be as follows −
The files under less/, js/, and fonts/ are the source code for Bootstrap CSS, JS, and icon fonts (respectively).
The files under less/, js/, and fonts/ are the source code for Bootstrap CSS, JS, and icon fonts (respectively).
The dist/ folder includes everything listed in the precompiled download section above.
The dist/ folder includes everything listed in the precompiled download section above.
docs-assets/, examples/, and all *.html files are Bootstrap documentation.
docs-assets/, examples/, and all *.html files are Bootstrap documentation.
A basic HTML template using Bootstrap would look like this −
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap 101 Template</title>
<meta name = "viewport" content = "width = device-width, initial-scale = 1.0">
<!-- Bootstrap -->
<link href = "css/bootstrap.min.css" rel = "stylesheet">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src = "https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src = "https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
<![endif]-->
</head>
<body>
<h1>Hello, world!</h1>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src = "https://code.jquery.com/jquery.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src = "js/bootstrap.min.js"></script>
</body>
</html>
Here you can see the jquery.js, bootstrap.min.js and bootstrap.min.css files that are included to make a normal HTM file to the Bootstrapped Template. Just make sure to include jQuery library before you include Bootstrap library.
More details about each of the elements in this above piece of code will be discussed in the chapter Bootstrap CSS Overview.
Now let's try an example using the above template. Try the following example using Live Demo option available at the top right corner of the below sample code box on our website −
<h1>Hello, world!</h1>
26 Lectures
2 hours
Anadi Sharma
54 Lectures
4.5 hours
Frahaan Hussain
161 Lectures
14.5 hours
Eduonix Learning Solutions
20 Lectures
4 hours
Azaz Patel
15 Lectures
1.5 hours
Muhammad Ismail
62 Lectures
8 hours
Yossef Ayman Zedan
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 3541,
"s": 3331,
"text": "It is very easy to setup and start using Bootstrap. This chapter will explain how to download and setup Bootstrap. We will also discuss the Bootstrap file structure, and demonstrate its usage with an example."
},
{
"code": null,
"e": 3691,
"s": 3541,
"text": "You can download the latest version of Bootstrap from https://getbootstrap.com/. When you click on this link, you will get to see a screen as below −"
},
{
"code": null,
"e": 3722,
"s": 3691,
"text": "Here you can see two buttons −"
},
{
"code": null,
"e": 3915,
"s": 3722,
"text": "Download Bootstrap − Clicking this, you can download the precompiled and minified versions of Bootstrap CSS, JavaScript, and fonts. No documentation or original source code files are included."
},
{
"code": null,
"e": 4108,
"s": 3915,
"text": "Download Bootstrap − Clicking this, you can download the precompiled and minified versions of Bootstrap CSS, JavaScript, and fonts. No documentation or original source code files are included."
},
{
"code": null,
"e": 4228,
"s": 4108,
"text": "Download Source − Clicking this, you can get the latest Bootstrap LESS and JavaScript source code directly from GitHub."
},
{
"code": null,
"e": 4348,
"s": 4228,
"text": "Download Source − Clicking this, you can get the latest Bootstrap LESS and JavaScript source code directly from GitHub."
},
{
"code": null,
"e": 4678,
"s": 4348,
"text": "For better understanding and ease of use, we shall use precompiled version of Bootstrap throughout the tutorial. As the files are complied and minified you don't have to bother every time including separate files for individual functionality. At the time of writing this tutorial the latest version (Bootstrap 3) was downloaded."
},
{
"code": null,
"e": 4809,
"s": 4678,
"text": "Once the compiled version Bootstrap is downloaded, extract the ZIP file, and you will see the following file/directory structure −"
},
{
"code": null,
"e": 5008,
"s": 4809,
"text": "As you can see, there are compiled CSS and JS (bootstrap.*), as well as compiled and minified CSS and JS (bootstrap.min.*). Fonts from Glyphicons are included, as it is the optional Bootstrap theme."
},
{
"code": null,
"e": 5103,
"s": 5008,
"text": "If you have downloaded the Bootstrap source code then the file structure would be as follows −"
},
{
"code": null,
"e": 5216,
"s": 5103,
"text": "The files under less/, js/, and fonts/ are the source code for Bootstrap CSS, JS, and icon fonts (respectively)."
},
{
"code": null,
"e": 5329,
"s": 5216,
"text": "The files under less/, js/, and fonts/ are the source code for Bootstrap CSS, JS, and icon fonts (respectively)."
},
{
"code": null,
"e": 5416,
"s": 5329,
"text": "The dist/ folder includes everything listed in the precompiled download section above."
},
{
"code": null,
"e": 5503,
"s": 5416,
"text": "The dist/ folder includes everything listed in the precompiled download section above."
},
{
"code": null,
"e": 5578,
"s": 5503,
"text": "docs-assets/, examples/, and all *.html files are Bootstrap documentation."
},
{
"code": null,
"e": 5653,
"s": 5578,
"text": "docs-assets/, examples/, and all *.html files are Bootstrap documentation."
},
{
"code": null,
"e": 5714,
"s": 5653,
"text": "A basic HTML template using Bootstrap would look like this −"
},
{
"code": null,
"e": 6756,
"s": 5714,
"text": "<!DOCTYPE html>\n<html>\n \n <head>\n <title>Bootstrap 101 Template</title>\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1.0\">\n \n <!-- Bootstrap -->\n <link href = \"css/bootstrap.min.css\" rel = \"stylesheet\">\n \n <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->\n <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->\n \n <!--[if lt IE 9]>\n <script src = \"https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js\"></script>\n <script src = \"https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js\"></script>\n <![endif]-->\n \n </head>\n \n <body>\n <h1>Hello, world!</h1>\n\n <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->\n <script src = \"https://code.jquery.com/jquery.js\"></script>\n \n <!-- Include all compiled plugins (below), or include individual files as needed -->\n <script src = \"js/bootstrap.min.js\"></script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 6986,
"s": 6756,
"text": "Here you can see the jquery.js, bootstrap.min.js and bootstrap.min.css files that are included to make a normal HTM file to the Bootstrapped Template. Just make sure to include jQuery library before you include Bootstrap library."
},
{
"code": null,
"e": 7112,
"s": 6986,
"text": "More details about each of the elements in this above piece of code will be discussed in the chapter Bootstrap CSS Overview."
},
{
"code": null,
"e": 7292,
"s": 7112,
"text": "Now let's try an example using the above template. Try the following example using Live Demo option available at the top right corner of the below sample code box on our website −"
},
{
"code": null,
"e": 7315,
"s": 7292,
"text": "<h1>Hello, world!</h1>"
},
{
"code": null,
"e": 7348,
"s": 7315,
"text": "\n 26 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 7362,
"s": 7348,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 7397,
"s": 7362,
"text": "\n 54 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 7414,
"s": 7397,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 7451,
"s": 7414,
"text": "\n 161 Lectures \n 14.5 hours \n"
},
{
"code": null,
"e": 7479,
"s": 7451,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 7512,
"s": 7479,
"text": "\n 20 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 7524,
"s": 7512,
"text": " Azaz Patel"
},
{
"code": null,
"e": 7559,
"s": 7524,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 7576,
"s": 7559,
"text": " Muhammad Ismail"
},
{
"code": null,
"e": 7609,
"s": 7576,
"text": "\n 62 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 7629,
"s": 7609,
"text": " Yossef Ayman Zedan"
},
{
"code": null,
"e": 7636,
"s": 7629,
"text": " Print"
},
{
"code": null,
"e": 7647,
"s": 7636,
"text": " Add Notes"
}
] |
Find length of one array element in bytes and total bytes consumed by the elements in Numpy - GeeksforGeeks | 23 Jul, 2021
In NumPy we can find the length of one array element in a byte with the help of itemsize . It will return the length of the array in integer. And in the numpy for calculating total bytes consumed by the elements with the help of nbytes.
Syntax: array.itemsize
Return :It will return length(int) of the array in bytes.
Syntax: array.nbytes
Return :It will return total bytes consumed by the elements.
Example 1:
Python
import numpy as np array = np.array([1,3,5], dtype=np.float64) # Size of the arrayprint(array.size) # Length of one array element in bytes,print( array.itemsize) # Total bytes consumed by the elements# of the arrayprint(array.nbytes)
Output:
3
8
24
Example 2:
Python
import numpy as np array = np.array([20, 34, 56, 78, 1, 9], dtype=np.float64) # Size of the arrayprint(array.size) # Length of one array element in bytes,print(array.itemsize) # Total bytes consumed by the elements# of the arrayprint(array.nbytes)
Output:
6
8
48
rajeev0719singh
Python numpy-arrayManipulation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python | [
{
"code": null,
"e": 25026,
"s": 24998,
"text": "\n23 Jul, 2021"
},
{
"code": null,
"e": 25263,
"s": 25026,
"text": "In NumPy we can find the length of one array element in a byte with the help of itemsize . It will return the length of the array in integer. And in the numpy for calculating total bytes consumed by the elements with the help of nbytes."
},
{
"code": null,
"e": 25288,
"s": 25263,
"text": "Syntax: array.itemsize "
},
{
"code": null,
"e": 25348,
"s": 25288,
"text": "Return :It will return length(int) of the array in bytes. "
},
{
"code": null,
"e": 25373,
"s": 25350,
"text": "Syntax: array.nbytes "
},
{
"code": null,
"e": 25435,
"s": 25373,
"text": "Return :It will return total bytes consumed by the elements. "
},
{
"code": null,
"e": 25446,
"s": 25435,
"text": "Example 1:"
},
{
"code": null,
"e": 25453,
"s": 25446,
"text": "Python"
},
{
"code": "import numpy as np array = np.array([1,3,5], dtype=np.float64) # Size of the arrayprint(array.size) # Length of one array element in bytes,print( array.itemsize) # Total bytes consumed by the elements# of the arrayprint(array.nbytes)",
"e": 25688,
"s": 25453,
"text": null
},
{
"code": null,
"e": 25698,
"s": 25688,
"text": " Output:"
},
{
"code": null,
"e": 25705,
"s": 25698,
"text": "3\n8\n24"
},
{
"code": null,
"e": 25716,
"s": 25705,
"text": "Example 2:"
},
{
"code": null,
"e": 25723,
"s": 25716,
"text": "Python"
},
{
"code": "import numpy as np array = np.array([20, 34, 56, 78, 1, 9], dtype=np.float64) # Size of the arrayprint(array.size) # Length of one array element in bytes,print(array.itemsize) # Total bytes consumed by the elements# of the arrayprint(array.nbytes)",
"e": 25972,
"s": 25723,
"text": null
},
{
"code": null,
"e": 25982,
"s": 25972,
"text": " Output: "
},
{
"code": null,
"e": 25989,
"s": 25982,
"text": "6\n8\n48"
},
{
"code": null,
"e": 26005,
"s": 25989,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 26036,
"s": 26005,
"text": "Python numpy-arrayManipulation"
},
{
"code": null,
"e": 26049,
"s": 26036,
"text": "Python-numpy"
},
{
"code": null,
"e": 26056,
"s": 26049,
"text": "Python"
},
{
"code": null,
"e": 26154,
"s": 26056,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26163,
"s": 26154,
"text": "Comments"
},
{
"code": null,
"e": 26176,
"s": 26163,
"text": "Old Comments"
},
{
"code": null,
"e": 26194,
"s": 26176,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26229,
"s": 26194,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26261,
"s": 26229,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26283,
"s": 26261,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26313,
"s": 26283,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 26355,
"s": 26313,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26381,
"s": 26355,
"text": "Python String | replace()"
},
{
"code": null,
"e": 26424,
"s": 26381,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 26461,
"s": 26424,
"text": "Create a Pandas DataFrame from Lists"
}
] |
Wide char and library functions in C++ | In this section we will see what is the wide character in C++. We will also see some
functions that are used to handle wide characters.
Wide characters are similar to character datatype. The main difference is that
char takes 1-byte space, but wide character takes 2-bytes (sometimes 4-byte
depending on compiler) of space in memory. For 2-byte space wide character can
hold 64K (65536) different characters. So the wide char can hold UNICODE
characters. The UNICODE values are international standard which allows for
encoding for characters virtually for any character of any language.
Live Demo
#include<iostream>
using namespace std;
int main() {
wchar_t wide_character = L'a';
cout << "The wide character is: " << wide_character << endl;
cout << "Wide character size: " <<sizeof(wide_character);
}
The wide character is: 97
Wide character size: 2
We can see that to make wide character we have to add ‘L’ before the character
literal. But the character value is not displayed in the output using cout. So to use
wide char we have to use wcout, and for taking input we have to use wcin.
We can make some wide character array, and print them as string.
Live Demo
#include<iostream>
using namespace std;
int main() {
char str1[] = "This is character array";
cout << str1 << endl;
wchar_t str2 [] = L"This is wide character array";
wcout << str2;
}
This is character array
This is wide character array
Now let us see some functions that are used for wide characters. | [
{
"code": null,
"e": 1198,
"s": 1062,
"text": "In this section we will see what is the wide character in C++. We will also see some\nfunctions that are used to handle wide characters."
},
{
"code": null,
"e": 1649,
"s": 1198,
"text": "Wide characters are similar to character datatype. The main difference is that\nchar takes 1-byte space, but wide character takes 2-bytes (sometimes 4-byte\ndepending on compiler) of space in memory. For 2-byte space wide character can\nhold 64K (65536) different characters. So the wide char can hold UNICODE\ncharacters. The UNICODE values are international standard which allows for\nencoding for characters virtually for any character of any language."
},
{
"code": null,
"e": 1660,
"s": 1649,
"text": " Live Demo"
},
{
"code": null,
"e": 1874,
"s": 1660,
"text": "#include<iostream>\nusing namespace std;\nint main() {\n wchar_t wide_character = L'a';\n cout << \"The wide character is: \" << wide_character << endl;\n cout << \"Wide character size: \" <<sizeof(wide_character);\n}"
},
{
"code": null,
"e": 1923,
"s": 1874,
"text": "The wide character is: 97\nWide character size: 2"
},
{
"code": null,
"e": 2162,
"s": 1923,
"text": "We can see that to make wide character we have to add ‘L’ before the character\nliteral. But the character value is not displayed in the output using cout. So to use\nwide char we have to use wcout, and for taking input we have to use wcin."
},
{
"code": null,
"e": 2227,
"s": 2162,
"text": "We can make some wide character array, and print them as string."
},
{
"code": null,
"e": 2238,
"s": 2227,
"text": " Live Demo"
},
{
"code": null,
"e": 2434,
"s": 2238,
"text": "#include<iostream>\nusing namespace std;\nint main() {\n char str1[] = \"This is character array\";\n cout << str1 << endl;\n wchar_t str2 [] = L\"This is wide character array\";\n wcout << str2;\n}"
},
{
"code": null,
"e": 2487,
"s": 2434,
"text": "This is character array\nThis is wide character array"
},
{
"code": null,
"e": 2552,
"s": 2487,
"text": "Now let us see some functions that are used for wide characters."
}
] |
How to Avoid ConcurrentModificationException in Java? - GeeksforGeeks | 16 Jun, 2021
ConcurrentModificationException is a predefined Exception in Java, which occurs while we are using Java Collections, i.e whenever we try to modify an object concurrently without permission ConcurrentModificationException occurs which is present in java.util package.
Procedure: Some steps are required in order to avoid the occurrence of this exception in a single-threaded environment. They are as follows:
Instead of iterating through collections classes, we can iterate through the arrays. This works perfectly fine for smaller lists what about the bigger list? It’s very basic we know that if the array size is huge then it affects the performance. Hence, this method is only effective for smaller size arrays.
The next method is the Synchronized block method, Here we actually lock the list in a synchronized block to avoid the exception. Isn’t that cool? but guess what this is also not an effective method to avoid Exception Why? Because the purpose of multithreading is not being used.
The better way is we have ConcurrentHashMap and CopyOnWriteArrayList Which is the best among the above Methods.
Methods:
Here two ways are proposed of which starting with the naive one and ending up with the optimal approach to reach the goal.
Using Loops: We used the Iterator remove() method instead of that we can use a for loop to avoid ConcurrentModificationException in a Single-threaded environment. If we add any extra objects then we can ensure that our code takes care of them.
Using the remove() Method: We can use the remove method to remove the object from the collection. Here there is a problem that is you can only remove the same object and not any other from the list
Using Loops: We used the Iterator remove() method instead of that we can use a for loop to avoid ConcurrentModificationException in a Single-threaded environment. If we add any extra objects then we can ensure that our code takes care of them.
Using the remove() Method: We can use the remove method to remove the object from the collection. Here there is a problem that is you can only remove the same object and not any other from the list
Example 1:
Java
// Java Program to Avoid
// AvoidConcurrentModificationException
// Importing Map and List utility classes
// from java.util package
import java.util.List;
import java.util.Map;
// Importing classes from java.util.concurrent package
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
// Main class
public class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating an object of List class
// Declaring object of string type
List<String> marvel
= new CopyOnWriteArrayList<String>();
// Adding elements to the above object created
// Custom input entries
marvel.add("IronMan");
marvel.add("BlackWidow");
marvel.add("Hulk");
marvel.add("DoctorStrange");
marvel.add("SpiderMan");
// Iterating over object created using size() method
for (int i = 0; i < marvel.size(); i++) {
// Print and display the object elements
// using get() method
System.out.println("Avenger : "
+ marvel.get(i));
// Condition check over object elements
// If specific element is matched
if (marvel.get(i).equals("BlackWidow")) {
marvel.remove(i);
i--;
// Add this specific element
marvel.add("CaptianAmerica");
}
}
// Now getting the final total size by checking
// how many elements are there inside object
System.out.println("Total Avengers : "
+ marvel.size());
}
}
Avenger : IronMan
Avenger : BlackWidow
Avenger : Hulk
Avenger : DoctorStrange
Avenger : SpiderMan
Avenger : CaptianAmerica
Total Avengers :5
Note: The Exception can also occur if we try to modify the structure of original list with sublist. An example for the same is below,
Example 2:
Java
// Java Program to Illustrate ConcurrentModificationException
// WithArrayListSubList
// Importing List and Arraylist classes utility classes
// from java.util package
import java.util.ArrayList;
import java.util.List;
// Main class
public class GFG {
// Main driver method
public static void main(String[] args) {
// Creating a List class object
// Declaring object of string type
List <String> names = new ArrayList <>();
// Adding elements to the object of List class
// Custom input entries
names.add("Java");
names.add("C++");
names.add("Phython");
names.add("JavaScript");
List < String > first2Names = names.subList(0, 2);
System.out.println(names + " , " + first2Names);
names.set(1, "Ruby");
// check the output below.
System.out.println(names + " , " + first2Names);
// Now we add another string to
// get ConcurrentModificationException
names.add("SQL");
// This line throws an exception
System.out.println(names + " , " + first2Names);
}
}
Output:
Henceforth, we have discussed how to avoid the Exception in both single-threaded and multithreaded environments successfully as depicted from the above outputs.
sweetyty
Java-Exceptions
Picked
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Initialize an ArrayList in Java
HashMap in Java with Examples
Interfaces in Java
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
ArrayList in Java
Multidimensional Arrays in Java
LinkedList in Java
Set in Java
Overriding in Java | [
{
"code": null,
"e": 24580,
"s": 24549,
"text": " \n16 Jun, 2021\n"
},
{
"code": null,
"e": 24849,
"s": 24580,
"text": "ConcurrentModificationException is a predefined Exception in Java, which occurs while we are using Java Collections, i.e whenever we try to modify an object concurrently without permission ConcurrentModificationException occurs which is present in java.util package."
},
{
"code": null,
"e": 24990,
"s": 24849,
"text": "Procedure: Some steps are required in order to avoid the occurrence of this exception in a single-threaded environment. They are as follows:"
},
{
"code": null,
"e": 25297,
"s": 24990,
"text": "Instead of iterating through collections classes, we can iterate through the arrays. This works perfectly fine for smaller lists what about the bigger list? It’s very basic we know that if the array size is huge then it affects the performance. Hence, this method is only effective for smaller size arrays."
},
{
"code": null,
"e": 25576,
"s": 25297,
"text": "The next method is the Synchronized block method, Here we actually lock the list in a synchronized block to avoid the exception. Isn’t that cool? but guess what this is also not an effective method to avoid Exception Why? Because the purpose of multithreading is not being used."
},
{
"code": null,
"e": 25688,
"s": 25576,
"text": "The better way is we have ConcurrentHashMap and CopyOnWriteArrayList Which is the best among the above Methods."
},
{
"code": null,
"e": 25697,
"s": 25688,
"text": "Methods:"
},
{
"code": null,
"e": 25820,
"s": 25697,
"text": "Here two ways are proposed of which starting with the naive one and ending up with the optimal approach to reach the goal."
},
{
"code": null,
"e": 26265,
"s": 25820,
"text": "\nUsing Loops: We used the Iterator remove() method instead of that we can use a for loop to avoid ConcurrentModificationException in a Single-threaded environment. If we add any extra objects then we can ensure that our code takes care of them.\nUsing the remove() Method: We can use the remove method to remove the object from the collection. Here there is a problem that is you can only remove the same object and not any other from the list\n"
},
{
"code": null,
"e": 26509,
"s": 26265,
"text": "Using Loops: We used the Iterator remove() method instead of that we can use a for loop to avoid ConcurrentModificationException in a Single-threaded environment. If we add any extra objects then we can ensure that our code takes care of them."
},
{
"code": null,
"e": 26708,
"s": 26509,
"text": "Using the remove() Method: We can use the remove method to remove the object from the collection. Here there is a problem that is you can only remove the same object and not any other from the list"
},
{
"code": null,
"e": 26719,
"s": 26708,
"text": "Example 1:"
},
{
"code": null,
"e": 26724,
"s": 26719,
"text": "Java"
},
{
"code": "\n\n\n\n\n\n\n// Java Program to Avoid\n// AvoidConcurrentModificationException\n \n// Importing Map and List utility classes\n// from java.util package\nimport java.util.List;\nimport java.util.Map;\n \n// Importing classes from java.util.concurrent package\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.CopyOnWriteArrayList;\n \n// Main class\npublic class GFG {\n \n // Main driver method\n public static void main(String[] args)\n {\n \n // Creating an object of List class\n // Declaring object of string type\n List<String> marvel\n = new CopyOnWriteArrayList<String>();\n \n // Adding elements to the above object created\n // Custom input entries\n marvel.add(\"IronMan\");\n marvel.add(\"BlackWidow\");\n marvel.add(\"Hulk\");\n marvel.add(\"DoctorStrange\");\n marvel.add(\"SpiderMan\");\n \n // Iterating over object created using size() method\n for (int i = 0; i < marvel.size(); i++) {\n \n // Print and display the object elements\n // using get() method\n System.out.println(\"Avenger : \"\n + marvel.get(i));\n \n // Condition check over object elements\n \n // If specific element is matched\n if (marvel.get(i).equals(\"BlackWidow\")) {\n \n marvel.remove(i);\n i--;\n \n // Add this specific element\n marvel.add(\"CaptianAmerica\");\n }\n }\n \n // Now getting the final total size by checking\n // how many elements are there inside object\n System.out.println(\"Total Avengers : \"\n + marvel.size());\n }\n}\n\n\n\n\n\n",
"e": 28449,
"s": 26734,
"text": null
},
{
"code": null,
"e": 28593,
"s": 28452,
"text": "Avenger : IronMan\nAvenger : BlackWidow\nAvenger : Hulk\nAvenger : DoctorStrange\nAvenger : SpiderMan\nAvenger : CaptianAmerica\nTotal Avengers :5"
},
{
"code": null,
"e": 28727,
"s": 28593,
"text": "Note: The Exception can also occur if we try to modify the structure of original list with sublist. An example for the same is below,"
},
{
"code": null,
"e": 28740,
"s": 28729,
"text": "Example 2:"
},
{
"code": null,
"e": 28747,
"s": 28742,
"text": "Java"
},
{
"code": "\n\n\n\n\n\n\n// Java Program to Illustrate ConcurrentModificationException\n// WithArrayListSubList\n \n// Importing List and Arraylist classes utility classes\n// from java.util package\nimport java.util.ArrayList;\nimport java.util.List;\n \n// Main class\npublic class GFG {\n \n // Main driver method\n public static void main(String[] args) {\n \n // Creating a List class object\n // Declaring object of string type\n List <String> names = new ArrayList <>();\n \n // Adding elements to the object of List class\n \n // Custom input entries\n names.add(\"Java\");\n names.add(\"C++\");\n names.add(\"Phython\");\n names.add(\"JavaScript\");\n \n List < String > first2Names = names.subList(0, 2);\n \n System.out.println(names + \" , \" + first2Names);\n \n names.set(1, \"Ruby\");\n \n // check the output below. \n System.out.println(names + \" , \" + first2Names);\n \n // Now we add another string to\n // get ConcurrentModificationException\n names.add(\"SQL\");\n \n // This line throws an exception\n System.out.println(names + \" , \" + first2Names);\n \n }\n}\n\n\n\n\n\n",
"e": 29913,
"s": 28757,
"text": null
},
{
"code": null,
"e": 29924,
"s": 29916,
"text": "Output:"
},
{
"code": null,
"e": 30090,
"s": 29928,
"text": "Henceforth, we have discussed how to avoid the Exception in both single-threaded and multithreaded environments successfully as depicted from the above outputs. "
},
{
"code": null,
"e": 30101,
"s": 30092,
"text": "sweetyty"
},
{
"code": null,
"e": 30119,
"s": 30101,
"text": "\nJava-Exceptions\n"
},
{
"code": null,
"e": 30128,
"s": 30119,
"text": "\nPicked\n"
},
{
"code": null,
"e": 30135,
"s": 30128,
"text": "\nJava\n"
},
{
"code": null,
"e": 30340,
"s": 30135,
"text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n "
},
{
"code": null,
"e": 30372,
"s": 30340,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 30402,
"s": 30372,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 30421,
"s": 30402,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 30472,
"s": 30421,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 30503,
"s": 30472,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 30521,
"s": 30503,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 30553,
"s": 30521,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 30572,
"s": 30553,
"text": "LinkedList in Java"
},
{
"code": null,
"e": 30584,
"s": 30572,
"text": "Set in Java"
}
] |
Tryit Editor v3.7 | Tryit: HSLA color values | [] |
Fix navbar to the bottom of the page with Bootstrap | To fix navbar to the bottom, use the navbar-fixed-bottom class:
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Example</title>
<link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
<script src = "/scripts/jquery.min.js"></script>
<script src = "/bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<nav class = "navbar navbar-default navbar-fixed-bottom" role = "navigation" style="background: orange;">
<div class = "navbar-header">
<a class = "navbar-brand" href = "#">Java Topics</a>
</div>
<div>
<ul class = "nav navbar-nav">
<li class = "active"><a href = "#">Basics</a></li>
<li><a href = "#">Interface</a></li>
<li><a href = "#">Polymorphism</a></li>
<li><a href = "#">Encapsulation</a></li>
</ul>
</div>
</nav>
</body>
</html> | [
{
"code": null,
"e": 1126,
"s": 1062,
"text": "To fix navbar to the bottom, use the navbar-fixed-bottom class:"
},
{
"code": null,
"e": 1136,
"s": 1126,
"text": "Live Demo"
},
{
"code": null,
"e": 2005,
"s": 1136,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <link href = \"/bootstrap/css/bootstrap.min.css\" rel = \"stylesheet\">\n <script src = \"/scripts/jquery.min.js\"></script>\n <script src = \"/bootstrap/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <nav class = \"navbar navbar-default navbar-fixed-bottom\" role = \"navigation\" style=\"background: orange;\">\n <div class = \"navbar-header\">\n <a class = \"navbar-brand\" href = \"#\">Java Topics</a>\n </div>\n <div>\n <ul class = \"nav navbar-nav\">\n <li class = \"active\"><a href = \"#\">Basics</a></li>\n <li><a href = \"#\">Interface</a></li>\n <li><a href = \"#\">Polymorphism</a></li>\n <li><a href = \"#\">Encapsulation</a></li>\n </ul>\n </div>\n </nav>\n </body>\n</html>"
}
] |
Pandas - All combinations of two columns - GeeksforGeeks | 15 Mar, 2021
In this article, we will see how to get the combination of two columns of a DataFrame. First, let’s create a sample DataFrame.
Code: An example code to create a data frame using dictionary.
Python3
# importing pandas module for the # data frameimport pandas as pd # creating data frame for student details # using dictionarydata = pd.DataFrame({'id': [7058, 7059, ], 'name': ['sravan', 'jyothika']}) print(data)
Output:
To combine two columns in a data frame using itertools module. It provides various functions that work on iterators to produce complex iterators. To get all combinations of columns we will be using itertools.product module. This function computes the cartesian product of input iterables. To compute the product of an iterable with itself, we use the optional repeat keyword argument to specify the number of repetitions. The output of this function is tuples in sorted order.
Syntax: itertools.product(iterables, repeat=1)
Code:
Python3
# import pandas as pdimport pandas as pd # creating data framedf = pd.DataFrame(data=[['sravan', 'Sudheer'], ['radha', 'vani'], ], columns=['gents', 'ladies']) print(df)
Output:
Code:
Python3
# importing productfrom itertools import product # apply product methodprint(list(product(df['gents'], df['ladies'])))
Output:
Picked
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?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Pandas dataframe.groupby()
Create a directory in Python
Defaultdict in Python
Python | Get unique values from a list | [
{
"code": null,
"e": 25647,
"s": 25619,
"text": "\n15 Mar, 2021"
},
{
"code": null,
"e": 25774,
"s": 25647,
"text": "In this article, we will see how to get the combination of two columns of a DataFrame. First, let’s create a sample DataFrame."
},
{
"code": null,
"e": 25837,
"s": 25774,
"text": "Code: An example code to create a data frame using dictionary."
},
{
"code": null,
"e": 25845,
"s": 25837,
"text": "Python3"
},
{
"code": "# importing pandas module for the # data frameimport pandas as pd # creating data frame for student details # using dictionarydata = pd.DataFrame({'id': [7058, 7059, ], 'name': ['sravan', 'jyothika']}) print(data)",
"e": 26083,
"s": 25845,
"text": null
},
{
"code": null,
"e": 26091,
"s": 26083,
"text": "Output:"
},
{
"code": null,
"e": 26568,
"s": 26091,
"text": "To combine two columns in a data frame using itertools module. It provides various functions that work on iterators to produce complex iterators. To get all combinations of columns we will be using itertools.product module. This function computes the cartesian product of input iterables. To compute the product of an iterable with itself, we use the optional repeat keyword argument to specify the number of repetitions. The output of this function is tuples in sorted order."
},
{
"code": null,
"e": 26615,
"s": 26568,
"text": "Syntax: itertools.product(iterables, repeat=1)"
},
{
"code": null,
"e": 26621,
"s": 26615,
"text": "Code:"
},
{
"code": null,
"e": 26629,
"s": 26621,
"text": "Python3"
},
{
"code": "# import pandas as pdimport pandas as pd # creating data framedf = pd.DataFrame(data=[['sravan', 'Sudheer'], ['radha', 'vani'], ], columns=['gents', 'ladies']) print(df)",
"e": 26842,
"s": 26629,
"text": null
},
{
"code": null,
"e": 26850,
"s": 26842,
"text": "Output:"
},
{
"code": null,
"e": 26856,
"s": 26850,
"text": "Code:"
},
{
"code": null,
"e": 26864,
"s": 26856,
"text": "Python3"
},
{
"code": "# importing productfrom itertools import product # apply product methodprint(list(product(df['gents'], df['ladies'])))",
"e": 26984,
"s": 26864,
"text": null
},
{
"code": null,
"e": 26992,
"s": 26984,
"text": "Output:"
},
{
"code": null,
"e": 26999,
"s": 26992,
"text": "Picked"
},
{
"code": null,
"e": 27013,
"s": 26999,
"text": "Python-pandas"
},
{
"code": null,
"e": 27020,
"s": 27013,
"text": "Python"
},
{
"code": null,
"e": 27118,
"s": 27020,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27150,
"s": 27118,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27192,
"s": 27150,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27234,
"s": 27192,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27290,
"s": 27234,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27317,
"s": 27290,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27348,
"s": 27317,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27384,
"s": 27348,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 27413,
"s": 27384,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 27435,
"s": 27413,
"text": "Defaultdict in Python"
}
] |
PHP 7 - Quick Guide | PHP 7 is a major release of PHP programming language and is touted to be a revolution in the way web applications can be developed and delivered for mobile to enterprises and the cloud. This release is considered to be the most important change for PHP after the release of PHP 5 in 2004.
There are dozens of features added to PHP 7, the most significant ones are mentioned below −
Improved performance − Having PHPNG code merged in PHP7, it is twice as fast as PHP 5.
Improved performance − Having PHPNG code merged in PHP7, it is twice as fast as PHP 5.
Lower Memory Consumption − Optimized PHP 7 utilizes lesser resource.
Lower Memory Consumption − Optimized PHP 7 utilizes lesser resource.
Scalar type declarations − Now parameter and return types can be enforced.
Scalar type declarations − Now parameter and return types can be enforced.
Consistent 64-bit support − Consistent support for 64-bit architecture machines.
Consistent 64-bit support − Consistent support for 64-bit architecture machines.
Improved Exception hierarchy − Exception hierarchy is improved.
Improved Exception hierarchy − Exception hierarchy is improved.
Many fatal errors converted to Exceptions − Range of exceptions is increased covering many fatal error converted as exceptions.
Many fatal errors converted to Exceptions − Range of exceptions is increased covering many fatal error converted as exceptions.
Secure random number generator − Addition of new secure random number generator API.
Secure random number generator − Addition of new secure random number generator API.
Deprecated SAPIs and extensions removed − Various old and unsupported SAPIs and extensions are removed from the latest version.
Deprecated SAPIs and extensions removed − Various old and unsupported SAPIs and extensions are removed from the latest version.
The null coalescing operator (??) − New null coalescing operator added.
The null coalescing operator (??) − New null coalescing operator added.
Return and Scalar Type Declarations − Support for return type and parameter type added.
Return and Scalar Type Declarations − Support for return type and parameter type added.
Anonymous Classes − Support for anonymous added.
Anonymous Classes − Support for anonymous added.
Zero cost asserts − Support for zero cost assert added.
Zero cost asserts − Support for zero cost assert added.
PHP 7 uses new Zend Engine 3.0 to improve application performance almost twice and 50% better memory consumption than PHP 5.6. It allows to serve more concurrent users without requiring any additional hardware. PHP 7 is designed and refactored considering today's workloads.
As per the Zend team, following illustrations show the performance comparison of PHP 7 vs PHP 5.6 and HHVM 3.7 on popular PHP based applications.
PHP 7 proves itself more than twice as faster, as compared to PHP 5.6 while executing Magento transactions.
PHP 7 proves itself more than twice as faster, as compared to PHP 5.6 while executing Drupal transactions.
PHP 7 proves itself more than twice as faster as compared to PHP 5.6 while executing Wordpress transactions.
In order to develop and run PHP Web pages, three vital components need to be installed on your computer system.
Web Server − PHP works with virtually all Web Server software, including Microsoft's Internet Information Server (IIS) but most often used is Apache Server. Download Apache for free here − http://httpd.apache.org/download.cgi
Web Server − PHP works with virtually all Web Server software, including Microsoft's Internet Information Server (IIS) but most often used is Apache Server. Download Apache for free here − http://httpd.apache.org/download.cgi
Database − PHP PHP works with virtually all database software, including Oracle and Sybase but most commonly used is MySQL database. Download MySQL for free here − http://www.mysql.com/downloads/
Database − PHP PHP works with virtually all database software, including Oracle and Sybase but most commonly used is MySQL database. Download MySQL for free here − http://www.mysql.com/downloads/
PHP Parser − In order to process PHP script instructions, a parser must be installed to generate HTML output that can be sent to the Web Browser. This tutorial will guide you how to install PHP parser on your computer.
PHP Parser − In order to process PHP script instructions, a parser must be installed to generate HTML output that can be sent to the Web Browser. This tutorial will guide you how to install PHP parser on your computer.
Before you proceed, it is important to make sure that you have proper environment setup on your machine to develop your web programs using PHP. Store the following php file in Apache's htdocs folder.
<?php
phpinfo();
?>
Type the following address into your browser's address box.
http://127.0.0.1/phpinfo.php
If this displays a page showing your PHP installation related information, then it means you have PHP and Webserver installed properly. Otherwise, you have to follow the given procedure to install PHP on your computer.
This section will guide you to install and configure PHP over the following four platforms −
PHP Installation on Linux or Unix with Apache
PHP Installation on Linux or Unix with Apache
PHP Installation on Mac OS X with Apache
PHP Installation on Mac OS X with Apache
PHP Installation on Windows NT/2000/XP with IIS
PHP Installation on Windows NT/2000/XP with IIS
PHP Installation on Windows NT/2000/XP with Apache
PHP Installation on Windows NT/2000/XP with Apache
If you are using Apache as a Web Server, then this section will guide you to edit Apache Configuration Files.
Check here − PHP Configuration in Apache Server
The PHP configuration file, php.ini, is the final and immediate way to affect PHP's functionality.
Check here − PHP.INI File Configuration
To configure IIS on your Windows machine, you can refer your IIS Reference Manual shipped along with IIS.
In PHP 7, a new feature, Scalar type declarations, has been introduced. Scalar type declaration has two options −
coercive − coercive is default mode and need not to be specified.
coercive − coercive is default mode and need not to be specified.
strict − strict mode has to explicitly hinted.
strict − strict mode has to explicitly hinted.
Following types for function parameters can be enforced using the above modes −
int
float
bool
string
interfaces
array
callable
<?php
// Coercive mode
function sum(int ...$ints) {
return array_sum($ints);
}
print(sum(2, '3', 4.1));
?>
It produces the following browser output −
9
<?php
// Strict mode
declare(strict_types = 1);
function sum(int ...$ints) {
return array_sum($ints);
}
print(sum(2, '3', 4.1));
?>
It produces the following browser output −
Fatal error: Uncaught TypeError: Argument 2 passed to sum() must be of the type integer, string given, ...
In PHP 7, a new feature, Return type declarations has been introduced. Return type declaration specifies the type of value that a function should return. Following types for return types can be declared.
int
float
bool
string
interfaces
array
callable
<?php
declare(strict_types = 1);
function returnIntValue(int $value): int {
return $value;
}
print(returnIntValue(5));
?>
It produces the following browser output −
5
<?php
declare(strict_types = 1);
function returnIntValue(int $value): int {
return $value + 1.0;
}
print(returnIntValue(5));
?>
It produces the following browser output −
Fatal error: Uncaught TypeError: Return value of returnIntValue() must be of the type integer, float returned...
In PHP 7, a new feature, null coalescing operator (??) has been introduced. It is used to replace the ternary operation in conjunction with isset() function. The Null coalescing operator returns its first operand if it exists and is not NULL; otherwise it returns its second operand.
<?php
// fetch the value of $_GET['user'] and returns 'not passed'
// if username is not passed
$username = $_GET['username'] ?? 'not passed';
print($username);
print("<br/>");
// Equivalent code using ternary operator
$username = isset($_GET['username']) ? $_GET['username'] : 'not passed';
print($username);
print("<br/>");
// Chaining ?? operation
$username = $_GET['username'] ?? $_POST['username'] ?? 'not passed';
print($username);
?>
It produces the following browser output −
not passed
not passed
not passed
In PHP 7, a new feature, spaceship operator has been introduced. It is used to compare two expressions. It returns -1, 0 or 1 when first expression is respectively less than, equal to, or greater than second expression.
<?php
//integer comparison
print( 1 <=> 1);print("<br/>");
print( 1 <=> 2);print("<br/>");
print( 2 <=> 1);print("<br/>");
print("<br/>");
//float comparison
print( 1.5 <=> 1.5);print("<br/>");
print( 1.5 <=> 2.5);print("<br/>");
print( 2.5 <=> 1.5);print("<br/>");
print("<br/>");
//string comparison
print( "a" <=> "a");print("<br/>");
print( "a" <=> "b");print("<br/>");
print( "b" <=> "a");print("<br/>");
?>
It produces the following browser output −
0
-1
1
0
-1
1
0
-1
1
Array constants can now be defined using the define() function. In PHP 5.6, they could only be defined using const keyword.
<?php
//define a array using define function
define('animals', [
'dog',
'cat',
'bird'
]);
print(animals[1]);
?>
It produces the following browser output −
cat
Anonymous classes can now be defined using new class. Anonymous class can be used in place of a full class definition.
<?php
interface Logger {
public function log(string $msg);
}
class Application {
private $logger;
public function getLogger(): Logger {
return $this->logger;
}
public function setLogger(Logger $logger) {
$this->logger = $logger;
}
}
$app = new Application;
$app->setLogger(new class implements Logger {
public function log(string $msg) {
print($msg);
}
});
$app->getLogger()->log("My first Log Message");
?>
It produces the following browser output −
My first Log Message
Closure::call() method is added as a shorthand way to temporarily bind an object scope to a closure and invoke it. It is much faster in performance as compared to bindTo of PHP 5.6.
<?php
class A {
private $x = 1;
}
// Define a closure Pre PHP 7 code
$getValue = function() {
return $this->x;
};
// Bind a clousure
$value = $getValue->bindTo(new A, 'A');
print($value());
?>
It produces the following browser output −
1
<?php
class A {
private $x = 1;
}
// PHP 7+ code, Define
$value = function() {
return $this->x;
};
print($value->call(new A));
?>
It produces the following browser output −
1
PHP 7 introduces Filtered unserialize() function to provide better security when unserializing objects on untrusted data. It prevents possible code injections and enables the developer to whitelist classes that can be unserialized.
<?php
class MyClass1 {
public $obj1prop;
}
class MyClass2 {
public $obj2prop;
}
$obj1 = new MyClass1();
$obj1->obj1prop = 1;
$obj2 = new MyClass2();
$obj2->obj2prop = 2;
$serializedObj1 = serialize($obj1);
$serializedObj2 = serialize($obj2);
// default behaviour that accepts all classes
// second argument can be ommited.
// if allowed_classes is passed as false, unserialize converts all objects into __PHP_Incomplete_Class object
$data = unserialize($serializedObj1 , ["allowed_classes" => true]);
// converts all objects into __PHP_Incomplete_Class object except those of MyClass1 and MyClass2
$data2 = unserialize($serializedObj2 , ["allowed_classes" => ["MyClass1", "MyClass2"]]);
print($data->obj1prop);
print("<br/>");
print($data2->obj2prop);
?>
It produces the following browser output −
1
2
In PHP7, a new IntlChar class is added, which seeks to expose additional ICU functionality. This class defines a number of static methods and constants, which can be used to manipulate unicode characters. You need to have Intl extension installed prior to using this class.
<?php
printf('%x', IntlChar::CODEPOINT_MAX);
print (IntlChar::charName('@'));
print(IntlChar::ispunct('!'));
?>
It produces the following browser output −
10ffff
COMMERCIAL AT
true
In PHP 7, following two new functions are introduced to generate cryptographically secure integers and strings in a cross platform way.
random_bytes() − Generates cryptographically secure pseudo-random bytes.
random_bytes() − Generates cryptographically secure pseudo-random bytes.
random_int() − Generates cryptographically secure pseudo-random integers.
random_int() − Generates cryptographically secure pseudo-random integers.
random_bytes() generates an arbitrary-length string of cryptographic random bytes that are suitable for cryptographic use, such as when generating salts, keys or initialization vectors.
string random_bytes ( int $length )
length − The length of the random string that should be returned in bytes.
length − The length of the random string that should be returned in bytes.
Returns a string containing the requested number of cryptographically secure random bytes.
Returns a string containing the requested number of cryptographically secure random bytes.
If an appropriate source of randomness cannot be found, an Exception will be thrown.
If an appropriate source of randomness cannot be found, an Exception will be thrown.
If invalid parameters are given, a TypeError will be thrown.
If invalid parameters are given, a TypeError will be thrown.
If an invalid length of bytes is given, an Error will be thrown.
If an invalid length of bytes is given, an Error will be thrown.
<?php
$bytes = random_bytes(5);
print(bin2hex($bytes));
?>
It produces the following browser output −
54cc305593
random_int() generates cryptographic random integers that are suitable for use where unbiased results are critical.
int random_int ( int $min , int $max )
min − The lowest value to be returned, which must be PHP_INT_MIN or higher.
min − The lowest value to be returned, which must be PHP_INT_MIN or higher.
max − The highest value to be returned, which must be less than or equal to PHP_INT_MAX.
max − The highest value to be returned, which must be less than or equal to PHP_INT_MAX.
Returns a cryptographically secure random integer in the range min to max, inclusive.
Returns a cryptographically secure random integer in the range min to max, inclusive.
If an appropriate source of randomness cannot be found, an Exception will be thrown.
If an appropriate source of randomness cannot be found, an Exception will be thrown.
If invalid parameters are given, a TypeError will be thrown.
If invalid parameters are given, a TypeError will be thrown.
If max is less than min, an Error will be thrown.
If max is less than min, an Error will be thrown.
<?php
print(random_int(100, 999));
print("");
print(random_int(-1000, 0));
?>
It produces the following browser output −
614
-882
Expectations are a backwards compatible enhancement to the older assert() function. Expectation allows for zero-cost assertions in production code, and provides the ability to throw custom exceptions when the assertion fails. assert() is now a language construct, where the first parameter is an expression as compared to being a string or Boolean to be tested.
1 − generate and execute code (development mode)
0 − generate code but jump around it at runtime
-1 − do not generate code (production mode)
1 − throw, when the assertion fails, either by throwing the object provided as the exception or by throwing a new AssertionError object if exception was not provided.
0 − use or generate a Throwable as described above, but only generates a warning based on that object rather than throwing it (compatible with PHP 5 behaviour)
assertion − The assertion. In PHP 5, this must be either a string to be evaluated or a Boolean to be tested. In PHP 7, this may also be any expression that returns a value, which will be executed and the result is used to indicate whether the assertion succeeded or failed.
assertion − The assertion. In PHP 5, this must be either a string to be evaluated or a Boolean to be tested. In PHP 7, this may also be any expression that returns a value, which will be executed and the result is used to indicate whether the assertion succeeded or failed.
description − An optional description that will be included in the failure message, if the assertion fails.
description − An optional description that will be included in the failure message, if the assertion fails.
exception − In PHP 7, the second parameter can be a Throwable object instead of a descriptive string, in which case this is the object that will be thrown, if the assertion fails and the assert.exception configuration directive is enabled.
exception − In PHP 7, the second parameter can be a Throwable object instead of a descriptive string, in which case this is the object that will be thrown, if the assertion fails and the assert.exception configuration directive is enabled.
FALSE if the assertion is false, TRUE otherwise.
<?php
ini_set('assert.exception', 1);
class CustomError extends AssertionError {}
assert(false, new CustomError('Custom Error Message!'));
?>
It produces the following browser output −
Fatal error: Uncaught CustomError: Custom Error Message! in...
From PHP7 onwards, a single use statement can be used to import Classes, functions and constants from same namespace instead of multiple use statements.
<?php
// Before PHP 7
use com\tutorialspoint\ClassA;
use com\tutorialspoint\ClassB;
use com\tutorialspoint\ClassC as C;
use function com\tutorialspoint\fn_a;
use function com\tutorialspoint\fn_b;
use function com\tutorialspoint\fn_c;
use const com\tutorialspoint\ConstA;
use const com\tutorialspoint\ConstB;
use const com\tutorialspoint\ConstC;
// PHP 7+ code
use com\tutorialspoint\{ClassA, ClassB, ClassC as C};
use function com\tutorialspoint\{fn_a, fn_b, fn_c};
use const com\tutorialspoint\{ConstA, ConstB, ConstC};
?>
From PHP 7, error handling and reporting has been changed. Instead of reporting errors through the traditional error reporting mechanism used by PHP 5, now most errors are handled by throwing Error exceptions. Similar to exceptions, these Error exceptions bubble up until they reach the first matching catch block. If there are no matching blocks, then a default exception handler installed with set_exception_handler() will be called. In case there is no default exception handler, then the exception will be converted to a fatal error and will be handled like a traditional error.
As the Error hierarchy is not extended from Exception, code that uses catch (Exception $e) { ... } blocks to handle uncaught exceptions in PHP 5 will not handle such errors. A catch (Error $e) { ... } block or a set_exception_handler() handler is required to handle fatal errors.
<?php
class MathOperations {
protected $n = 10;
// Try to get the Division by Zero error object and display as Exception
public function doOperation(): string {
try {
$value = $this->n % 0;
return $value;
} catch (DivisionByZeroError $e) {
return $e->getMessage();
}
}
}
$mathOperationsObj = new MathOperations();
print($mathOperationsObj->doOperation());
?>
It produces the following browser output −
Modulo by zero
PHP 7 introduces a new function intdiv(), which performs integer division of its operands and return the division as int.
<?php
$value = intdiv(10,3);
var_dump($value);
print(" ");
print($value);
?>
It produces the following browser output −
int(3)
3
From PHP7+, session_start() function accepts an array of options to override the session configuration directives set in php.ini. These options supports session.lazy_write, which is by default on and causes PHP to overwrite any session file if the session data has changed.
Another option added is read_and_close, which indicates that the session data should be read and then the session should immediately be closed unchanged. For example, Set session.cache_limiter to private and set the flag to close the session immediately after reading it, using the following code snippet.
<?php
session_start([
'cache_limiter' => 'private',
'read_and_close' => true,
]);
?>
Following features are deprecated and may be removed from future releases of PHP.
PHP 4 style Constructors are methods having same name as the class they are defined in, are now deprecated, and will be removed in the future. PHP 7 will emit E_DEPRECATED if a PHP 4 constructor is the only constructor defined within a class. Classes implementing a __construct() method are unaffected.
<?php
class A {
function A() {
print('Style Constructor');
}
}
?>
It produces the following browser output −
Deprecated: Methods with the same name as their class will not be constructors
in a future version of PHP; A has a deprecated constructor in...
Static calls to non-static methods are deprecated, and may be removed in the future.
<?php
class A {
function b() {
print('Non-static call');
}
}
A::b();
?>
It produces the following browser output −
Deprecated: Non-static method A::b() should not be called statically in...
Non-static call
The salt option for the password_hash() function has been deprecated so that the developers do not generate their own (usually insecure) salts. The function itself generates a cryptographically secure salt, when no salt is provided by the developer - thus custom salt generation is not required any more.
The capture_session_meta SSL context option has been deprecated. SSL metadata is now used through the stream_get_meta_data() function.
Following Extensions have been removed from PHP 7 onwards −
ereg
mssql
mysql
sybase_ct
Following SAPIs have been removed from PHP 7 onwards −
aolserver
apache
apache_hooks
apache2filter
caudium
continuity
isapi
milter
nsapi
phttpd
pi3web
roxen
thttpd
tux
webjames
45 Lectures
9 hours
Malhar Lathkar
34 Lectures
4 hours
Syed Raza
84 Lectures
5.5 hours
Frahaan Hussain
17 Lectures
1 hours
Nivedita Jain
100 Lectures
34 hours
Azaz Patel
43 Lectures
5.5 hours
Vijay Kumar Parvatha Reddy
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2366,
"s": 2077,
"text": "PHP 7 is a major release of PHP programming language and is touted to be a revolution in the way web applications can be developed and delivered for mobile to enterprises and the cloud. This release is considered to be the most important change for PHP after the release of PHP 5 in 2004."
},
{
"code": null,
"e": 2459,
"s": 2366,
"text": "There are dozens of features added to PHP 7, the most significant ones are mentioned below −"
},
{
"code": null,
"e": 2546,
"s": 2459,
"text": "Improved performance − Having PHPNG code merged in PHP7, it is twice as fast as PHP 5."
},
{
"code": null,
"e": 2633,
"s": 2546,
"text": "Improved performance − Having PHPNG code merged in PHP7, it is twice as fast as PHP 5."
},
{
"code": null,
"e": 2702,
"s": 2633,
"text": "Lower Memory Consumption − Optimized PHP 7 utilizes lesser resource."
},
{
"code": null,
"e": 2771,
"s": 2702,
"text": "Lower Memory Consumption − Optimized PHP 7 utilizes lesser resource."
},
{
"code": null,
"e": 2846,
"s": 2771,
"text": "Scalar type declarations − Now parameter and return types can be enforced."
},
{
"code": null,
"e": 2921,
"s": 2846,
"text": "Scalar type declarations − Now parameter and return types can be enforced."
},
{
"code": null,
"e": 3002,
"s": 2921,
"text": "Consistent 64-bit support − Consistent support for 64-bit architecture machines."
},
{
"code": null,
"e": 3083,
"s": 3002,
"text": "Consistent 64-bit support − Consistent support for 64-bit architecture machines."
},
{
"code": null,
"e": 3147,
"s": 3083,
"text": "Improved Exception hierarchy − Exception hierarchy is improved."
},
{
"code": null,
"e": 3211,
"s": 3147,
"text": "Improved Exception hierarchy − Exception hierarchy is improved."
},
{
"code": null,
"e": 3339,
"s": 3211,
"text": "Many fatal errors converted to Exceptions − Range of exceptions is increased covering many fatal error converted as exceptions."
},
{
"code": null,
"e": 3467,
"s": 3339,
"text": "Many fatal errors converted to Exceptions − Range of exceptions is increased covering many fatal error converted as exceptions."
},
{
"code": null,
"e": 3552,
"s": 3467,
"text": "Secure random number generator − Addition of new secure random number generator API."
},
{
"code": null,
"e": 3637,
"s": 3552,
"text": "Secure random number generator − Addition of new secure random number generator API."
},
{
"code": null,
"e": 3765,
"s": 3637,
"text": "Deprecated SAPIs and extensions removed − Various old and unsupported SAPIs and extensions are removed from the latest version."
},
{
"code": null,
"e": 3893,
"s": 3765,
"text": "Deprecated SAPIs and extensions removed − Various old and unsupported SAPIs and extensions are removed from the latest version."
},
{
"code": null,
"e": 3965,
"s": 3893,
"text": "The null coalescing operator (??) − New null coalescing operator added."
},
{
"code": null,
"e": 4037,
"s": 3965,
"text": "The null coalescing operator (??) − New null coalescing operator added."
},
{
"code": null,
"e": 4125,
"s": 4037,
"text": "Return and Scalar Type Declarations − Support for return type and parameter type added."
},
{
"code": null,
"e": 4213,
"s": 4125,
"text": "Return and Scalar Type Declarations − Support for return type and parameter type added."
},
{
"code": null,
"e": 4262,
"s": 4213,
"text": "Anonymous Classes − Support for anonymous added."
},
{
"code": null,
"e": 4311,
"s": 4262,
"text": "Anonymous Classes − Support for anonymous added."
},
{
"code": null,
"e": 4367,
"s": 4311,
"text": "Zero cost asserts − Support for zero cost assert added."
},
{
"code": null,
"e": 4423,
"s": 4367,
"text": "Zero cost asserts − Support for zero cost assert added."
},
{
"code": null,
"e": 4698,
"s": 4423,
"text": "PHP 7 uses new Zend Engine 3.0 to improve application performance almost twice and 50% better memory consumption than PHP 5.6. It allows to serve more concurrent users without requiring any additional hardware. PHP 7 is designed and refactored considering today's workloads."
},
{
"code": null,
"e": 4844,
"s": 4698,
"text": "As per the Zend team, following illustrations show the performance comparison of PHP 7 vs PHP 5.6 and HHVM 3.7 on popular PHP based applications."
},
{
"code": null,
"e": 4952,
"s": 4844,
"text": "PHP 7 proves itself more than twice as faster, as compared to PHP 5.6 while executing Magento transactions."
},
{
"code": null,
"e": 5059,
"s": 4952,
"text": "PHP 7 proves itself more than twice as faster, as compared to PHP 5.6 while executing Drupal transactions."
},
{
"code": null,
"e": 5168,
"s": 5059,
"text": "PHP 7 proves itself more than twice as faster as compared to PHP 5.6 while executing Wordpress transactions."
},
{
"code": null,
"e": 5280,
"s": 5168,
"text": "In order to develop and run PHP Web pages, three vital components need to be installed on your computer system."
},
{
"code": null,
"e": 5506,
"s": 5280,
"text": "Web Server − PHP works with virtually all Web Server software, including Microsoft's Internet Information Server (IIS) but most often used is Apache Server. Download Apache for free here − http://httpd.apache.org/download.cgi"
},
{
"code": null,
"e": 5732,
"s": 5506,
"text": "Web Server − PHP works with virtually all Web Server software, including Microsoft's Internet Information Server (IIS) but most often used is Apache Server. Download Apache for free here − http://httpd.apache.org/download.cgi"
},
{
"code": null,
"e": 5928,
"s": 5732,
"text": "Database − PHP PHP works with virtually all database software, including Oracle and Sybase but most commonly used is MySQL database. Download MySQL for free here − http://www.mysql.com/downloads/"
},
{
"code": null,
"e": 6124,
"s": 5928,
"text": "Database − PHP PHP works with virtually all database software, including Oracle and Sybase but most commonly used is MySQL database. Download MySQL for free here − http://www.mysql.com/downloads/"
},
{
"code": null,
"e": 6343,
"s": 6124,
"text": "PHP Parser − In order to process PHP script instructions, a parser must be installed to generate HTML output that can be sent to the Web Browser. This tutorial will guide you how to install PHP parser on your computer."
},
{
"code": null,
"e": 6562,
"s": 6343,
"text": "PHP Parser − In order to process PHP script instructions, a parser must be installed to generate HTML output that can be sent to the Web Browser. This tutorial will guide you how to install PHP parser on your computer."
},
{
"code": null,
"e": 6762,
"s": 6562,
"text": "Before you proceed, it is important to make sure that you have proper environment setup on your machine to develop your web programs using PHP. Store the following php file in Apache's htdocs folder."
},
{
"code": null,
"e": 6785,
"s": 6762,
"text": "<?php\n phpinfo();\n?>"
},
{
"code": null,
"e": 6845,
"s": 6785,
"text": "Type the following address into your browser's address box."
},
{
"code": null,
"e": 6875,
"s": 6845,
"text": "http://127.0.0.1/phpinfo.php\n"
},
{
"code": null,
"e": 7094,
"s": 6875,
"text": "If this displays a page showing your PHP installation related information, then it means you have PHP and Webserver installed properly. Otherwise, you have to follow the given procedure to install PHP on your computer."
},
{
"code": null,
"e": 7187,
"s": 7094,
"text": "This section will guide you to install and configure PHP over the following four platforms −"
},
{
"code": null,
"e": 7233,
"s": 7187,
"text": "PHP Installation on Linux or Unix with Apache"
},
{
"code": null,
"e": 7279,
"s": 7233,
"text": "PHP Installation on Linux or Unix with Apache"
},
{
"code": null,
"e": 7320,
"s": 7279,
"text": "PHP Installation on Mac OS X with Apache"
},
{
"code": null,
"e": 7361,
"s": 7320,
"text": "PHP Installation on Mac OS X with Apache"
},
{
"code": null,
"e": 7410,
"s": 7361,
"text": "PHP Installation on Windows NT/2000/XP with IIS"
},
{
"code": null,
"e": 7459,
"s": 7410,
"text": "PHP Installation on Windows NT/2000/XP with IIS"
},
{
"code": null,
"e": 7511,
"s": 7459,
"text": "PHP Installation on Windows NT/2000/XP with Apache"
},
{
"code": null,
"e": 7563,
"s": 7511,
"text": "PHP Installation on Windows NT/2000/XP with Apache"
},
{
"code": null,
"e": 7673,
"s": 7563,
"text": "If you are using Apache as a Web Server, then this section will guide you to edit Apache Configuration Files."
},
{
"code": null,
"e": 7722,
"s": 7673,
"text": "Check here − PHP Configuration in Apache Server"
},
{
"code": null,
"e": 7821,
"s": 7722,
"text": "The PHP configuration file, php.ini, is the final and immediate way to affect PHP's functionality."
},
{
"code": null,
"e": 7861,
"s": 7821,
"text": "Check here − PHP.INI File Configuration"
},
{
"code": null,
"e": 7967,
"s": 7861,
"text": "To configure IIS on your Windows machine, you can refer your IIS Reference Manual shipped along with IIS."
},
{
"code": null,
"e": 8081,
"s": 7967,
"text": "In PHP 7, a new feature, Scalar type declarations, has been introduced. Scalar type declaration has two options −"
},
{
"code": null,
"e": 8147,
"s": 8081,
"text": "coercive − coercive is default mode and need not to be specified."
},
{
"code": null,
"e": 8213,
"s": 8147,
"text": "coercive − coercive is default mode and need not to be specified."
},
{
"code": null,
"e": 8260,
"s": 8213,
"text": "strict − strict mode has to explicitly hinted."
},
{
"code": null,
"e": 8307,
"s": 8260,
"text": "strict − strict mode has to explicitly hinted."
},
{
"code": null,
"e": 8387,
"s": 8307,
"text": "Following types for function parameters can be enforced using the above modes −"
},
{
"code": null,
"e": 8391,
"s": 8387,
"text": "int"
},
{
"code": null,
"e": 8397,
"s": 8391,
"text": "float"
},
{
"code": null,
"e": 8402,
"s": 8397,
"text": "bool"
},
{
"code": null,
"e": 8409,
"s": 8402,
"text": "string"
},
{
"code": null,
"e": 8420,
"s": 8409,
"text": "interfaces"
},
{
"code": null,
"e": 8426,
"s": 8420,
"text": "array"
},
{
"code": null,
"e": 8435,
"s": 8426,
"text": "callable"
},
{
"code": null,
"e": 8560,
"s": 8435,
"text": "<?php\n // Coercive mode\n function sum(int ...$ints) {\n return array_sum($ints);\n }\n print(sum(2, '3', 4.1));\n?>"
},
{
"code": null,
"e": 8603,
"s": 8560,
"text": "It produces the following browser output −"
},
{
"code": null,
"e": 8606,
"s": 8603,
"text": "9\n"
},
{
"code": null,
"e": 8759,
"s": 8606,
"text": "<?php\n // Strict mode\n declare(strict_types = 1);\n function sum(int ...$ints) {\n return array_sum($ints);\n }\n print(sum(2, '3', 4.1));\n?>"
},
{
"code": null,
"e": 8802,
"s": 8759,
"text": "It produces the following browser output −"
},
{
"code": null,
"e": 8910,
"s": 8802,
"text": "Fatal error: Uncaught TypeError: Argument 2 passed to sum() must be of the type integer, string given, ...\n"
},
{
"code": null,
"e": 9114,
"s": 8910,
"text": "In PHP 7, a new feature, Return type declarations has been introduced. Return type declaration specifies the type of value that a function should return. Following types for return types can be declared."
},
{
"code": null,
"e": 9118,
"s": 9114,
"text": "int"
},
{
"code": null,
"e": 9124,
"s": 9118,
"text": "float"
},
{
"code": null,
"e": 9129,
"s": 9124,
"text": "bool"
},
{
"code": null,
"e": 9136,
"s": 9129,
"text": "string"
},
{
"code": null,
"e": 9147,
"s": 9136,
"text": "interfaces"
},
{
"code": null,
"e": 9153,
"s": 9147,
"text": "array"
},
{
"code": null,
"e": 9162,
"s": 9153,
"text": "callable"
},
{
"code": null,
"e": 9302,
"s": 9162,
"text": "<?php\n declare(strict_types = 1);\n function returnIntValue(int $value): int {\n return $value;\n }\n print(returnIntValue(5));\n?>"
},
{
"code": null,
"e": 9345,
"s": 9302,
"text": "It produces the following browser output −"
},
{
"code": null,
"e": 9348,
"s": 9345,
"text": "5\n"
},
{
"code": null,
"e": 9494,
"s": 9348,
"text": "<?php\n declare(strict_types = 1);\n function returnIntValue(int $value): int {\n return $value + 1.0;\n }\n print(returnIntValue(5));\n?>"
},
{
"code": null,
"e": 9537,
"s": 9494,
"text": "It produces the following browser output −"
},
{
"code": null,
"e": 9651,
"s": 9537,
"text": "Fatal error: Uncaught TypeError: Return value of returnIntValue() must be of the type integer, float returned...\n"
},
{
"code": null,
"e": 9935,
"s": 9651,
"text": "In PHP 7, a new feature, null coalescing operator (??) has been introduced. It is used to replace the ternary operation in conjunction with isset() function. The Null coalescing operator returns its first operand if it exists and is not NULL; otherwise it returns its second operand."
},
{
"code": null,
"e": 10413,
"s": 9935,
"text": "<?php\n // fetch the value of $_GET['user'] and returns 'not passed'\n // if username is not passed\n $username = $_GET['username'] ?? 'not passed';\n print($username);\n print(\"<br/>\");\n\n // Equivalent code using ternary operator\n $username = isset($_GET['username']) ? $_GET['username'] : 'not passed';\n print($username);\n print(\"<br/>\");\n // Chaining ?? operation\n $username = $_GET['username'] ?? $_POST['username'] ?? 'not passed';\n print($username);\n?>"
},
{
"code": null,
"e": 10456,
"s": 10413,
"text": "It produces the following browser output −"
},
{
"code": null,
"e": 10490,
"s": 10456,
"text": "not passed\nnot passed\nnot passed\n"
},
{
"code": null,
"e": 10710,
"s": 10490,
"text": "In PHP 7, a new feature, spaceship operator has been introduced. It is used to compare two expressions. It returns -1, 0 or 1 when first expression is respectively less than, equal to, or greater than second expression."
},
{
"code": null,
"e": 11165,
"s": 10710,
"text": "<?php\n //integer comparison\n print( 1 <=> 1);print(\"<br/>\");\n print( 1 <=> 2);print(\"<br/>\");\n print( 2 <=> 1);print(\"<br/>\");\n print(\"<br/>\");\n //float comparison\n print( 1.5 <=> 1.5);print(\"<br/>\");\n print( 1.5 <=> 2.5);print(\"<br/>\");\n print( 2.5 <=> 1.5);print(\"<br/>\");\n print(\"<br/>\");\n //string comparison\n print( \"a\" <=> \"a\");print(\"<br/>\");\n print( \"a\" <=> \"b\");print(\"<br/>\");\n print( \"b\" <=> \"a\");print(\"<br/>\");\n?>"
},
{
"code": null,
"e": 11208,
"s": 11165,
"text": "It produces the following browser output −"
},
{
"code": null,
"e": 11232,
"s": 11208,
"text": "0\n-1\n1\n\n0\n-1\n1\n\n0\n-1\n1\n"
},
{
"code": null,
"e": 11356,
"s": 11232,
"text": "Array constants can now be defined using the define() function. In PHP 5.6, they could only be defined using const keyword."
},
{
"code": null,
"e": 11498,
"s": 11356,
"text": "<?php\n //define a array using define function\n define('animals', [\n 'dog',\n 'cat',\n 'bird'\n ]);\n print(animals[1]);\n?>"
},
{
"code": null,
"e": 11541,
"s": 11498,
"text": "It produces the following browser output −"
},
{
"code": null,
"e": 11546,
"s": 11541,
"text": "cat\n"
},
{
"code": null,
"e": 11665,
"s": 11546,
"text": "Anonymous classes can now be defined using new class. Anonymous class can be used in place of a full class definition."
},
{
"code": null,
"e": 12179,
"s": 11665,
"text": "<?php\n interface Logger {\n public function log(string $msg);\n }\n\n class Application {\n private $logger;\n\n public function getLogger(): Logger {\n return $this->logger;\n }\n\n public function setLogger(Logger $logger) {\n $this->logger = $logger;\n } \n }\n\n $app = new Application;\n $app->setLogger(new class implements Logger {\n public function log(string $msg) {\n print($msg);\n }\n });\n\n $app->getLogger()->log(\"My first Log Message\");\n?>"
},
{
"code": null,
"e": 12222,
"s": 12179,
"text": "It produces the following browser output −"
},
{
"code": null,
"e": 12244,
"s": 12222,
"text": "My first Log Message\n"
},
{
"code": null,
"e": 12426,
"s": 12244,
"text": "Closure::call() method is added as a shorthand way to temporarily bind an object scope to a closure and invoke it. It is much faster in performance as compared to bindTo of PHP 5.6."
},
{
"code": null,
"e": 12659,
"s": 12426,
"text": "<?php\n class A {\n private $x = 1;\n }\n\n // Define a closure Pre PHP 7 code\n $getValue = function() {\n return $this->x;\n };\n\n // Bind a clousure\n $value = $getValue->bindTo(new A, 'A'); \n\n print($value());\n?>"
},
{
"code": null,
"e": 12702,
"s": 12659,
"text": "It produces the following browser output −"
},
{
"code": null,
"e": 12705,
"s": 12702,
"text": "1\n"
},
{
"code": null,
"e": 12867,
"s": 12705,
"text": "<?php\n class A {\n private $x = 1;\n }\n\n // PHP 7+ code, Define\n $value = function() {\n return $this->x;\n };\n\n print($value->call(new A));\n?>"
},
{
"code": null,
"e": 12910,
"s": 12867,
"text": "It produces the following browser output −"
},
{
"code": null,
"e": 12913,
"s": 12910,
"text": "1\n"
},
{
"code": null,
"e": 13145,
"s": 12913,
"text": "PHP 7 introduces Filtered unserialize() function to provide better security when unserializing objects on untrusted data. It prevents possible code injections and enables the developer to whitelist classes that can be unserialized."
},
{
"code": null,
"e": 13978,
"s": 13145,
"text": "<?php\n class MyClass1 { \n public $obj1prop; \n }\n class MyClass2 {\n public $obj2prop;\n }\n\n $obj1 = new MyClass1();\n $obj1->obj1prop = 1;\n $obj2 = new MyClass2();\n $obj2->obj2prop = 2;\n\n $serializedObj1 = serialize($obj1);\n $serializedObj2 = serialize($obj2);\n\n // default behaviour that accepts all classes\n // second argument can be ommited.\n // if allowed_classes is passed as false, unserialize converts all objects into __PHP_Incomplete_Class object\n $data = unserialize($serializedObj1 , [\"allowed_classes\" => true]);\n\n // converts all objects into __PHP_Incomplete_Class object except those of MyClass1 and MyClass2\n $data2 = unserialize($serializedObj2 , [\"allowed_classes\" => [\"MyClass1\", \"MyClass2\"]]);\n\n print($data->obj1prop);\n print(\"<br/>\");\n print($data2->obj2prop);\n?>"
},
{
"code": null,
"e": 14021,
"s": 13978,
"text": "It produces the following browser output −"
},
{
"code": null,
"e": 14026,
"s": 14021,
"text": "1\n2\n"
},
{
"code": null,
"e": 14300,
"s": 14026,
"text": "In PHP7, a new IntlChar class is added, which seeks to expose additional ICU functionality. This class defines a number of static methods and constants, which can be used to manipulate unicode characters. You need to have Intl extension installed prior to using this class."
},
{
"code": null,
"e": 14421,
"s": 14300,
"text": "<?php\n printf('%x', IntlChar::CODEPOINT_MAX);\n print (IntlChar::charName('@'));\n print(IntlChar::ispunct('!'));\n?>"
},
{
"code": null,
"e": 14464,
"s": 14421,
"text": "It produces the following browser output −"
},
{
"code": null,
"e": 14491,
"s": 14464,
"text": "10ffff\nCOMMERCIAL AT\ntrue\n"
},
{
"code": null,
"e": 14627,
"s": 14491,
"text": "In PHP 7, following two new functions are introduced to generate cryptographically secure integers and strings in a cross platform way."
},
{
"code": null,
"e": 14700,
"s": 14627,
"text": "random_bytes() − Generates cryptographically secure pseudo-random bytes."
},
{
"code": null,
"e": 14773,
"s": 14700,
"text": "random_bytes() − Generates cryptographically secure pseudo-random bytes."
},
{
"code": null,
"e": 14847,
"s": 14773,
"text": "random_int() − Generates cryptographically secure pseudo-random integers."
},
{
"code": null,
"e": 14921,
"s": 14847,
"text": "random_int() − Generates cryptographically secure pseudo-random integers."
},
{
"code": null,
"e": 15107,
"s": 14921,
"text": "random_bytes() generates an arbitrary-length string of cryptographic random bytes that are suitable for cryptographic use, such as when generating salts, keys or initialization vectors."
},
{
"code": null,
"e": 15144,
"s": 15107,
"text": "string random_bytes ( int $length )\n"
},
{
"code": null,
"e": 15219,
"s": 15144,
"text": "length − The length of the random string that should be returned in bytes."
},
{
"code": null,
"e": 15294,
"s": 15219,
"text": "length − The length of the random string that should be returned in bytes."
},
{
"code": null,
"e": 15385,
"s": 15294,
"text": "Returns a string containing the requested number of cryptographically secure random bytes."
},
{
"code": null,
"e": 15476,
"s": 15385,
"text": "Returns a string containing the requested number of cryptographically secure random bytes."
},
{
"code": null,
"e": 15561,
"s": 15476,
"text": "If an appropriate source of randomness cannot be found, an Exception will be thrown."
},
{
"code": null,
"e": 15646,
"s": 15561,
"text": "If an appropriate source of randomness cannot be found, an Exception will be thrown."
},
{
"code": null,
"e": 15707,
"s": 15646,
"text": "If invalid parameters are given, a TypeError will be thrown."
},
{
"code": null,
"e": 15768,
"s": 15707,
"text": "If invalid parameters are given, a TypeError will be thrown."
},
{
"code": null,
"e": 15833,
"s": 15768,
"text": "If an invalid length of bytes is given, an Error will be thrown."
},
{
"code": null,
"e": 15898,
"s": 15833,
"text": "If an invalid length of bytes is given, an Error will be thrown."
},
{
"code": null,
"e": 15963,
"s": 15898,
"text": "<?php\n $bytes = random_bytes(5);\n print(bin2hex($bytes));\n?>"
},
{
"code": null,
"e": 16006,
"s": 15963,
"text": "It produces the following browser output −"
},
{
"code": null,
"e": 16018,
"s": 16006,
"text": "54cc305593\n"
},
{
"code": null,
"e": 16134,
"s": 16018,
"text": "random_int() generates cryptographic random integers that are suitable for use where unbiased results are critical."
},
{
"code": null,
"e": 16174,
"s": 16134,
"text": "int random_int ( int $min , int $max )\n"
},
{
"code": null,
"e": 16250,
"s": 16174,
"text": "min − The lowest value to be returned, which must be PHP_INT_MIN or higher."
},
{
"code": null,
"e": 16326,
"s": 16250,
"text": "min − The lowest value to be returned, which must be PHP_INT_MIN or higher."
},
{
"code": null,
"e": 16415,
"s": 16326,
"text": "max − The highest value to be returned, which must be less than or equal to PHP_INT_MAX."
},
{
"code": null,
"e": 16504,
"s": 16415,
"text": "max − The highest value to be returned, which must be less than or equal to PHP_INT_MAX."
},
{
"code": null,
"e": 16590,
"s": 16504,
"text": "Returns a cryptographically secure random integer in the range min to max, inclusive."
},
{
"code": null,
"e": 16676,
"s": 16590,
"text": "Returns a cryptographically secure random integer in the range min to max, inclusive."
},
{
"code": null,
"e": 16761,
"s": 16676,
"text": "If an appropriate source of randomness cannot be found, an Exception will be thrown."
},
{
"code": null,
"e": 16846,
"s": 16761,
"text": "If an appropriate source of randomness cannot be found, an Exception will be thrown."
},
{
"code": null,
"e": 16907,
"s": 16846,
"text": "If invalid parameters are given, a TypeError will be thrown."
},
{
"code": null,
"e": 16968,
"s": 16907,
"text": "If invalid parameters are given, a TypeError will be thrown."
},
{
"code": null,
"e": 17018,
"s": 16968,
"text": "If max is less than min, an Error will be thrown."
},
{
"code": null,
"e": 17068,
"s": 17018,
"text": "If max is less than min, an Error will be thrown."
},
{
"code": null,
"e": 17155,
"s": 17068,
"text": "<?php\n print(random_int(100, 999));\n print(\"\");\n print(random_int(-1000, 0));\n?>"
},
{
"code": null,
"e": 17198,
"s": 17155,
"text": "It produces the following browser output −"
},
{
"code": null,
"e": 17208,
"s": 17198,
"text": "614\n-882\n"
},
{
"code": null,
"e": 17570,
"s": 17208,
"text": "Expectations are a backwards compatible enhancement to the older assert() function. Expectation allows for zero-cost assertions in production code, and provides the ability to throw custom exceptions when the assertion fails. assert() is now a language construct, where the first parameter is an expression as compared to being a string or Boolean to be tested."
},
{
"code": null,
"e": 17619,
"s": 17570,
"text": "1 − generate and execute code (development mode)"
},
{
"code": null,
"e": 17667,
"s": 17619,
"text": "0 − generate code but jump around it at runtime"
},
{
"code": null,
"e": 17711,
"s": 17667,
"text": "-1 − do not generate code (production mode)"
},
{
"code": null,
"e": 17878,
"s": 17711,
"text": "1 − throw, when the assertion fails, either by throwing the object provided as the exception or by throwing a new AssertionError object if exception was not provided."
},
{
"code": null,
"e": 18038,
"s": 17878,
"text": "0 − use or generate a Throwable as described above, but only generates a warning based on that object rather than throwing it (compatible with PHP 5 behaviour)"
},
{
"code": null,
"e": 18312,
"s": 18038,
"text": "assertion − The assertion. In PHP 5, this must be either a string to be evaluated or a Boolean to be tested. In PHP 7, this may also be any expression that returns a value, which will be executed and the result is used to indicate whether the assertion succeeded or failed."
},
{
"code": null,
"e": 18586,
"s": 18312,
"text": "assertion − The assertion. In PHP 5, this must be either a string to be evaluated or a Boolean to be tested. In PHP 7, this may also be any expression that returns a value, which will be executed and the result is used to indicate whether the assertion succeeded or failed."
},
{
"code": null,
"e": 18694,
"s": 18586,
"text": "description − An optional description that will be included in the failure message, if the assertion fails."
},
{
"code": null,
"e": 18802,
"s": 18694,
"text": "description − An optional description that will be included in the failure message, if the assertion fails."
},
{
"code": null,
"e": 19042,
"s": 18802,
"text": "exception − In PHP 7, the second parameter can be a Throwable object instead of a descriptive string, in which case this is the object that will be thrown, if the assertion fails and the assert.exception configuration directive is enabled."
},
{
"code": null,
"e": 19282,
"s": 19042,
"text": "exception − In PHP 7, the second parameter can be a Throwable object instead of a descriptive string, in which case this is the object that will be thrown, if the assertion fails and the assert.exception configuration directive is enabled."
},
{
"code": null,
"e": 19331,
"s": 19282,
"text": "FALSE if the assertion is false, TRUE otherwise."
},
{
"code": null,
"e": 19484,
"s": 19331,
"text": "<?php\n ini_set('assert.exception', 1);\n\n class CustomError extends AssertionError {}\n\n assert(false, new CustomError('Custom Error Message!'));\n?>"
},
{
"code": null,
"e": 19527,
"s": 19484,
"text": "It produces the following browser output −"
},
{
"code": null,
"e": 19591,
"s": 19527,
"text": "Fatal error: Uncaught CustomError: Custom Error Message! in...\n"
},
{
"code": null,
"e": 19744,
"s": 19591,
"text": "From PHP7 onwards, a single use statement can be used to import Classes, functions and constants from same namespace instead of multiple use statements."
},
{
"code": null,
"e": 20314,
"s": 19744,
"text": "<?php\n // Before PHP 7\n use com\\tutorialspoint\\ClassA;\n use com\\tutorialspoint\\ClassB;\n use com\\tutorialspoint\\ClassC as C;\n\n use function com\\tutorialspoint\\fn_a;\n use function com\\tutorialspoint\\fn_b;\n use function com\\tutorialspoint\\fn_c;\n\n use const com\\tutorialspoint\\ConstA;\n use const com\\tutorialspoint\\ConstB;\n use const com\\tutorialspoint\\ConstC;\n\n // PHP 7+ code\n use com\\tutorialspoint\\{ClassA, ClassB, ClassC as C};\n use function com\\tutorialspoint\\{fn_a, fn_b, fn_c};\n use const com\\tutorialspoint\\{ConstA, ConstB, ConstC};\n\n?>"
},
{
"code": null,
"e": 20897,
"s": 20314,
"text": "From PHP 7, error handling and reporting has been changed. Instead of reporting errors through the traditional error reporting mechanism used by PHP 5, now most errors are handled by throwing Error exceptions. Similar to exceptions, these Error exceptions bubble up until they reach the first matching catch block. If there are no matching blocks, then a default exception handler installed with set_exception_handler() will be called. In case there is no default exception handler, then the exception will be converted to a fatal error and will be handled like a traditional error."
},
{
"code": null,
"e": 21177,
"s": 20897,
"text": "As the Error hierarchy is not extended from Exception, code that uses catch (Exception $e) { ... } blocks to handle uncaught exceptions in PHP 5 will not handle such errors. A catch (Error $e) { ... } block or a set_exception_handler() handler is required to handle fatal errors."
},
{
"code": null,
"e": 21637,
"s": 21177,
"text": "<?php\n class MathOperations {\n protected $n = 10;\n\n // Try to get the Division by Zero error object and display as Exception\n public function doOperation(): string {\n try {\n $value = $this->n % 0;\n return $value;\n } catch (DivisionByZeroError $e) {\n return $e->getMessage();\n }\n }\n }\n\n $mathOperationsObj = new MathOperations();\n print($mathOperationsObj->doOperation());\n?>"
},
{
"code": null,
"e": 21680,
"s": 21637,
"text": "It produces the following browser output −"
},
{
"code": null,
"e": 21696,
"s": 21680,
"text": "Modulo by zero\n"
},
{
"code": null,
"e": 21818,
"s": 21696,
"text": "PHP 7 introduces a new function intdiv(), which performs integer division of its operands and return the division as int."
},
{
"code": null,
"e": 21907,
"s": 21818,
"text": "<?php\n $value = intdiv(10,3);\n var_dump($value);\n print(\" \");\n print($value);\n?>"
},
{
"code": null,
"e": 21950,
"s": 21907,
"text": "It produces the following browser output −"
},
{
"code": null,
"e": 21961,
"s": 21950,
"text": "int(3) \n3\n"
},
{
"code": null,
"e": 22235,
"s": 21961,
"text": "From PHP7+, session_start() function accepts an array of options to override the session configuration directives set in php.ini. These options supports session.lazy_write, which is by default on and causes PHP to overwrite any session file if the session data has changed."
},
{
"code": null,
"e": 22541,
"s": 22235,
"text": "Another option added is read_and_close, which indicates that the session data should be read and then the session should immediately be closed unchanged. For example, Set session.cache_limiter to private and set the flag to close the session immediately after reading it, using the following code snippet."
},
{
"code": null,
"e": 22644,
"s": 22541,
"text": "<?php\n session_start([\n 'cache_limiter' => 'private',\n 'read_and_close' => true,\n ]);\n?>"
},
{
"code": null,
"e": 22726,
"s": 22644,
"text": "Following features are deprecated and may be removed from future releases of PHP."
},
{
"code": null,
"e": 23029,
"s": 22726,
"text": "PHP 4 style Constructors are methods having same name as the class they are defined in, are now deprecated, and will be removed in the future. PHP 7 will emit E_DEPRECATED if a PHP 4 constructor is the only constructor defined within a class. Classes implementing a __construct() method are unaffected."
},
{
"code": null,
"e": 23122,
"s": 23029,
"text": "<?php\n class A {\n function A() {\n print('Style Constructor');\n }\n }\n?>"
},
{
"code": null,
"e": 23165,
"s": 23122,
"text": "It produces the following browser output −"
},
{
"code": null,
"e": 23311,
"s": 23165,
"text": "Deprecated: Methods with the same name as their class will not be constructors \nin a future version of PHP; A has a deprecated constructor in...\n"
},
{
"code": null,
"e": 23396,
"s": 23311,
"text": "Static calls to non-static methods are deprecated, and may be removed in the future."
},
{
"code": null,
"e": 23498,
"s": 23396,
"text": "<?php\n class A {\n function b() {\n print('Non-static call');\n }\n }\n A::b();\n?>"
},
{
"code": null,
"e": 23541,
"s": 23498,
"text": "It produces the following browser output −"
},
{
"code": null,
"e": 23633,
"s": 23541,
"text": "Deprecated: Non-static method A::b() should not be called statically in...\nNon-static call\n"
},
{
"code": null,
"e": 23938,
"s": 23633,
"text": "The salt option for the password_hash() function has been deprecated so that the developers do not generate their own (usually insecure) salts. The function itself generates a cryptographically secure salt, when no salt is provided by the developer - thus custom salt generation is not required any more."
},
{
"code": null,
"e": 24073,
"s": 23938,
"text": "The capture_session_meta SSL context option has been deprecated. SSL metadata is now used through the stream_get_meta_data() function."
},
{
"code": null,
"e": 24133,
"s": 24073,
"text": "Following Extensions have been removed from PHP 7 onwards −"
},
{
"code": null,
"e": 24138,
"s": 24133,
"text": "ereg"
},
{
"code": null,
"e": 24144,
"s": 24138,
"text": "mssql"
},
{
"code": null,
"e": 24150,
"s": 24144,
"text": "mysql"
},
{
"code": null,
"e": 24160,
"s": 24150,
"text": "sybase_ct"
},
{
"code": null,
"e": 24215,
"s": 24160,
"text": "Following SAPIs have been removed from PHP 7 onwards −"
},
{
"code": null,
"e": 24225,
"s": 24215,
"text": "aolserver"
},
{
"code": null,
"e": 24232,
"s": 24225,
"text": "apache"
},
{
"code": null,
"e": 24245,
"s": 24232,
"text": "apache_hooks"
},
{
"code": null,
"e": 24259,
"s": 24245,
"text": "apache2filter"
},
{
"code": null,
"e": 24267,
"s": 24259,
"text": "caudium"
},
{
"code": null,
"e": 24278,
"s": 24267,
"text": "continuity"
},
{
"code": null,
"e": 24284,
"s": 24278,
"text": "isapi"
},
{
"code": null,
"e": 24291,
"s": 24284,
"text": "milter"
},
{
"code": null,
"e": 24297,
"s": 24291,
"text": "nsapi"
},
{
"code": null,
"e": 24304,
"s": 24297,
"text": "phttpd"
},
{
"code": null,
"e": 24311,
"s": 24304,
"text": "pi3web"
},
{
"code": null,
"e": 24317,
"s": 24311,
"text": "roxen"
},
{
"code": null,
"e": 24324,
"s": 24317,
"text": "thttpd"
},
{
"code": null,
"e": 24328,
"s": 24324,
"text": "tux"
},
{
"code": null,
"e": 24337,
"s": 24328,
"text": "webjames"
},
{
"code": null,
"e": 24370,
"s": 24337,
"text": "\n 45 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 24386,
"s": 24370,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 24419,
"s": 24386,
"text": "\n 34 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 24430,
"s": 24419,
"text": " Syed Raza"
},
{
"code": null,
"e": 24465,
"s": 24430,
"text": "\n 84 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 24482,
"s": 24465,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 24515,
"s": 24482,
"text": "\n 17 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 24530,
"s": 24515,
"text": " Nivedita Jain"
},
{
"code": null,
"e": 24565,
"s": 24530,
"text": "\n 100 Lectures \n 34 hours \n"
},
{
"code": null,
"e": 24577,
"s": 24565,
"text": " Azaz Patel"
},
{
"code": null,
"e": 24612,
"s": 24577,
"text": "\n 43 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 24640,
"s": 24612,
"text": " Vijay Kumar Parvatha Reddy"
},
{
"code": null,
"e": 24647,
"s": 24640,
"text": " Print"
},
{
"code": null,
"e": 24658,
"s": 24647,
"text": " Add Notes"
}
] |
AtomicBoolean compareAndSet() method in Java with Examples - GeeksforGeeks | 27 Feb, 2019
The java.util.concurrent.atomic.AtomicBoolean.compareAndSet() is an inbuilt method in java that sets the value to the passed value in the parameter if the current value is equal to the expected value which is also passed in the parameter. The function returns a boolean value which gives us an idea if the update was done or not.
Syntax:
public final boolean compareAndSet(boolean expect, boolean val)
Parameters: The function accepts two mandatory parameters which are described below:
expect: which specifies the value that the atomic object should be.
val: which specifies the value to be updated if the atomic Boolean is equal to expect.
Return Value: The function returns a boolean value, it returns true on success else false.
Below programs illustrate the above function:
Program 1:
// Java Program to demonstrates// the compareAndSet() function import java.util.concurrent.atomic.AtomicBoolean; public class GFG { public static void main(String args[]) { // Initially value as false AtomicBoolean val = new AtomicBoolean(false); // Prints the updated value System.out.println("Previous value: " + val); // Checks if previous value was false // and then updates it boolean res = val.compareAndSet(false, true); // Checks if the value was updated. if (res) System.out.println("The value was" + " updated and it is " + val); else System.out.println("The value was " + "not updated"); }}
Previous value: false
The value was updated and it is true
Program 2:
// Java Program to demonstrates// the compareAndSet() function import java.util.concurrent.atomic.AtomicBoolean; public class GFG { public static void main(String args[]) { // Initially value as true AtomicBoolean val = new AtomicBoolean(true); // Prints the updated value System.out.println("Previous value: " + val); // Checks if previous value was true // and then updates it boolean res = val.compareAndSet(true, false); // Checks if the value was updated. if (res) System.out.println("The value was" + " updated and it is " + val); else System.out.println("The value was " + "not updated"); }}
Previous value: true
The value was updated and it is false
Reference: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicBoolean.html#compareAndSet(boolean, %20boolean)
Java-AtomicBoolean
Java-concurrent-package
Java-Functions
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
HashMap in Java with Examples
Interfaces in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multithreading in Java
Set in Java
Multidimensional Arrays in Java | [
{
"code": null,
"e": 26095,
"s": 26067,
"text": "\n27 Feb, 2019"
},
{
"code": null,
"e": 26425,
"s": 26095,
"text": "The java.util.concurrent.atomic.AtomicBoolean.compareAndSet() is an inbuilt method in java that sets the value to the passed value in the parameter if the current value is equal to the expected value which is also passed in the parameter. The function returns a boolean value which gives us an idea if the update was done or not."
},
{
"code": null,
"e": 26433,
"s": 26425,
"text": "Syntax:"
},
{
"code": null,
"e": 26497,
"s": 26433,
"text": "public final boolean compareAndSet(boolean expect, boolean val)"
},
{
"code": null,
"e": 26582,
"s": 26497,
"text": "Parameters: The function accepts two mandatory parameters which are described below:"
},
{
"code": null,
"e": 26650,
"s": 26582,
"text": "expect: which specifies the value that the atomic object should be."
},
{
"code": null,
"e": 26737,
"s": 26650,
"text": "val: which specifies the value to be updated if the atomic Boolean is equal to expect."
},
{
"code": null,
"e": 26828,
"s": 26737,
"text": "Return Value: The function returns a boolean value, it returns true on success else false."
},
{
"code": null,
"e": 26874,
"s": 26828,
"text": "Below programs illustrate the above function:"
},
{
"code": null,
"e": 26885,
"s": 26874,
"text": "Program 1:"
},
{
"code": "// Java Program to demonstrates// the compareAndSet() function import java.util.concurrent.atomic.AtomicBoolean; public class GFG { public static void main(String args[]) { // Initially value as false AtomicBoolean val = new AtomicBoolean(false); // Prints the updated value System.out.println(\"Previous value: \" + val); // Checks if previous value was false // and then updates it boolean res = val.compareAndSet(false, true); // Checks if the value was updated. if (res) System.out.println(\"The value was\" + \" updated and it is \" + val); else System.out.println(\"The value was \" + \"not updated\"); }}",
"e": 27714,
"s": 26885,
"text": null
},
{
"code": null,
"e": 27774,
"s": 27714,
"text": "Previous value: false\nThe value was updated and it is true\n"
},
{
"code": null,
"e": 27785,
"s": 27774,
"text": "Program 2:"
},
{
"code": "// Java Program to demonstrates// the compareAndSet() function import java.util.concurrent.atomic.AtomicBoolean; public class GFG { public static void main(String args[]) { // Initially value as true AtomicBoolean val = new AtomicBoolean(true); // Prints the updated value System.out.println(\"Previous value: \" + val); // Checks if previous value was true // and then updates it boolean res = val.compareAndSet(true, false); // Checks if the value was updated. if (res) System.out.println(\"The value was\" + \" updated and it is \" + val); else System.out.println(\"The value was \" + \"not updated\"); }}",
"e": 28611,
"s": 27785,
"text": null
},
{
"code": null,
"e": 28671,
"s": 28611,
"text": "Previous value: true\nThe value was updated and it is false\n"
},
{
"code": null,
"e": 28806,
"s": 28671,
"text": "Reference: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicBoolean.html#compareAndSet(boolean, %20boolean)"
},
{
"code": null,
"e": 28825,
"s": 28806,
"text": "Java-AtomicBoolean"
},
{
"code": null,
"e": 28849,
"s": 28825,
"text": "Java-concurrent-package"
},
{
"code": null,
"e": 28864,
"s": 28849,
"text": "Java-Functions"
},
{
"code": null,
"e": 28869,
"s": 28864,
"text": "Java"
},
{
"code": null,
"e": 28874,
"s": 28869,
"text": "Java"
},
{
"code": null,
"e": 28972,
"s": 28874,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28987,
"s": 28972,
"text": "Stream In Java"
},
{
"code": null,
"e": 29017,
"s": 28987,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 29036,
"s": 29017,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 29054,
"s": 29036,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 29086,
"s": 29054,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 29106,
"s": 29086,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 29130,
"s": 29106,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 29153,
"s": 29130,
"text": "Multithreading in Java"
},
{
"code": null,
"e": 29165,
"s": 29153,
"text": "Set in Java"
}
] |
Python | Data Comparison and Selection in Pandas - GeeksforGeeks | 17 Sep, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages, and makes importing and analyzing data much easier.
The most important thing in Data Analysis is comparing values and selecting data accordingly. The “==” operator works for multiple values in a Pandas Data frame too. Following two examples will show how to compare and select data from a Pandas Data frame.
To download the CSV file used, Click Here.
Example #1: Comparing DataIn the following example, a data frame is made from a csv file. In the Gender Column, there are only 3 types of values (“Male”, “Female” or NaN). Every row of Gender column is compared to “Male” and a boolean series is returned after that.
# importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv("employees.csv") # storing boolean series in newnew = data["Gender"] == "Male" # inserting new series in data framedata["New"]= new # displaydata
Output:As show in the output image, for Gender= “Male”, the value in New Column is True and for “Female” and NaN values it is False.
Example #2: Selecting DataIn the following example, the boolean series is passed to the data and only Rows having Gender=”Male” are returned.
# importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv("employees.csv") # storing boolean series in newnew = data["Gender"] != "Female" # inserting new series in data framedata["New"]= new # displaydata[new] # OR # data[data["Gender"]=="Male"]# Both are the same
Output:As shown in the output image, Data frame having Gender=”Male” is returned.
Note: For NaN values, the boolean value is False.
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
Selecting rows in pandas DataFrame based on conditions
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Defaultdict in Python
Python OOPs Concepts
Python | os.path.join() method
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 24316,
"s": 24288,
"text": "\n17 Sep, 2018"
},
{
"code": null,
"e": 24531,
"s": 24316,
"text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages, and makes importing and analyzing data much easier."
},
{
"code": null,
"e": 24787,
"s": 24531,
"text": "The most important thing in Data Analysis is comparing values and selecting data accordingly. The “==” operator works for multiple values in a Pandas Data frame too. Following two examples will show how to compare and select data from a Pandas Data frame."
},
{
"code": null,
"e": 24830,
"s": 24787,
"text": "To download the CSV file used, Click Here."
},
{
"code": null,
"e": 25096,
"s": 24830,
"text": "Example #1: Comparing DataIn the following example, a data frame is made from a csv file. In the Gender Column, there are only 3 types of values (“Male”, “Female” or NaN). Every row of Gender column is compared to “Male” and a boolean series is returned after that."
},
{
"code": "# importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv(\"employees.csv\") # storing boolean series in newnew = data[\"Gender\"] == \"Male\" # inserting new series in data framedata[\"New\"]= new # displaydata",
"e": 25344,
"s": 25096,
"text": null
},
{
"code": null,
"e": 25477,
"s": 25344,
"text": "Output:As show in the output image, for Gender= “Male”, the value in New Column is True and for “Female” and NaN values it is False."
},
{
"code": null,
"e": 25620,
"s": 25477,
"text": " Example #2: Selecting DataIn the following example, the boolean series is passed to the data and only Rows having Gender=”Male” are returned."
},
{
"code": "# importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv(\"employees.csv\") # storing boolean series in newnew = data[\"Gender\"] != \"Female\" # inserting new series in data framedata[\"New\"]= new # displaydata[new] # OR # data[data[\"Gender\"]==\"Male\"]# Both are the same",
"e": 25931,
"s": 25620,
"text": null
},
{
"code": null,
"e": 26013,
"s": 25931,
"text": "Output:As shown in the output image, Data frame having Gender=”Male” is returned."
},
{
"code": null,
"e": 26063,
"s": 26013,
"text": "Note: For NaN values, the boolean value is False."
},
{
"code": null,
"e": 26087,
"s": 26063,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 26119,
"s": 26087,
"text": "Python pandas-dataFrame-methods"
},
{
"code": null,
"e": 26133,
"s": 26119,
"text": "Python-pandas"
},
{
"code": null,
"e": 26140,
"s": 26133,
"text": "Python"
},
{
"code": null,
"e": 26238,
"s": 26140,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26247,
"s": 26238,
"text": "Comments"
},
{
"code": null,
"e": 26260,
"s": 26247,
"text": "Old Comments"
},
{
"code": null,
"e": 26292,
"s": 26260,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26347,
"s": 26292,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 26403,
"s": 26347,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26445,
"s": 26403,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26487,
"s": 26445,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26526,
"s": 26487,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26548,
"s": 26526,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26569,
"s": 26548,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 26600,
"s": 26569,
"text": "Python | os.path.join() method"
}
] |
C# Program to Get the Operating System Version of Computer using Environment Class - GeeksforGeeks | 24 Oct, 2021
In C#, Environment Class provides information about the current platform and manipulates, the current platform. It is useful for getting and setting various operating system-related information. We can use it in such a way that it retrieves command-line arguments information, exit codes information, environment variable settings information, contents of the call stack information, and time since the last system boot in milliseconds information. In this article, we are going to discuss how to get the operating system version of the computer. So we use the OSVersion property of the Environment class. This property returns the current OS version of the system or platform identifier. It will also return an InvalidOperationException if this property does not get the current version of the system or a platform identifier that is not part of PlatformID.
Syntax:
Environment.OSVersion
spa
Return: It returns the platform identifier or the version of the system.
Example:
In the below example, using the OsVersion property of Environment class we find the current OS version of our computer system.
C#
// C# program to get the current operating// system version of the computer // Using Environment Classusing System;using System.Collections; class GFG{ static public void Main() { // Display the current OS version of the system // Using OSVersion property of the Environment class Console.WriteLine("The current operating System version is " + Environment.OSVersion); }}
Output:
The current operating System version is Unix 20.3.0.0
CSharp-programs
Picked
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extension Method in C#
HashSet in C# with Examples
Partial Classes in C#
C# | Inheritance
C# | Generics - Introduction
Top 50 C# Interview Questions & Answers
Switch Statement in C#
Convert String to Character Array in C#
C# | How to insert an element in an Array?
Lambda Expressions in C# | [
{
"code": null,
"e": 25547,
"s": 25519,
"text": "\n24 Oct, 2021"
},
{
"code": null,
"e": 26407,
"s": 25547,
"text": "In C#, Environment Class provides information about the current platform and manipulates, the current platform. It is useful for getting and setting various operating system-related information. We can use it in such a way that it retrieves command-line arguments information, exit codes information, environment variable settings information, contents of the call stack information, and time since the last system boot in milliseconds information. In this article, we are going to discuss how to get the operating system version of the computer. So we use the OSVersion property of the Environment class. This property returns the current OS version of the system or platform identifier. It will also return an InvalidOperationException if this property does not get the current version of the system or a platform identifier that is not part of PlatformID. "
},
{
"code": null,
"e": 26415,
"s": 26407,
"text": "Syntax:"
},
{
"code": null,
"e": 26437,
"s": 26415,
"text": "Environment.OSVersion"
},
{
"code": null,
"e": 26441,
"s": 26437,
"text": "spa"
},
{
"code": null,
"e": 26514,
"s": 26441,
"text": "Return: It returns the platform identifier or the version of the system."
},
{
"code": null,
"e": 26524,
"s": 26514,
"text": "Example: "
},
{
"code": null,
"e": 26651,
"s": 26524,
"text": "In the below example, using the OsVersion property of Environment class we find the current OS version of our computer system."
},
{
"code": null,
"e": 26654,
"s": 26651,
"text": "C#"
},
{
"code": "// C# program to get the current operating// system version of the computer // Using Environment Classusing System;using System.Collections; class GFG{ static public void Main() { // Display the current OS version of the system // Using OSVersion property of the Environment class Console.WriteLine(\"The current operating System version is \" + Environment.OSVersion); }}",
"e": 27086,
"s": 26654,
"text": null
},
{
"code": null,
"e": 27094,
"s": 27086,
"text": "Output:"
},
{
"code": null,
"e": 27148,
"s": 27094,
"text": "The current operating System version is Unix 20.3.0.0"
},
{
"code": null,
"e": 27164,
"s": 27148,
"text": "CSharp-programs"
},
{
"code": null,
"e": 27171,
"s": 27164,
"text": "Picked"
},
{
"code": null,
"e": 27174,
"s": 27171,
"text": "C#"
},
{
"code": null,
"e": 27272,
"s": 27174,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27295,
"s": 27272,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 27323,
"s": 27295,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 27345,
"s": 27323,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 27362,
"s": 27345,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 27391,
"s": 27362,
"text": "C# | Generics - Introduction"
},
{
"code": null,
"e": 27431,
"s": 27391,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 27454,
"s": 27431,
"text": "Switch Statement in C#"
},
{
"code": null,
"e": 27494,
"s": 27454,
"text": "Convert String to Character Array in C#"
},
{
"code": null,
"e": 27537,
"s": 27494,
"text": "C# | How to insert an element in an Array?"
}
] |
Show or hide children components in Angular 10 - GeeksforGeeks | 25 Jan, 2021
Prerequisites: Angular must be installed
In this article, we will see how we can show or hide the child components in Angular.
Lets start by creating a new project. Create a new folder and initialize a new angular project. Run the project to verify it is working.
ng new myProject
ng serve -o
This will create a new project in the current directory. Now we can clear the app.component.html file and create a child component in order to demonstrate how we can show or hide it.
ng generate component comp1
Now the setup part is over. Lets add this components in our app.component.html file:
<app-comp1></app-comp1>
We will create a button to show and hide the component. Lets add the button code in app.component.html file.
<button type="button" (click)="showhideUtility()">
{{buttonTitle}}
</button>
Here showhideUtility() is a method and buttonTitle is a variable that we need to define in our app.component.ts file.
app.component.ts
import { Component } from '@angular/core';@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']}) export class AppComponent { title = 'myProject'; buttonTitle:string = "Hide"; showhideUtility(){ }}
Our child component is still blank so lets add some content. Go to comp1.component.html and add the following code:
comp1.component.html
<div> This is the Child Component</div>
And add some css in comp1.component.css in order to get a nice view:
div{
height:200px;
width: 200px;
border: 2px lightblue solid;
border-radius: 10px;
background-color: lightgreen;
}
Now coming back to app.component.ts, add a new property ‘visible’ that will be a boolean variable to define the show/hide state. When user triggers the show hide method, it should flip the value of the ‘visible’ variable. So finally our app.component.ts will look like this:
app.component.ts
import { Component } from '@angular/core';@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { title = 'myProject'; buttonTitle:string = "Hide"; visible:boolean = true; showhideUtility(){ this.visible = this.visible?false:true; this.buttonTitle = this.visible?"Hide":"Show"; }}
Add a ngIf directive to comp1 to show or hide the component. So finally app.component.html looks like this:
app.component.html
<app-comp1 *ngIf="visible"></app-comp1> <button type="button" (click)="showhideutility()">{{buttonTitle}}</button>
Now save all the files and run the project using :
ng serve -o
The project will run on http://localhost:4200 by default. You will the output like this:
When Show button is Clicked
When Hide Button is Clicked
AngularJS-Misc
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Angular PrimeNG Calendar Component
Angular PrimeNG Messages Component
Auth Guards in Angular 9/10/11
Angular PrimeNG Dropdown Component
How to bundle an Angular app for production?
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": 26206,
"s": 26178,
"text": "\n25 Jan, 2021"
},
{
"code": null,
"e": 26249,
"s": 26206,
"text": "Prerequisites: Angular must be installed "
},
{
"code": null,
"e": 26337,
"s": 26249,
"text": "In this article, we will see how we can show or hide the child components in Angular. "
},
{
"code": null,
"e": 26474,
"s": 26337,
"text": "Lets start by creating a new project. Create a new folder and initialize a new angular project. Run the project to verify it is working."
},
{
"code": null,
"e": 26505,
"s": 26474,
"text": "ng new myProject\nng serve -o "
},
{
"code": null,
"e": 26688,
"s": 26505,
"text": "This will create a new project in the current directory. Now we can clear the app.component.html file and create a child component in order to demonstrate how we can show or hide it."
},
{
"code": null,
"e": 26718,
"s": 26688,
"text": "ng generate component comp1 "
},
{
"code": null,
"e": 26803,
"s": 26718,
"text": "Now the setup part is over. Lets add this components in our app.component.html file:"
},
{
"code": null,
"e": 26829,
"s": 26803,
"text": "<app-comp1></app-comp1> "
},
{
"code": null,
"e": 26938,
"s": 26829,
"text": "We will create a button to show and hide the component. Lets add the button code in app.component.html file."
},
{
"code": null,
"e": 27021,
"s": 26938,
"text": "<button type=\"button\" (click)=\"showhideUtility()\">\n {{buttonTitle}}\n</button> "
},
{
"code": null,
"e": 27139,
"s": 27021,
"text": "Here showhideUtility() is a method and buttonTitle is a variable that we need to define in our app.component.ts file."
},
{
"code": null,
"e": 27156,
"s": 27139,
"text": "app.component.ts"
},
{
"code": "import { Component } from '@angular/core';@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']}) export class AppComponent { title = 'myProject'; buttonTitle:string = \"Hide\"; showhideUtility(){ }}",
"e": 27426,
"s": 27156,
"text": null
},
{
"code": null,
"e": 27542,
"s": 27426,
"text": "Our child component is still blank so lets add some content. Go to comp1.component.html and add the following code:"
},
{
"code": null,
"e": 27563,
"s": 27542,
"text": "comp1.component.html"
},
{
"code": "<div> This is the Child Component</div>",
"e": 27605,
"s": 27563,
"text": null
},
{
"code": null,
"e": 27674,
"s": 27605,
"text": "And add some css in comp1.component.css in order to get a nice view:"
},
{
"code": null,
"e": 27789,
"s": 27674,
"text": "div{\nheight:200px;\nwidth: 200px;\nborder: 2px lightblue solid;\nborder-radius: 10px;\nbackground-color: lightgreen;\n}"
},
{
"code": null,
"e": 28064,
"s": 27789,
"text": "Now coming back to app.component.ts, add a new property ‘visible’ that will be a boolean variable to define the show/hide state. When user triggers the show hide method, it should flip the value of the ‘visible’ variable. So finally our app.component.ts will look like this:"
},
{
"code": null,
"e": 28081,
"s": 28064,
"text": "app.component.ts"
},
{
"code": "import { Component } from '@angular/core';@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { title = 'myProject'; buttonTitle:string = \"Hide\"; visible:boolean = true; showhideUtility(){ this.visible = this.visible?false:true; this.buttonTitle = this.visible?\"Hide\":\"Show\"; }}",
"e": 28446,
"s": 28081,
"text": null
},
{
"code": null,
"e": 28554,
"s": 28446,
"text": "Add a ngIf directive to comp1 to show or hide the component. So finally app.component.html looks like this:"
},
{
"code": null,
"e": 28573,
"s": 28554,
"text": "app.component.html"
},
{
"code": "<app-comp1 *ngIf=\"visible\"></app-comp1> <button type=\"button\" (click)=\"showhideutility()\">{{buttonTitle}}</button>",
"e": 28693,
"s": 28573,
"text": null
},
{
"code": null,
"e": 28744,
"s": 28693,
"text": "Now save all the files and run the project using :"
},
{
"code": null,
"e": 28758,
"s": 28744,
"text": "ng serve -o "
},
{
"code": null,
"e": 28849,
"s": 28758,
"text": "The project will run on http://localhost:4200 by default. You will the output like this: "
},
{
"code": null,
"e": 28877,
"s": 28849,
"text": "When Show button is Clicked"
},
{
"code": null,
"e": 28905,
"s": 28877,
"text": "When Hide Button is Clicked"
},
{
"code": null,
"e": 28920,
"s": 28905,
"text": "AngularJS-Misc"
},
{
"code": null,
"e": 28930,
"s": 28920,
"text": "AngularJS"
},
{
"code": null,
"e": 28947,
"s": 28930,
"text": "Web Technologies"
},
{
"code": null,
"e": 29045,
"s": 28947,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29080,
"s": 29045,
"text": "Angular PrimeNG Calendar Component"
},
{
"code": null,
"e": 29115,
"s": 29080,
"text": "Angular PrimeNG Messages Component"
},
{
"code": null,
"e": 29146,
"s": 29115,
"text": "Auth Guards in Angular 9/10/11"
},
{
"code": null,
"e": 29181,
"s": 29146,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 29226,
"s": 29181,
"text": "How to bundle an Angular app for production?"
},
{
"code": null,
"e": 29266,
"s": 29226,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29299,
"s": 29266,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29344,
"s": 29299,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29387,
"s": 29344,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Java Basic Data Types | Practice | GeeksforGeeks | Read a value and store it in the appropriate Java Data Type.
Example 1:
Input:
18
abc
9.9876
Output:
18
abc
9.9876
Explanation:
The three inputs are stored in approriate
data types and then printed in order.
Your Task:
Your task is to complete each of the given functions
javaIntType() : read an integer input, store it in appropriate data type and return it.
javaStringType() : read a string input, store it in appropriate data type and return it.
javaFloatType() : read a float input, store it in appropriate data type and return it.
Each of the function have an object of Scanner in the parameter to be used to read the input.
Expected Time Complexity: O(1)
Expected Auxiliary Space: O(1)
0
indhu64771 month ago
class Solution {
int javaIntType(Scanner sc) { return sc.nextInt(); } String javaStringType(Scanner sc) { return sc.next(); } float javaFloatType(Scanner sc) { return sc.nextFloat(); }};
+2
imohdalam1 month ago
Java | O(1)
class Solution {
int javaIntType(Scanner sc) {
// code here
int ans = sc.nextInt();
return ans;
}
String javaStringType(Scanner sc) {
// code here
String ans = sc.next();
return ans;
}
float javaFloatType(Scanner sc) {
// code here
float ans = sc.nextFloat();
return ans;
}
};
0
rohitpandey484Premium2 months ago
Java Solution
class Solution {
int javaIntType(Scanner sc) { return sc.nextInt(); } String javaStringType(Scanner sc) { return sc.next(); } float javaFloatType(Scanner sc) { return sc.nextFloat(); }};
0
sachin1947s2 months ago
Class Solution
0
vishwajeetofficial20222 months ago
//JAVA SOLUTION
class Solution {
int javaIntType(Scanner sc) {
// code here
return sc.nextInt();
}
String javaStringType(Scanner sc) {
// code here
return sc.next();
}
float javaFloatType(Scanner sc) {
// code here
return sc.nextFloat();
}
};
0
shaktig1011013 months ago
package abc;
import java.util.Scanner;
class Solution {
int nextIntType(Scanner sc ){
return sc.nextInt ();
}
String nextStringType(Scanner sc){
return sc.next();
}
Float nextFloatType(Scanner sc){
return sc.nextFloatType();
}
}
0
neetathakur88783 months ago
class Solution {
int javaIntType(Scanner sc) { return sc.nextInt(); } String javaStringType(Scanner sc) { return sc.next(); } float javaFloatType(Scanner sc) { return sc.nextFloat(); }};
0
rishitachail1253 months ago
// { Driver Code Startsimport java.io.*;import java.util.*;
class GFG { public static void main(String args[]) throws IOException { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while (t-- > 0) { Solution ob = new Solution(); System.out.println(ob.javaIntType(sc)); System.out.println(ob.javaStringType(sc)); System.out.println(ob.javaFloatType(sc)); } }}// } Driver Code Ends
class Solution {
int javaIntType(Scanner sc) { // code here return sc.nextInt(); } String javaStringType(Scanner sc) { // code here return sc.next(); } float javaFloatType(Scanner sc) { // code here return sc.nextFloat(); }};
0
gauravverma9918187053 months ago
#Code Here#
class Solution {
int nextIntType(Scanner sc ){
return sc.nextInt ();
}
String nextStringType(Scanner sc){
return sc.next();
}
Float nextFloatType(Scanner sc){
return sc.nextFloatType();
}
};
0
pinaksangamnerkar1234 months ago
ArrayList<Integer> list = new ArrayList<Integer>();
int res = 0;
for(Integer i1: A)
res ^= i1;
for(Integer i1: A)
list.add(res ^ i1);
return list;
}
}
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": 288,
"s": 226,
"text": "Read a value and store it in the appropriate Java Data Type. "
},
{
"code": null,
"e": 300,
"s": 288,
"text": "\nExample 1:"
},
{
"code": null,
"e": 445,
"s": 300,
"text": "Input: \n18 \nabc \n9.9876 \nOutput:\n18 \nabc \n9.9876 \nExplanation:\nThe three inputs are stored in approriate \ndata types and then printed in order.\n"
},
{
"code": null,
"e": 874,
"s": 447,
"text": "Your Task:\nYour task is to complete each of the given functions \njavaIntType() : read an integer input, store it in appropriate data type and return it. \njavaStringType() : read a string input, store it in appropriate data type and return it. \njavaFloatType() : read a float input, store it in appropriate data type and return it. \nEach of the function have an object of Scanner in the parameter to be used to read the input."
},
{
"code": null,
"e": 937,
"s": 874,
"text": "\nExpected Time Complexity: O(1)\nExpected Auxiliary Space: O(1)"
},
{
"code": null,
"e": 939,
"s": 937,
"text": "0"
},
{
"code": null,
"e": 960,
"s": 939,
"text": "indhu64771 month ago"
},
{
"code": null,
"e": 977,
"s": 960,
"text": "class Solution {"
},
{
"code": null,
"e": 1192,
"s": 977,
"text": " int javaIntType(Scanner sc) { return sc.nextInt(); } String javaStringType(Scanner sc) { return sc.next(); } float javaFloatType(Scanner sc) { return sc.nextFloat(); }};"
},
{
"code": null,
"e": 1195,
"s": 1192,
"text": "+2"
},
{
"code": null,
"e": 1216,
"s": 1195,
"text": "imohdalam1 month ago"
},
{
"code": null,
"e": 1228,
"s": 1216,
"text": "Java | O(1)"
},
{
"code": null,
"e": 1639,
"s": 1228,
"text": "class Solution {\n\n int javaIntType(Scanner sc) {\n // code here\n int ans = sc.nextInt();\n \n return ans;\n }\n \n String javaStringType(Scanner sc) {\n // code here\n String ans = sc.next();\n \n return ans;\n }\n \n float javaFloatType(Scanner sc) {\n // code here\n float ans = sc.nextFloat();\n \n return ans;\n }\n};"
},
{
"code": null,
"e": 1641,
"s": 1639,
"text": "0"
},
{
"code": null,
"e": 1675,
"s": 1641,
"text": "rohitpandey484Premium2 months ago"
},
{
"code": null,
"e": 1690,
"s": 1675,
"text": "Java Solution "
},
{
"code": null,
"e": 1707,
"s": 1690,
"text": "class Solution {"
},
{
"code": null,
"e": 1914,
"s": 1707,
"text": " int javaIntType(Scanner sc) { return sc.nextInt(); } String javaStringType(Scanner sc) { return sc.next(); } float javaFloatType(Scanner sc) { return sc.nextFloat(); }};"
},
{
"code": null,
"e": 1916,
"s": 1914,
"text": "0"
},
{
"code": null,
"e": 1940,
"s": 1916,
"text": "sachin1947s2 months ago"
},
{
"code": null,
"e": 1956,
"s": 1940,
"text": "Class Solution"
},
{
"code": null,
"e": 1960,
"s": 1958,
"text": "0"
},
{
"code": null,
"e": 1995,
"s": 1960,
"text": "vishwajeetofficial20222 months ago"
},
{
"code": null,
"e": 2329,
"s": 1995,
"text": "//JAVA SOLUTION\n\nclass Solution {\n\n int javaIntType(Scanner sc) {\n // code here\n return sc.nextInt();\n }\n \n String javaStringType(Scanner sc) {\n // code here\n return sc.next();\n }\n \n float javaFloatType(Scanner sc) {\n // code here\n return sc.nextFloat();\n }\n};"
},
{
"code": null,
"e": 2331,
"s": 2329,
"text": "0"
},
{
"code": null,
"e": 2357,
"s": 2331,
"text": "shaktig1011013 months ago"
},
{
"code": null,
"e": 2590,
"s": 2357,
"text": "package abc;\nimport java.util.Scanner;\nclass Solution {\n\nint nextIntType(Scanner sc ){\nreturn sc.nextInt ();\n}\n\nString nextStringType(Scanner sc){\nreturn sc.next();\n}\n\nFloat nextFloatType(Scanner sc){\nreturn sc.nextFloatType();\n}\n\n}"
},
{
"code": null,
"e": 2592,
"s": 2590,
"text": "0"
},
{
"code": null,
"e": 2620,
"s": 2592,
"text": "neetathakur88783 months ago"
},
{
"code": null,
"e": 2637,
"s": 2620,
"text": "class Solution {"
},
{
"code": null,
"e": 2844,
"s": 2637,
"text": " int javaIntType(Scanner sc) { return sc.nextInt(); } String javaStringType(Scanner sc) { return sc.next(); } float javaFloatType(Scanner sc) { return sc.nextFloat(); }};"
},
{
"code": null,
"e": 2846,
"s": 2844,
"text": "0"
},
{
"code": null,
"e": 2874,
"s": 2846,
"text": "rishitachail1253 months ago"
},
{
"code": null,
"e": 2934,
"s": 2874,
"text": "// { Driver Code Startsimport java.io.*;import java.util.*;"
},
{
"code": null,
"e": 3339,
"s": 2934,
"text": "class GFG { public static void main(String args[]) throws IOException { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while (t-- > 0) { Solution ob = new Solution(); System.out.println(ob.javaIntType(sc)); System.out.println(ob.javaStringType(sc)); System.out.println(ob.javaFloatType(sc)); } }}// } Driver Code Ends"
},
{
"code": null,
"e": 3356,
"s": 3339,
"text": "class Solution {"
},
{
"code": null,
"e": 3620,
"s": 3356,
"text": " int javaIntType(Scanner sc) { // code here return sc.nextInt(); } String javaStringType(Scanner sc) { // code here return sc.next(); } float javaFloatType(Scanner sc) { // code here return sc.nextFloat(); }};"
},
{
"code": null,
"e": 3622,
"s": 3620,
"text": "0"
},
{
"code": null,
"e": 3655,
"s": 3622,
"text": "gauravverma9918187053 months ago"
},
{
"code": null,
"e": 3863,
"s": 3655,
"text": "#Code Here#\nclass Solution {\n\nint nextIntType(Scanner sc ){\nreturn sc.nextInt ();\n}\n\nString nextStringType(Scanner sc){\nreturn sc.next();\n}\n\nFloat nextFloatType(Scanner sc){\nreturn sc.nextFloatType();\n}\n\n};\n"
},
{
"code": null,
"e": 3865,
"s": 3863,
"text": "0"
},
{
"code": null,
"e": 3898,
"s": 3865,
"text": "pinaksangamnerkar1234 months ago"
},
{
"code": null,
"e": 4154,
"s": 3898,
"text": "ArrayList<Integer> list = new ArrayList<Integer>();\n \n int res = 0;\n \n for(Integer i1: A)\n res ^= i1;\n \n for(Integer i1: A)\n list.add(res ^ i1);\n \n \n return list;\n }\n}"
},
{
"code": null,
"e": 4300,
"s": 4154,
"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": 4336,
"s": 4300,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 4346,
"s": 4336,
"text": "\nProblem\n"
},
{
"code": null,
"e": 4356,
"s": 4346,
"text": "\nContest\n"
},
{
"code": null,
"e": 4419,
"s": 4356,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 4567,
"s": 4419,
"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": 4775,
"s": 4567,
"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": 4881,
"s": 4775,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Factorial of Large numbers using Logarithmic identity - GeeksforGeeks | 01 Jun, 2020
Given a very large number N, the task is to find the factorial of the number using Log.
Factorial of a non-negative integer is the multiplication of all integers smaller than or equal to N.
We have previously discussed a simple program to find the factorial in this article. Here, we will discuss an efficient way to find the factorial of large numbers.
Examples:
Input: N = 100Output: 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
Input: N = 50Output: 30414093201713378043612608166064768844377641568960512000000000000
Approach: The most common iterative version runs in expected O(N) time. But as numbers become big it will be wrong to assume that multiplication takes constant time. The naive approach takes O(K*M) time for multiplication where K is the length of the multiplier and M is the length of the multiplicand. Therefore, the idea is to use logarithmic properties:
As we know that and
Therefore:
Another property isby substituting the value of ln(N!).
Below is the implementation of the above approach:
C++
// C++ program to compute the// factorial of big numbers #include <bits/stdc++.h>using namespace std; // Maximum number of digits// in output#define MAX 1000 // Function to find the factorial// of large number and return// them in string formatstring factorial(long long n){ if (n > MAX) { cout << " Integer Overflow" << endl; return ""; } long long counter; long double sum = 0; // Base case if (n == 0) return "1"; // Calculate the sum of // logarithmic values for (counter = 1; counter <= n; counter++) { sum = sum + log(counter); } // Number becomes too big to hold in // unsigned long integers. // Hence converted to string // Answer is sometimes under // estimated due to floating point // operations so round() is used string result = to_string(round(exp(sum))); return result;} // Driver codeint main(){ clock_t tStart = clock(); string str; str = factorial(100); cout << "The factorial is: " << str << endl; // Calculates the time taken // by the algorithm to execute cout << "Time taken: " << setprecision(10) << ((double)(clock() - tStart) / CLOCKS_PER_SEC) << " s" << endl;}
The factorial is: 93326215443944231979346762015249956831505959550546075483971433508015162170687116519232751238036777284091181469944786448222582618323317549251483571058789842944.000000Time taken: 0.000114 s
Time Complexity: O(N), where N is the given number.
factorial
large-numbers
Mathematical
Mathematical
factorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Find all factors of a natural number | Set 1
Program to find sum of elements in a given array
The Knight's tour problem | Backtracking-1
Operators in C / C++
Find minimum number of coins that make a given value
Euclidean algorithms (Basic and Extended)
Write a program to calculate pow(x,n)
Write a program to reverse digits of a number
Check if a number is Palindrome
Print all possible combinations of r elements in a given array of size n | [
{
"code": null,
"e": 24177,
"s": 24149,
"text": "\n01 Jun, 2020"
},
{
"code": null,
"e": 24265,
"s": 24177,
"text": "Given a very large number N, the task is to find the factorial of the number using Log."
},
{
"code": null,
"e": 24367,
"s": 24265,
"text": "Factorial of a non-negative integer is the multiplication of all integers smaller than or equal to N."
},
{
"code": null,
"e": 24531,
"s": 24367,
"text": "We have previously discussed a simple program to find the factorial in this article. Here, we will discuss an efficient way to find the factorial of large numbers."
},
{
"code": null,
"e": 24541,
"s": 24531,
"text": "Examples:"
},
{
"code": null,
"e": 24722,
"s": 24541,
"text": "Input: N = 100Output: 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000"
},
{
"code": null,
"e": 24809,
"s": 24722,
"text": "Input: N = 50Output: 30414093201713378043612608166064768844377641568960512000000000000"
},
{
"code": null,
"e": 25166,
"s": 24809,
"text": "Approach: The most common iterative version runs in expected O(N) time. But as numbers become big it will be wrong to assume that multiplication takes constant time. The naive approach takes O(K*M) time for multiplication where K is the length of the multiplier and M is the length of the multiplicand. Therefore, the idea is to use logarithmic properties:"
},
{
"code": null,
"e": 25188,
"s": 25166,
"text": "As we know that and "
},
{
"code": null,
"e": 25199,
"s": 25188,
"text": "Therefore:"
},
{
"code": null,
"e": 25255,
"s": 25199,
"text": "Another property isby substituting the value of ln(N!)."
},
{
"code": null,
"e": 25306,
"s": 25255,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 25310,
"s": 25306,
"text": "C++"
},
{
"code": "// C++ program to compute the// factorial of big numbers #include <bits/stdc++.h>using namespace std; // Maximum number of digits// in output#define MAX 1000 // Function to find the factorial// of large number and return// them in string formatstring factorial(long long n){ if (n > MAX) { cout << \" Integer Overflow\" << endl; return \"\"; } long long counter; long double sum = 0; // Base case if (n == 0) return \"1\"; // Calculate the sum of // logarithmic values for (counter = 1; counter <= n; counter++) { sum = sum + log(counter); } // Number becomes too big to hold in // unsigned long integers. // Hence converted to string // Answer is sometimes under // estimated due to floating point // operations so round() is used string result = to_string(round(exp(sum))); return result;} // Driver codeint main(){ clock_t tStart = clock(); string str; str = factorial(100); cout << \"The factorial is: \" << str << endl; // Calculates the time taken // by the algorithm to execute cout << \"Time taken: \" << setprecision(10) << ((double)(clock() - tStart) / CLOCKS_PER_SEC) << \" s\" << endl;}",
"e": 26581,
"s": 25310,
"text": null
},
{
"code": null,
"e": 26787,
"s": 26581,
"text": "The factorial is: 93326215443944231979346762015249956831505959550546075483971433508015162170687116519232751238036777284091181469944786448222582618323317549251483571058789842944.000000Time taken: 0.000114 s"
},
{
"code": null,
"e": 26839,
"s": 26787,
"text": "Time Complexity: O(N), where N is the given number."
},
{
"code": null,
"e": 26849,
"s": 26839,
"text": "factorial"
},
{
"code": null,
"e": 26863,
"s": 26849,
"text": "large-numbers"
},
{
"code": null,
"e": 26876,
"s": 26863,
"text": "Mathematical"
},
{
"code": null,
"e": 26889,
"s": 26876,
"text": "Mathematical"
},
{
"code": null,
"e": 26899,
"s": 26889,
"text": "factorial"
},
{
"code": null,
"e": 26997,
"s": 26899,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27006,
"s": 26997,
"text": "Comments"
},
{
"code": null,
"e": 27019,
"s": 27006,
"text": "Old Comments"
},
{
"code": null,
"e": 27064,
"s": 27019,
"text": "Find all factors of a natural number | Set 1"
},
{
"code": null,
"e": 27113,
"s": 27064,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 27156,
"s": 27113,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 27177,
"s": 27156,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 27230,
"s": 27177,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 27272,
"s": 27230,
"text": "Euclidean algorithms (Basic and Extended)"
},
{
"code": null,
"e": 27310,
"s": 27272,
"text": "Write a program to calculate pow(x,n)"
},
{
"code": null,
"e": 27356,
"s": 27310,
"text": "Write a program to reverse digits of a number"
},
{
"code": null,
"e": 27388,
"s": 27356,
"text": "Check if a number is Palindrome"
}
] |
10 Python mini-projects that everyone should build (with codes) | by Abhay Parashar | Towards Data Science | Hi there, I am Abhay
We are in 2020. we all know that the industry is growing day by day. if you see from 2013 to 2019 the growth of python in the industry is around 40% and it is said that it will grow up to 20% more in the next few years. the increased rate of python developers is increased by 30% in the past few years.so there is no better time for learning python and to learn python there is no better way than doing projects.
In this blog, we will create 10 python mini-projects.
Dice roll simulatorGuess the number gameRandom password generatorBinary searchSending emails using pythonMedium Article ReaderAlarm clockURL shortenerWeather appKey logger
Dice roll simulator
Guess the number game
Random password generator
Binary search
Sending emails using python
Medium Article Reader
Alarm clock
URL shortener
Weather app
Key logger
The goal is to create a program that will simulate the roll of dice.
Topics: random module, looping, and if-else
Hint: Using a random module generate a random number between the range from 1 to 6 when the user wants.
GIVE A TRY ON YOUR OWN
import random while True: print(''' 1. roll the dice 2. exit ''') user = int(input("what you want to do\n")) if user==1: number = random.randint(1,6) print(number) else: break
The main goal of the project is to create a program that randomly select a number in a range then the user has to guess the number. user has three chances to guess the number if he guess correct then a message print saying “you guess right “otherwise a negative message prints.
Topics: random module, for loop, f strings
GIVE A TRY ON YOUR OWN
import randomnumber = random.randint(1,10)for i in range(0,3): user = int(input("guess the number")) if user == number: print("Hurray!!") print(f"you guessed the number right it's {number}") breakif user != number: print(f"Your guess is incorrect the number is {number}")
To create a program that takes a number and generate a random password length of that number.
Topics: random module, joining strings, taking input
Hint: Create a string with all characters, then take random characters from it and concatenate each char to make a big string.
GIVE A TRY ON YOUR OWN
import randompasslen = int(input("enter the length of password"))s="abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()?"p = "".join(random.sample(s,passlen ))print (p)
The goal of binary search is to search whether a given number is present in the string or not.
Topics: list,sorting,searching
Hint: First Check whether it is present in the middle or not then check for front and rear.
GIVE A TRY ON YOUR OWN
lst = [1,3,2,4,5,6,9,8,7,10]lst.sort()first=0last=len(lst)-1mid = (first+last)//2item = int(input("enter the number to be search"))found = Falsewhile( first<=last and not found): mid = (first + last)//2 if lst[mid] == item : print(f"found at location {mid}") found= True else: if item < lst[mid]: last = mid - 1 else: first = mid + 1 if found == False: print("Number not found")
To create a python script that can send emails
Topics: import packages, SMTP lib, sending a request to the server
GIVE A TRY ON YOUR OWN
import smtplib from email.message import EmailMessageemail = EmailMessage() ## Creating a object for EmailMessageemail['from'] = 'xyz name' ## Person who is sendingemail['to'] = 'xyz id' ## Whom we are sendingemail['subject'] = 'xyz subject' ## Subject of emailemail.set_content("Xyz content of email") ## content of emailwith smtlib.SMTP(host='smtp.gmail.com',port=587)as smtp: ## sending request to server smtp.ehlo() ## server objectsmtp.starttls() ## used to send data between server and clientsmtop.login("email_id","Password") ## login id and password of gmailsmtp.send_message(email) ## Sending emailprint("email send") ## Printing success message
The task is to create a script that can read articles from a link.
Topics: web scraping, text to speech
Hint: Take the URL of the article as input, scrape the text from the link and then pass it to text to speech.
GIVE A TRY ON YOUR OWN
import pyttsx3import requestsfrom bs4 import BeautifulSoupengine = pyttsx3.init('sapi5')voices = engine.getProperty('voices')engine.setProperty('voice', voices[0].id)def speak(audio): engine.say(audio) engine.runAndWait()text = str(input("Paste article\n"))res = requests.get(text)soup = BeautifulSoup(res.text,'html.parser')articles = []for i in range(len(soup.select('.p'))): article = soup.select('.p')[i].getText().strip() articles.append(article)text = " ".join(articles)speak(text)# engine.save_to_file(text, 'test.mp3') ## If you want to save the speech as a audio fileengine.runAndWait()
Our task is to build an alarm clock using python
Topics: DateTime module, play sound library
Create a python script to a short URL using an API.
To run the above code do python filename.py url .
python tinyurl_url_shortener.py https://www.wikipedia.org/
Our task is to create a python script that can give information about weather.
Topics: Web scraping, scraping google
Hint: Use web scraping to scrape weather information straight from google.
Our task is to create a key logger that can store the key presses in a txt file.
Topics: pynput library, interaction with files
Hint: Using pynput read the key presses and then save them onto a txt file.
Thanks, For reading😄
medium.com
Thanks For Reading Till Here, If You Like My Content and Want To Support Me The Best Way is —
Follow Me On Medium.Connect With Me On LinkedIn.Become a Medium Member With The Cost of One Pizza Using My Referral Link. a small part of your membership fee will go to me.Subscribe To My Email List To Never Miss An Article From Me.
Follow Me On Medium.
Connect With Me On LinkedIn.
Become a Medium Member With The Cost of One Pizza Using My Referral Link. a small part of your membership fee will go to me.
Subscribe To My Email List To Never Miss An Article From Me. | [
{
"code": null,
"e": 193,
"s": 172,
"text": "Hi there, I am Abhay"
},
{
"code": null,
"e": 606,
"s": 193,
"text": "We are in 2020. we all know that the industry is growing day by day. if you see from 2013 to 2019 the growth of python in the industry is around 40% and it is said that it will grow up to 20% more in the next few years. the increased rate of python developers is increased by 30% in the past few years.so there is no better time for learning python and to learn python there is no better way than doing projects."
},
{
"code": null,
"e": 660,
"s": 606,
"text": "In this blog, we will create 10 python mini-projects."
},
{
"code": null,
"e": 832,
"s": 660,
"text": "Dice roll simulatorGuess the number gameRandom password generatorBinary searchSending emails using pythonMedium Article ReaderAlarm clockURL shortenerWeather appKey logger"
},
{
"code": null,
"e": 852,
"s": 832,
"text": "Dice roll simulator"
},
{
"code": null,
"e": 874,
"s": 852,
"text": "Guess the number game"
},
{
"code": null,
"e": 900,
"s": 874,
"text": "Random password generator"
},
{
"code": null,
"e": 914,
"s": 900,
"text": "Binary search"
},
{
"code": null,
"e": 942,
"s": 914,
"text": "Sending emails using python"
},
{
"code": null,
"e": 964,
"s": 942,
"text": "Medium Article Reader"
},
{
"code": null,
"e": 976,
"s": 964,
"text": "Alarm clock"
},
{
"code": null,
"e": 990,
"s": 976,
"text": "URL shortener"
},
{
"code": null,
"e": 1002,
"s": 990,
"text": "Weather app"
},
{
"code": null,
"e": 1013,
"s": 1002,
"text": "Key logger"
},
{
"code": null,
"e": 1082,
"s": 1013,
"text": "The goal is to create a program that will simulate the roll of dice."
},
{
"code": null,
"e": 1126,
"s": 1082,
"text": "Topics: random module, looping, and if-else"
},
{
"code": null,
"e": 1230,
"s": 1126,
"text": "Hint: Using a random module generate a random number between the range from 1 to 6 when the user wants."
},
{
"code": null,
"e": 1253,
"s": 1230,
"text": "GIVE A TRY ON YOUR OWN"
},
{
"code": null,
"e": 1528,
"s": 1253,
"text": "import random while True: print(''' 1. roll the dice 2. exit ''') user = int(input(\"what you want to do\\n\")) if user==1: number = random.randint(1,6) print(number) else: break"
},
{
"code": null,
"e": 1806,
"s": 1528,
"text": "The main goal of the project is to create a program that randomly select a number in a range then the user has to guess the number. user has three chances to guess the number if he guess correct then a message print saying “you guess right “otherwise a negative message prints."
},
{
"code": null,
"e": 1849,
"s": 1806,
"text": "Topics: random module, for loop, f strings"
},
{
"code": null,
"e": 1872,
"s": 1849,
"text": "GIVE A TRY ON YOUR OWN"
},
{
"code": null,
"e": 2174,
"s": 1872,
"text": "import randomnumber = random.randint(1,10)for i in range(0,3): user = int(input(\"guess the number\")) if user == number: print(\"Hurray!!\") print(f\"you guessed the number right it's {number}\") breakif user != number: print(f\"Your guess is incorrect the number is {number}\")"
},
{
"code": null,
"e": 2268,
"s": 2174,
"text": "To create a program that takes a number and generate a random password length of that number."
},
{
"code": null,
"e": 2321,
"s": 2268,
"text": "Topics: random module, joining strings, taking input"
},
{
"code": null,
"e": 2448,
"s": 2321,
"text": "Hint: Create a string with all characters, then take random characters from it and concatenate each char to make a big string."
},
{
"code": null,
"e": 2471,
"s": 2448,
"text": "GIVE A TRY ON YOUR OWN"
},
{
"code": null,
"e": 2663,
"s": 2471,
"text": "import randompasslen = int(input(\"enter the length of password\"))s=\"abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()?\"p = \"\".join(random.sample(s,passlen ))print (p)"
},
{
"code": null,
"e": 2758,
"s": 2663,
"text": "The goal of binary search is to search whether a given number is present in the string or not."
},
{
"code": null,
"e": 2789,
"s": 2758,
"text": "Topics: list,sorting,searching"
},
{
"code": null,
"e": 2881,
"s": 2789,
"text": "Hint: First Check whether it is present in the middle or not then check for front and rear."
},
{
"code": null,
"e": 2904,
"s": 2881,
"text": "GIVE A TRY ON YOUR OWN"
},
{
"code": null,
"e": 3350,
"s": 2904,
"text": "lst = [1,3,2,4,5,6,9,8,7,10]lst.sort()first=0last=len(lst)-1mid = (first+last)//2item = int(input(\"enter the number to be search\"))found = Falsewhile( first<=last and not found): mid = (first + last)//2 if lst[mid] == item : print(f\"found at location {mid}\") found= True else: if item < lst[mid]: last = mid - 1 else: first = mid + 1 if found == False: print(\"Number not found\")"
},
{
"code": null,
"e": 3397,
"s": 3350,
"text": "To create a python script that can send emails"
},
{
"code": null,
"e": 3464,
"s": 3397,
"text": "Topics: import packages, SMTP lib, sending a request to the server"
},
{
"code": null,
"e": 3487,
"s": 3464,
"text": "GIVE A TRY ON YOUR OWN"
},
{
"code": null,
"e": 4182,
"s": 3487,
"text": "import smtplib from email.message import EmailMessageemail = EmailMessage() ## Creating a object for EmailMessageemail['from'] = 'xyz name' ## Person who is sendingemail['to'] = 'xyz id' ## Whom we are sendingemail['subject'] = 'xyz subject' ## Subject of emailemail.set_content(\"Xyz content of email\") ## content of emailwith smtlib.SMTP(host='smtp.gmail.com',port=587)as smtp: ## sending request to server smtp.ehlo() ## server objectsmtp.starttls() ## used to send data between server and clientsmtop.login(\"email_id\",\"Password\") ## login id and password of gmailsmtp.send_message(email) ## Sending emailprint(\"email send\") ## Printing success message"
},
{
"code": null,
"e": 4249,
"s": 4182,
"text": "The task is to create a script that can read articles from a link."
},
{
"code": null,
"e": 4286,
"s": 4249,
"text": "Topics: web scraping, text to speech"
},
{
"code": null,
"e": 4396,
"s": 4286,
"text": "Hint: Take the URL of the article as input, scrape the text from the link and then pass it to text to speech."
},
{
"code": null,
"e": 4419,
"s": 4396,
"text": "GIVE A TRY ON YOUR OWN"
},
{
"code": null,
"e": 5023,
"s": 4419,
"text": "import pyttsx3import requestsfrom bs4 import BeautifulSoupengine = pyttsx3.init('sapi5')voices = engine.getProperty('voices')engine.setProperty('voice', voices[0].id)def speak(audio): engine.say(audio) engine.runAndWait()text = str(input(\"Paste article\\n\"))res = requests.get(text)soup = BeautifulSoup(res.text,'html.parser')articles = []for i in range(len(soup.select('.p'))): article = soup.select('.p')[i].getText().strip() articles.append(article)text = \" \".join(articles)speak(text)# engine.save_to_file(text, 'test.mp3') ## If you want to save the speech as a audio fileengine.runAndWait()"
},
{
"code": null,
"e": 5072,
"s": 5023,
"text": "Our task is to build an alarm clock using python"
},
{
"code": null,
"e": 5116,
"s": 5072,
"text": "Topics: DateTime module, play sound library"
},
{
"code": null,
"e": 5168,
"s": 5116,
"text": "Create a python script to a short URL using an API."
},
{
"code": null,
"e": 5218,
"s": 5168,
"text": "To run the above code do python filename.py url ."
},
{
"code": null,
"e": 5277,
"s": 5218,
"text": "python tinyurl_url_shortener.py https://www.wikipedia.org/"
},
{
"code": null,
"e": 5356,
"s": 5277,
"text": "Our task is to create a python script that can give information about weather."
},
{
"code": null,
"e": 5394,
"s": 5356,
"text": "Topics: Web scraping, scraping google"
},
{
"code": null,
"e": 5469,
"s": 5394,
"text": "Hint: Use web scraping to scrape weather information straight from google."
},
{
"code": null,
"e": 5550,
"s": 5469,
"text": "Our task is to create a key logger that can store the key presses in a txt file."
},
{
"code": null,
"e": 5597,
"s": 5550,
"text": "Topics: pynput library, interaction with files"
},
{
"code": null,
"e": 5673,
"s": 5597,
"text": "Hint: Using pynput read the key presses and then save them onto a txt file."
},
{
"code": null,
"e": 5694,
"s": 5673,
"text": "Thanks, For reading😄"
},
{
"code": null,
"e": 5705,
"s": 5694,
"text": "medium.com"
},
{
"code": null,
"e": 5799,
"s": 5705,
"text": "Thanks For Reading Till Here, If You Like My Content and Want To Support Me The Best Way is —"
},
{
"code": null,
"e": 6032,
"s": 5799,
"text": "Follow Me On Medium.Connect With Me On LinkedIn.Become a Medium Member With The Cost of One Pizza Using My Referral Link. a small part of your membership fee will go to me.Subscribe To My Email List To Never Miss An Article From Me."
},
{
"code": null,
"e": 6053,
"s": 6032,
"text": "Follow Me On Medium."
},
{
"code": null,
"e": 6082,
"s": 6053,
"text": "Connect With Me On LinkedIn."
},
{
"code": null,
"e": 6207,
"s": 6082,
"text": "Become a Medium Member With The Cost of One Pizza Using My Referral Link. a small part of your membership fee will go to me."
}
] |
Program for sum of geometric series in C | Given three inputs first one is “a” which is for the first term of geometric series second is “r” which is the common ratio and “n” which are the number of series whose sum we have to find.
Geometric series is a series which have a constant ratio between its successive terms. Using the above stated inputs “a”, “r” and “n” we have to find the geometric series i.e., a, ar, ar2 , ar3 , ar4 , ... and their sum, i.e., a + ar + ar2+ ar3 + ar4 +...
Input
a = 1
r = 0.5
n = 5
Output
1.937500
Input
a = 2
r = 2.0
n = 8
Output
510.000000
Take all the inputs a, r, n.
Take all the inputs a, r, n.
Calculate the sum of geometric series, adding the full series.
Calculate the sum of geometric series, adding the full series.
Start
In function float sumgeometric(float a, float r, int n)
Step 1→Declare and Initialize sum = 0
Step 2→ Loop For i = 0 and i < n and i++
Set sum = sum + a
Set a = a * r
Step 3→ Return sum
In function int main()
Step 1→ Declare and initialize a = 1
Step 2→ Declare and Initialize float r = 0.5
Step 3→ Declare and initialize n = 5
Step 4→ Print sumgeometric(a, r, n)
Stop
Live Demo
#include <stdio.h>
// function to calculate sum of
// geometric series
float sumgeometric(float a, float r, int n){
float sum = 0;
for (int i = 0; i < n; i++){
sum = sum + a;
a = a * r;
}
return sum;
}
int main(){
int a = 1; // first term
float r = 0.5; // their common ratio
int n = 5; // number of terms
printf("%f", sumgeometric(a, r, n));
return 0;
}
If run the above code it will generate the following output −
1.937500 | [
{
"code": null,
"e": 1252,
"s": 1062,
"text": "Given three inputs first one is “a” which is for the first term of geometric series second is “r” which is the common ratio and “n” which are the number of series whose sum we have to find."
},
{
"code": null,
"e": 1508,
"s": 1252,
"text": "Geometric series is a series which have a constant ratio between its successive terms. Using the above stated inputs “a”, “r” and “n” we have to find the geometric series i.e., a, ar, ar2 , ar3 , ar4 , ... and their sum, i.e., a + ar + ar2+ ar3 + ar4 +..."
},
{
"code": null,
"e": 1514,
"s": 1508,
"text": "Input"
},
{
"code": null,
"e": 1534,
"s": 1514,
"text": "a = 1\nr = 0.5\nn = 5"
},
{
"code": null,
"e": 1541,
"s": 1534,
"text": "Output"
},
{
"code": null,
"e": 1550,
"s": 1541,
"text": "1.937500"
},
{
"code": null,
"e": 1556,
"s": 1550,
"text": "Input"
},
{
"code": null,
"e": 1576,
"s": 1556,
"text": "a = 2\nr = 2.0\nn = 8"
},
{
"code": null,
"e": 1583,
"s": 1576,
"text": "Output"
},
{
"code": null,
"e": 1594,
"s": 1583,
"text": "510.000000"
},
{
"code": null,
"e": 1623,
"s": 1594,
"text": "Take all the inputs a, r, n."
},
{
"code": null,
"e": 1652,
"s": 1623,
"text": "Take all the inputs a, r, n."
},
{
"code": null,
"e": 1715,
"s": 1652,
"text": "Calculate the sum of geometric series, adding the full series."
},
{
"code": null,
"e": 1778,
"s": 1715,
"text": "Calculate the sum of geometric series, adding the full series."
},
{
"code": null,
"e": 2186,
"s": 1778,
"text": "Start\nIn function float sumgeometric(float a, float r, int n)\n Step 1→Declare and Initialize sum = 0\n Step 2→ Loop For i = 0 and i < n and i++\n Set sum = sum + a\n Set a = a * r\n Step 3→ Return sum\nIn function int main()\n Step 1→ Declare and initialize a = 1\n Step 2→ Declare and Initialize float r = 0.5\n Step 3→ Declare and initialize n = 5\n Step 4→ Print sumgeometric(a, r, n)\nStop"
},
{
"code": null,
"e": 2197,
"s": 2186,
"text": " Live Demo"
},
{
"code": null,
"e": 2591,
"s": 2197,
"text": "#include <stdio.h>\n// function to calculate sum of\n// geometric series\nfloat sumgeometric(float a, float r, int n){\n float sum = 0;\n for (int i = 0; i < n; i++){\n sum = sum + a;\n a = a * r;\n }\n return sum;\n}\nint main(){\n int a = 1; // first term\n float r = 0.5; // their common ratio\n int n = 5; // number of terms\n printf(\"%f\", sumgeometric(a, r, n));\n return 0;\n}"
},
{
"code": null,
"e": 2653,
"s": 2591,
"text": "If run the above code it will generate the following output −"
},
{
"code": null,
"e": 2662,
"s": 2653,
"text": "1.937500"
}
] |
Clojure - Functions with Multiple Arguments | Clojure functions can be defined with zero or more parameters. The values you pass to functions are called arguments, and the arguments can be of any type. The number of parameters is the function’s arity. This chapter discusses some function definitions with different arities.
In the following example, the function demo is defined with multiple arguments for each function definition.
(defn demo [] (* 2 2))
(defn demo [x] (* 2 x))
(defn demo [x y] (* 2 x y))
In the above example, the first function definition is a 0-arity function, since it has 0 arguements, one-param is 1-arity, and two-params is 2-arity and so on.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2653,
"s": 2374,
"text": "Clojure functions can be defined with zero or more parameters. The values you pass to functions are called arguments, and the arguments can be of any type. The number of parameters is the function’s arity. This chapter discusses some function definitions with different arities."
},
{
"code": null,
"e": 2762,
"s": 2653,
"text": "In the following example, the function demo is defined with multiple arguments for each function definition."
},
{
"code": null,
"e": 2837,
"s": 2762,
"text": "(defn demo [] (* 2 2))\n(defn demo [x] (* 2 x))\n(defn demo [x y] (* 2 x y))"
},
{
"code": null,
"e": 2998,
"s": 2837,
"text": "In the above example, the first function definition is a 0-arity function, since it has 0 arguements, one-param is 1-arity, and two-params is 2-arity and so on."
},
{
"code": null,
"e": 3005,
"s": 2998,
"text": " Print"
},
{
"code": null,
"e": 3016,
"s": 3005,
"text": " Add Notes"
}
] |
Kotlin – Property initialization using "by lazy" vs. "lateinit" | Kotlin library provides two different access modifiers for property declaration.
In this article, we will highlight the difference between these two access
modifiers and how we can use them in our application.
In order to create a "lateInit" variable, we just need to add the keyword "lateInit" as an access modifier of that variable. Following are a set of conditions that need to be followed in order to use "lateInit" in Kotlin.
Use "lateInit" with a mutable variable. That means, we need to use "var" keyword with "lateInit".
Use "lateInit" with a mutable variable. That means, we need to use "var" keyword with "lateInit".
"lateInit" is allowed only with non-NULLable data types.
"lateInit" is allowed only with non-NULLable data types.
"lateInit" does not work with primitive data types.
"lateInit" does not work with primitive data types.
"lateInit" can be used when the variable property does not have any getter and setter methods.
"lateInit" can be used when the variable property does not have any getter and setter methods.
We will be declaring a variable as lateInit and we will see how we can access the same throughout the program.
class Tutorial {
lateinit var name : String
fun checkLateInit(){
// checking whether the value is assigned or not
if(this::name.isInitialized)
println("Your value is not assigned");
else{
// initializing name
name = "www.tutorialspoint.com/"
println(this.name)
// this will return true
}
}
}
fun main() {
var obj=Tutorial();
obj.checkLateInit();
}
Once you execute the code, it will generate the following output −
www.tutorialspoint.com/
For efficient memory management, Kotlin has introduced a new feature called as Lazy initialization. When the lazy keyword is used, the object will be created only when it is called, otherwise there will be no object creation. lazy() is a function that takes a lambda and returns an instance of lazy which can serve as a delegate of lazy properties upon which it has been applied. It has been designed to prevent unnecessary initialization of objects.
Lazy can be used only with non-NULLable variables.
Lazy can be used only with non-NULLable variables.
Variable can only be val. "var" is not allowed .
Variable can only be val. "var" is not allowed .
Object will be initialized only once. Thereafter, you receive the value from the cache memory.
Object will be initialized only once. Thereafter, you receive the value from the cache memory.
The object will not be initialized until it has been used in the application.
The object will not be initialized until it has been used in the application.
In this example, we will declare a lazy variable "myName" and we could see that the call to this parts of the code will happen only once and when the value is initialized, it will remember the value throughout the application. Once the value is assigned using lazy initialization, it cannot be reassigned .
class Demo {
val myName: String by lazy {
println("Welcome to Lazy declaration");
"www.tutorialspoint.com"
}
}
fun main() {
var obj=Demo();
println(obj.myName);
println("Second time call to the same object--"+obj.myName);
}
Once you execute the code, it will generate the following output −
Welcome to Lazy declaration
www.tutorialspoint.com
Second time call to the same object--www.tutorialspoint.com | [
{
"code": null,
"e": 1143,
"s": 1062,
"text": "Kotlin library provides two different access modifiers for property declaration."
},
{
"code": null,
"e": 1272,
"s": 1143,
"text": "In this article, we will highlight the difference between these two access\nmodifiers and how we can use them in our application."
},
{
"code": null,
"e": 1494,
"s": 1272,
"text": "In order to create a \"lateInit\" variable, we just need to add the keyword \"lateInit\" as an access modifier of that variable. Following are a set of conditions that need to be followed in order to use \"lateInit\" in Kotlin."
},
{
"code": null,
"e": 1592,
"s": 1494,
"text": "Use \"lateInit\" with a mutable variable. That means, we need to use \"var\" keyword with \"lateInit\"."
},
{
"code": null,
"e": 1690,
"s": 1592,
"text": "Use \"lateInit\" with a mutable variable. That means, we need to use \"var\" keyword with \"lateInit\"."
},
{
"code": null,
"e": 1747,
"s": 1690,
"text": "\"lateInit\" is allowed only with non-NULLable data types."
},
{
"code": null,
"e": 1804,
"s": 1747,
"text": "\"lateInit\" is allowed only with non-NULLable data types."
},
{
"code": null,
"e": 1856,
"s": 1804,
"text": "\"lateInit\" does not work with primitive data types."
},
{
"code": null,
"e": 1908,
"s": 1856,
"text": "\"lateInit\" does not work with primitive data types."
},
{
"code": null,
"e": 2003,
"s": 1908,
"text": "\"lateInit\" can be used when the variable property does not have any getter and setter methods."
},
{
"code": null,
"e": 2098,
"s": 2003,
"text": "\"lateInit\" can be used when the variable property does not have any getter and setter methods."
},
{
"code": null,
"e": 2209,
"s": 2098,
"text": "We will be declaring a variable as lateInit and we will see how we can access the same throughout the program."
},
{
"code": null,
"e": 2645,
"s": 2209,
"text": "class Tutorial {\n\n lateinit var name : String\n\n fun checkLateInit(){\n // checking whether the value is assigned or not\n if(this::name.isInitialized)\n println(\"Your value is not assigned\");\n\n else{\n // initializing name\n name = \"www.tutorialspoint.com/\"\n println(this.name)\n // this will return true\n }\n }\n}\n\nfun main() {\n var obj=Tutorial();\n obj.checkLateInit();\n}"
},
{
"code": null,
"e": 2712,
"s": 2645,
"text": "Once you execute the code, it will generate the following output −"
},
{
"code": null,
"e": 2736,
"s": 2712,
"text": "www.tutorialspoint.com/"
},
{
"code": null,
"e": 3187,
"s": 2736,
"text": "For efficient memory management, Kotlin has introduced a new feature called as Lazy initialization. When the lazy keyword is used, the object will be created only when it is called, otherwise there will be no object creation. lazy() is a function that takes a lambda and returns an instance of lazy which can serve as a delegate of lazy properties upon which it has been applied. It has been designed to prevent unnecessary initialization of objects."
},
{
"code": null,
"e": 3238,
"s": 3187,
"text": "Lazy can be used only with non-NULLable variables."
},
{
"code": null,
"e": 3289,
"s": 3238,
"text": "Lazy can be used only with non-NULLable variables."
},
{
"code": null,
"e": 3338,
"s": 3289,
"text": "Variable can only be val. \"var\" is not allowed ."
},
{
"code": null,
"e": 3387,
"s": 3338,
"text": "Variable can only be val. \"var\" is not allowed ."
},
{
"code": null,
"e": 3482,
"s": 3387,
"text": "Object will be initialized only once. Thereafter, you receive the value from the cache memory."
},
{
"code": null,
"e": 3577,
"s": 3482,
"text": "Object will be initialized only once. Thereafter, you receive the value from the cache memory."
},
{
"code": null,
"e": 3655,
"s": 3577,
"text": "The object will not be initialized until it has been used in the application."
},
{
"code": null,
"e": 3733,
"s": 3655,
"text": "The object will not be initialized until it has been used in the application."
},
{
"code": null,
"e": 4040,
"s": 3733,
"text": "In this example, we will declare a lazy variable \"myName\" and we could see that the call to this parts of the code will happen only once and when the value is initialized, it will remember the value throughout the application. Once the value is assigned using lazy initialization, it cannot be reassigned ."
},
{
"code": null,
"e": 4292,
"s": 4040,
"text": "class Demo {\n val myName: String by lazy {\n println(\"Welcome to Lazy declaration\");\n \"www.tutorialspoint.com\"\n }\n}\n\nfun main() {\n var obj=Demo();\n println(obj.myName);\n println(\"Second time call to the same object--\"+obj.myName);\n}"
},
{
"code": null,
"e": 4359,
"s": 4292,
"text": "Once you execute the code, it will generate the following output −"
},
{
"code": null,
"e": 4470,
"s": 4359,
"text": "Welcome to Lazy declaration\nwww.tutorialspoint.com\nSecond time call to the same object--www.tutorialspoint.com"
}
] |
Arduino - If statement | It takes an expression in parenthesis and a statement or block of statements. If the expression is true then the statement or block of statements gets executed otherwise these statements are skipped.
Form 1
if (expression)
statement;
You can use the if statement without braces { } if you have one statement.
Form 2
if (expression) {
Block of statements;
}
/* Global variable definition */
int A = 5 ;
int B = 9 ;
Void setup () {
}
Void loop () {
/* check the boolean condition */
if (A > B) /* if condition is true then execute the following statement*/
A++;
/* check the boolean condition */
If ( ( A < B ) && ( B != 0 )) /* if condition is true then execute the following statement*/ {
A += B;
B--;
}
}
65 Lectures
6.5 hours
Amit Rana
43 Lectures
3 hours
Amit Rana
20 Lectures
2 hours
Ashraf Said
19 Lectures
1.5 hours
Ashraf Said
11 Lectures
47 mins
Ashraf Said
9 Lectures
41 mins
Ashraf Said
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 3070,
"s": 2870,
"text": "It takes an expression in parenthesis and a statement or block of statements. If the expression is true then the statement or block of statements gets executed otherwise these statements are skipped."
},
{
"code": null,
"e": 3077,
"s": 3070,
"text": "Form 1"
},
{
"code": null,
"e": 3108,
"s": 3077,
"text": "if (expression)\n statement;\n"
},
{
"code": null,
"e": 3183,
"s": 3108,
"text": "You can use the if statement without braces { } if you have one statement."
},
{
"code": null,
"e": 3190,
"s": 3183,
"text": "Form 2"
},
{
"code": null,
"e": 3235,
"s": 3190,
"text": "if (expression) {\n Block of statements;\n}\n"
},
{
"code": null,
"e": 3618,
"s": 3235,
"text": "/* Global variable definition */\nint A = 5 ;\nint B = 9 ;\n\nVoid setup () {\n\n}\n\nVoid loop () {\n /* check the boolean condition */\n if (A > B) /* if condition is true then execute the following statement*/\n A++;\n /* check the boolean condition */\n If ( ( A < B ) && ( B != 0 )) /* if condition is true then execute the following statement*/ { \n A += B;\n B--;\n }\n}"
},
{
"code": null,
"e": 3653,
"s": 3618,
"text": "\n 65 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 3664,
"s": 3653,
"text": " Amit Rana"
},
{
"code": null,
"e": 3697,
"s": 3664,
"text": "\n 43 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 3708,
"s": 3697,
"text": " Amit Rana"
},
{
"code": null,
"e": 3741,
"s": 3708,
"text": "\n 20 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3754,
"s": 3741,
"text": " Ashraf Said"
},
{
"code": null,
"e": 3789,
"s": 3754,
"text": "\n 19 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3802,
"s": 3789,
"text": " Ashraf Said"
},
{
"code": null,
"e": 3834,
"s": 3802,
"text": "\n 11 Lectures \n 47 mins\n"
},
{
"code": null,
"e": 3847,
"s": 3834,
"text": " Ashraf Said"
},
{
"code": null,
"e": 3878,
"s": 3847,
"text": "\n 9 Lectures \n 41 mins\n"
},
{
"code": null,
"e": 3891,
"s": 3878,
"text": " Ashraf Said"
},
{
"code": null,
"e": 3898,
"s": 3891,
"text": " Print"
},
{
"code": null,
"e": 3909,
"s": 3898,
"text": " Add Notes"
}
] |
MySQL Tryit Editor v1.0 | SELECT CONCAT("SQL ", "Tutorial ", "is ", "fun!") AS ConcatenatedString;
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, and Opera.
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data. | [
{
"code": null,
"e": 73,
"s": 0,
"text": "SELECT CONCAT(\"SQL \", \"Tutorial \", \"is \", \"fun!\") AS ConcatenatedString;"
},
{
"code": null,
"e": 75,
"s": 73,
"text": ""
},
{
"code": null,
"e": 147,
"s": 84,
"text": "Edit the SQL Statement, and click \"Run SQL\" to see the result."
},
{
"code": null,
"e": 207,
"s": 147,
"text": "This SQL-Statement is not supported in the WebSQL Database."
},
{
"code": null,
"e": 275,
"s": 207,
"text": "The example still works, because it uses a modified version of SQL."
},
{
"code": null,
"e": 313,
"s": 275,
"text": "Your browser does not support WebSQL."
},
{
"code": null,
"e": 398,
"s": 313,
"text": "Your are now using a light-version of the Try-SQL Editor, with a read-only Database."
},
{
"code": null,
"e": 572,
"s": 398,
"text": "If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time."
},
{
"code": null,
"e": 623,
"s": 572,
"text": "Our Try-SQL Editor uses WebSQL to demonstrate SQL."
},
{
"code": null,
"e": 691,
"s": 623,
"text": "A Database-object is created in your browser, for testing purposes."
},
{
"code": null,
"e": 862,
"s": 691,
"text": "You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the \"Restore Database\" button."
},
{
"code": null,
"e": 962,
"s": 862,
"text": "WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object."
},
{
"code": null,
"e": 1012,
"s": 962,
"text": "WebSQL is supported in Chrome, Safari, and Opera."
}
] |
Software Testing Tools - GeeksforGeeks | 30 Jan, 2020
Software Testing tools are the tools which are used for the testing of software. Software testing tools are often used to assure firmness, thoroughness and performance in testing software products. Unit testing and subsequent integration testing can be performed by software testing tools. These tools are used to fulfill all the requirements of planned testing activities. These tools also works as commercial software testing tools. The quality of the software is evaluated by software testers with the help of various testing tools.
Types of Testing Tools:As software testing is of two types, static testing and dynamic testing. Also the tools used during these testing are named accordingly on these testings. Testing tools can be categorized into two types which are as follows:
1. Static Test Tools
2. Dynamic Test Tools
These are explained in detail as following below:
1. Static Test Tools:Static test tools are used to work on the static testing processes. In the testing through these tools, typical approach is taken. These tools do not test the real execution of the software. Certain input and output are not required in these tools. Static test tools consists of the following:
Flow analyzers:Flow analyzers provides flexibility in data flow from input to output.
Path Tests:It finds the not used code and code with inconsistency in the software.
Coverage Analyzers:All rationale paths in the software are assured by the coverage analyzers.
Interface Analyzers:They check out the consequences of passing variables and data in the modules.
2. Dynamic Test Tools:Dynamic testing process is performed by the dynamic test tools. These tools test the software with existing or current data. Dynamic test tools comprises of the following:
Test driver:Test driver provides the input data to a module-under-test (MUT).
Test Beds:It displays source code along with the program under execution at the same time.
Emulators:Emulators provides the response facilities which are used to imitate parts of the system not yet developed.
Mutation Analyzers:They are used for testing fault tolerance of the system by knowingly providing the errors in the code of the software.
Software Testing
Software Engineering
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
DFD for Library Management System
What is DFD(Data Flow Diagram)?
Software Engineering | Black box testing
Software Engineering | Software Design Process
System Testing
RUP and its Phases
Software Engineering | Seven Principles of software testing
Software Development Life Cycle (SDLC)
Software Engineering | Incremental process model
Software Engineering | Rapid application development model (RAD) | [
{
"code": null,
"e": 24948,
"s": 24920,
"text": "\n30 Jan, 2020"
},
{
"code": null,
"e": 25484,
"s": 24948,
"text": "Software Testing tools are the tools which are used for the testing of software. Software testing tools are often used to assure firmness, thoroughness and performance in testing software products. Unit testing and subsequent integration testing can be performed by software testing tools. These tools are used to fulfill all the requirements of planned testing activities. These tools also works as commercial software testing tools. The quality of the software is evaluated by software testers with the help of various testing tools."
},
{
"code": null,
"e": 25732,
"s": 25484,
"text": "Types of Testing Tools:As software testing is of two types, static testing and dynamic testing. Also the tools used during these testing are named accordingly on these testings. Testing tools can be categorized into two types which are as follows:"
},
{
"code": null,
"e": 25775,
"s": 25732,
"text": "1. Static Test Tools\n2. Dynamic Test Tools"
},
{
"code": null,
"e": 25825,
"s": 25775,
"text": "These are explained in detail as following below:"
},
{
"code": null,
"e": 26140,
"s": 25825,
"text": "1. Static Test Tools:Static test tools are used to work on the static testing processes. In the testing through these tools, typical approach is taken. These tools do not test the real execution of the software. Certain input and output are not required in these tools. Static test tools consists of the following:"
},
{
"code": null,
"e": 26226,
"s": 26140,
"text": "Flow analyzers:Flow analyzers provides flexibility in data flow from input to output."
},
{
"code": null,
"e": 26309,
"s": 26226,
"text": "Path Tests:It finds the not used code and code with inconsistency in the software."
},
{
"code": null,
"e": 26403,
"s": 26309,
"text": "Coverage Analyzers:All rationale paths in the software are assured by the coverage analyzers."
},
{
"code": null,
"e": 26501,
"s": 26403,
"text": "Interface Analyzers:They check out the consequences of passing variables and data in the modules."
},
{
"code": null,
"e": 26695,
"s": 26501,
"text": "2. Dynamic Test Tools:Dynamic testing process is performed by the dynamic test tools. These tools test the software with existing or current data. Dynamic test tools comprises of the following:"
},
{
"code": null,
"e": 26773,
"s": 26695,
"text": "Test driver:Test driver provides the input data to a module-under-test (MUT)."
},
{
"code": null,
"e": 26864,
"s": 26773,
"text": "Test Beds:It displays source code along with the program under execution at the same time."
},
{
"code": null,
"e": 26982,
"s": 26864,
"text": "Emulators:Emulators provides the response facilities which are used to imitate parts of the system not yet developed."
},
{
"code": null,
"e": 27120,
"s": 26982,
"text": "Mutation Analyzers:They are used for testing fault tolerance of the system by knowingly providing the errors in the code of the software."
},
{
"code": null,
"e": 27137,
"s": 27120,
"text": "Software Testing"
},
{
"code": null,
"e": 27158,
"s": 27137,
"text": "Software Engineering"
},
{
"code": null,
"e": 27256,
"s": 27158,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27265,
"s": 27256,
"text": "Comments"
},
{
"code": null,
"e": 27278,
"s": 27265,
"text": "Old Comments"
},
{
"code": null,
"e": 27312,
"s": 27278,
"text": "DFD for Library Management System"
},
{
"code": null,
"e": 27344,
"s": 27312,
"text": "What is DFD(Data Flow Diagram)?"
},
{
"code": null,
"e": 27385,
"s": 27344,
"text": "Software Engineering | Black box testing"
},
{
"code": null,
"e": 27432,
"s": 27385,
"text": "Software Engineering | Software Design Process"
},
{
"code": null,
"e": 27447,
"s": 27432,
"text": "System Testing"
},
{
"code": null,
"e": 27466,
"s": 27447,
"text": "RUP and its Phases"
},
{
"code": null,
"e": 27526,
"s": 27466,
"text": "Software Engineering | Seven Principles of software testing"
},
{
"code": null,
"e": 27565,
"s": 27526,
"text": "Software Development Life Cycle (SDLC)"
},
{
"code": null,
"e": 27614,
"s": 27565,
"text": "Software Engineering | Incremental process model"
}
] |
Multi-Line Statements in Python | Statements in Python typically end with a new line. Python does, however, allow the use of the line continuation character (\) to denote that the line should continue. For example −
total = item_one + \
item_two + \
item_three
Statements contained within the [], {}, or () brackets do not need to use the line continuation character. For example −
days = ['Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday'] | [
{
"code": null,
"e": 1244,
"s": 1062,
"text": "Statements in Python typically end with a new line. Python does, however, allow the use of the line continuation character (\\) to denote that the line should continue. For example −"
},
{
"code": null,
"e": 1305,
"s": 1244,
"text": "total = item_one + \\\n item_two + \\\n item_three"
},
{
"code": null,
"e": 1426,
"s": 1305,
"text": "Statements contained within the [], {}, or () brackets do not need to use the line continuation character. For example −"
},
{
"code": null,
"e": 1497,
"s": 1426,
"text": "days = ['Monday', 'Tuesday', 'Wednesday',\n 'Thursday', 'Friday']"
}
] |
Maximum Collatz sequence length | Practice | GeeksforGeeks | Starting with any positive integer N, we define the Collatz sequence corresponding to N as the numbers formed by the following operations:
If N is even, N→ N/2
if N is odd, N→ 3N+ 1
It is conjectured but not yet proven that no matter which positive integer we start with; we always end up with 1.
For example, 10 → 5 → 16 → 8 → 4 → 2 → 1. You have to give the maximum collatz sequence length among all the numbers from 1 to N(both included).
Example 1:
Input: N = 1
Output: 1
Explaination: Here N can have only one
value 1.
Example 2:
Input: N = 3
Output: 8
Explaination: For N= 3 we need to check
sequence length when sequence starts with
1, 2, and 3.
when sequence starts with 1, it's : 1
length = 1
when sequence starts with 2, it's : 2->1,
length = 2
when sequence starts with 3, it's :
3->10->5->16->8->4->2->1, length = 8.
Your Task:
You do not need to read input or print anything. Your task is to complete the function collatzLength()which takes N as input parameter and returns the maximum collatz sequence length.
Expected Time Complexity:O(N)
Expected Auxiliary Space: O(N)
Constraints:
1 < N < 106
0
hazemk5375 months ago
it is brute force or dp
0
hazemk537
This comment was deleted.
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": 675,
"s": 226,
"text": "Starting with any positive integer N, we define the Collatz sequence corresponding to N as the numbers formed by the following operations:\nIf N is even, N→ N/2\nif N is odd, N→ 3N+ 1\nIt is conjectured but not yet proven that no matter which positive integer we start with; we always end up with 1.\nFor example, 10 → 5 → 16 → 8 → 4 → 2 → 1. You have to give the maximum collatz sequence length among all the numbers from 1 to N(both included)."
},
{
"code": null,
"e": 687,
"s": 675,
"text": "\nExample 1:"
},
{
"code": null,
"e": 759,
"s": 687,
"text": "Input: N = 1\nOutput: 1\nExplaination: Here N can have only one \nvalue 1."
},
{
"code": null,
"e": 771,
"s": 759,
"text": "\nExample 2:"
},
{
"code": null,
"e": 1071,
"s": 771,
"text": "Input: N = 3\nOutput: 8\nExplaination: For N= 3 we need to check \nsequence length when sequence starts with \n1, 2, and 3.\nwhen sequence starts with 1, it's : 1 \nlength = 1\nwhen sequence starts with 2, it's : 2->1, \nlength = 2\nwhen sequence starts with 3, it's : \n3->10->5->16->8->4->2->1, length = 8.\n"
},
{
"code": null,
"e": 1267,
"s": 1071,
"text": "\nYour Task:\nYou do not need to read input or print anything. Your task is to complete the function collatzLength()which takes N as input parameter and returns the maximum collatz sequence length."
},
{
"code": null,
"e": 1329,
"s": 1267,
"text": "\nExpected Time Complexity:O(N)\nExpected Auxiliary Space: O(N)"
},
{
"code": null,
"e": 1355,
"s": 1329,
"text": "\nConstraints:\n1 < N < 106"
},
{
"code": null,
"e": 1357,
"s": 1355,
"text": "0"
},
{
"code": null,
"e": 1379,
"s": 1357,
"text": "hazemk5375 months ago"
},
{
"code": null,
"e": 1403,
"s": 1379,
"text": "it is brute force or dp"
},
{
"code": null,
"e": 1405,
"s": 1403,
"text": "0"
},
{
"code": null,
"e": 1415,
"s": 1405,
"text": "hazemk537"
},
{
"code": null,
"e": 1441,
"s": 1415,
"text": "This comment was deleted."
},
{
"code": null,
"e": 1587,
"s": 1441,
"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": 1623,
"s": 1587,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 1633,
"s": 1623,
"text": "\nProblem\n"
},
{
"code": null,
"e": 1643,
"s": 1633,
"text": "\nContest\n"
},
{
"code": null,
"e": 1706,
"s": 1643,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 1854,
"s": 1706,
"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": 2062,
"s": 1854,
"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": 2168,
"s": 2062,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
SAP Ariba - Quick Guide | SAP Ariba is a cloud-based innovative solution that allows suppliers and buyers to connect and do business on a single platform. It improves over all vendor management system of an organization by providing less costly ways of procurement and making business simple. Ariba acts as supply chain, procurement service to do business globally. SAP Ariba digitally transforms your supply chain, procurement and contract management process.
In today’s world, there is a need to control your supply chain and to collaborate with your suppliers in an efficient way. To enable healthy supply chain, you need to have suppliers with visibility to every part of procurement process so that they can maintain an efficient supply chain and help organizations to grow their and own business.
The cloud based innovative solution was first developed in 1996 by a company named Ariba and was later acquired by SAP in 2012 with a total acquisition cost of 4.3 billion USD with each share cost $45. Thus, the name SAP Ariba. At the onset, Ariba was a B2B company to do procurement over Internet and was the first one to introduce IPO in 1999.
In this section, we will learn about the key features of SAP Ariba.
SAP Ariba is a B2B solution that allows you to connect to the world’s largest network of vendors and suppliers and enhance business collaboration with the right business partners.
SAP Ariba is a B2B solution that allows you to connect to the world’s largest network of vendors and suppliers and enhance business collaboration with the right business partners.
SAP Ariba allows organizations to connect with the right suppliers with deep visibility to your inside vendor and procurement management processes giving way to error free business transactions.
SAP Ariba allows organizations to connect with the right suppliers with deep visibility to your inside vendor and procurement management processes giving way to error free business transactions.
With SAP Ariba, you can directly connect Ariba network with millions of suppliers meeting your business needs and managing supply chain.
With SAP Ariba, you can directly connect Ariba network with millions of suppliers meeting your business needs and managing supply chain.
SAP Ariba network removes overall complexity in procurement process and suppliers and buyers can manage all key terms of vendor management on a single network.
SAP Ariba network removes overall complexity in procurement process and suppliers and buyers can manage all key terms of vendor management on a single network.
With acquisition of SAP, Ariba can easily integrate with different SAP ERP solutions like SAP ECC and S/4 HANA with easy to configure workflows to automate different processes in complete procurement cycle.
With acquisition of SAP, Ariba can easily integrate with different SAP ERP solutions like SAP ECC and S/4 HANA with easy to configure workflows to automate different processes in complete procurement cycle.
You can easily integrate master and transactional data from different ERP solution to Ariba processes.
You can easily integrate master and transactional data from different ERP solution to Ariba processes.
SAP Ariba is a cloud-based Procurement solution, which help buyers and suppliers to meet at one single network. SAP Ariba Partner program enables you with tools, resources, and benefits to help build, run, and grow your business.
Following are the key benefits of using SAP Ariba −
One of the key advantages of using Ariba solution is that it simplifies procurement and sourcing process with easy synchronization to SAP SRM and other ERP software.
One of the key advantages of using Ariba solution is that it simplifies procurement and sourcing process with easy synchronization to SAP SRM and other ERP software.
It enhances supplier, buyers and user experience by bringing in a digital transformation to the supply chain process.
It enhances supplier, buyers and user experience by bringing in a digital transformation to the supply chain process.
With cloud-based solution, SAP Ariba can be accessed from different locations. It requires very low initial capital cost for setting up the solution.
With cloud-based solution, SAP Ariba can be accessed from different locations. It requires very low initial capital cost for setting up the solution.
With SAP Ariba, there is an easy setup of key procurement processes - Procure to pay (integration of purchase department with Accounts payable department), Procure to Order by maintaining shopping carts.
With SAP Ariba, there is an easy setup of key procurement processes - Procure to pay (integration of purchase department with Accounts payable department), Procure to Order by maintaining shopping carts.
There is easy transfer of master data. Organization structure, suppliers and GL data can be easily transferred to Ariba solution using optimal way of integration.
There is easy transfer of master data. Organization structure, suppliers and GL data can be easily transferred to Ariba solution using optimal way of integration.
SAP Ariba enables easy transfer of transactional data. Invoice details, goods receipt, PO details can be easily transferred to Ariba solution with optimum integration.
SAP Ariba enables easy transfer of transactional data. Invoice details, goods receipt, PO details can be easily transferred to Ariba solution with optimum integration.
We can use integration toolkit to connect ERP system with Ariba solution.
We can use integration toolkit to connect ERP system with Ariba solution.
The following illustration shows Ariba as the world's largest B2B trading platform
In SAP Ariba, you can access and configure new accounts, set email notifications, electronic order and invoice routing and other account related configuration for new suppliers.
Go to https://supplier.ariba.com.
Go to https://supplier.ariba.com.
To login to your account, enter username and password.
To login to your account, enter username and password.
To configure account access and configuration, you need to navigate to Company Settings tab.
To configure account access and configuration, you need to navigate to Company Settings tab.
Navigate to Company Profile tab to update company profile information.
Navigate to Company Profile tab to update company profile information.
From the company profile menu, you can update the below information −
Basic company profile
Business Details
Marketing
Company Contacts
Certification details
Additional documents
SAP Ariba allows you to set notifications and access network notification. You can choose on the email notifications you want to receive and you can also enter the email address where you want these notifications to be sent.
To set notifications,go to Notification tab → Network
You can enter three email addresses for each notification and these should be separated with a comma. As mentioned, preferred language configured by Administrator controls the language used in sending notifications.
You can manage electronic order routing by using Network Settings option →Electronic Order Routing. You can select from the following methods to transact business with your customers −
Email
Online
cXML
EDI
Fax
Using this option, you can send PO to Ariba inbox without sending extra copies elsewhere.
You have the option to include document in email message by selecting check box; this will further send a complete copy of PO in email.
The ERP system can be configured with Ariba solution and the PO can be sent via EDI.
There are different ways you can also manage electronic invoice routing. To set preferences −
Go to Electronic Invoice Routing
Go to Electronic Invoice Routing
You can select from one of the following routing methods − Online, cXML, and EDI. You can also set email notification for invoice routing.
You can select from one of the following routing methods − Online, cXML, and EDI. You can also set email notification for invoice routing.
With Tax Invoicing option, you can also enter Tax ID, VAT ID and other tax related supporting data.
With Tax Invoicing option, you can also enter Tax ID, VAT ID and other tax related supporting data.
You can use Invoice Archival option to specify frequency of zipped invoice archives. Goto Tax Invoicing and Archiving tab → Invoice Archival → Configure Invoice Archival. You can select from the following frequency −
Twice Daily
Daily
Weekly
Biweekly
Monthly
You can also select the Archive Immediately option to archive invoices in zip format immediately.
In SAP Ariba, administrators and users perform different roles. Administrators of Ariba system perform the following responsibilities −
Account configuration and management – registering new accounts in SAP Ariba network.
Account configuration and management – registering new accounts in SAP Ariba network.
Handle account login issues and act as primary contact for Ariba users.
Handle account login issues and act as primary contact for Ariba users.
Creating new roles in Ariba system.
Creating new roles in Ariba system.
Linked to user name and login entered during registration.
Linked to user name and login entered during registration.
A user has the following primary tasks in Ariba system −
Users can have different roles concerning procurement and supply chain process.
Users can have different roles concerning procurement and supply chain process.
Users can update their profile in Ariba system.
Users can update their profile in Ariba system.
Configuring notifications and workflows based on roles and responsibilities.
Configuring notifications and workflows based on roles and responsibilities.
Administrator’s primary task is to create new users and roles in Ariba system.
To create new user and role, navigate to Account Settings → User tab. This will open Users page.
To create new user and role, navigate to Account Settings → User tab. This will open Users page.
To create new role, under Manage User Roles → Create Role button.
To create new role, under Manage User Roles → Create Role button.
Enter the name of role and description for the role to be created.
Enter the name of role and description for the role to be created.
Now, add permissions to role that is based user job responsibilities.
Now, add permissions to role that is based user job responsibilities.
To save new role, click Save. You can also check detail of an existing role, edit or delete a Role.
To save new role, click Save. You can also check detail of an existing role, edit or delete a Role.
To create new User, click Create User button and mention the details about user including name and contact. Next is to select a role for new user based on roles and click Done.
To create new User, click Create User button and mention the details about user including name and contact. Next is to select a role for new user based on roles and click Done.
Note − It is possible to create 250 users in Ariba network.
You can also manage existing user accounts. Select an existing user under User tab and to make changes, click Edit. To make a user an administrator, click Make Administrator option.
SAP Ariba provides different plans based on the number of transactions allowed under each plan. There are also customized plans based on your business needs.
Following are some common Ariba plans −
Select
Premier
Enterprise
Enterprise Plus Plan Monthly Price Transaction Volume Threshold
You can use SAP Ariba at no cost, if you transact five or less documents − POs, invoices, service entry sheets, etc. or your transaction volume should be less than the below threshold for one customer annually.
The below table shows the number of chargeable transactions for each currency annually −
When you cross the document and transaction threshold limit for one customer as mentioned above annually, suppliers are enrolled to paid subscription and need to pay fee based on the number of transactions listed in the above table.
In this section, we will learn about the various fee types.
This fee is based on the financial volume you transact annually with all customers through Ariba Network.
This fee is based on the number of documents you transact annually with all customers, as well as your technology usage.
In order to help customers with high number of annual transactions, Ariba has set up an annual cap of maximum limit of transaction fees as shown in the table below −
Subscription fee is based on the number of documents you processed annually. The fee also includes technology usage. Ariba offers four paid subscriptions and each subscription is based on the number of documents that can be transacted annually based on currency. There are four subscription plans −
Bronze
Silver
Gold
Platinum
When you cross the document and transaction volume chargeable thresholds, SAP will charge either quarterly or annually based on selection, depending on when you first crossed the thresholds. If you are a new supplier, you will be billed quarterly, and it will be in advance for your next quarterly or annual period on the basis of your Ariba Network usage during your prior billing period.
You can pay your bill by going to − https://service.ariba.com/Supplier.aw
Log in to your account with your ID and password.
Log in to your account with your ID and password.
Find your company name in the top right corner and click on it.
Find your company name in the top right corner and click on it.
Click on Service Subscriptions.
Click on Service Subscriptions.
Click the Billing tab to view your invoice(s).
Click the Billing tab to view your invoice(s).
Find the invoice you want to pay and click Pay Invoice.
Find the invoice you want to pay and click Pay Invoice.
Select your payment method (credit card, check, or electronic settlement) and click Next.
Select your payment method (credit card, check, or electronic settlement) and click Next.
Enter your credit card information, if applicable.
Enter your credit card information, if applicable.
Confirm your subscription package, if applicable.
Confirm your subscription package, if applicable.
If paying by cheque or electronic settlement, download your invoice and submit to your disbursement process for payment.
If paying by cheque or electronic settlement, download your invoice and submit to your disbursement process for payment.
SAP Ariba Network users can make bill payment using a credit card, electronic fund transfer or by using bank cheque. For small amount invoices, you should only pay using a Credit card. The following table shows subscription fee fall below minimum threshold and should be paid by credit card −
For any help, a SAP Ariba Network user can visit the Help Center. After you log into your account, click the link in the upper-right corner of your dashboard.
SAP Business Suite can connect to Ariba network using non-modifying add-ons that come with Ariba Network integration 1.0. Using these add-ons, you can send or receive message in the format supported by SAP Ariba- cXML.
With the use of Ariba add-ons, you can integrate single SAP ERP system or multiple systems with Ariba network. Integration can be performed directly or by using a middleware. One of the common integration options comes with the use of HANA Cloud Integration (HCI). With Ariba Network integration 1.0, following Business suites can be connected to Ariba network −
SAP ERP
SAP ERP
SAP Supplier Relationship Management
SAP Supplier Relationship Management
SAP Supply Network Collaboration SNC
SAP Supply Network Collaboration SNC
Following are the benefits of using Ariba Network Integration 1.0 −
You do not require an additional infrastructure or system to connect with SAP Business Suite.
You do not require an additional infrastructure or system to connect with SAP Business Suite.
Ariba Network Integration supports minimum SAP ERP 6.0.
Ariba Network Integration supports minimum SAP ERP 6.0.
With the use of Ariba add-ons, the network complexity is removed.
With the use of Ariba add-ons, the network complexity is removed.
It does not require any upgrade, update to be performed.
It does not require any upgrade, update to be performed.
Ariba Network integrations should be deployed on every ERP system that you want to integrate.
Ariba Network integrations should be deployed on every ERP system that you want to integrate.
In this section, we will look into the product requirement for integration.
SAP ERP system starting with SAP ERP 6.0.
SAP ERP system starting with SAP ERP 6.0.
Ariba integration scenario with SAP ERP core functionality supported.
Ariba integration scenario with SAP ERP core functionality supported.
Ariba Foundation
Ariba Foundation
Add-on “ARBFNDI1” starting with AS ABAP 7.0000
Add-on “ARBFNDI1” starting with AS ABAP 7.0000
Add-on “ARBFNDI2” starting with AS ABAP 7.01
Add-on “ARBFNDI2” starting with AS ABAP 7.01
Add-on “ARBERPI1” based on add-on “ARBFNDI1”
Add-on “ARBERPI1” based on add-on “ARBFNDI1”
SAP NetWeaver PI (optional) − This is the middleware to connect SAP ERP with Ariba Network.
SAP NetWeaver PI (optional) − This is the middleware to connect SAP ERP with Ariba Network.
Starting with SAP NetWeaver PI 7.1.
Starting with SAP NetWeaver PI 7.1.
Java stack sufficient, therefore SAP NetWeaver PI − JAVA only (AEX) supported.
Java stack sufficient, therefore SAP NetWeaver PI − JAVA only (AEX) supported.
ESR Content with Ariba cXML interfaces.
ESR Content with Ariba cXML interfaces.
Ariba Network Adapter for SAP NetWeaver (starting with Release Cloud Integration 1.0) − released for SAP NetWeaver PI 7.1 up to EHP1 for SAP NetWeaver PI 7.4.
Ariba Network Adapter for SAP NetWeaver (starting with Release Cloud Integration 1.0) − released for SAP NetWeaver PI 7.1 up to EHP1 for SAP NetWeaver PI 7.4.
Ariba integration tool kit is a Java based tool which can be used to upload master data or download transaction data from the SAP ERP system. With Ariba integration tool kit, it reads CSV files, zips the files and sends them as MIME messages to Ariba procurement solution using HTTP. Integration can be done with the following ways −
File based integration
File based integration
Web services based integration
Web services based integration
Direct Connectivity
Direct Connectivity
Using Middleware connectivity
Using Middleware connectivity
You can move master and transactional data from SAP to Ariba system using file-based integration. Master data extracted from SAP in the form of .csv files. These .csv files are transferred to Ariba system using Ariba Tool kit.
The following illustration shows file based integration and master data import to Ariba.
Follow these steps for transfer of transactional data from SAP to Ariba using the file-based integration method −
In the first step, the data transfer tool exports data from Ariba procurement solution in the form of *.csv files.
In the first step, the data transfer tool exports data from Ariba procurement solution in the form of *.csv files.
Ariba provided ABAP program then reads these *.csv files and transfers data to SAP ERP.
Ariba provided ABAP program then reads these *.csv files and transfers data to SAP ERP.
ABAP program then retrieves the status of each export transaction from SAP ERP.
ABAP program then retrieves the status of each export transaction from SAP ERP.
The data transfer tool reads these *.csv files and updates them into Ariba.
The data transfer tool reads these *.csv files and updates them into Ariba.
This is used to perform real time integration of Ariba to SAP ERP using SAP PI and this integration option is available by default. If you use any other middleware like SOA, you will require configuring the setup manually. In Web service-based integration, a SOAP message is generated based on the WSDL and this is dispatched to a web services server using SAP Process Integration PI.
With direct integration, .csv files are moved from SAP ERP to Ariba system. The .CSV files with master data is sent to Ariba system in the form of SOAP message. The direct integration option for master data is available from Ariba cloud integration 4.0 or later and transactional data integration is available from 6.0 or later.
Mediated connectivity integration is available in Ariba Cloud integration 5.0 or later and the movement of transactional data from 6.0 or later. The mediated connectivity integration method can be used with SAP PI to exchange file data or by sending information as SOAP message.
When you use SAP PI for integration, you need to define receiver and sender communication channel. Note that SAP Ariba provides an Ariba Network Adapter for SAP PI/PO integration and is known as add-on module for SAP business applications that allows to send and receive document in cXML format to and from Ariba Network. By following Ariba SN cXML standards, it is also possible to develop own network adapters instead of buying a commercial one.
The following screenshot shows the receiver communication channel for SAP PI/PO integration −
The following screenshot shows the sender communication channel for SAP PI/PO −
Ariba Administrator is responsible for configuration of SAP PI URL for all the exports tasks in web-based integration. The sample URL looks like −
SoapURL = "http://<PIserver>:<port>
<servername>:50000/XISOAPAdapter/MessageServlet?channel=:<Businessystemname>:
<communication_channel_name>";
Using Ariba Procurement solution, a user can enter information about the items ordered by them. For this, Ariba system and SAP ERP system should receive information in the same way. By setting system parameters, you can configure receiving tolerances in the below system parameters. These parameters can be set by submitting a request with Ariba contact and the Ariba support representative will contact you −
Application.Procure.OverReceivingOperator
Application.Procure.OverReceivingPercentage
Application.Procure.OverReceivingQuantity
Application.Procure.OverReceivingValue
Application.Procure.UnderReceivingOperator
Application.Procure.UnderReceivingQuantity
Application.Procure.UnderReceivingValue
Application.Procure.UnderReceivingPercentage
An ERP order is generated when you create a requisition first time. To generate an ERP order by default, the default browser should be changed in the service manager.
Let us now see the steps to generate ERP order by default.
Login to the Service Manager using the Power User. On the left side, you have the Site Manager option → Customer Sites.
Login as Customer Support Admin and click Customization Manager → Advance Tab and then select Parameters. You need to search for order methods and click the Edit option.
Move ariba.sap.server.SAPPOERP to the top of the list → OK → Save.
While Configuring SAP Ariba Procurement Solution, you can also define preferred ordering method for Purchase Order that will be sent to suppliers. Following are the supported formats −
cXML
Fax
URL
Print
Email
Online
In case this field is blank, it takes the URL as the ordering method by default. If you want the Purchase Order to be downloaded in a CSV file, you must set the value of the preferred ordering method to Print. To set your preferred ordering method, please have your Designated Support Contact log a service request following which an Ariba Customer Support representative will contact you.
With the use of parameters, you can also enable cancel order integration. To enable this, parameter Application.Procure.UseCancelOrderIntegration must be set to “Yes”. You can submit an Ariba service request following which an Ariba support representative will contact you to set this parameter value.
You can also set a unique number for Purchase Order identifier. By default, Ariba Procurement Solution generates order number starting from EP10. To specify your unique number for Purchase Orders, you can submit an Ariba service request following which an Ariba support representative will contact you.
In Ariba, you can also create split orders where line items are in different currencies. In this case, an order that will be created should be split based on the different currency types. The SAP ERP system does not support Purchase Orders with line items having different currency types.
To split an order, you need to go to the Advance tab and select Split Order on this field and click OK. To publish order, click Publish button.
SAP Ariba is an online platform to provide services to buyers and suppliers. Ariba’s online services are used by buyers of goods or services or by suppliers of goods and services. Ariba has set different terms applicable for the use of online services by buyers. The terms of use document shows the terms applicable to goods and services suppliers.
https://service.ariba.com/Authenticator.aw/ad/termsCenter?tou=supplier
https://service.ariba.com/Authenticator.aw/ad/termsCenter?tou=marketplace
Let us now look into the other terms and policies for services provided by Ariba −
Long-Term Document Archiving
Country Coverage
Dynamic Discounting Credit Memos
AribaPay
Supply Chain Financing
Cloud Integration Gateway
Master Content Services
To check details about the above-mentioned Ariba terms, navigate to this link − https://service.ariba.com/Authenticator.aw/ad/termsCenter
In the SAP ERP system, you may have generation information known as master data that you need to integrate with Ariba Procurement solution. In Ariba Procurement solution, you can configure events for standard data import from SAP. Master data is known as data, which is required to perform operations in specific businesses or business units. Ex. Vendor is a type of master data, which is used for creating purchase orders or contracts.
In this section, we will see what are some commonly used SAP Master Data −
This field in ERP system is used to store customer related information in the SAP ERP system.
Vendor master is used to store supplier related information in SAP ERP system.
Material master is used to store product and component related information in SAP ERP system.
Bill of material is used to store the list of components needed to produce a finished product.
This field is used to store the list of steps or operations needed to come up with a finished product.
Condition records are product prices, taxes, discounts or surcharges stored in SAP ERP system.
Purchasing info records are components' purchase prices offered by suppliers.
To import master data from ERP system to Ariba, you can use any of the following methods −
By using the Data Transfer Tool.
By using the Data Transfer Tool.
You can configure integrations events manually from the Ariba Administrator console.
You can configure integrations events manually from the Ariba Administrator console.
You can also use Ariba Integration Toolkit through the Direct Connectivity Integration method.
You can also use Ariba Integration Toolkit through the Direct Connectivity Integration method.
Using SAP Process integration PI to integrate master data directly from an SAP ERP system to the Ariba Procurement Solution system.
Using SAP Process integration PI to integrate master data directly from an SAP ERP system to the Ariba Procurement Solution system.
Normally, Ariba solution imports data from ERP system which are required to create Purchase Orders, Invoice and receipt information from SAP. The following master data is imported to Ariba Procurement solution −
Account assignment categories
Accounting field display status
WBS (Work Breakdown Structure) elements
Currency conversion rates
Material groups
Plants
Purchasing organizations
Language-specific names for data imports
Asset accounts
Cost centers
Company Codes
General ledger accounts
Supplier Locations
Payment terms
Remittance Locations
User and User groups
Internal orders
Purchasing groups
Vendors
Tax codes
To perform master data import, transport request must be downloaded and exported to the SAP ERP system. Before you start with the import of master data, the following SAP Note must be implemented −
1402826
1716777
Note − 1716777 is the SAP Note related to Runtime error IMPORT_WRONG_END_POS when displaying class.
Authorization object must be created to allow running import transactions. Authorization objects are part of transport system and they should have a role defined under PFCG T-code. Under PFCG role, you should assign Ariba RFC functional module. For example, /ARBA/BAPI_PO_CREATE1 and other Ariba Procure-to-Pay function modules.
Authorization objects to perform data import should be created with the following details −
Object name: F_KKMIGRAT
Object name: F_KKMIGRAT
Description: FI-CA IS Migration Workbench
Description: FI-CA IS Migration Workbench
Authorization Class: FI Authorization
Authorization Class: FI Authorization
Fields −
EMG_ACTVT = 1
EMG_ACTVT = 1
EMG_FIRMA = *
EMG_FIRMA = *
EMG_GROUP = FILCreating
EMG_GROUP = FILCreating
To maintain authorization objects, go to T-code: SU21 and create a new Authorization Object.
While performing master data import from SAP ERP to your Ariba procurement solution, you will come across a few limitations −
If you have supplier location linked to multiple vendors, it is not supported in integration to Ariba Procurement solution.
If you have supplier location linked to multiple vendors, it is not supported in integration to Ariba Procurement solution.
Master data, which is exported using direct integration tool kit cannot be archived.
Master data, which is exported using direct integration tool kit cannot be archived.
In SAP system, you can create payment terms with day limit; however, Ariba Procurement solution payment terms does not support day limit.
In SAP system, you can create payment terms with day limit; however, Ariba Procurement solution payment terms does not support day limit.
Incremental load can be run only for specific master data tasks.
Incremental load can be run only for specific master data tasks.
To perform master data import, you need to create mapping of SAP and Ariba Procurement field values. To perform export of data, a custom table /ARBA/FIELD_MAP must be maintained to map the SAP and Ariba Procurement Solution system field values.
The following values should be maintained −
If you do not perform the mapping of fields, Ariba procurement solution integrated with SAP shows SAP field name in Ariba Procurement solution. The example given below shows how fields are mapped −
To create roles for authorization object, use T-code: PFCG and enter the name of the role.
Click Single Role option; it will open Authorization tab → Change Authorization Data.
In the template page, do not select a template. In the Manual selection of authorizations page, enter a name in the Authorization object text box. Ensure that you enter /ARB and click Continue.
The Change Role − The Authorizations page appears, and you need to enter the parent node; for example, ZTRANSACTION_DATA to expand it. You can see the /ARB object class you created.
Now, click on the Program Name child node. The Field Values dialog box appears. In the Field values dialog box, ensure that you have the following entries −
Object: /ARBA/PROG
Field name: PROGRAM
In the Value Intrvl section, enter all the transaction data report names in the From column. Save the entries and regenerate the profiles created.
For importing supplier data, Ariba Procurement Solution integrated with SAP downloads supplier data in the SupplierConsolidated.csv using fields in below tables −
Suppliers available in the LFA1 (Vendor Master Table)
Suppliers available in the LFA1 (Vendor Master Table)
Suppliers that are not marked for deletion for a given PORG
Suppliers that are not marked for deletion for a given PORG
Suppliers that do not have a centrally imposed purchasing block
Suppliers that do not have a centrally imposed purchasing block
Suppliers that are not blocked for any function
Suppliers that are not blocked for any function
You need to ensure that you maintain the right value of SystemID and vendor fields in the table. When supplier data is imported, values for SystemID field is imported in .csv file.
Function Module/ARBA/VENDOR_EXPORTCSV
Files − SupplierConsolidated.csvPurchaseOrgSupplierCombo.csv
While maintaining supplier location data, these 2 parameters are used − /ARBA/SL_VENDOR_ADDRESS and /ARBA/SL_PARTNER_TYPE. While importing supplier location data, you must maintain at least one of these parameters in /ARBA/TVARV table. In case you do not maintain one of these parameters, it shows an error.
Function Module/ARBA/SUPPLIER_LOCATION_EXPORTCSV
File − SupplierLocationConsolidated.csv
Payment terms indicate the negotiated discount between a buying organization and supplier for a specified number of days before payment is due.
Function Module/ARBA/PAYMENTTERM_EXPORTCSV
File − PaymentTermsConsolidated.csv
Transactional data includes Purchase Order, invoice, receipts, payments and other business related information. Transactional data comes with a time stamp and a numerical value referring to one or more objects.
Following methods are commonly used for integrating transactional data between SAP ERP and Ariba Procurement solution −
Using file channel option
Using file channel option
Using the web services channel
Using the web services channel
Using user interface option
Using user interface option
Using mediated connectivity integration
Using mediated connectivity integration
For each file channel, you have scheduled integration events. An Ariba administrator can run these events manually. An executable program code is defined and scheduled to run. The code picks csv data file from Ariba Procurement solution and exports to SAP ERP database.
CSV files are generated using transaction events and these are picked by data transfer tool. To move data to ERP database, SAP transports should be imported. SAP transports are a combination of SAP Programs, RFCs, and supporting structures. The SAP executable programs are used to move the exported data into SAP ERP. The BAPI executable programs help in the moving of data into SAP ERP.
SAP programs usually contain the following parameters −
Logical File Name − This defines the logical path and the physical location of the CSV files.
Logical File Name − This defines the logical path and the physical location of the CSV files.
Directory Separator − This is the physical separator for directories in SAP ERP.
Directory Separator − This is the physical separator for directories in SAP ERP.
Encoding in response files − Encoding technique that is used UTF-8 by default.
Encoding in response files − Encoding technique that is used UTF-8 by default.
Variant − Variant Name
Variant − Variant Name
Partition − Partition Name
Partition − Partition Name
The following tables show different transactional data integration event components −
The Web service method is based on the use of SOAP URLs configured by Ariba administrators. For all outbound events, a SOAP URL is generated automatically to be present in the generated WSDL according to the following logic −
<IncomingHttpServerURL> / <ContextRoot> / soap / <realm name> / <event_name>
In each WSDL, you have the following components −
Import − This component is used to associate a namespace with a document location.
Import − This component is used to associate a namespace with a document location.
Types − This component is used to define user created data types, which will be used in the document.
Types − This component is used to define user created data types, which will be used in the document.
Message − This component is used to define all the parts of an individual message.
Message − This component is used to define all the parts of an individual message.
PortType − This is a container of supported operations by the web service. The operations in PortType are ordered. These operations indicate whether a message is inbound or outbound.
PortType − This is a container of supported operations by the web service. The operations in PortType are ordered. These operations indicate whether a message is inbound or outbound.
Binding − This element defines the operation to protocol mapping. (for example, http, https, MIME, etc.).
Binding − This element defines the operation to protocol mapping. (for example, http, https, MIME, etc.).
Service − This component is used to define the operation to address mapping and it shows the actual address the request should be forwarded.
Service − This component is used to define the operation to address mapping and it shows the actual address the request should be forwarded.
There are various transactional data integration events spread across SAP ERP and Ariba Procurement solution.
The following table shows example URLs for each data integration event −
In Ariba Procurement Solution, buyers can also use direct connectivity option to integrate data to SAP ERP system. This feature is supported in SAP ERP 6.0 and later versions. Using this option, ERP system sends a request to Ariba Procurement Solution with the header part containing parameter details for extraction of transactional data.
To use this option, transport request must be downloaded and imported into SAP ERP system.
When you use direct connection option using user interface, following limitations are applied −
No email notification while an error occurs during the transactional data integration.
No email notification while an error occurs during the transactional data integration.
Ariba administrator can see all error messages only in the runtime monitor of the SAP ERP and SAP Process integration.
Ariba administrator can see all error messages only in the runtime monitor of the SAP ERP and SAP Process integration.
When you check T-code SLGI, it does not store details of all error log in this transaction.
When you check T-code SLGI, it does not store details of all error log in this transaction.
This method uses SAP Process Integration layer with mediated connectivity option for integration of transactional data. Using SAP PI provides a secure way of integration and all certificates and key stores are created and stored in SAP Process Integration key store.
To use this option, transport request must be downloaded and imported into SAP ERP system. When you use direct connection option using user interface, following limitations are applied −
No email notification while an error occurs during the transactional data integration.
No email notification while an error occurs during the transactional data integration.
All error messages can be seen only in the runtime monitor of the SAP ERP and SAP Process integration by Ariba administrator.
All error messages can be seen only in the runtime monitor of the SAP ERP and SAP Process integration by Ariba administrator.
When you check T-code SLGI, it does not store detail of all error log in this transaction.
When you check T-code SLGI, it does not store detail of all error log in this transaction.
To integrate Ariba Procurement solution with SAP ERP system, you must download ERP transport to your procurement solution. While importing transports, you should define a target client while adding to the import queue. Transport management system in SAP system is installed and configured by SAP administrators.
The sequence to install the transports is mentioned inside the “Readme.txt” file and this file is in the ZIP file that you download from connect.ariba.com. You can also import real time integration transport. However, you need to configure SAP ERP system to use real time system with your procurement solution.
To specify target client, you should use SAP Transport Management system, T-code: STMS
Log on to the SAP system, that you want to add as a System, in client 000 and enter the transaction code → STMS. If system is not added, TMS will check configuration file DOMAIN.CFG and will prompt you to create one. Click → Select the Proposal and Save. The system will remain in ‘Waiting’ status initially.
To complete the task → login to the Domain Controller System → Transaction STMS → Go to Overview → Systems. You can now see that a new system is available. Go to SAP System → Approve.
Mapping workbooks are used to import/export data between Ariba Procurement Solution and ERP system. These mapping workbooks can be customized based on business needs. When an outbound transaction happens, data transforms from XML to cXML and is uploaded to Ariba Procurement Solution. For inbound transactions, it is reverse order – the data is transformed from cXML to XML and moved to ERP system.
Mapping workbooks can be downloaded from https://connect.ariba.com and you can customize the mapping of fields between XML and cXML based on your business requirements.
Step 1 − To download mapping workbooks, login to https://connect.ariba.com
If you do not have username and password for Ariba Connect, you can contact Ariba account executive. You can use any of the below options to manage your account −
Forgotten Password
New User
Can’t access your account
Step 2 − You have to click on Home tab → Product Summary page, click Ariba Cloud Integration; this will further open Ariba Cloud Integration page.
Step 3 − Under the Integration Tools section, click Integration tools for Ariba Procure-to-Pay.
The Integration tools for Ariba Procure-to-Pay page appears.
Navigate to Integration Tools for SAP → Tool and click Mapping Workbooks.
The Mapping Workbooks for Ariba Procurement Solutions integrated with SAP for Cloud Integration X.0 page appears. Click Download and specify a location on your hard drive to download the mapping workbooks.
Mapping workbooks are available for download in Zip format.
In this chapter, we will learn how to install SAP Ariba. Consider the following to install SAP Ariba −
SAP Ariba Notes Installation
SAP Ariba Adapter Installation
Ariba Functional Configuration
SAP Ariba Web Services Configuration
Customizing Adapter as per business requirement
To install SAP Ariba Adapter, you need to go to support.ariba.com and login using your SID and password.
To download software, you need to have a DSC (Designated Support Contact) ID. New users can register on the Ariba portal. Open https://support.ariba.com → New User Registration
Once you login to Ariba Portal, search for Ariba Network Adapter for SAP NetWeaver. As mentioned, Ariba Network Adapter is available only for DSCs.
The next step is to Import required AN adapter files (.tpz) into SAP Enterprise Service Repository.
You need to import the required Ariba Network product and component definitions (.zip) into System Landscape directory SLD.
Below are Ariba troubleshooting codes that can be used to fix any of the issues −
The following message types should be used to enable integration −
OrderRequest (outbound)
ConfirmationRequest (inbound)
ShipNoticeRequest (inbound)
ServiceEntryRequest (inbound)
ReceiptRequest (outbound)
InvoiceDetailRequest (inbound)
CopyRequest.InvoiceDetailRequest (outbound)
StatusUpdateRequest (outbound)
PaymentProposalRequest (outbound)
CopyRequest.PaymentProposalRequest (inbound)
PaymentRemittanceRequest (outbound)
PaymentRemittanceStatusUpdateRequest (outbound)
After the installation of SAP Ariba and the sample data load is complete, Ariba tools undergo default configuration. The default configuration contains configuration files to define parameters.
There are two types of configuration files −
These files exist in the directory BuyerServerRoot/ariba. The files define the default Ariba Buyer configuration. You never change system files as part of an implementation.
These files exist in the directory BuyerServerRoot/config and these files are modified during implementation.
Note − To change Ariba configuration, you should modify the files in the config directory. The files in Ariba directory should not be modified.
Ariba buyers use different file extensions for different file types. The below table lists common file types in the Config directory −
In SAP Ariba, each configuration has one parameter set applicable to all partitions. Within config/parameters.table, parameters are grouped into two types. The types are described below −
These parameters are same across your configuration, at the server level. While the value of this parameter is set in the System section, it is applied to every partition that exists in your configuration.
The values for these parameters are different for different partitions. While a value you set for this parameter in the Application section initially applies to all partitions, however it is possible to provide different values for different partitions as well.
You can also create custom parameters under system or application parameter section of config/parameter.table file. By default, you don’t have any parameter under custom section.
You need to protect sensitive information and encrypt information in configuration files to protect it. Ariba buyer configuration files can contain sensitive information like computer names, passwords, or personal information. All these values are in plain text format and for protection, the values should be encrypted.
You can use aribaencrypt command and supply a string as an argument. This will update config/parameter.table with encrypted value.
Use aribaencrypt-key <key>. Here, key is the name of an existing parameter in Parameters.table. This will ask you to confirm action and post confirmation, the key is properly encrypted and stored in Parameters.table. No further steps are required.
You need to secure the data through Ariba Administrator using the following −
Access to integration events and scheduled tasks should be secured from Ariba Administrator by using ExecutePermissionPull integration event.
Access to integration events and scheduled tasks should be secured from Ariba Administrator by using ExecutePermissionPull integration event.
It is also possible to implement file level security by using “EditPermissionPull” integration event.
It is also possible to implement file level security by using “EditPermissionPull” integration event.
To ensure administrator tasks are secure, you need to change workspace and task permissions in the workspace configuration files.
To ensure administrator tasks are secure, you need to change workspace and task permissions in the workspace configuration files.
You also need to secure different objects in Ariba configuration. This can be done by assigning read and edit permissions to object in ObjectPermission.csv file.
While using default configuration, ObjectPermission.csv file is in the below directory −
config/variants/Plain/partitions/None/data/ObjectPermission.csv
ObjectPermission.csv file contains the below fields −
In SAP Ariba buyer configuration, BuyerServerRoot/logs contains log files. Few of the files also contain the node name from which the files have been generated.
The below table lists down a few common log files of the log directory. Ariba Administrator can download any of the log files using log files task option −
When we compare SAP Vendor Management systems like SRM or SAP Ariba system with ServiceNow, ServiceNow is considered as an IT Service Management software which is used to transform IT services and infrastructure using single cloud based platform.
Service Now tool is used to automate IT Service management processes, it is primarily used for managing technology-based Service Management tasks to initiate workflows, approval tasks, and other IT Service management processed.
The following image shows common features which are available in Service Now Jakarta edition −
When you compare SAP Ariba with Service Now, Ariba is open to all systems and all types of goods and services, and provides an option to connect to all types of suppliers and buyers on a single global network.
Using Ariba Network (AN), you can collaborate with the right business partners, and enhance your solution with targeted apps and extensions. When users are connected to AN, it allows you to connect to millions of suppliers and merchandisers (direct or indirect). Following are the key features provided by the SAP Ariba network −
One of the key advantages of using Ariba solution is that it simplifies procurement and sourcing process with easy synchronization to SAP SRM and other ERP software.
One of the key advantages of using Ariba solution is that it simplifies procurement and sourcing process with easy synchronization to SAP SRM and other ERP software.
It enhances the experience of suppliers and buyers by creating digital transformation to supply chain process.
It enhances the experience of suppliers and buyers by creating digital transformation to supply chain process.
With cloud-based solution, SAP Ariba can be accessed from different locations with a very low initial capital cost for setting up the solution.
With cloud-based solution, SAP Ariba can be accessed from different locations with a very low initial capital cost for setting up the solution.
There is easy setup of key procurement processes – Procure to pay (integration of purchase department with Accounts payable department), Procure to Order by maintaining shopping carts.
There is easy setup of key procurement processes – Procure to pay (integration of purchase department with Accounts payable department), Procure to Order by maintaining shopping carts.
SAP Ariba enables easy transfer of master data – organization structure, suppliers and GL data to Ariba solution using optimal way of integration.
SAP Ariba enables easy transfer of master data – organization structure, suppliers and GL data to Ariba solution using optimal way of integration.
SAP Ariba offers an end-to-end automated system that removes complexity and allows buyers and suppliers to manage everything from contracts to payments all in one place.
SAP Ariba offers an end-to-end automated system that removes complexity and allows buyers and suppliers to manage everything from contracts to payments all in one place.
SAP SRM is a SAP product that facilitates the procurement of goods via a web-based platform. Organizations can procure all type of products like direct and indirect material, services and this can be integrated with SAP ERP modules and other non-SAP backend systems for accounting and planning.
SAP SRM allows you to optimize your procurement process to work effectively with suppliers to get long term benefits and also to perform forecasting, procurement cycle and to work with partners. You can reduce the time span and costing of procurement cycle using innovative methods to manage business processes with key suppliers.
SAP SRM supports the full procurement cycle, i.e., starting from source and purchase to pay through complete procurement process with suppliers and effectively managing supplier to build long-term relationship.
SAP SRM helps you to emphasize supplier performance management, streamline the procurement operations, put compliance with contracts and purchasing policies, and improve overall cost management and expenditure.
The future of SAP SRM is SAP S/4 HANA and SAP Ariba system for exceptional procurement and vendor management capabilities. When you have SAP S/4 HANA implemented, you can easily extend your procurement solution from on-premise solution to cloud and it allows to exchange information, improve visibility with great efficiency and effectiveness with your suppliers.
1. Ariba offers an end-to-end automated system that removes complexity and allows buyers and suppliers to manage everything from contracts to payments all in one place.
2. Ariba Network is one of the key components, which provides a cloud-based B2B marketplace where buyers and suppliers can find each other and do business on a single platform.
With use of custom and compound reports in Ariba, it is much more advanced as compared to standard reporting in an ERP system. Following report types are supported in Ariba system −
Prepackaged Reports
Investigate Data
Custom Reports
Multi-fact Reports
Exporting Reports
Compound Reports
In SAP Ariba cloud solution, following solution areas are covered −
SAP Ariba Supplier Management − It manages supplier information, lifecycle, performance, and risk all in one place and can be accessed from anywhere.
SAP Ariba Supplier Management − It manages supplier information, lifecycle, performance, and risk all in one place and can be accessed from anywhere.
SAP Ariba Strategic Sourcing − It manages sourcing, contracting, and spend analysis processes for all types of spend – direct materials, indirect materials, and services.
SAP Ariba Strategic Sourcing − It manages sourcing, contracting, and spend analysis processes for all types of spend – direct materials, indirect materials, and services.
SAP Ariba Solutions for Direct Spend − Helps to connect the people, partners, processes, and information needed to manage all design-to-deliver activities.
SAP Ariba Solutions for Direct Spend − Helps to connect the people, partners, processes, and information needed to manage all design-to-deliver activities.
SAP Ariba Procurement − Helps in achieving compliance, visibility, and control while cutting costs and risks.
SAP Ariba Procurement − Helps in achieving compliance, visibility, and control while cutting costs and risks.
SAP Ariba Financial Supply Chain − This closes the source-to-settle loop by boosting free cash flow, freeing up working capital, and delivering more bottom-line value.
SAP Ariba Financial Supply Chain − This closes the source-to-settle loop by boosting free cash flow, freeing up working capital, and delivering more bottom-line value.
SAP Ariba modules provide easy to use workflow designs that do not need customization by technical experts. It provides preconfigured workflows based on best practices that you can use right way. With the use of drag-drop functionalities, you can easily modify rules and with the use of workflow builder, users can easily build, test and deploy workflows.
https://www.ariba.com/solutions/solutions-overview/financial-supply-chain/invoice-management
There are different configuration workflows that can be used.
From the same link, you can check other existing configurable workflows in Ariba solution −
In this chapter, we will see the Report Types supported in the Ariba system −
Prepackaged Reports
Investigate Data
Custom Reports
Multi-fact Reports
Exporting Reports
Compound Reports
Apart from this, if you are using SAP S/4 HANA system, it also provides different standard reports w.r.t. Procurement system.
There are various dashboards’ views under each Ariba module that can be customized based on the requirement and used for reporting purpose.
In SAP Ariba, users can also modify CSV files that pull report data, to specify report properties or permissions. Report properties can be changed using the below integration events −
ReportQueryPull Integration Event − This is used to Query API queries associated with each report.
ReportQueryPull Integration Event − This is used to Query API queries associated with each report.
ReportMetaPull Integration Event − This event is used to define report visualization and appearance of each report in Ariba system.
ReportMetaPull Integration Event − This event is used to define report visualization and appearance of each report in Ariba system.
ReportPermissionMap.csv File − This defines list of reports in Ariba system and it contains one line for each report.
ReportPermissionMap.csv File − This defines list of reports in Ariba system and it contains one line for each report.
ReportColumnMeta.csv File − This is used to define column name in each report.
ReportColumnMeta.csv File − This is used to define column name in each report.
SAP S/4 HANA integration with the Ariba Network is native to SAP S/4HANA and this can be performed as part of SAP S/4HANA with guided configuration. You can navigate to “Ariba account settings” and it doesn’t require use of middleware. To meet your organization policies, you can integrate using a middleware like SAP Process Orchestration PI/PO on-premise or SAP HANA Cloud Integration HCI in the cloud. SAP also provides best practices to show you which mediated connectivity alternatives should be used for integration.
With the integration of SAP S/4HANA and Ariba, cloud allows the following processes −
Purchase order collaboration
Invoice collaboration
Service procurement
Discount management
Payment
There are three ways of connecting SAP S/4HANA with the Ariba Network −
You establish a system connection between SAP S/4HANA and the Ariba Network without using middleware. Under Ariba account settings, you have direct connectivity option.
You establish a system connection using SAP HANA Cloud Integration between SAP S/4HANA and the Ariba Network.
You establish a system connection using middleware between SAP S/4HANA and the Ariba Network.
The SAP Process Integration design packages (TPZ files) are available on this link https://connect.ariba.com in a ZIP file. You must download the ZIP file and extract the files for your required version.
You can also refer to SAP Note 1991088 to know more about integration.
For integration between SAP S/4 HANA and Ariba Network, you should use SAP Activate and best practices. To check best practices, open URL − https://rapid.sap.com/bp/
Navigate to SAP S/4HANA → Integration → SAP Best Practices for SAP S/4HANA integration with Ariba Solutions
Following is the link of SAP best practices explorer to learn SAP Ariba network integration with S/4 HANA for different scope items −
https://rapid.sap.com/bp/#/browse/search?q=Ariba&from=0&size=50
To open any of the best practices, you can click on any link and it will show business benefits and process flow under that best practice.
Following are the various requirements and responsibilities of a SAP Ariba Developer −
Experience of Ariba integration with backend ERP systems and 2-4 full life-cycle implementations of Ariba applications.
Experience of Ariba integration with backend ERP systems and 2-4 full life-cycle implementations of Ariba applications.
Technical knowledge of Ariba solutions and products.
Technical knowledge of Ariba solutions and products.
Ariba On Demand implementation experience, should include experience in one or more of the following areas −
SAP Ariba Procurement capabilities including SAP Ariba Buying and Invoicing, SAP Ariba Guided Buying, SAP Ariba Catalog and SAP Ariba Invoice Management.
SAP Ariba Commerce Automation, Payables and Supply Chain Collaboration using the Ariba Network.
Experience of SAP Ariba integration with SAP S/4HANA, SAP ERP or other non-SAP backend systems.
Knowledge of implementing SAP Notes and best practices for integration.
Knowledge of customizing a solution as per business requirement and the ability to convert business requirements into technical specifications.
Ariba On Demand implementation experience, should include experience in one or more of the following areas −
SAP Ariba Procurement capabilities including SAP Ariba Buying and Invoicing, SAP Ariba Guided Buying, SAP Ariba Catalog and SAP Ariba Invoice Management.
SAP Ariba Procurement capabilities including SAP Ariba Buying and Invoicing, SAP Ariba Guided Buying, SAP Ariba Catalog and SAP Ariba Invoice Management.
SAP Ariba Commerce Automation, Payables and Supply Chain Collaboration using the Ariba Network.
SAP Ariba Commerce Automation, Payables and Supply Chain Collaboration using the Ariba Network.
Experience of SAP Ariba integration with SAP S/4HANA, SAP ERP or other non-SAP backend systems.
Experience of SAP Ariba integration with SAP S/4HANA, SAP ERP or other non-SAP backend systems.
Knowledge of implementing SAP Notes and best practices for integration.
Knowledge of implementing SAP Notes and best practices for integration.
Knowledge of customizing a solution as per business requirement and the ability to convert business requirements into technical specifications.
Knowledge of customizing a solution as per business requirement and the ability to convert business requirements into technical specifications.
25 Lectures
6 hours
Sanjo Thomas
26 Lectures
2 hours
Neha Gupta
30 Lectures
2.5 hours
Sumit Agarwal
30 Lectures
4 hours
Sumit Agarwal
14 Lectures
1.5 hours
Neha Malik
13 Lectures
1.5 hours
Neha Malik
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2673,
"s": 2238,
"text": "SAP Ariba is a cloud-based innovative solution that allows suppliers and buyers to connect and do business on a single platform. It improves over all vendor management system of an organization by providing less costly ways of procurement and making business simple. Ariba acts as supply chain, procurement service to do business globally. SAP Ariba digitally transforms your supply chain, procurement and contract management process."
},
{
"code": null,
"e": 3015,
"s": 2673,
"text": "In today’s world, there is a need to control your supply chain and to collaborate with your suppliers in an efficient way. To enable healthy supply chain, you need to have suppliers with visibility to every part of procurement process so that they can maintain an efficient supply chain and help organizations to grow their and own business."
},
{
"code": null,
"e": 3361,
"s": 3015,
"text": "The cloud based innovative solution was first developed in 1996 by a company named Ariba and was later acquired by SAP in 2012 with a total acquisition cost of 4.3 billion USD with each share cost $45. Thus, the name SAP Ariba. At the onset, Ariba was a B2B company to do procurement over Internet and was the first one to introduce IPO in 1999."
},
{
"code": null,
"e": 3429,
"s": 3361,
"text": "In this section, we will learn about the key features of SAP Ariba."
},
{
"code": null,
"e": 3609,
"s": 3429,
"text": "SAP Ariba is a B2B solution that allows you to connect to the world’s largest network of vendors and suppliers and enhance business collaboration with the right business partners."
},
{
"code": null,
"e": 3789,
"s": 3609,
"text": "SAP Ariba is a B2B solution that allows you to connect to the world’s largest network of vendors and suppliers and enhance business collaboration with the right business partners."
},
{
"code": null,
"e": 3984,
"s": 3789,
"text": "SAP Ariba allows organizations to connect with the right suppliers with deep visibility to your inside vendor and procurement management processes giving way to error free business transactions."
},
{
"code": null,
"e": 4179,
"s": 3984,
"text": "SAP Ariba allows organizations to connect with the right suppliers with deep visibility to your inside vendor and procurement management processes giving way to error free business transactions."
},
{
"code": null,
"e": 4316,
"s": 4179,
"text": "With SAP Ariba, you can directly connect Ariba network with millions of suppliers meeting your business needs and managing supply chain."
},
{
"code": null,
"e": 4453,
"s": 4316,
"text": "With SAP Ariba, you can directly connect Ariba network with millions of suppliers meeting your business needs and managing supply chain."
},
{
"code": null,
"e": 4613,
"s": 4453,
"text": "SAP Ariba network removes overall complexity in procurement process and suppliers and buyers can manage all key terms of vendor management on a single network."
},
{
"code": null,
"e": 4773,
"s": 4613,
"text": "SAP Ariba network removes overall complexity in procurement process and suppliers and buyers can manage all key terms of vendor management on a single network."
},
{
"code": null,
"e": 4980,
"s": 4773,
"text": "With acquisition of SAP, Ariba can easily integrate with different SAP ERP solutions like SAP ECC and S/4 HANA with easy to configure workflows to automate different processes in complete procurement cycle."
},
{
"code": null,
"e": 5187,
"s": 4980,
"text": "With acquisition of SAP, Ariba can easily integrate with different SAP ERP solutions like SAP ECC and S/4 HANA with easy to configure workflows to automate different processes in complete procurement cycle."
},
{
"code": null,
"e": 5290,
"s": 5187,
"text": "You can easily integrate master and transactional data from different ERP solution to Ariba processes."
},
{
"code": null,
"e": 5393,
"s": 5290,
"text": "You can easily integrate master and transactional data from different ERP solution to Ariba processes."
},
{
"code": null,
"e": 5623,
"s": 5393,
"text": "SAP Ariba is a cloud-based Procurement solution, which help buyers and suppliers to meet at one single network. SAP Ariba Partner program enables you with tools, resources, and benefits to help build, run, and grow your business."
},
{
"code": null,
"e": 5675,
"s": 5623,
"text": "Following are the key benefits of using SAP Ariba −"
},
{
"code": null,
"e": 5841,
"s": 5675,
"text": "One of the key advantages of using Ariba solution is that it simplifies procurement and sourcing process with easy synchronization to SAP SRM and other ERP software."
},
{
"code": null,
"e": 6007,
"s": 5841,
"text": "One of the key advantages of using Ariba solution is that it simplifies procurement and sourcing process with easy synchronization to SAP SRM and other ERP software."
},
{
"code": null,
"e": 6125,
"s": 6007,
"text": "It enhances supplier, buyers and user experience by bringing in a digital transformation to the supply chain process."
},
{
"code": null,
"e": 6243,
"s": 6125,
"text": "It enhances supplier, buyers and user experience by bringing in a digital transformation to the supply chain process."
},
{
"code": null,
"e": 6393,
"s": 6243,
"text": "With cloud-based solution, SAP Ariba can be accessed from different locations. It requires very low initial capital cost for setting up the solution."
},
{
"code": null,
"e": 6543,
"s": 6393,
"text": "With cloud-based solution, SAP Ariba can be accessed from different locations. It requires very low initial capital cost for setting up the solution."
},
{
"code": null,
"e": 6747,
"s": 6543,
"text": "With SAP Ariba, there is an easy setup of key procurement processes - Procure to pay (integration of purchase department with Accounts payable department), Procure to Order by maintaining shopping carts."
},
{
"code": null,
"e": 6951,
"s": 6747,
"text": "With SAP Ariba, there is an easy setup of key procurement processes - Procure to pay (integration of purchase department with Accounts payable department), Procure to Order by maintaining shopping carts."
},
{
"code": null,
"e": 7114,
"s": 6951,
"text": "There is easy transfer of master data. Organization structure, suppliers and GL data can be easily transferred to Ariba solution using optimal way of integration."
},
{
"code": null,
"e": 7277,
"s": 7114,
"text": "There is easy transfer of master data. Organization structure, suppliers and GL data can be easily transferred to Ariba solution using optimal way of integration."
},
{
"code": null,
"e": 7445,
"s": 7277,
"text": "SAP Ariba enables easy transfer of transactional data. Invoice details, goods receipt, PO details can be easily transferred to Ariba solution with optimum integration."
},
{
"code": null,
"e": 7613,
"s": 7445,
"text": "SAP Ariba enables easy transfer of transactional data. Invoice details, goods receipt, PO details can be easily transferred to Ariba solution with optimum integration."
},
{
"code": null,
"e": 7687,
"s": 7613,
"text": "We can use integration toolkit to connect ERP system with Ariba solution."
},
{
"code": null,
"e": 7761,
"s": 7687,
"text": "We can use integration toolkit to connect ERP system with Ariba solution."
},
{
"code": null,
"e": 7844,
"s": 7761,
"text": "The following illustration shows Ariba as the world's largest B2B trading platform"
},
{
"code": null,
"e": 8022,
"s": 7844,
"text": "In SAP Ariba, you can access and configure new accounts, set email notifications, electronic order and invoice routing and other account related configuration for new suppliers."
},
{
"code": null,
"e": 8056,
"s": 8022,
"text": "Go to https://supplier.ariba.com."
},
{
"code": null,
"e": 8090,
"s": 8056,
"text": "Go to https://supplier.ariba.com."
},
{
"code": null,
"e": 8145,
"s": 8090,
"text": "To login to your account, enter username and password."
},
{
"code": null,
"e": 8200,
"s": 8145,
"text": "To login to your account, enter username and password."
},
{
"code": null,
"e": 8293,
"s": 8200,
"text": "To configure account access and configuration, you need to navigate to Company Settings tab."
},
{
"code": null,
"e": 8386,
"s": 8293,
"text": "To configure account access and configuration, you need to navigate to Company Settings tab."
},
{
"code": null,
"e": 8457,
"s": 8386,
"text": "Navigate to Company Profile tab to update company profile information."
},
{
"code": null,
"e": 8528,
"s": 8457,
"text": "Navigate to Company Profile tab to update company profile information."
},
{
"code": null,
"e": 8598,
"s": 8528,
"text": "From the company profile menu, you can update the below information −"
},
{
"code": null,
"e": 8620,
"s": 8598,
"text": "Basic company profile"
},
{
"code": null,
"e": 8637,
"s": 8620,
"text": "Business Details"
},
{
"code": null,
"e": 8647,
"s": 8637,
"text": "Marketing"
},
{
"code": null,
"e": 8664,
"s": 8647,
"text": "Company Contacts"
},
{
"code": null,
"e": 8686,
"s": 8664,
"text": "Certification details"
},
{
"code": null,
"e": 8707,
"s": 8686,
"text": "Additional documents"
},
{
"code": null,
"e": 8932,
"s": 8707,
"text": "SAP Ariba allows you to set notifications and access network notification. You can choose on the email notifications you want to receive and you can also enter the email address where you want these notifications to be sent."
},
{
"code": null,
"e": 8986,
"s": 8932,
"text": "To set notifications,go to Notification tab → Network"
},
{
"code": null,
"e": 9202,
"s": 8986,
"text": "You can enter three email addresses for each notification and these should be separated with a comma. As mentioned, preferred language configured by Administrator controls the language used in sending notifications."
},
{
"code": null,
"e": 9387,
"s": 9202,
"text": "You can manage electronic order routing by using Network Settings option →Electronic Order Routing. You can select from the following methods to transact business with your customers −"
},
{
"code": null,
"e": 9393,
"s": 9387,
"text": "Email"
},
{
"code": null,
"e": 9400,
"s": 9393,
"text": "Online"
},
{
"code": null,
"e": 9405,
"s": 9400,
"text": "cXML"
},
{
"code": null,
"e": 9409,
"s": 9405,
"text": "EDI"
},
{
"code": null,
"e": 9413,
"s": 9409,
"text": "Fax"
},
{
"code": null,
"e": 9503,
"s": 9413,
"text": "Using this option, you can send PO to Ariba inbox without sending extra copies elsewhere."
},
{
"code": null,
"e": 9640,
"s": 9503,
"text": "You have the option to include document in email message by selecting check box; this will further send a complete copy of PO in email."
},
{
"code": null,
"e": 9725,
"s": 9640,
"text": "The ERP system can be configured with Ariba solution and the PO can be sent via EDI."
},
{
"code": null,
"e": 9819,
"s": 9725,
"text": "There are different ways you can also manage electronic invoice routing. To set preferences −"
},
{
"code": null,
"e": 9852,
"s": 9819,
"text": "Go to Electronic Invoice Routing"
},
{
"code": null,
"e": 9885,
"s": 9852,
"text": "Go to Electronic Invoice Routing"
},
{
"code": null,
"e": 10024,
"s": 9885,
"text": "You can select from one of the following routing methods − Online, cXML, and EDI. You can also set email notification for invoice routing."
},
{
"code": null,
"e": 10163,
"s": 10024,
"text": "You can select from one of the following routing methods − Online, cXML, and EDI. You can also set email notification for invoice routing."
},
{
"code": null,
"e": 10263,
"s": 10163,
"text": "With Tax Invoicing option, you can also enter Tax ID, VAT ID and other tax related supporting data."
},
{
"code": null,
"e": 10363,
"s": 10263,
"text": "With Tax Invoicing option, you can also enter Tax ID, VAT ID and other tax related supporting data."
},
{
"code": null,
"e": 10580,
"s": 10363,
"text": "You can use Invoice Archival option to specify frequency of zipped invoice archives. Goto Tax Invoicing and Archiving tab → Invoice Archival → Configure Invoice Archival. You can select from the following frequency −"
},
{
"code": null,
"e": 10592,
"s": 10580,
"text": "Twice Daily"
},
{
"code": null,
"e": 10598,
"s": 10592,
"text": "Daily"
},
{
"code": null,
"e": 10605,
"s": 10598,
"text": "Weekly"
},
{
"code": null,
"e": 10614,
"s": 10605,
"text": "Biweekly"
},
{
"code": null,
"e": 10622,
"s": 10614,
"text": "Monthly"
},
{
"code": null,
"e": 10720,
"s": 10622,
"text": "You can also select the Archive Immediately option to archive invoices in zip format immediately."
},
{
"code": null,
"e": 10856,
"s": 10720,
"text": "In SAP Ariba, administrators and users perform different roles. Administrators of Ariba system perform the following responsibilities −"
},
{
"code": null,
"e": 10942,
"s": 10856,
"text": "Account configuration and management – registering new accounts in SAP Ariba network."
},
{
"code": null,
"e": 11028,
"s": 10942,
"text": "Account configuration and management – registering new accounts in SAP Ariba network."
},
{
"code": null,
"e": 11100,
"s": 11028,
"text": "Handle account login issues and act as primary contact for Ariba users."
},
{
"code": null,
"e": 11172,
"s": 11100,
"text": "Handle account login issues and act as primary contact for Ariba users."
},
{
"code": null,
"e": 11208,
"s": 11172,
"text": "Creating new roles in Ariba system."
},
{
"code": null,
"e": 11244,
"s": 11208,
"text": "Creating new roles in Ariba system."
},
{
"code": null,
"e": 11303,
"s": 11244,
"text": "Linked to user name and login entered during registration."
},
{
"code": null,
"e": 11362,
"s": 11303,
"text": "Linked to user name and login entered during registration."
},
{
"code": null,
"e": 11419,
"s": 11362,
"text": "A user has the following primary tasks in Ariba system −"
},
{
"code": null,
"e": 11499,
"s": 11419,
"text": "Users can have different roles concerning procurement and supply chain process."
},
{
"code": null,
"e": 11579,
"s": 11499,
"text": "Users can have different roles concerning procurement and supply chain process."
},
{
"code": null,
"e": 11627,
"s": 11579,
"text": "Users can update their profile in Ariba system."
},
{
"code": null,
"e": 11675,
"s": 11627,
"text": "Users can update their profile in Ariba system."
},
{
"code": null,
"e": 11752,
"s": 11675,
"text": "Configuring notifications and workflows based on roles and responsibilities."
},
{
"code": null,
"e": 11829,
"s": 11752,
"text": "Configuring notifications and workflows based on roles and responsibilities."
},
{
"code": null,
"e": 11908,
"s": 11829,
"text": "Administrator’s primary task is to create new users and roles in Ariba system."
},
{
"code": null,
"e": 12005,
"s": 11908,
"text": "To create new user and role, navigate to Account Settings → User tab. This will open Users page."
},
{
"code": null,
"e": 12102,
"s": 12005,
"text": "To create new user and role, navigate to Account Settings → User tab. This will open Users page."
},
{
"code": null,
"e": 12168,
"s": 12102,
"text": "To create new role, under Manage User Roles → Create Role button."
},
{
"code": null,
"e": 12234,
"s": 12168,
"text": "To create new role, under Manage User Roles → Create Role button."
},
{
"code": null,
"e": 12301,
"s": 12234,
"text": "Enter the name of role and description for the role to be created."
},
{
"code": null,
"e": 12368,
"s": 12301,
"text": "Enter the name of role and description for the role to be created."
},
{
"code": null,
"e": 12438,
"s": 12368,
"text": "Now, add permissions to role that is based user job responsibilities."
},
{
"code": null,
"e": 12508,
"s": 12438,
"text": "Now, add permissions to role that is based user job responsibilities."
},
{
"code": null,
"e": 12608,
"s": 12508,
"text": "To save new role, click Save. You can also check detail of an existing role, edit or delete a Role."
},
{
"code": null,
"e": 12708,
"s": 12608,
"text": "To save new role, click Save. You can also check detail of an existing role, edit or delete a Role."
},
{
"code": null,
"e": 12885,
"s": 12708,
"text": "To create new User, click Create User button and mention the details about user including name and contact. Next is to select a role for new user based on roles and click Done."
},
{
"code": null,
"e": 13062,
"s": 12885,
"text": "To create new User, click Create User button and mention the details about user including name and contact. Next is to select a role for new user based on roles and click Done."
},
{
"code": null,
"e": 13122,
"s": 13062,
"text": "Note − It is possible to create 250 users in Ariba network."
},
{
"code": null,
"e": 13304,
"s": 13122,
"text": "You can also manage existing user accounts. Select an existing user under User tab and to make changes, click Edit. To make a user an administrator, click Make Administrator option."
},
{
"code": null,
"e": 13462,
"s": 13304,
"text": "SAP Ariba provides different plans based on the number of transactions allowed under each plan. There are also customized plans based on your business needs."
},
{
"code": null,
"e": 13502,
"s": 13462,
"text": "Following are some common Ariba plans −"
},
{
"code": null,
"e": 13509,
"s": 13502,
"text": "Select"
},
{
"code": null,
"e": 13517,
"s": 13509,
"text": "Premier"
},
{
"code": null,
"e": 13528,
"s": 13517,
"text": "Enterprise"
},
{
"code": null,
"e": 13592,
"s": 13528,
"text": "Enterprise Plus Plan Monthly Price Transaction Volume Threshold"
},
{
"code": null,
"e": 13803,
"s": 13592,
"text": "You can use SAP Ariba at no cost, if you transact five or less documents − POs, invoices, service entry sheets, etc. or your transaction volume should be less than the below threshold for one customer annually."
},
{
"code": null,
"e": 13892,
"s": 13803,
"text": "The below table shows the number of chargeable transactions for each currency annually −"
},
{
"code": null,
"e": 14125,
"s": 13892,
"text": "When you cross the document and transaction threshold limit for one customer as mentioned above annually, suppliers are enrolled to paid subscription and need to pay fee based on the number of transactions listed in the above table."
},
{
"code": null,
"e": 14185,
"s": 14125,
"text": "In this section, we will learn about the various fee types."
},
{
"code": null,
"e": 14291,
"s": 14185,
"text": "This fee is based on the financial volume you transact annually with all customers through Ariba Network."
},
{
"code": null,
"e": 14412,
"s": 14291,
"text": "This fee is based on the number of documents you transact annually with all customers, as well as your technology usage."
},
{
"code": null,
"e": 14578,
"s": 14412,
"text": "In order to help customers with high number of annual transactions, Ariba has set up an annual cap of maximum limit of transaction fees as shown in the table below −"
},
{
"code": null,
"e": 14877,
"s": 14578,
"text": "Subscription fee is based on the number of documents you processed annually. The fee also includes technology usage. Ariba offers four paid subscriptions and each subscription is based on the number of documents that can be transacted annually based on currency. There are four subscription plans −"
},
{
"code": null,
"e": 14884,
"s": 14877,
"text": "Bronze"
},
{
"code": null,
"e": 14891,
"s": 14884,
"text": "Silver"
},
{
"code": null,
"e": 14896,
"s": 14891,
"text": "Gold"
},
{
"code": null,
"e": 14905,
"s": 14896,
"text": "Platinum"
},
{
"code": null,
"e": 15295,
"s": 14905,
"text": "When you cross the document and transaction volume chargeable thresholds, SAP will charge either quarterly or annually based on selection, depending on when you first crossed the thresholds. If you are a new supplier, you will be billed quarterly, and it will be in advance for your next quarterly or annual period on the basis of your Ariba Network usage during your prior billing period."
},
{
"code": null,
"e": 15369,
"s": 15295,
"text": "You can pay your bill by going to − https://service.ariba.com/Supplier.aw"
},
{
"code": null,
"e": 15419,
"s": 15369,
"text": "Log in to your account with your ID and password."
},
{
"code": null,
"e": 15469,
"s": 15419,
"text": "Log in to your account with your ID and password."
},
{
"code": null,
"e": 15533,
"s": 15469,
"text": "Find your company name in the top right corner and click on it."
},
{
"code": null,
"e": 15597,
"s": 15533,
"text": "Find your company name in the top right corner and click on it."
},
{
"code": null,
"e": 15629,
"s": 15597,
"text": "Click on Service Subscriptions."
},
{
"code": null,
"e": 15661,
"s": 15629,
"text": "Click on Service Subscriptions."
},
{
"code": null,
"e": 15708,
"s": 15661,
"text": "Click the Billing tab to view your invoice(s)."
},
{
"code": null,
"e": 15755,
"s": 15708,
"text": "Click the Billing tab to view your invoice(s)."
},
{
"code": null,
"e": 15811,
"s": 15755,
"text": "Find the invoice you want to pay and click Pay Invoice."
},
{
"code": null,
"e": 15867,
"s": 15811,
"text": "Find the invoice you want to pay and click Pay Invoice."
},
{
"code": null,
"e": 15957,
"s": 15867,
"text": "Select your payment method (credit card, check, or electronic settlement) and click Next."
},
{
"code": null,
"e": 16047,
"s": 15957,
"text": "Select your payment method (credit card, check, or electronic settlement) and click Next."
},
{
"code": null,
"e": 16098,
"s": 16047,
"text": "Enter your credit card information, if applicable."
},
{
"code": null,
"e": 16149,
"s": 16098,
"text": "Enter your credit card information, if applicable."
},
{
"code": null,
"e": 16199,
"s": 16149,
"text": "Confirm your subscription package, if applicable."
},
{
"code": null,
"e": 16249,
"s": 16199,
"text": "Confirm your subscription package, if applicable."
},
{
"code": null,
"e": 16370,
"s": 16249,
"text": "If paying by cheque or electronic settlement, download your invoice and submit to your disbursement process for payment."
},
{
"code": null,
"e": 16491,
"s": 16370,
"text": "If paying by cheque or electronic settlement, download your invoice and submit to your disbursement process for payment."
},
{
"code": null,
"e": 16784,
"s": 16491,
"text": "SAP Ariba Network users can make bill payment using a credit card, electronic fund transfer or by using bank cheque. For small amount invoices, you should only pay using a Credit card. The following table shows subscription fee fall below minimum threshold and should be paid by credit card −"
},
{
"code": null,
"e": 16943,
"s": 16784,
"text": "For any help, a SAP Ariba Network user can visit the Help Center. After you log into your account, click the link in the upper-right corner of your dashboard."
},
{
"code": null,
"e": 17162,
"s": 16943,
"text": "SAP Business Suite can connect to Ariba network using non-modifying add-ons that come with Ariba Network integration 1.0. Using these add-ons, you can send or receive message in the format supported by SAP Ariba- cXML."
},
{
"code": null,
"e": 17525,
"s": 17162,
"text": "With the use of Ariba add-ons, you can integrate single SAP ERP system or multiple systems with Ariba network. Integration can be performed directly or by using a middleware. One of the common integration options comes with the use of HANA Cloud Integration (HCI). With Ariba Network integration 1.0, following Business suites can be connected to Ariba network −"
},
{
"code": null,
"e": 17533,
"s": 17525,
"text": "SAP ERP"
},
{
"code": null,
"e": 17541,
"s": 17533,
"text": "SAP ERP"
},
{
"code": null,
"e": 17578,
"s": 17541,
"text": "SAP Supplier Relationship Management"
},
{
"code": null,
"e": 17615,
"s": 17578,
"text": "SAP Supplier Relationship Management"
},
{
"code": null,
"e": 17652,
"s": 17615,
"text": "SAP Supply Network Collaboration SNC"
},
{
"code": null,
"e": 17689,
"s": 17652,
"text": "SAP Supply Network Collaboration SNC"
},
{
"code": null,
"e": 17757,
"s": 17689,
"text": "Following are the benefits of using Ariba Network Integration 1.0 −"
},
{
"code": null,
"e": 17851,
"s": 17757,
"text": "You do not require an additional infrastructure or system to connect with SAP Business Suite."
},
{
"code": null,
"e": 17945,
"s": 17851,
"text": "You do not require an additional infrastructure or system to connect with SAP Business Suite."
},
{
"code": null,
"e": 18001,
"s": 17945,
"text": "Ariba Network Integration supports minimum SAP ERP 6.0."
},
{
"code": null,
"e": 18057,
"s": 18001,
"text": "Ariba Network Integration supports minimum SAP ERP 6.0."
},
{
"code": null,
"e": 18123,
"s": 18057,
"text": "With the use of Ariba add-ons, the network complexity is removed."
},
{
"code": null,
"e": 18189,
"s": 18123,
"text": "With the use of Ariba add-ons, the network complexity is removed."
},
{
"code": null,
"e": 18246,
"s": 18189,
"text": "It does not require any upgrade, update to be performed."
},
{
"code": null,
"e": 18303,
"s": 18246,
"text": "It does not require any upgrade, update to be performed."
},
{
"code": null,
"e": 18397,
"s": 18303,
"text": "Ariba Network integrations should be deployed on every ERP system that you want to integrate."
},
{
"code": null,
"e": 18491,
"s": 18397,
"text": "Ariba Network integrations should be deployed on every ERP system that you want to integrate."
},
{
"code": null,
"e": 18567,
"s": 18491,
"text": "In this section, we will look into the product requirement for integration."
},
{
"code": null,
"e": 18609,
"s": 18567,
"text": "SAP ERP system starting with SAP ERP 6.0."
},
{
"code": null,
"e": 18651,
"s": 18609,
"text": "SAP ERP system starting with SAP ERP 6.0."
},
{
"code": null,
"e": 18721,
"s": 18651,
"text": "Ariba integration scenario with SAP ERP core functionality supported."
},
{
"code": null,
"e": 18791,
"s": 18721,
"text": "Ariba integration scenario with SAP ERP core functionality supported."
},
{
"code": null,
"e": 18808,
"s": 18791,
"text": "Ariba Foundation"
},
{
"code": null,
"e": 18825,
"s": 18808,
"text": "Ariba Foundation"
},
{
"code": null,
"e": 18872,
"s": 18825,
"text": "Add-on “ARBFNDI1” starting with AS ABAP 7.0000"
},
{
"code": null,
"e": 18919,
"s": 18872,
"text": "Add-on “ARBFNDI1” starting with AS ABAP 7.0000"
},
{
"code": null,
"e": 18964,
"s": 18919,
"text": "Add-on “ARBFNDI2” starting with AS ABAP 7.01"
},
{
"code": null,
"e": 19009,
"s": 18964,
"text": "Add-on “ARBFNDI2” starting with AS ABAP 7.01"
},
{
"code": null,
"e": 19054,
"s": 19009,
"text": "Add-on “ARBERPI1” based on add-on “ARBFNDI1”"
},
{
"code": null,
"e": 19099,
"s": 19054,
"text": "Add-on “ARBERPI1” based on add-on “ARBFNDI1”"
},
{
"code": null,
"e": 19191,
"s": 19099,
"text": "SAP NetWeaver PI (optional) − This is the middleware to connect SAP ERP with Ariba Network."
},
{
"code": null,
"e": 19283,
"s": 19191,
"text": "SAP NetWeaver PI (optional) − This is the middleware to connect SAP ERP with Ariba Network."
},
{
"code": null,
"e": 19319,
"s": 19283,
"text": "Starting with SAP NetWeaver PI 7.1."
},
{
"code": null,
"e": 19355,
"s": 19319,
"text": "Starting with SAP NetWeaver PI 7.1."
},
{
"code": null,
"e": 19434,
"s": 19355,
"text": "Java stack sufficient, therefore SAP NetWeaver PI − JAVA only (AEX) supported."
},
{
"code": null,
"e": 19513,
"s": 19434,
"text": "Java stack sufficient, therefore SAP NetWeaver PI − JAVA only (AEX) supported."
},
{
"code": null,
"e": 19553,
"s": 19513,
"text": "ESR Content with Ariba cXML interfaces."
},
{
"code": null,
"e": 19593,
"s": 19553,
"text": "ESR Content with Ariba cXML interfaces."
},
{
"code": null,
"e": 19752,
"s": 19593,
"text": "Ariba Network Adapter for SAP NetWeaver (starting with Release Cloud Integration 1.0) − released for SAP NetWeaver PI 7.1 up to EHP1 for SAP NetWeaver PI 7.4."
},
{
"code": null,
"e": 19911,
"s": 19752,
"text": "Ariba Network Adapter for SAP NetWeaver (starting with Release Cloud Integration 1.0) − released for SAP NetWeaver PI 7.1 up to EHP1 for SAP NetWeaver PI 7.4."
},
{
"code": null,
"e": 20245,
"s": 19911,
"text": "Ariba integration tool kit is a Java based tool which can be used to upload master data or download transaction data from the SAP ERP system. With Ariba integration tool kit, it reads CSV files, zips the files and sends them as MIME messages to Ariba procurement solution using HTTP. Integration can be done with the following ways −"
},
{
"code": null,
"e": 20268,
"s": 20245,
"text": "File based integration"
},
{
"code": null,
"e": 20291,
"s": 20268,
"text": "File based integration"
},
{
"code": null,
"e": 20322,
"s": 20291,
"text": "Web services based integration"
},
{
"code": null,
"e": 20353,
"s": 20322,
"text": "Web services based integration"
},
{
"code": null,
"e": 20373,
"s": 20353,
"text": "Direct Connectivity"
},
{
"code": null,
"e": 20393,
"s": 20373,
"text": "Direct Connectivity"
},
{
"code": null,
"e": 20423,
"s": 20393,
"text": "Using Middleware connectivity"
},
{
"code": null,
"e": 20453,
"s": 20423,
"text": "Using Middleware connectivity"
},
{
"code": null,
"e": 20680,
"s": 20453,
"text": "You can move master and transactional data from SAP to Ariba system using file-based integration. Master data extracted from SAP in the form of .csv files. These .csv files are transferred to Ariba system using Ariba Tool kit."
},
{
"code": null,
"e": 20769,
"s": 20680,
"text": "The following illustration shows file based integration and master data import to Ariba."
},
{
"code": null,
"e": 20883,
"s": 20769,
"text": "Follow these steps for transfer of transactional data from SAP to Ariba using the file-based integration method −"
},
{
"code": null,
"e": 20998,
"s": 20883,
"text": "In the first step, the data transfer tool exports data from Ariba procurement solution in the form of *.csv files."
},
{
"code": null,
"e": 21113,
"s": 20998,
"text": "In the first step, the data transfer tool exports data from Ariba procurement solution in the form of *.csv files."
},
{
"code": null,
"e": 21201,
"s": 21113,
"text": "Ariba provided ABAP program then reads these *.csv files and transfers data to SAP ERP."
},
{
"code": null,
"e": 21289,
"s": 21201,
"text": "Ariba provided ABAP program then reads these *.csv files and transfers data to SAP ERP."
},
{
"code": null,
"e": 21369,
"s": 21289,
"text": "ABAP program then retrieves the status of each export transaction from SAP ERP."
},
{
"code": null,
"e": 21449,
"s": 21369,
"text": "ABAP program then retrieves the status of each export transaction from SAP ERP."
},
{
"code": null,
"e": 21525,
"s": 21449,
"text": "The data transfer tool reads these *.csv files and updates them into Ariba."
},
{
"code": null,
"e": 21601,
"s": 21525,
"text": "The data transfer tool reads these *.csv files and updates them into Ariba."
},
{
"code": null,
"e": 21986,
"s": 21601,
"text": "This is used to perform real time integration of Ariba to SAP ERP using SAP PI and this integration option is available by default. If you use any other middleware like SOA, you will require configuring the setup manually. In Web service-based integration, a SOAP message is generated based on the WSDL and this is dispatched to a web services server using SAP Process Integration PI."
},
{
"code": null,
"e": 22315,
"s": 21986,
"text": "With direct integration, .csv files are moved from SAP ERP to Ariba system. The .CSV files with master data is sent to Ariba system in the form of SOAP message. The direct integration option for master data is available from Ariba cloud integration 4.0 or later and transactional data integration is available from 6.0 or later."
},
{
"code": null,
"e": 22594,
"s": 22315,
"text": "Mediated connectivity integration is available in Ariba Cloud integration 5.0 or later and the movement of transactional data from 6.0 or later. The mediated connectivity integration method can be used with SAP PI to exchange file data or by sending information as SOAP message."
},
{
"code": null,
"e": 23042,
"s": 22594,
"text": "When you use SAP PI for integration, you need to define receiver and sender communication channel. Note that SAP Ariba provides an Ariba Network Adapter for SAP PI/PO integration and is known as add-on module for SAP business applications that allows to send and receive document in cXML format to and from Ariba Network. By following Ariba SN cXML standards, it is also possible to develop own network adapters instead of buying a commercial one."
},
{
"code": null,
"e": 23136,
"s": 23042,
"text": "The following screenshot shows the receiver communication channel for SAP PI/PO integration −"
},
{
"code": null,
"e": 23216,
"s": 23136,
"text": "The following screenshot shows the sender communication channel for SAP PI/PO −"
},
{
"code": null,
"e": 23363,
"s": 23216,
"text": "Ariba Administrator is responsible for configuration of SAP PI URL for all the exports tasks in web-based integration. The sample URL looks like −"
},
{
"code": null,
"e": 23515,
"s": 23363,
"text": "SoapURL = \"http://<PIserver>:<port>\n <servername>:50000/XISOAPAdapter/MessageServlet?channel=:<Businessystemname>:\n <communication_channel_name>\";\n"
},
{
"code": null,
"e": 23925,
"s": 23515,
"text": "Using Ariba Procurement solution, a user can enter information about the items ordered by them. For this, Ariba system and SAP ERP system should receive information in the same way. By setting system parameters, you can configure receiving tolerances in the below system parameters. These parameters can be set by submitting a request with Ariba contact and the Ariba support representative will contact you −"
},
{
"code": null,
"e": 23967,
"s": 23925,
"text": "Application.Procure.OverReceivingOperator"
},
{
"code": null,
"e": 24011,
"s": 23967,
"text": "Application.Procure.OverReceivingPercentage"
},
{
"code": null,
"e": 24053,
"s": 24011,
"text": "Application.Procure.OverReceivingQuantity"
},
{
"code": null,
"e": 24092,
"s": 24053,
"text": "Application.Procure.OverReceivingValue"
},
{
"code": null,
"e": 24135,
"s": 24092,
"text": "Application.Procure.UnderReceivingOperator"
},
{
"code": null,
"e": 24178,
"s": 24135,
"text": "Application.Procure.UnderReceivingQuantity"
},
{
"code": null,
"e": 24218,
"s": 24178,
"text": "Application.Procure.UnderReceivingValue"
},
{
"code": null,
"e": 24263,
"s": 24218,
"text": "Application.Procure.UnderReceivingPercentage"
},
{
"code": null,
"e": 24430,
"s": 24263,
"text": "An ERP order is generated when you create a requisition first time. To generate an ERP order by default, the default browser should be changed in the service manager."
},
{
"code": null,
"e": 24489,
"s": 24430,
"text": "Let us now see the steps to generate ERP order by default."
},
{
"code": null,
"e": 24609,
"s": 24489,
"text": "Login to the Service Manager using the Power User. On the left side, you have the Site Manager option → Customer Sites."
},
{
"code": null,
"e": 24779,
"s": 24609,
"text": "Login as Customer Support Admin and click Customization Manager → Advance Tab and then select Parameters. You need to search for order methods and click the Edit option."
},
{
"code": null,
"e": 24846,
"s": 24779,
"text": "Move ariba.sap.server.SAPPOERP to the top of the list → OK → Save."
},
{
"code": null,
"e": 25031,
"s": 24846,
"text": "While Configuring SAP Ariba Procurement Solution, you can also define preferred ordering method for Purchase Order that will be sent to suppliers. Following are the supported formats −"
},
{
"code": null,
"e": 25036,
"s": 25031,
"text": "cXML"
},
{
"code": null,
"e": 25040,
"s": 25036,
"text": "Fax"
},
{
"code": null,
"e": 25044,
"s": 25040,
"text": "URL"
},
{
"code": null,
"e": 25050,
"s": 25044,
"text": "Print"
},
{
"code": null,
"e": 25056,
"s": 25050,
"text": "Email"
},
{
"code": null,
"e": 25063,
"s": 25056,
"text": "Online"
},
{
"code": null,
"e": 25453,
"s": 25063,
"text": "In case this field is blank, it takes the URL as the ordering method by default. If you want the Purchase Order to be downloaded in a CSV file, you must set the value of the preferred ordering method to Print. To set your preferred ordering method, please have your Designated Support Contact log a service request following which an Ariba Customer Support representative will contact you."
},
{
"code": null,
"e": 25755,
"s": 25453,
"text": "With the use of parameters, you can also enable cancel order integration. To enable this, parameter Application.Procure.UseCancelOrderIntegration must be set to “Yes”. You can submit an Ariba service request following which an Ariba support representative will contact you to set this parameter value."
},
{
"code": null,
"e": 26058,
"s": 25755,
"text": "You can also set a unique number for Purchase Order identifier. By default, Ariba Procurement Solution generates order number starting from EP10. To specify your unique number for Purchase Orders, you can submit an Ariba service request following which an Ariba support representative will contact you."
},
{
"code": null,
"e": 26347,
"s": 26058,
"text": "In Ariba, you can also create split orders where line items are in different currencies. In this case, an order that will be created should be split based on the different currency types. The SAP ERP system does not support Purchase Orders with line items having different currency types."
},
{
"code": null,
"e": 26491,
"s": 26347,
"text": "To split an order, you need to go to the Advance tab and select Split Order on this field and click OK. To publish order, click Publish button."
},
{
"code": null,
"e": 26840,
"s": 26491,
"text": "SAP Ariba is an online platform to provide services to buyers and suppliers. Ariba’s online services are used by buyers of goods or services or by suppliers of goods and services. Ariba has set different terms applicable for the use of online services by buyers. The terms of use document shows the terms applicable to goods and services suppliers."
},
{
"code": null,
"e": 26911,
"s": 26840,
"text": "https://service.ariba.com/Authenticator.aw/ad/termsCenter?tou=supplier"
},
{
"code": null,
"e": 26985,
"s": 26911,
"text": "https://service.ariba.com/Authenticator.aw/ad/termsCenter?tou=marketplace"
},
{
"code": null,
"e": 27068,
"s": 26985,
"text": "Let us now look into the other terms and policies for services provided by Ariba −"
},
{
"code": null,
"e": 27097,
"s": 27068,
"text": "Long-Term Document Archiving"
},
{
"code": null,
"e": 27114,
"s": 27097,
"text": "Country Coverage"
},
{
"code": null,
"e": 27147,
"s": 27114,
"text": "Dynamic Discounting Credit Memos"
},
{
"code": null,
"e": 27156,
"s": 27147,
"text": "AribaPay"
},
{
"code": null,
"e": 27179,
"s": 27156,
"text": "Supply Chain Financing"
},
{
"code": null,
"e": 27205,
"s": 27179,
"text": "Cloud Integration Gateway"
},
{
"code": null,
"e": 27229,
"s": 27205,
"text": "Master Content Services"
},
{
"code": null,
"e": 27367,
"s": 27229,
"text": "To check details about the above-mentioned Ariba terms, navigate to this link − https://service.ariba.com/Authenticator.aw/ad/termsCenter"
},
{
"code": null,
"e": 27804,
"s": 27367,
"text": "In the SAP ERP system, you may have generation information known as master data that you need to integrate with Ariba Procurement solution. In Ariba Procurement solution, you can configure events for standard data import from SAP. Master data is known as data, which is required to perform operations in specific businesses or business units. Ex. Vendor is a type of master data, which is used for creating purchase orders or contracts."
},
{
"code": null,
"e": 27879,
"s": 27804,
"text": "In this section, we will see what are some commonly used SAP Master Data −"
},
{
"code": null,
"e": 27973,
"s": 27879,
"text": "This field in ERP system is used to store customer related information in the SAP ERP system."
},
{
"code": null,
"e": 28052,
"s": 27973,
"text": "Vendor master is used to store supplier related information in SAP ERP system."
},
{
"code": null,
"e": 28146,
"s": 28052,
"text": "Material master is used to store product and component related information in SAP ERP system."
},
{
"code": null,
"e": 28241,
"s": 28146,
"text": "Bill of material is used to store the list of components needed to produce a finished product."
},
{
"code": null,
"e": 28344,
"s": 28241,
"text": "This field is used to store the list of steps or operations needed to come up with a finished product."
},
{
"code": null,
"e": 28439,
"s": 28344,
"text": "Condition records are product prices, taxes, discounts or surcharges stored in SAP ERP system."
},
{
"code": null,
"e": 28517,
"s": 28439,
"text": "Purchasing info records are components' purchase prices offered by suppliers."
},
{
"code": null,
"e": 28608,
"s": 28517,
"text": "To import master data from ERP system to Ariba, you can use any of the following methods −"
},
{
"code": null,
"e": 28641,
"s": 28608,
"text": "By using the Data Transfer Tool."
},
{
"code": null,
"e": 28674,
"s": 28641,
"text": "By using the Data Transfer Tool."
},
{
"code": null,
"e": 28759,
"s": 28674,
"text": "You can configure integrations events manually from the Ariba Administrator console."
},
{
"code": null,
"e": 28844,
"s": 28759,
"text": "You can configure integrations events manually from the Ariba Administrator console."
},
{
"code": null,
"e": 28939,
"s": 28844,
"text": "You can also use Ariba Integration Toolkit through the Direct Connectivity Integration method."
},
{
"code": null,
"e": 29034,
"s": 28939,
"text": "You can also use Ariba Integration Toolkit through the Direct Connectivity Integration method."
},
{
"code": null,
"e": 29166,
"s": 29034,
"text": "Using SAP Process integration PI to integrate master data directly from an SAP ERP system to the Ariba Procurement Solution system."
},
{
"code": null,
"e": 29298,
"s": 29166,
"text": "Using SAP Process integration PI to integrate master data directly from an SAP ERP system to the Ariba Procurement Solution system."
},
{
"code": null,
"e": 29510,
"s": 29298,
"text": "Normally, Ariba solution imports data from ERP system which are required to create Purchase Orders, Invoice and receipt information from SAP. The following master data is imported to Ariba Procurement solution −"
},
{
"code": null,
"e": 29540,
"s": 29510,
"text": "Account assignment categories"
},
{
"code": null,
"e": 29572,
"s": 29540,
"text": "Accounting field display status"
},
{
"code": null,
"e": 29612,
"s": 29572,
"text": "WBS (Work Breakdown Structure) elements"
},
{
"code": null,
"e": 29638,
"s": 29612,
"text": "Currency conversion rates"
},
{
"code": null,
"e": 29654,
"s": 29638,
"text": "Material groups"
},
{
"code": null,
"e": 29661,
"s": 29654,
"text": "Plants"
},
{
"code": null,
"e": 29686,
"s": 29661,
"text": "Purchasing organizations"
},
{
"code": null,
"e": 29727,
"s": 29686,
"text": "Language-specific names for data imports"
},
{
"code": null,
"e": 29742,
"s": 29727,
"text": "Asset accounts"
},
{
"code": null,
"e": 29755,
"s": 29742,
"text": "Cost centers"
},
{
"code": null,
"e": 29769,
"s": 29755,
"text": "Company Codes"
},
{
"code": null,
"e": 29793,
"s": 29769,
"text": "General ledger accounts"
},
{
"code": null,
"e": 29812,
"s": 29793,
"text": "Supplier Locations"
},
{
"code": null,
"e": 29826,
"s": 29812,
"text": "Payment terms"
},
{
"code": null,
"e": 29847,
"s": 29826,
"text": "Remittance Locations"
},
{
"code": null,
"e": 29868,
"s": 29847,
"text": "User and User groups"
},
{
"code": null,
"e": 29884,
"s": 29868,
"text": "Internal orders"
},
{
"code": null,
"e": 29902,
"s": 29884,
"text": "Purchasing groups"
},
{
"code": null,
"e": 29910,
"s": 29902,
"text": "Vendors"
},
{
"code": null,
"e": 29920,
"s": 29910,
"text": "Tax codes"
},
{
"code": null,
"e": 30118,
"s": 29920,
"text": "To perform master data import, transport request must be downloaded and exported to the SAP ERP system. Before you start with the import of master data, the following SAP Note must be implemented −"
},
{
"code": null,
"e": 30135,
"s": 30118,
"text": "1402826\n1716777\n"
},
{
"code": null,
"e": 30235,
"s": 30135,
"text": "Note − 1716777 is the SAP Note related to Runtime error IMPORT_WRONG_END_POS when displaying class."
},
{
"code": null,
"e": 30564,
"s": 30235,
"text": "Authorization object must be created to allow running import transactions. Authorization objects are part of transport system and they should have a role defined under PFCG T-code. Under PFCG role, you should assign Ariba RFC functional module. For example, /ARBA/BAPI_PO_CREATE1 and other Ariba Procure-to-Pay function modules."
},
{
"code": null,
"e": 30656,
"s": 30564,
"text": "Authorization objects to perform data import should be created with the following details −"
},
{
"code": null,
"e": 30680,
"s": 30656,
"text": "Object name: F_KKMIGRAT"
},
{
"code": null,
"e": 30704,
"s": 30680,
"text": "Object name: F_KKMIGRAT"
},
{
"code": null,
"e": 30746,
"s": 30704,
"text": "Description: FI-CA IS Migration Workbench"
},
{
"code": null,
"e": 30788,
"s": 30746,
"text": "Description: FI-CA IS Migration Workbench"
},
{
"code": null,
"e": 30826,
"s": 30788,
"text": "Authorization Class: FI Authorization"
},
{
"code": null,
"e": 30864,
"s": 30826,
"text": "Authorization Class: FI Authorization"
},
{
"code": null,
"e": 30873,
"s": 30864,
"text": "Fields −"
},
{
"code": null,
"e": 30887,
"s": 30873,
"text": "EMG_ACTVT = 1"
},
{
"code": null,
"e": 30901,
"s": 30887,
"text": "EMG_ACTVT = 1"
},
{
"code": null,
"e": 30915,
"s": 30901,
"text": "EMG_FIRMA = *"
},
{
"code": null,
"e": 30929,
"s": 30915,
"text": "EMG_FIRMA = *"
},
{
"code": null,
"e": 30953,
"s": 30929,
"text": "EMG_GROUP = FILCreating"
},
{
"code": null,
"e": 30977,
"s": 30953,
"text": "EMG_GROUP = FILCreating"
},
{
"code": null,
"e": 31070,
"s": 30977,
"text": "To maintain authorization objects, go to T-code: SU21 and create a new Authorization Object."
},
{
"code": null,
"e": 31196,
"s": 31070,
"text": "While performing master data import from SAP ERP to your Ariba procurement solution, you will come across a few limitations −"
},
{
"code": null,
"e": 31320,
"s": 31196,
"text": "If you have supplier location linked to multiple vendors, it is not supported in integration to Ariba Procurement solution."
},
{
"code": null,
"e": 31444,
"s": 31320,
"text": "If you have supplier location linked to multiple vendors, it is not supported in integration to Ariba Procurement solution."
},
{
"code": null,
"e": 31529,
"s": 31444,
"text": "Master data, which is exported using direct integration tool kit cannot be archived."
},
{
"code": null,
"e": 31614,
"s": 31529,
"text": "Master data, which is exported using direct integration tool kit cannot be archived."
},
{
"code": null,
"e": 31752,
"s": 31614,
"text": "In SAP system, you can create payment terms with day limit; however, Ariba Procurement solution payment terms does not support day limit."
},
{
"code": null,
"e": 31890,
"s": 31752,
"text": "In SAP system, you can create payment terms with day limit; however, Ariba Procurement solution payment terms does not support day limit."
},
{
"code": null,
"e": 31955,
"s": 31890,
"text": "Incremental load can be run only for specific master data tasks."
},
{
"code": null,
"e": 32020,
"s": 31955,
"text": "Incremental load can be run only for specific master data tasks."
},
{
"code": null,
"e": 32265,
"s": 32020,
"text": "To perform master data import, you need to create mapping of SAP and Ariba Procurement field values. To perform export of data, a custom table /ARBA/FIELD_MAP must be maintained to map the SAP and Ariba Procurement Solution system field values."
},
{
"code": null,
"e": 32309,
"s": 32265,
"text": "The following values should be maintained −"
},
{
"code": null,
"e": 32507,
"s": 32309,
"text": "If you do not perform the mapping of fields, Ariba procurement solution integrated with SAP shows SAP field name in Ariba Procurement solution. The example given below shows how fields are mapped −"
},
{
"code": null,
"e": 32598,
"s": 32507,
"text": "To create roles for authorization object, use T-code: PFCG and enter the name of the role."
},
{
"code": null,
"e": 32684,
"s": 32598,
"text": "Click Single Role option; it will open Authorization tab → Change Authorization Data."
},
{
"code": null,
"e": 32878,
"s": 32684,
"text": "In the template page, do not select a template. In the Manual selection of authorizations page, enter a name in the Authorization object text box. Ensure that you enter /ARB and click Continue."
},
{
"code": null,
"e": 33060,
"s": 32878,
"text": "The Change Role − The Authorizations page appears, and you need to enter the parent node; for example, ZTRANSACTION_DATA to expand it. You can see the /ARB object class you created."
},
{
"code": null,
"e": 33217,
"s": 33060,
"text": "Now, click on the Program Name child node. The Field Values dialog box appears. In the Field values dialog box, ensure that you have the following entries −"
},
{
"code": null,
"e": 33257,
"s": 33217,
"text": "Object: /ARBA/PROG\nField name: PROGRAM\n"
},
{
"code": null,
"e": 33404,
"s": 33257,
"text": "In the Value Intrvl section, enter all the transaction data report names in the From column. Save the entries and regenerate the profiles created."
},
{
"code": null,
"e": 33567,
"s": 33404,
"text": "For importing supplier data, Ariba Procurement Solution integrated with SAP downloads supplier data in the SupplierConsolidated.csv using fields in below tables −"
},
{
"code": null,
"e": 33621,
"s": 33567,
"text": "Suppliers available in the LFA1 (Vendor Master Table)"
},
{
"code": null,
"e": 33675,
"s": 33621,
"text": "Suppliers available in the LFA1 (Vendor Master Table)"
},
{
"code": null,
"e": 33735,
"s": 33675,
"text": "Suppliers that are not marked for deletion for a given PORG"
},
{
"code": null,
"e": 33795,
"s": 33735,
"text": "Suppliers that are not marked for deletion for a given PORG"
},
{
"code": null,
"e": 33859,
"s": 33795,
"text": "Suppliers that do not have a centrally imposed purchasing block"
},
{
"code": null,
"e": 33923,
"s": 33859,
"text": "Suppliers that do not have a centrally imposed purchasing block"
},
{
"code": null,
"e": 33971,
"s": 33923,
"text": "Suppliers that are not blocked for any function"
},
{
"code": null,
"e": 34019,
"s": 33971,
"text": "Suppliers that are not blocked for any function"
},
{
"code": null,
"e": 34200,
"s": 34019,
"text": "You need to ensure that you maintain the right value of SystemID and vendor fields in the table. When supplier data is imported, values for SystemID field is imported in .csv file."
},
{
"code": null,
"e": 34238,
"s": 34200,
"text": "Function Module/ARBA/VENDOR_EXPORTCSV"
},
{
"code": null,
"e": 34299,
"s": 34238,
"text": "Files − SupplierConsolidated.csvPurchaseOrgSupplierCombo.csv"
},
{
"code": null,
"e": 34607,
"s": 34299,
"text": "While maintaining supplier location data, these 2 parameters are used − /ARBA/SL_VENDOR_ADDRESS and /ARBA/SL_PARTNER_TYPE. While importing supplier location data, you must maintain at least one of these parameters in /ARBA/TVARV table. In case you do not maintain one of these parameters, it shows an error."
},
{
"code": null,
"e": 34656,
"s": 34607,
"text": "Function Module/ARBA/SUPPLIER_LOCATION_EXPORTCSV"
},
{
"code": null,
"e": 34696,
"s": 34656,
"text": "File − SupplierLocationConsolidated.csv"
},
{
"code": null,
"e": 34840,
"s": 34696,
"text": "Payment terms indicate the negotiated discount between a buying organization and supplier for a specified number of days before payment is due."
},
{
"code": null,
"e": 34883,
"s": 34840,
"text": "Function Module/ARBA/PAYMENTTERM_EXPORTCSV"
},
{
"code": null,
"e": 34919,
"s": 34883,
"text": "File − PaymentTermsConsolidated.csv"
},
{
"code": null,
"e": 35130,
"s": 34919,
"text": "Transactional data includes Purchase Order, invoice, receipts, payments and other business related information. Transactional data comes with a time stamp and a numerical value referring to one or more objects."
},
{
"code": null,
"e": 35250,
"s": 35130,
"text": "Following methods are commonly used for integrating transactional data between SAP ERP and Ariba Procurement solution −"
},
{
"code": null,
"e": 35276,
"s": 35250,
"text": "Using file channel option"
},
{
"code": null,
"e": 35302,
"s": 35276,
"text": "Using file channel option"
},
{
"code": null,
"e": 35333,
"s": 35302,
"text": "Using the web services channel"
},
{
"code": null,
"e": 35364,
"s": 35333,
"text": "Using the web services channel"
},
{
"code": null,
"e": 35392,
"s": 35364,
"text": "Using user interface option"
},
{
"code": null,
"e": 35420,
"s": 35392,
"text": "Using user interface option"
},
{
"code": null,
"e": 35460,
"s": 35420,
"text": "Using mediated connectivity integration"
},
{
"code": null,
"e": 35500,
"s": 35460,
"text": "Using mediated connectivity integration"
},
{
"code": null,
"e": 35770,
"s": 35500,
"text": "For each file channel, you have scheduled integration events. An Ariba administrator can run these events manually. An executable program code is defined and scheduled to run. The code picks csv data file from Ariba Procurement solution and exports to SAP ERP database."
},
{
"code": null,
"e": 36158,
"s": 35770,
"text": "CSV files are generated using transaction events and these are picked by data transfer tool. To move data to ERP database, SAP transports should be imported. SAP transports are a combination of SAP Programs, RFCs, and supporting structures. The SAP executable programs are used to move the exported data into SAP ERP. The BAPI executable programs help in the moving of data into SAP ERP."
},
{
"code": null,
"e": 36214,
"s": 36158,
"text": "SAP programs usually contain the following parameters −"
},
{
"code": null,
"e": 36308,
"s": 36214,
"text": "Logical File Name − This defines the logical path and the physical location of the CSV files."
},
{
"code": null,
"e": 36402,
"s": 36308,
"text": "Logical File Name − This defines the logical path and the physical location of the CSV files."
},
{
"code": null,
"e": 36483,
"s": 36402,
"text": "Directory Separator − This is the physical separator for directories in SAP ERP."
},
{
"code": null,
"e": 36564,
"s": 36483,
"text": "Directory Separator − This is the physical separator for directories in SAP ERP."
},
{
"code": null,
"e": 36643,
"s": 36564,
"text": "Encoding in response files − Encoding technique that is used UTF-8 by default."
},
{
"code": null,
"e": 36722,
"s": 36643,
"text": "Encoding in response files − Encoding technique that is used UTF-8 by default."
},
{
"code": null,
"e": 36745,
"s": 36722,
"text": "Variant − Variant Name"
},
{
"code": null,
"e": 36768,
"s": 36745,
"text": "Variant − Variant Name"
},
{
"code": null,
"e": 36795,
"s": 36768,
"text": "Partition − Partition Name"
},
{
"code": null,
"e": 36822,
"s": 36795,
"text": "Partition − Partition Name"
},
{
"code": null,
"e": 36908,
"s": 36822,
"text": "The following tables show different transactional data integration event components −"
},
{
"code": null,
"e": 37134,
"s": 36908,
"text": "The Web service method is based on the use of SOAP URLs configured by Ariba administrators. For all outbound events, a SOAP URL is generated automatically to be present in the generated WSDL according to the following logic −"
},
{
"code": null,
"e": 37212,
"s": 37134,
"text": "<IncomingHttpServerURL> / <ContextRoot> / soap / <realm name> / <event_name>\n"
},
{
"code": null,
"e": 37262,
"s": 37212,
"text": "In each WSDL, you have the following components −"
},
{
"code": null,
"e": 37345,
"s": 37262,
"text": "Import − This component is used to associate a namespace with a document location."
},
{
"code": null,
"e": 37428,
"s": 37345,
"text": "Import − This component is used to associate a namespace with a document location."
},
{
"code": null,
"e": 37530,
"s": 37428,
"text": "Types − This component is used to define user created data types, which will be used in the document."
},
{
"code": null,
"e": 37632,
"s": 37530,
"text": "Types − This component is used to define user created data types, which will be used in the document."
},
{
"code": null,
"e": 37715,
"s": 37632,
"text": "Message − This component is used to define all the parts of an individual message."
},
{
"code": null,
"e": 37798,
"s": 37715,
"text": "Message − This component is used to define all the parts of an individual message."
},
{
"code": null,
"e": 37981,
"s": 37798,
"text": "PortType − This is a container of supported operations by the web service. The operations in PortType are ordered. These operations indicate whether a message is inbound or outbound."
},
{
"code": null,
"e": 38164,
"s": 37981,
"text": "PortType − This is a container of supported operations by the web service. The operations in PortType are ordered. These operations indicate whether a message is inbound or outbound."
},
{
"code": null,
"e": 38270,
"s": 38164,
"text": "Binding − This element defines the operation to protocol mapping. (for example, http, https, MIME, etc.)."
},
{
"code": null,
"e": 38376,
"s": 38270,
"text": "Binding − This element defines the operation to protocol mapping. (for example, http, https, MIME, etc.)."
},
{
"code": null,
"e": 38517,
"s": 38376,
"text": "Service − This component is used to define the operation to address mapping and it shows the actual address the request should be forwarded."
},
{
"code": null,
"e": 38658,
"s": 38517,
"text": "Service − This component is used to define the operation to address mapping and it shows the actual address the request should be forwarded."
},
{
"code": null,
"e": 38768,
"s": 38658,
"text": "There are various transactional data integration events spread across SAP ERP and Ariba Procurement solution."
},
{
"code": null,
"e": 38841,
"s": 38768,
"text": "The following table shows example URLs for each data integration event −"
},
{
"code": null,
"e": 39181,
"s": 38841,
"text": "In Ariba Procurement Solution, buyers can also use direct connectivity option to integrate data to SAP ERP system. This feature is supported in SAP ERP 6.0 and later versions. Using this option, ERP system sends a request to Ariba Procurement Solution with the header part containing parameter details for extraction of transactional data."
},
{
"code": null,
"e": 39272,
"s": 39181,
"text": "To use this option, transport request must be downloaded and imported into SAP ERP system."
},
{
"code": null,
"e": 39368,
"s": 39272,
"text": "When you use direct connection option using user interface, following limitations are applied −"
},
{
"code": null,
"e": 39455,
"s": 39368,
"text": "No email notification while an error occurs during the transactional data integration."
},
{
"code": null,
"e": 39542,
"s": 39455,
"text": "No email notification while an error occurs during the transactional data integration."
},
{
"code": null,
"e": 39661,
"s": 39542,
"text": "Ariba administrator can see all error messages only in the runtime monitor of the SAP ERP and SAP Process integration."
},
{
"code": null,
"e": 39780,
"s": 39661,
"text": "Ariba administrator can see all error messages only in the runtime monitor of the SAP ERP and SAP Process integration."
},
{
"code": null,
"e": 39872,
"s": 39780,
"text": "When you check T-code SLGI, it does not store details of all error log in this transaction."
},
{
"code": null,
"e": 39964,
"s": 39872,
"text": "When you check T-code SLGI, it does not store details of all error log in this transaction."
},
{
"code": null,
"e": 40231,
"s": 39964,
"text": "This method uses SAP Process Integration layer with mediated connectivity option for integration of transactional data. Using SAP PI provides a secure way of integration and all certificates and key stores are created and stored in SAP Process Integration key store."
},
{
"code": null,
"e": 40418,
"s": 40231,
"text": "To use this option, transport request must be downloaded and imported into SAP ERP system. When you use direct connection option using user interface, following limitations are applied −"
},
{
"code": null,
"e": 40505,
"s": 40418,
"text": "No email notification while an error occurs during the transactional data integration."
},
{
"code": null,
"e": 40592,
"s": 40505,
"text": "No email notification while an error occurs during the transactional data integration."
},
{
"code": null,
"e": 40718,
"s": 40592,
"text": "All error messages can be seen only in the runtime monitor of the SAP ERP and SAP Process integration by Ariba administrator."
},
{
"code": null,
"e": 40844,
"s": 40718,
"text": "All error messages can be seen only in the runtime monitor of the SAP ERP and SAP Process integration by Ariba administrator."
},
{
"code": null,
"e": 40935,
"s": 40844,
"text": "When you check T-code SLGI, it does not store detail of all error log in this transaction."
},
{
"code": null,
"e": 41026,
"s": 40935,
"text": "When you check T-code SLGI, it does not store detail of all error log in this transaction."
},
{
"code": null,
"e": 41338,
"s": 41026,
"text": "To integrate Ariba Procurement solution with SAP ERP system, you must download ERP transport to your procurement solution. While importing transports, you should define a target client while adding to the import queue. Transport management system in SAP system is installed and configured by SAP administrators."
},
{
"code": null,
"e": 41649,
"s": 41338,
"text": "The sequence to install the transports is mentioned inside the “Readme.txt” file and this file is in the ZIP file that you download from connect.ariba.com. You can also import real time integration transport. However, you need to configure SAP ERP system to use real time system with your procurement solution."
},
{
"code": null,
"e": 41736,
"s": 41649,
"text": "To specify target client, you should use SAP Transport Management system, T-code: STMS"
},
{
"code": null,
"e": 42045,
"s": 41736,
"text": "Log on to the SAP system, that you want to add as a System, in client 000 and enter the transaction code → STMS. If system is not added, TMS will check configuration file DOMAIN.CFG and will prompt you to create one. Click → Select the Proposal and Save. The system will remain in ‘Waiting’ status initially."
},
{
"code": null,
"e": 42229,
"s": 42045,
"text": "To complete the task → login to the Domain Controller System → Transaction STMS → Go to Overview → Systems. You can now see that a new system is available. Go to SAP System → Approve."
},
{
"code": null,
"e": 42628,
"s": 42229,
"text": "Mapping workbooks are used to import/export data between Ariba Procurement Solution and ERP system. These mapping workbooks can be customized based on business needs. When an outbound transaction happens, data transforms from XML to cXML and is uploaded to Ariba Procurement Solution. For inbound transactions, it is reverse order – the data is transformed from cXML to XML and moved to ERP system."
},
{
"code": null,
"e": 42797,
"s": 42628,
"text": "Mapping workbooks can be downloaded from https://connect.ariba.com and you can customize the mapping of fields between XML and cXML based on your business requirements."
},
{
"code": null,
"e": 42872,
"s": 42797,
"text": "Step 1 − To download mapping workbooks, login to https://connect.ariba.com"
},
{
"code": null,
"e": 43035,
"s": 42872,
"text": "If you do not have username and password for Ariba Connect, you can contact Ariba account executive. You can use any of the below options to manage your account −"
},
{
"code": null,
"e": 43054,
"s": 43035,
"text": "Forgotten Password"
},
{
"code": null,
"e": 43063,
"s": 43054,
"text": "New User"
},
{
"code": null,
"e": 43089,
"s": 43063,
"text": "Can’t access your account"
},
{
"code": null,
"e": 43236,
"s": 43089,
"text": "Step 2 − You have to click on Home tab → Product Summary page, click Ariba Cloud Integration; this will further open Ariba Cloud Integration page."
},
{
"code": null,
"e": 43332,
"s": 43236,
"text": "Step 3 − Under the Integration Tools section, click Integration tools for Ariba Procure-to-Pay."
},
{
"code": null,
"e": 43393,
"s": 43332,
"text": "The Integration tools for Ariba Procure-to-Pay page appears."
},
{
"code": null,
"e": 43467,
"s": 43393,
"text": "Navigate to Integration Tools for SAP → Tool and click Mapping Workbooks."
},
{
"code": null,
"e": 43673,
"s": 43467,
"text": "The Mapping Workbooks for Ariba Procurement Solutions integrated with SAP for Cloud Integration X.0 page appears. Click Download and specify a location on your hard drive to download the mapping workbooks."
},
{
"code": null,
"e": 43733,
"s": 43673,
"text": "Mapping workbooks are available for download in Zip format."
},
{
"code": null,
"e": 43836,
"s": 43733,
"text": "In this chapter, we will learn how to install SAP Ariba. Consider the following to install SAP Ariba −"
},
{
"code": null,
"e": 43865,
"s": 43836,
"text": "SAP Ariba Notes Installation"
},
{
"code": null,
"e": 43896,
"s": 43865,
"text": "SAP Ariba Adapter Installation"
},
{
"code": null,
"e": 43927,
"s": 43896,
"text": "Ariba Functional Configuration"
},
{
"code": null,
"e": 43964,
"s": 43927,
"text": "SAP Ariba Web Services Configuration"
},
{
"code": null,
"e": 44012,
"s": 43964,
"text": "Customizing Adapter as per business requirement"
},
{
"code": null,
"e": 44117,
"s": 44012,
"text": "To install SAP Ariba Adapter, you need to go to support.ariba.com and login using your SID and password."
},
{
"code": null,
"e": 44294,
"s": 44117,
"text": "To download software, you need to have a DSC (Designated Support Contact) ID. New users can register on the Ariba portal. Open https://support.ariba.com → New User Registration"
},
{
"code": null,
"e": 44442,
"s": 44294,
"text": "Once you login to Ariba Portal, search for Ariba Network Adapter for SAP NetWeaver. As mentioned, Ariba Network Adapter is available only for DSCs."
},
{
"code": null,
"e": 44542,
"s": 44442,
"text": "The next step is to Import required AN adapter files (.tpz) into SAP Enterprise Service Repository."
},
{
"code": null,
"e": 44666,
"s": 44542,
"text": "You need to import the required Ariba Network product and component definitions (.zip) into System Landscape directory SLD."
},
{
"code": null,
"e": 44748,
"s": 44666,
"text": "Below are Ariba troubleshooting codes that can be used to fix any of the issues −"
},
{
"code": null,
"e": 44815,
"s": 44748,
"text": "The following message types should be used to enable integration −"
},
{
"code": null,
"e": 44839,
"s": 44815,
"text": "OrderRequest (outbound)"
},
{
"code": null,
"e": 44869,
"s": 44839,
"text": "ConfirmationRequest (inbound)"
},
{
"code": null,
"e": 44897,
"s": 44869,
"text": "ShipNoticeRequest (inbound)"
},
{
"code": null,
"e": 44927,
"s": 44897,
"text": "ServiceEntryRequest (inbound)"
},
{
"code": null,
"e": 44953,
"s": 44927,
"text": "ReceiptRequest (outbound)"
},
{
"code": null,
"e": 44984,
"s": 44953,
"text": "InvoiceDetailRequest (inbound)"
},
{
"code": null,
"e": 45028,
"s": 44984,
"text": "CopyRequest.InvoiceDetailRequest (outbound)"
},
{
"code": null,
"e": 45059,
"s": 45028,
"text": "StatusUpdateRequest (outbound)"
},
{
"code": null,
"e": 45093,
"s": 45059,
"text": "PaymentProposalRequest (outbound)"
},
{
"code": null,
"e": 45138,
"s": 45093,
"text": "CopyRequest.PaymentProposalRequest (inbound)"
},
{
"code": null,
"e": 45174,
"s": 45138,
"text": "PaymentRemittanceRequest (outbound)"
},
{
"code": null,
"e": 45222,
"s": 45174,
"text": "PaymentRemittanceStatusUpdateRequest (outbound)"
},
{
"code": null,
"e": 45416,
"s": 45222,
"text": "After the installation of SAP Ariba and the sample data load is complete, Ariba tools undergo default configuration. The default configuration contains configuration files to define parameters."
},
{
"code": null,
"e": 45461,
"s": 45416,
"text": "There are two types of configuration files −"
},
{
"code": null,
"e": 45635,
"s": 45461,
"text": "These files exist in the directory BuyerServerRoot/ariba. The files define the default Ariba Buyer configuration. You never change system files as part of an implementation."
},
{
"code": null,
"e": 45745,
"s": 45635,
"text": "These files exist in the directory BuyerServerRoot/config and these files are modified during implementation."
},
{
"code": null,
"e": 45889,
"s": 45745,
"text": "Note − To change Ariba configuration, you should modify the files in the config directory. The files in Ariba directory should not be modified."
},
{
"code": null,
"e": 46024,
"s": 45889,
"text": "Ariba buyers use different file extensions for different file types. The below table lists common file types in the Config directory −"
},
{
"code": null,
"e": 46212,
"s": 46024,
"text": "In SAP Ariba, each configuration has one parameter set applicable to all partitions. Within config/parameters.table, parameters are grouped into two types. The types are described below −"
},
{
"code": null,
"e": 46418,
"s": 46212,
"text": "These parameters are same across your configuration, at the server level. While the value of this parameter is set in the System section, it is applied to every partition that exists in your configuration."
},
{
"code": null,
"e": 46680,
"s": 46418,
"text": "The values for these parameters are different for different partitions. While a value you set for this parameter in the Application section initially applies to all partitions, however it is possible to provide different values for different partitions as well."
},
{
"code": null,
"e": 46859,
"s": 46680,
"text": "You can also create custom parameters under system or application parameter section of config/parameter.table file. By default, you don’t have any parameter under custom section."
},
{
"code": null,
"e": 47180,
"s": 46859,
"text": "You need to protect sensitive information and encrypt information in configuration files to protect it. Ariba buyer configuration files can contain sensitive information like computer names, passwords, or personal information. All these values are in plain text format and for protection, the values should be encrypted."
},
{
"code": null,
"e": 47311,
"s": 47180,
"text": "You can use aribaencrypt command and supply a string as an argument. This will update config/parameter.table with encrypted value."
},
{
"code": null,
"e": 47559,
"s": 47311,
"text": "Use aribaencrypt-key <key>. Here, key is the name of an existing parameter in Parameters.table. This will ask you to confirm action and post confirmation, the key is properly encrypted and stored in Parameters.table. No further steps are required."
},
{
"code": null,
"e": 47637,
"s": 47559,
"text": "You need to secure the data through Ariba Administrator using the following −"
},
{
"code": null,
"e": 47779,
"s": 47637,
"text": "Access to integration events and scheduled tasks should be secured from Ariba Administrator by using ExecutePermissionPull integration event."
},
{
"code": null,
"e": 47921,
"s": 47779,
"text": "Access to integration events and scheduled tasks should be secured from Ariba Administrator by using ExecutePermissionPull integration event."
},
{
"code": null,
"e": 48023,
"s": 47921,
"text": "It is also possible to implement file level security by using “EditPermissionPull” integration event."
},
{
"code": null,
"e": 48125,
"s": 48023,
"text": "It is also possible to implement file level security by using “EditPermissionPull” integration event."
},
{
"code": null,
"e": 48255,
"s": 48125,
"text": "To ensure administrator tasks are secure, you need to change workspace and task permissions in the workspace configuration files."
},
{
"code": null,
"e": 48385,
"s": 48255,
"text": "To ensure administrator tasks are secure, you need to change workspace and task permissions in the workspace configuration files."
},
{
"code": null,
"e": 48547,
"s": 48385,
"text": "You also need to secure different objects in Ariba configuration. This can be done by assigning read and edit permissions to object in ObjectPermission.csv file."
},
{
"code": null,
"e": 48636,
"s": 48547,
"text": "While using default configuration, ObjectPermission.csv file is in the below directory −"
},
{
"code": null,
"e": 48700,
"s": 48636,
"text": "config/variants/Plain/partitions/None/data/ObjectPermission.csv"
},
{
"code": null,
"e": 48754,
"s": 48700,
"text": "ObjectPermission.csv file contains the below fields −"
},
{
"code": null,
"e": 48915,
"s": 48754,
"text": "In SAP Ariba buyer configuration, BuyerServerRoot/logs contains log files. Few of the files also contain the node name from which the files have been generated."
},
{
"code": null,
"e": 49071,
"s": 48915,
"text": "The below table lists down a few common log files of the log directory. Ariba Administrator can download any of the log files using log files task option −"
},
{
"code": null,
"e": 49318,
"s": 49071,
"text": "When we compare SAP Vendor Management systems like SRM or SAP Ariba system with ServiceNow, ServiceNow is considered as an IT Service Management software which is used to transform IT services and infrastructure using single cloud based platform."
},
{
"code": null,
"e": 49546,
"s": 49318,
"text": "Service Now tool is used to automate IT Service management processes, it is primarily used for managing technology-based Service Management tasks to initiate workflows, approval tasks, and other IT Service management processed."
},
{
"code": null,
"e": 49641,
"s": 49546,
"text": "The following image shows common features which are available in Service Now Jakarta edition −"
},
{
"code": null,
"e": 49851,
"s": 49641,
"text": "When you compare SAP Ariba with Service Now, Ariba is open to all systems and all types of goods and services, and provides an option to connect to all types of suppliers and buyers on a single global network."
},
{
"code": null,
"e": 50181,
"s": 49851,
"text": "Using Ariba Network (AN), you can collaborate with the right business partners, and enhance your solution with targeted apps and extensions. When users are connected to AN, it allows you to connect to millions of suppliers and merchandisers (direct or indirect). Following are the key features provided by the SAP Ariba network −"
},
{
"code": null,
"e": 50347,
"s": 50181,
"text": "One of the key advantages of using Ariba solution is that it simplifies procurement and sourcing process with easy synchronization to SAP SRM and other ERP software."
},
{
"code": null,
"e": 50513,
"s": 50347,
"text": "One of the key advantages of using Ariba solution is that it simplifies procurement and sourcing process with easy synchronization to SAP SRM and other ERP software."
},
{
"code": null,
"e": 50624,
"s": 50513,
"text": "It enhances the experience of suppliers and buyers by creating digital transformation to supply chain process."
},
{
"code": null,
"e": 50735,
"s": 50624,
"text": "It enhances the experience of suppliers and buyers by creating digital transformation to supply chain process."
},
{
"code": null,
"e": 50879,
"s": 50735,
"text": "With cloud-based solution, SAP Ariba can be accessed from different locations with a very low initial capital cost for setting up the solution."
},
{
"code": null,
"e": 51023,
"s": 50879,
"text": "With cloud-based solution, SAP Ariba can be accessed from different locations with a very low initial capital cost for setting up the solution."
},
{
"code": null,
"e": 51208,
"s": 51023,
"text": "There is easy setup of key procurement processes – Procure to pay (integration of purchase department with Accounts payable department), Procure to Order by maintaining shopping carts."
},
{
"code": null,
"e": 51393,
"s": 51208,
"text": "There is easy setup of key procurement processes – Procure to pay (integration of purchase department with Accounts payable department), Procure to Order by maintaining shopping carts."
},
{
"code": null,
"e": 51540,
"s": 51393,
"text": "SAP Ariba enables easy transfer of master data – organization structure, suppliers and GL data to Ariba solution using optimal way of integration."
},
{
"code": null,
"e": 51687,
"s": 51540,
"text": "SAP Ariba enables easy transfer of master data – organization structure, suppliers and GL data to Ariba solution using optimal way of integration."
},
{
"code": null,
"e": 51857,
"s": 51687,
"text": "SAP Ariba offers an end-to-end automated system that removes complexity and allows buyers and suppliers to manage everything from contracts to payments all in one place."
},
{
"code": null,
"e": 52027,
"s": 51857,
"text": "SAP Ariba offers an end-to-end automated system that removes complexity and allows buyers and suppliers to manage everything from contracts to payments all in one place."
},
{
"code": null,
"e": 52322,
"s": 52027,
"text": "SAP SRM is a SAP product that facilitates the procurement of goods via a web-based platform. Organizations can procure all type of products like direct and indirect material, services and this can be integrated with SAP ERP modules and other non-SAP backend systems for accounting and planning."
},
{
"code": null,
"e": 52653,
"s": 52322,
"text": "SAP SRM allows you to optimize your procurement process to work effectively with suppliers to get long term benefits and also to perform forecasting, procurement cycle and to work with partners. You can reduce the time span and costing of procurement cycle using innovative methods to manage business processes with key suppliers."
},
{
"code": null,
"e": 52864,
"s": 52653,
"text": "SAP SRM supports the full procurement cycle, i.e., starting from source and purchase to pay through complete procurement process with suppliers and effectively managing supplier to build long-term relationship."
},
{
"code": null,
"e": 53075,
"s": 52864,
"text": "SAP SRM helps you to emphasize supplier performance management, streamline the procurement operations, put compliance with contracts and purchasing policies, and improve overall cost management and expenditure."
},
{
"code": null,
"e": 53439,
"s": 53075,
"text": "The future of SAP SRM is SAP S/4 HANA and SAP Ariba system for exceptional procurement and vendor management capabilities. When you have SAP S/4 HANA implemented, you can easily extend your procurement solution from on-premise solution to cloud and it allows to exchange information, improve visibility with great efficiency and effectiveness with your suppliers."
},
{
"code": null,
"e": 53608,
"s": 53439,
"text": "1. Ariba offers an end-to-end automated system that removes complexity and allows buyers and suppliers to manage everything from contracts to payments all in one place."
},
{
"code": null,
"e": 53785,
"s": 53608,
"text": "2. Ariba Network is one of the key components, which provides a cloud-based B2B marketplace where buyers and suppliers can find each other and do business on a single platform."
},
{
"code": null,
"e": 53967,
"s": 53785,
"text": "With use of custom and compound reports in Ariba, it is much more advanced as compared to standard reporting in an ERP system. Following report types are supported in Ariba system −"
},
{
"code": null,
"e": 53987,
"s": 53967,
"text": "Prepackaged Reports"
},
{
"code": null,
"e": 54004,
"s": 53987,
"text": "Investigate Data"
},
{
"code": null,
"e": 54019,
"s": 54004,
"text": "Custom Reports"
},
{
"code": null,
"e": 54038,
"s": 54019,
"text": "Multi-fact Reports"
},
{
"code": null,
"e": 54056,
"s": 54038,
"text": "Exporting Reports"
},
{
"code": null,
"e": 54073,
"s": 54056,
"text": "Compound Reports"
},
{
"code": null,
"e": 54141,
"s": 54073,
"text": "In SAP Ariba cloud solution, following solution areas are covered −"
},
{
"code": null,
"e": 54291,
"s": 54141,
"text": "SAP Ariba Supplier Management − It manages supplier information, lifecycle, performance, and risk all in one place and can be accessed from anywhere."
},
{
"code": null,
"e": 54441,
"s": 54291,
"text": "SAP Ariba Supplier Management − It manages supplier information, lifecycle, performance, and risk all in one place and can be accessed from anywhere."
},
{
"code": null,
"e": 54612,
"s": 54441,
"text": "SAP Ariba Strategic Sourcing − It manages sourcing, contracting, and spend analysis processes for all types of spend – direct materials, indirect materials, and services."
},
{
"code": null,
"e": 54783,
"s": 54612,
"text": "SAP Ariba Strategic Sourcing − It manages sourcing, contracting, and spend analysis processes for all types of spend – direct materials, indirect materials, and services."
},
{
"code": null,
"e": 54939,
"s": 54783,
"text": "SAP Ariba Solutions for Direct Spend − Helps to connect the people, partners, processes, and information needed to manage all design-to-deliver activities."
},
{
"code": null,
"e": 55095,
"s": 54939,
"text": "SAP Ariba Solutions for Direct Spend − Helps to connect the people, partners, processes, and information needed to manage all design-to-deliver activities."
},
{
"code": null,
"e": 55205,
"s": 55095,
"text": "SAP Ariba Procurement − Helps in achieving compliance, visibility, and control while cutting costs and risks."
},
{
"code": null,
"e": 55315,
"s": 55205,
"text": "SAP Ariba Procurement − Helps in achieving compliance, visibility, and control while cutting costs and risks."
},
{
"code": null,
"e": 55484,
"s": 55315,
"text": "SAP Ariba Financial Supply Chain − This closes the source-to-settle loop by boosting free cash flow, freeing up working capital, and delivering more bottom-line value."
},
{
"code": null,
"e": 55653,
"s": 55484,
"text": "SAP Ariba Financial Supply Chain − This closes the source-to-settle loop by boosting free cash flow, freeing up working capital, and delivering more bottom-line value."
},
{
"code": null,
"e": 56009,
"s": 55653,
"text": "SAP Ariba modules provide easy to use workflow designs that do not need customization by technical experts. It provides preconfigured workflows based on best practices that you can use right way. With the use of drag-drop functionalities, you can easily modify rules and with the use of workflow builder, users can easily build, test and deploy workflows."
},
{
"code": null,
"e": 56102,
"s": 56009,
"text": "https://www.ariba.com/solutions/solutions-overview/financial-supply-chain/invoice-management"
},
{
"code": null,
"e": 56164,
"s": 56102,
"text": "There are different configuration workflows that can be used."
},
{
"code": null,
"e": 56256,
"s": 56164,
"text": "From the same link, you can check other existing configurable workflows in Ariba solution −"
},
{
"code": null,
"e": 56334,
"s": 56256,
"text": "In this chapter, we will see the Report Types supported in the Ariba system −"
},
{
"code": null,
"e": 56354,
"s": 56334,
"text": "Prepackaged Reports"
},
{
"code": null,
"e": 56371,
"s": 56354,
"text": "Investigate Data"
},
{
"code": null,
"e": 56386,
"s": 56371,
"text": "Custom Reports"
},
{
"code": null,
"e": 56405,
"s": 56386,
"text": "Multi-fact Reports"
},
{
"code": null,
"e": 56423,
"s": 56405,
"text": "Exporting Reports"
},
{
"code": null,
"e": 56440,
"s": 56423,
"text": "Compound Reports"
},
{
"code": null,
"e": 56566,
"s": 56440,
"text": "Apart from this, if you are using SAP S/4 HANA system, it also provides different standard reports w.r.t. Procurement system."
},
{
"code": null,
"e": 56706,
"s": 56566,
"text": "There are various dashboards’ views under each Ariba module that can be customized based on the requirement and used for reporting purpose."
},
{
"code": null,
"e": 56890,
"s": 56706,
"text": "In SAP Ariba, users can also modify CSV files that pull report data, to specify report properties or permissions. Report properties can be changed using the below integration events −"
},
{
"code": null,
"e": 56989,
"s": 56890,
"text": "ReportQueryPull Integration Event − This is used to Query API queries associated with each report."
},
{
"code": null,
"e": 57088,
"s": 56989,
"text": "ReportQueryPull Integration Event − This is used to Query API queries associated with each report."
},
{
"code": null,
"e": 57220,
"s": 57088,
"text": "ReportMetaPull Integration Event − This event is used to define report visualization and appearance of each report in Ariba system."
},
{
"code": null,
"e": 57352,
"s": 57220,
"text": "ReportMetaPull Integration Event − This event is used to define report visualization and appearance of each report in Ariba system."
},
{
"code": null,
"e": 57470,
"s": 57352,
"text": "ReportPermissionMap.csv File − This defines list of reports in Ariba system and it contains one line for each report."
},
{
"code": null,
"e": 57588,
"s": 57470,
"text": "ReportPermissionMap.csv File − This defines list of reports in Ariba system and it contains one line for each report."
},
{
"code": null,
"e": 57667,
"s": 57588,
"text": "ReportColumnMeta.csv File − This is used to define column name in each report."
},
{
"code": null,
"e": 57746,
"s": 57667,
"text": "ReportColumnMeta.csv File − This is used to define column name in each report."
},
{
"code": null,
"e": 58269,
"s": 57746,
"text": "SAP S/4 HANA integration with the Ariba Network is native to SAP S/4HANA and this can be performed as part of SAP S/4HANA with guided configuration. You can navigate to “Ariba account settings” and it doesn’t require use of middleware. To meet your organization policies, you can integrate using a middleware like SAP Process Orchestration PI/PO on-premise or SAP HANA Cloud Integration HCI in the cloud. SAP also provides best practices to show you which mediated connectivity alternatives should be used for integration."
},
{
"code": null,
"e": 58355,
"s": 58269,
"text": "With the integration of SAP S/4HANA and Ariba, cloud allows the following processes −"
},
{
"code": null,
"e": 58384,
"s": 58355,
"text": "Purchase order collaboration"
},
{
"code": null,
"e": 58406,
"s": 58384,
"text": "Invoice collaboration"
},
{
"code": null,
"e": 58426,
"s": 58406,
"text": "Service procurement"
},
{
"code": null,
"e": 58446,
"s": 58426,
"text": "Discount management"
},
{
"code": null,
"e": 58454,
"s": 58446,
"text": "Payment"
},
{
"code": null,
"e": 58526,
"s": 58454,
"text": "There are three ways of connecting SAP S/4HANA with the Ariba Network −"
},
{
"code": null,
"e": 58695,
"s": 58526,
"text": "You establish a system connection between SAP S/4HANA and the Ariba Network without using middleware. Under Ariba account settings, you have direct connectivity option."
},
{
"code": null,
"e": 58805,
"s": 58695,
"text": "You establish a system connection using SAP HANA Cloud Integration between SAP S/4HANA and the Ariba Network."
},
{
"code": null,
"e": 58899,
"s": 58805,
"text": "You establish a system connection using middleware between SAP S/4HANA and the Ariba Network."
},
{
"code": null,
"e": 59103,
"s": 58899,
"text": "The SAP Process Integration design packages (TPZ files) are available on this link https://connect.ariba.com in a ZIP file. You must download the ZIP file and extract the files for your required version."
},
{
"code": null,
"e": 59174,
"s": 59103,
"text": "You can also refer to SAP Note 1991088 to know more about integration."
},
{
"code": null,
"e": 59340,
"s": 59174,
"text": "For integration between SAP S/4 HANA and Ariba Network, you should use SAP Activate and best practices. To check best practices, open URL − https://rapid.sap.com/bp/"
},
{
"code": null,
"e": 59448,
"s": 59340,
"text": "Navigate to SAP S/4HANA → Integration → SAP Best Practices for SAP S/4HANA integration with Ariba Solutions"
},
{
"code": null,
"e": 59582,
"s": 59448,
"text": "Following is the link of SAP best practices explorer to learn SAP Ariba network integration with S/4 HANA for different scope items −"
},
{
"code": null,
"e": 59646,
"s": 59582,
"text": "https://rapid.sap.com/bp/#/browse/search?q=Ariba&from=0&size=50"
},
{
"code": null,
"e": 59785,
"s": 59646,
"text": "To open any of the best practices, you can click on any link and it will show business benefits and process flow under that best practice."
},
{
"code": null,
"e": 59872,
"s": 59785,
"text": "Following are the various requirements and responsibilities of a SAP Ariba Developer −"
},
{
"code": null,
"e": 59992,
"s": 59872,
"text": "Experience of Ariba integration with backend ERP systems and 2-4 full life-cycle implementations of Ariba applications."
},
{
"code": null,
"e": 60112,
"s": 59992,
"text": "Experience of Ariba integration with backend ERP systems and 2-4 full life-cycle implementations of Ariba applications."
},
{
"code": null,
"e": 60165,
"s": 60112,
"text": "Technical knowledge of Ariba solutions and products."
},
{
"code": null,
"e": 60218,
"s": 60165,
"text": "Technical knowledge of Ariba solutions and products."
},
{
"code": null,
"e": 60892,
"s": 60218,
"text": "Ariba On Demand implementation experience, should include experience in one or more of the following areas −\n\nSAP Ariba Procurement capabilities including SAP Ariba Buying and Invoicing, SAP Ariba Guided Buying, SAP Ariba Catalog and SAP Ariba Invoice Management.\nSAP Ariba Commerce Automation, Payables and Supply Chain Collaboration using the Ariba Network.\nExperience of SAP Ariba integration with SAP S/4HANA, SAP ERP or other non-SAP backend systems.\nKnowledge of implementing SAP Notes and best practices for integration.\nKnowledge of customizing a solution as per business requirement and the ability to convert business requirements into technical specifications.\n\n"
},
{
"code": null,
"e": 61001,
"s": 60892,
"text": "Ariba On Demand implementation experience, should include experience in one or more of the following areas −"
},
{
"code": null,
"e": 61155,
"s": 61001,
"text": "SAP Ariba Procurement capabilities including SAP Ariba Buying and Invoicing, SAP Ariba Guided Buying, SAP Ariba Catalog and SAP Ariba Invoice Management."
},
{
"code": null,
"e": 61309,
"s": 61155,
"text": "SAP Ariba Procurement capabilities including SAP Ariba Buying and Invoicing, SAP Ariba Guided Buying, SAP Ariba Catalog and SAP Ariba Invoice Management."
},
{
"code": null,
"e": 61405,
"s": 61309,
"text": "SAP Ariba Commerce Automation, Payables and Supply Chain Collaboration using the Ariba Network."
},
{
"code": null,
"e": 61501,
"s": 61405,
"text": "SAP Ariba Commerce Automation, Payables and Supply Chain Collaboration using the Ariba Network."
},
{
"code": null,
"e": 61597,
"s": 61501,
"text": "Experience of SAP Ariba integration with SAP S/4HANA, SAP ERP or other non-SAP backend systems."
},
{
"code": null,
"e": 61693,
"s": 61597,
"text": "Experience of SAP Ariba integration with SAP S/4HANA, SAP ERP or other non-SAP backend systems."
},
{
"code": null,
"e": 61765,
"s": 61693,
"text": "Knowledge of implementing SAP Notes and best practices for integration."
},
{
"code": null,
"e": 61837,
"s": 61765,
"text": "Knowledge of implementing SAP Notes and best practices for integration."
},
{
"code": null,
"e": 61981,
"s": 61837,
"text": "Knowledge of customizing a solution as per business requirement and the ability to convert business requirements into technical specifications."
},
{
"code": null,
"e": 62125,
"s": 61981,
"text": "Knowledge of customizing a solution as per business requirement and the ability to convert business requirements into technical specifications."
},
{
"code": null,
"e": 62158,
"s": 62125,
"text": "\n 25 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 62172,
"s": 62158,
"text": " Sanjo Thomas"
},
{
"code": null,
"e": 62205,
"s": 62172,
"text": "\n 26 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 62217,
"s": 62205,
"text": " Neha Gupta"
},
{
"code": null,
"e": 62252,
"s": 62217,
"text": "\n 30 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 62267,
"s": 62252,
"text": " Sumit Agarwal"
},
{
"code": null,
"e": 62300,
"s": 62267,
"text": "\n 30 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 62315,
"s": 62300,
"text": " Sumit Agarwal"
},
{
"code": null,
"e": 62350,
"s": 62315,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 62362,
"s": 62350,
"text": " Neha Malik"
},
{
"code": null,
"e": 62397,
"s": 62362,
"text": "\n 13 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 62409,
"s": 62397,
"text": " Neha Malik"
},
{
"code": null,
"e": 62416,
"s": 62409,
"text": " Print"
},
{
"code": null,
"e": 62427,
"s": 62416,
"text": " Add Notes"
}
] |
Which anime is the best?. Using data visualization show how... | by Mubarak Ganiyu | Towards Data Science | Anime is a form of Japanese-made cartoon that is very popular around the world. Different anime series have been released over the past twenty years, some of which have made a massive impact in the TV culture.
Naruto is an example of one of the these influential anime series. It has the ability to make anyone who sits down to watch it for just a few minutes get absorbed by its beautiful storytelling combined with insanely action-packed scenes. Every time I still watch Naruto, I get this nostalgic feeling as I grew up watching this great work of art.
The best anime to be ever produced according to my opinion would be Attack on Titan. Watching Shingeki no Kyojin (Japanese for Attack on Titan), I saw Hajime Isayama set the pace for future anime series in terms of entertainment. The anime provides its viewers with a lot of unanswered questions, massive plot twists and action-fueled events. I can’t wait for the next season to come out next fall.
There are other incredibly made anime series such as Fullmetal Achemist: Brotherhood, Psycho-pass, Dragonball-Z, Death Note, Bleach and Hunter x Hunter. However, the question that still puzzles me is which of these anime is the best?
In order to conduct this research properly, the anime dataset was obtained from Kaggle using this link. Upon loading it on Jupyter Notebook, it was refined to include important features such as: name, type, episodes, score, rank and popularity. Below is the top five rows of the newly-formed dataset:
Using this dataset, some data analysis with visualization was carried out.
The first graph that was plotted was comparing the ratings of anime series to how popular they are.
The graph clearly shows that the anime series that have the highest ratings tend to be the most popular. Using the correlation coefficient table, the graph has a correlation coefficient of -0.85. This shows that the ratings have a negatively strong correlation with the popularity of the anime. This implies that as the ratings increase, the popularity rank of the anime gets closer to the top.
The dataset was modified to include the top 30 anime series for further analysis to find out how they fare against each other. Below is the code that was used to extract the top 30 most popular anime:
df_anime11 = df_anime1.sort_values(by = "popularity", ascending = True).reset_index()df_anime11 = df_anime11[df_anime11['popularity'] != 0.0].reset_index()df_anime11 = df_anime11.head(30)df_anime12 = df_anime11[['name', 'type', 'episodes', 'score', 'rank', 'popularity']]df_anime12
A horizontal bar chart was built to show which anime series produced the most episodes among the top 30 most popular anime series.
Naruto shippuuden is first with 500 episodes. Bleach is second with about 366 episodes. Naruto, which is also part of the Naruto series, has 220 episodes and sits in third place. Fairy Tail and Hunter x Hunter come in fourth and fifth place with 175 and 148 episodes respectively.
Another horizontal bar chart was made showcase how the top 30 most popular anime rank against one another.
The first place goes to Fullmetal Alchemist: Brotherhood with a rating of 9.24. Steins:Gate and Hunter x Hunter are second and third respectively with 9.14 and 9.12 respectively. Code Geass: Hangaku no Lelouch R2 came is fourth place with a rating of 8.94 . Cod Geass: Hangaku no Lelouch is fifth with a rating of 8.77.
My two favorite anime series, Naruto shippuuden and Shingeki no Kyojin got ratings of 8.19 and 8.48 respectively. They also both came in sixteenth and ninth place respectively.
The full version of the code that was used to conduct the research can be seen here. | [
{
"code": null,
"e": 382,
"s": 172,
"text": "Anime is a form of Japanese-made cartoon that is very popular around the world. Different anime series have been released over the past twenty years, some of which have made a massive impact in the TV culture."
},
{
"code": null,
"e": 728,
"s": 382,
"text": "Naruto is an example of one of the these influential anime series. It has the ability to make anyone who sits down to watch it for just a few minutes get absorbed by its beautiful storytelling combined with insanely action-packed scenes. Every time I still watch Naruto, I get this nostalgic feeling as I grew up watching this great work of art."
},
{
"code": null,
"e": 1127,
"s": 728,
"text": "The best anime to be ever produced according to my opinion would be Attack on Titan. Watching Shingeki no Kyojin (Japanese for Attack on Titan), I saw Hajime Isayama set the pace for future anime series in terms of entertainment. The anime provides its viewers with a lot of unanswered questions, massive plot twists and action-fueled events. I can’t wait for the next season to come out next fall."
},
{
"code": null,
"e": 1361,
"s": 1127,
"text": "There are other incredibly made anime series such as Fullmetal Achemist: Brotherhood, Psycho-pass, Dragonball-Z, Death Note, Bleach and Hunter x Hunter. However, the question that still puzzles me is which of these anime is the best?"
},
{
"code": null,
"e": 1662,
"s": 1361,
"text": "In order to conduct this research properly, the anime dataset was obtained from Kaggle using this link. Upon loading it on Jupyter Notebook, it was refined to include important features such as: name, type, episodes, score, rank and popularity. Below is the top five rows of the newly-formed dataset:"
},
{
"code": null,
"e": 1737,
"s": 1662,
"text": "Using this dataset, some data analysis with visualization was carried out."
},
{
"code": null,
"e": 1837,
"s": 1737,
"text": "The first graph that was plotted was comparing the ratings of anime series to how popular they are."
},
{
"code": null,
"e": 2232,
"s": 1837,
"text": "The graph clearly shows that the anime series that have the highest ratings tend to be the most popular. Using the correlation coefficient table, the graph has a correlation coefficient of -0.85. This shows that the ratings have a negatively strong correlation with the popularity of the anime. This implies that as the ratings increase, the popularity rank of the anime gets closer to the top."
},
{
"code": null,
"e": 2433,
"s": 2232,
"text": "The dataset was modified to include the top 30 anime series for further analysis to find out how they fare against each other. Below is the code that was used to extract the top 30 most popular anime:"
},
{
"code": null,
"e": 2715,
"s": 2433,
"text": "df_anime11 = df_anime1.sort_values(by = \"popularity\", ascending = True).reset_index()df_anime11 = df_anime11[df_anime11['popularity'] != 0.0].reset_index()df_anime11 = df_anime11.head(30)df_anime12 = df_anime11[['name', 'type', 'episodes', 'score', 'rank', 'popularity']]df_anime12"
},
{
"code": null,
"e": 2846,
"s": 2715,
"text": "A horizontal bar chart was built to show which anime series produced the most episodes among the top 30 most popular anime series."
},
{
"code": null,
"e": 3127,
"s": 2846,
"text": "Naruto shippuuden is first with 500 episodes. Bleach is second with about 366 episodes. Naruto, which is also part of the Naruto series, has 220 episodes and sits in third place. Fairy Tail and Hunter x Hunter come in fourth and fifth place with 175 and 148 episodes respectively."
},
{
"code": null,
"e": 3234,
"s": 3127,
"text": "Another horizontal bar chart was made showcase how the top 30 most popular anime rank against one another."
},
{
"code": null,
"e": 3554,
"s": 3234,
"text": "The first place goes to Fullmetal Alchemist: Brotherhood with a rating of 9.24. Steins:Gate and Hunter x Hunter are second and third respectively with 9.14 and 9.12 respectively. Code Geass: Hangaku no Lelouch R2 came is fourth place with a rating of 8.94 . Cod Geass: Hangaku no Lelouch is fifth with a rating of 8.77."
},
{
"code": null,
"e": 3731,
"s": 3554,
"text": "My two favorite anime series, Naruto shippuuden and Shingeki no Kyojin got ratings of 8.19 and 8.48 respectively. They also both came in sixteenth and ninth place respectively."
}
] |
How to access JavaScript properties? | There are three ways to access JavaScript properties −
Using dot property access: object.property
Using square brackets notation: object[‘property’]
Using object destructuring: let {property} = object
Following is the code for accessing JavaScript object properties −
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.result,
.sample {
font-size: 18px;
font-weight: 500;
color: blueviolet;
}
.sample {
color: red;
}
</style>
</head>
<body>
<h1>Access JavaScript object properties</h1>
<div><pre class="sample">{a:22,b:44}</pre></div>
<div class="result"></div>
<button class="Btn">Access</button>
<h3>Click on the above button to access object properites</h3>
<script>
let resEle = document.querySelector(".result");
let BtnEle = document.querySelector(".Btn");
let obj = { a: 22, b: 44 };
BtnEle.addEventListener("click", () => {
resEle.innerHTML += "obj.a = " + obj.a + "<br>";
resEle.innerHTML += "obj['a'] = " + obj["a"] + "<br>";
let { a } = obj;
resEle.innerHTML += "{a}=obj = " + a + "<br>";
});
</script>
</body>
</html>
On clicking the ‘Access’ button − | [
{
"code": null,
"e": 1117,
"s": 1062,
"text": "There are three ways to access JavaScript properties −"
},
{
"code": null,
"e": 1160,
"s": 1117,
"text": "Using dot property access: object.property"
},
{
"code": null,
"e": 1211,
"s": 1160,
"text": "Using square brackets notation: object[‘property’]"
},
{
"code": null,
"e": 1263,
"s": 1211,
"text": "Using object destructuring: let {property} = object"
},
{
"code": null,
"e": 1330,
"s": 1263,
"text": "Following is the code for accessing JavaScript object properties −"
},
{
"code": null,
"e": 1341,
"s": 1330,
"text": " Live Demo"
},
{
"code": null,
"e": 2384,
"s": 1341,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n<title>Document</title>\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n .result,\n .sample {\n font-size: 18px;\n font-weight: 500;\n color: blueviolet;\n }\n .sample {\n color: red;\n }\n</style>\n</head>\n<body>\n<h1>Access JavaScript object properties</h1>\n<div><pre class=\"sample\">{a:22,b:44}</pre></div>\n<div class=\"result\"></div>\n<button class=\"Btn\">Access</button>\n<h3>Click on the above button to access object properites</h3>\n<script>\n let resEle = document.querySelector(\".result\");\n let BtnEle = document.querySelector(\".Btn\");\n let obj = { a: 22, b: 44 };\n BtnEle.addEventListener(\"click\", () => {\n resEle.innerHTML += \"obj.a = \" + obj.a + \"<br>\";\n resEle.innerHTML += \"obj['a'] = \" + obj[\"a\"] + \"<br>\";\n let { a } = obj;\n resEle.innerHTML += \"{a}=obj = \" + a + \"<br>\";\n });\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2418,
"s": 2384,
"text": "On clicking the ‘Access’ button −"
}
] |
iOS - GameKit | Gamekit is a framework that provides leader board, achievements, and more features to an iOS application. In this tutorial, we will be explaining the steps involved in adding a leader board and updating the score.
Step 1 − In iTunes connect, ensure that you have a unique App ID and when we create the application update with the bundle ID and code signing in Xcode with corresponding provisioning profile.
Step 2 − Create a new application and update application information. You can know more about this in apple-add new apps documentation.
Step 3 − Setup a leader board in Manage Game Center of your application's page where add a single leaderboard and give leaderboard ID and score Type. Here we give leader board ID as tutorialsPoint.
Step 4 − The next steps are related to handling code and creating UI for our application.
Step 5 − Create a single view application and enter the bundle identifier is the identifier specified in iTunes connect.
Step 6 − Update the ViewController.xib as shown below −
Step 7 − Select your project file, then select targets and then add GameKit.framework.
Step 8 − Create IBActions for the buttons we have added.
Step 9 − Update the ViewController.h file as follows −
#import <UIKit/UIKit.h>
#import <GameKit/GameKit.h>
@interface ViewController : UIViewController
<GKLeaderboardViewControllerDelegate>
-(IBAction)updateScore:(id)sender;
-(IBAction)showLeaderBoard:(id)sender;
@end
Step 10 − Update ViewController.m as follows −
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
if([GKLocalPlayer localPlayer].authenticated == NO) {
[[GKLocalPlayer localPlayer]
authenticateWithCompletionHandler:^(NSError *error) {
NSLog(@"Error%@",error);
}];
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void) updateScore: (int64_t) score
forLeaderboardID: (NSString*) category {
GKScore *scoreObj = [[GKScore alloc]
initWithCategory:category];
scoreObj.value = score;
scoreObj.context = 0;
[scoreObj reportScoreWithCompletionHandler:^(NSError *error) {
// Completion code can be added here
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:nil message:@"Score Updated Succesfully"
delegate:self cancelButtonTitle:@"Ok" otherButtonTitles: nil];
[alert show];
}];
}
-(IBAction)updateScore:(id)sender {
[self updateScore:200 forLeaderboardID:@"tutorialsPoint"];
}
-(IBAction)showLeaderBoard:(id)sender {
GKLeaderboardViewController *leaderboardViewController =
[[GKLeaderboardViewController alloc] init];
leaderboardViewController.leaderboardDelegate = self;
[self presentModalViewController:
leaderboardViewController animated:YES];
}
#pragma mark - Gamekit delegates
- (void)leaderboardViewControllerDidFinish:
(GKLeaderboardViewController *)viewController {
[self dismissModalViewControllerAnimated:YES];
}
@end
When we run the application, we'll get the following output −
When we click "show leader board", we would get a screen similar to the following −
When we click "update score", the score will be updated to our leader board and we will get an alert as shown below −
23 Lectures
1.5 hours
Ashish Sharma
9 Lectures
1 hours
Abhilash Nelson
14 Lectures
1.5 hours
Abhilash Nelson
15 Lectures
1.5 hours
Abhilash Nelson
10 Lectures
1 hours
Abhilash Nelson
69 Lectures
4 hours
Frahaan Hussain
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2305,
"s": 2091,
"text": "Gamekit is a framework that provides leader board, achievements, and more features to an iOS application. In this tutorial, we will be explaining the steps involved in adding a leader board and updating the score."
},
{
"code": null,
"e": 2498,
"s": 2305,
"text": "Step 1 − In iTunes connect, ensure that you have a unique App ID and when we create the application update with the bundle ID and code signing in Xcode with corresponding provisioning profile."
},
{
"code": null,
"e": 2634,
"s": 2498,
"text": "Step 2 − Create a new application and update application information. You can know more about this in apple-add new apps documentation."
},
{
"code": null,
"e": 2832,
"s": 2634,
"text": "Step 3 − Setup a leader board in Manage Game Center of your application's page where add a single leaderboard and give leaderboard ID and score Type. Here we give leader board ID as tutorialsPoint."
},
{
"code": null,
"e": 2922,
"s": 2832,
"text": "Step 4 − The next steps are related to handling code and creating UI for our application."
},
{
"code": null,
"e": 3043,
"s": 2922,
"text": "Step 5 − Create a single view application and enter the bundle identifier is the identifier specified in iTunes connect."
},
{
"code": null,
"e": 3099,
"s": 3043,
"text": "Step 6 − Update the ViewController.xib as shown below −"
},
{
"code": null,
"e": 3186,
"s": 3099,
"text": "Step 7 − Select your project file, then select targets and then add GameKit.framework."
},
{
"code": null,
"e": 3244,
"s": 3186,
"text": "Step 8 − Create IBActions for the buttons we have added. "
},
{
"code": null,
"e": 3299,
"s": 3244,
"text": "Step 9 − Update the ViewController.h file as follows −"
},
{
"code": null,
"e": 3516,
"s": 3299,
"text": "#import <UIKit/UIKit.h>\n#import <GameKit/GameKit.h>\n\n@interface ViewController : UIViewController\n<GKLeaderboardViewControllerDelegate>\n\n-(IBAction)updateScore:(id)sender;\n-(IBAction)showLeaderBoard:(id)sender;\n\n@end"
},
{
"code": null,
"e": 3563,
"s": 3516,
"text": "Step 10 − Update ViewController.m as follows −"
},
{
"code": null,
"e": 5139,
"s": 3563,
"text": "#import \"ViewController.h\"\n\n@interface ViewController ()\n@end\n\n@implementation ViewController\n\n- (void)viewDidLoad {\n [super viewDidLoad];\n if([GKLocalPlayer localPlayer].authenticated == NO) {\n [[GKLocalPlayer localPlayer] \n authenticateWithCompletionHandler:^(NSError *error) {\n NSLog(@\"Error%@\",error);\n }];\n } \n}\n\n- (void)didReceiveMemoryWarning {\n [super didReceiveMemoryWarning];\n // Dispose of any resources that can be recreated.\n}\n\n- (void) updateScore: (int64_t) score \n forLeaderboardID: (NSString*) category {\n GKScore *scoreObj = [[GKScore alloc]\n initWithCategory:category];\n scoreObj.value = score;\n scoreObj.context = 0;\n \n [scoreObj reportScoreWithCompletionHandler:^(NSError *error) {\n // Completion code can be added here\n UIAlertView *alert = [[UIAlertView alloc]\n initWithTitle:nil message:@\"Score Updated Succesfully\" \n delegate:self cancelButtonTitle:@\"Ok\" otherButtonTitles: nil];\n [alert show];\n }];\n}\n\n-(IBAction)updateScore:(id)sender {\n [self updateScore:200 forLeaderboardID:@\"tutorialsPoint\"];\n}\n\n-(IBAction)showLeaderBoard:(id)sender {\n GKLeaderboardViewController *leaderboardViewController =\n [[GKLeaderboardViewController alloc] init];\n leaderboardViewController.leaderboardDelegate = self;\n [self presentModalViewController:\n leaderboardViewController animated:YES];\n}\n\n#pragma mark - Gamekit delegates\n- (void)leaderboardViewControllerDidFinish:\n(GKLeaderboardViewController *)viewController {\n [self dismissModalViewControllerAnimated:YES];\n}\n@end"
},
{
"code": null,
"e": 5201,
"s": 5139,
"text": "When we run the application, we'll get the following output −"
},
{
"code": null,
"e": 5285,
"s": 5201,
"text": "When we click \"show leader board\", we would get a screen similar to the following −"
},
{
"code": null,
"e": 5403,
"s": 5285,
"text": "When we click \"update score\", the score will be updated to our leader board and we will get an alert as shown below −"
},
{
"code": null,
"e": 5438,
"s": 5403,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5453,
"s": 5438,
"text": " Ashish Sharma"
},
{
"code": null,
"e": 5485,
"s": 5453,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5502,
"s": 5485,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 5537,
"s": 5502,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5554,
"s": 5537,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 5589,
"s": 5554,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5606,
"s": 5589,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 5639,
"s": 5606,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5656,
"s": 5639,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 5689,
"s": 5656,
"text": "\n 69 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 5706,
"s": 5689,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5713,
"s": 5706,
"text": " Print"
},
{
"code": null,
"e": 5724,
"s": 5713,
"text": " Add Notes"
}
] |
Anonymous object in Java | Yes, we can use a method on an object without assigning it to any reference.
Live Demo
public class Tester {
public String message(){
return "Hello World!";
}
public static void main(String[] args) {
System.out.println(new Tester().message());
}
}
Here we've used message() method on new Tester() which is an anonymous object. | [
{
"code": null,
"e": 1140,
"s": 1062,
"text": "Yes, we can use a method on an object without assigning it to any reference. "
},
{
"code": null,
"e": 1150,
"s": 1140,
"text": "Live Demo"
},
{
"code": null,
"e": 1339,
"s": 1150,
"text": "public class Tester {\n public String message(){\n return \"Hello World!\";\n }\n public static void main(String[] args) {\n System.out.println(new Tester().message());\n }\n } "
},
{
"code": null,
"e": 1418,
"s": 1339,
"text": "Here we've used message() method on new Tester() which is an anonymous object."
}
] |
F# - Bitwise Operators | Bitwise operators work on bits and perform bit-by-bit operation. The truth tables for &&& (bitwise AND), ||| (bitwise OR), and ^^^ (bitwise exclusive OR) are as follows −
Assume if A = 60; and B = 13; now in binary format they will be as follows −
A = 0011 1100
B = 0000 1101
A&&&B = 0000 1100
A|||B = 0011 1101
A^^^B = 0011 0001
~~~A = 1100 0011
The Bitwise operators supported by F# language are listed in the following table. Assume variable A holds 60 and variable B holds 13, then −
let a : int32 = 60 // 60 = 0011 1100
let b : int32 = 13 // 13 = 0000 1101
let mutable c : int32 = 0
c <- a &&& b // 12 = 0000 1100
printfn "Line 1 - Value of c is %d" c
c <- a ||| b // 61 = 0011 1101
printfn "Line 2 - Value of c is %d" c
c <- a ^^^ b // 49 = 0011 0001
printfn "Line 3 - Value of c is %d" c
c <- ~~~a // -61 = 1100 0011
printfn "Line 4 - Value of c is %d" c
c <- a <<< 2 // 240 = 1111 0000
printfn "Line 5 - Value of c is %d" c
c <- a >>> 2 // 15 = 0000 1111
printfn "Line 6 - Value of c is %d" c
When you compile and execute the program, it yields the following output −
Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is 49
Line 4 - Value of c is 49
Line 5 - Value of c is 240
Line 6 - Value of c is 15
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2332,
"s": 2161,
"text": "Bitwise operators work on bits and perform bit-by-bit operation. The truth tables for &&& (bitwise AND), ||| (bitwise OR), and ^^^ (bitwise exclusive OR) are as follows −"
},
{
"code": null,
"e": 2409,
"s": 2332,
"text": "Assume if A = 60; and B = 13; now in binary format they will be as follows −"
},
{
"code": null,
"e": 2423,
"s": 2409,
"text": "A = 0011 1100"
},
{
"code": null,
"e": 2437,
"s": 2423,
"text": "B = 0000 1101"
},
{
"code": null,
"e": 2455,
"s": 2437,
"text": "A&&&B = 0000 1100"
},
{
"code": null,
"e": 2473,
"s": 2455,
"text": "A|||B = 0011 1101"
},
{
"code": null,
"e": 2491,
"s": 2473,
"text": "A^^^B = 0011 0001"
},
{
"code": null,
"e": 2508,
"s": 2491,
"text": "~~~A = 1100 0011"
},
{
"code": null,
"e": 2649,
"s": 2508,
"text": "The Bitwise operators supported by F# language are listed in the following table. Assume variable A holds 60 and variable B holds 13, then −"
},
{
"code": null,
"e": 3168,
"s": 2649,
"text": "let a : int32 = 60 // 60 = 0011 1100\nlet b : int32 = 13 // 13 = 0000 1101\nlet mutable c : int32 = 0\n\nc <- a &&& b // 12 = 0000 1100\nprintfn \"Line 1 - Value of c is %d\" c\n\nc <- a ||| b // 61 = 0011 1101\nprintfn \"Line 2 - Value of c is %d\" c\n\nc <- a ^^^ b // 49 = 0011 0001\nprintfn \"Line 3 - Value of c is %d\" c\n\nc <- ~~~a // -61 = 1100 0011\nprintfn \"Line 4 - Value of c is %d\" c\n\nc <- a <<< 2 // 240 = 1111 0000\nprintfn \"Line 5 - Value of c is %d\" c\n\nc <- a >>> 2 // 15 = 0000 1111\nprintfn \"Line 6 - Value of c is %d\" c"
},
{
"code": null,
"e": 3243,
"s": 3168,
"text": "When you compile and execute the program, it yields the following output −"
},
{
"code": null,
"e": 3401,
"s": 3243,
"text": "Line 1 - Value of c is 12\nLine 2 - Value of c is 61\nLine 3 - Value of c is 49\nLine 4 - Value of c is 49\nLine 5 - Value of c is 240\nLine 6 - Value of c is 15\n"
},
{
"code": null,
"e": 3408,
"s": 3401,
"text": " Print"
},
{
"code": null,
"e": 3419,
"s": 3408,
"text": " Add Notes"
}
] |
Downcasting in Java | Yes, a variable can be downcast to its lower range substitute by casting. It may lead to data loss although. See the example below −
Live Demo
public class Tester {
public static void main(String[] args) {
int a = 300;
byte b = (byte)a;
System.out.println(b);
}
}
It will print output as
44 | [
{
"code": null,
"e": 1195,
"s": 1062,
"text": "Yes, a variable can be downcast to its lower range substitute by casting. It may lead to data loss although. See the example below −"
},
{
"code": null,
"e": 1206,
"s": 1195,
"text": " Live Demo"
},
{
"code": null,
"e": 1351,
"s": 1206,
"text": "public class Tester {\n public static void main(String[] args) {\n int a = 300;\n byte b = (byte)a;\n System.out.println(b);\n }\n}"
},
{
"code": null,
"e": 1375,
"s": 1351,
"text": "It will print output as"
},
{
"code": null,
"e": 1378,
"s": 1375,
"text": "44"
}
] |
XSD - Complex Empty Element | Complex Empty Element can only have attribute, but no content. See the following example −
<student rollno = "393" />
We can declare Complex Empty elements using the following methods −
Define a complex type element "StudentType" and then create element student of type "StudentType".
<xs:complexType name = "StudentType">
<xs:attribute name = 'rollno' type = 'xs:positiveInteger'/>
</xs:complexType>
<xs:element name = 'student' type = 'StudentType' />
Define an element of complexType with complexContent. ComplexContent specifies that the content of the element is to be restricted.
<xs:element name = "student">
<xs:complexType>
<xs:complexContent>
<xs:restriction base = "xs:integer">
<xs:attribute name = "rollno" type = "xs:positiveInteger"/>
</xs:restriction>
</xs:complexContent>
</xs:complexType>
</xs:element>
Define an element of complexType with required attribute element only.
<xs:element name = "student">
<xs:complexType>
<xs:attribute name = "rollno" type = "xs:positiveInteger"/>
</xs:complexType>
</xs:element>
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 1795,
"s": 1704,
"text": "Complex Empty Element can only have attribute, but no content. See the following example −"
},
{
"code": null,
"e": 1823,
"s": 1795,
"text": "<student rollno = \"393\" />\n"
},
{
"code": null,
"e": 1891,
"s": 1823,
"text": "We can declare Complex Empty elements using the following methods −"
},
{
"code": null,
"e": 1990,
"s": 1891,
"text": "Define a complex type element \"StudentType\" and then create element student of type \"StudentType\"."
},
{
"code": null,
"e": 2170,
"s": 1990,
"text": "<xs:complexType name = \"StudentType\">\n <xs:attribute name = 'rollno' type = 'xs:positiveInteger'/> \n</xs:complexType>\n\n<xs:element name = 'student' type = 'StudentType' />\t\t\t "
},
{
"code": null,
"e": 2302,
"s": 2170,
"text": "Define an element of complexType with complexContent. ComplexContent specifies that the content of the element is to be restricted."
},
{
"code": null,
"e": 2588,
"s": 2302,
"text": "<xs:element name = \"student\">\n <xs:complexType>\n <xs:complexContent>\n <xs:restriction base = \"xs:integer\">\n <xs:attribute name = \"rollno\" type = \"xs:positiveInteger\"/>\n </xs:restriction>\n </xs:complexContent>\n </xs:complexType>\n</xs:element>\t\t "
},
{
"code": null,
"e": 2659,
"s": 2588,
"text": "Define an element of complexType with required attribute element only."
},
{
"code": null,
"e": 2810,
"s": 2659,
"text": "<xs:element name = \"student\">\n <xs:complexType>\n <xs:attribute name = \"rollno\" type = \"xs:positiveInteger\"/>\n </xs:complexType>\n</xs:element>"
},
{
"code": null,
"e": 2817,
"s": 2810,
"text": " Print"
},
{
"code": null,
"e": 2828,
"s": 2817,
"text": " Add Notes"
}
] |
Bootstrap Navigation Bar | A navigation bar is a navigation header that is placed at the top of the
page:
Home
Page 1
Page 2
Page 3
With Bootstrap, a navigation bar can extend or collapse, depending on the
screen size.
A standard navigation bar is created with <nav class="navbar navbar-default">.
The following example shows how to add a navigation bar to the top of the page:
Note: All of the examples on this page will show a navigation bar that takes up
too much space on small screens (however, the navigation bar will be on one single
line on large screens - because Bootstrap is responsive). This problem (with the
small screens) will be
solved in the last example on this page.
If you don't like the style of the default navigation bar, Bootstrap provides an alternative,
black navbar:
Home
Page 1
Page 2
Page 3
Just change the .navbar-default class into .navbar-inverse:
Home
Page 1
Page 1-1
Page 1-2
Page 1-3
Page 1-1
Page 1-2
Page 1-3
Page 2
Page 3
Navigation bars can also hold dropdown menus.
The following example adds a dropdown menu for the "Page 1"
button:
Home
Page 1
Page 2
Sign Up
Login
The .navbar-right class is used to right-align navigation bar buttons.
In the following example we insert a "Sign Up" button and a "Login" button to
the right in the navigation bar. We also add a glyphicon on each of the two new
buttons:
Home
Link
Link
To add buttons inside the navbar, add the .navbar-btn class on a Bootstrap
button:
Home
Page 1
Page 2
To add form elements inside the navbar, add the .navbar-form class to a form element and add an input(s). Note that we have added a .form-group class to the div container holding the input. This adds proper padding if you have more than one inputs (you will learn more about this in the Forms chapter).
You can also use the .input-group and .input-group-addon classes to attach an icon or help text next to the input field. You will learn more about these classes in the Bootstrap Inputs chapter.
Home
Page 1
Page 2
Link
Link
Some text
Use the .navbar-text class to vertical align any elements inside the navbar that are not links (ensures proper padding
and text color).
The navigation bar can also be fixed at the top or at the bottom of the page.
A fixed navigation bar stays visible in a fixed position (top or bottom)
independent of the page scroll.
Link
Link
A fixed navigation bar stays visible in a fixed position (top or bottom) independent of the page scroll.
The .navbar-fixed-top class makes the navigation bar fixed at
the top:
The .navbar-fixed-bottom class makes the navigation bar stay at
the bottom:
The navigation bar often takes up too much space on a small screen.
We should hide the navigation bar; and only show it when it is needed.
In the following example the navigation bar is replaced by a button
in the top right corner. Only when the button is clicked, the navigation bar will be
displayed:
Link
Link
Link
Click on the button in the top right corner to reveal the navigation links.
Add the required class names to create a default Navigation Bar.
<nav class="">
<div class="container-fluid">
<ul class="nav navbar-nav">
<li><a href="#">Page 1</a></li>
<li><a href="#">Page 2</a></li>
<li><a href="#">Page 3</a></li>
</ul>
</div>
</nav>
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:
help@w3schools.com
Your message has been sent to W3Schools. | [
{
"code": null,
"e": 80,
"s": 0,
"text": "A navigation bar is a navigation header that is placed at the top of the \npage:"
},
{
"code": null,
"e": 85,
"s": 80,
"text": "Home"
},
{
"code": null,
"e": 92,
"s": 85,
"text": "Page 1"
},
{
"code": null,
"e": 99,
"s": 92,
"text": "Page 2"
},
{
"code": null,
"e": 106,
"s": 99,
"text": "Page 3"
},
{
"code": null,
"e": 194,
"s": 106,
"text": "With Bootstrap, a navigation bar can extend or collapse, depending on the \nscreen size."
},
{
"code": null,
"e": 273,
"s": 194,
"text": "A standard navigation bar is created with <nav class=\"navbar navbar-default\">."
},
{
"code": null,
"e": 353,
"s": 273,
"text": "The following example shows how to add a navigation bar to the top of the page:"
},
{
"code": null,
"e": 665,
"s": 353,
"text": "Note: All of the examples on this page will show a navigation bar that takes up \ntoo much space on small screens (however, the navigation bar will be on one single \nline on large screens - because Bootstrap is responsive). This problem (with the \nsmall screens) will be \nsolved in the last example on this page."
},
{
"code": null,
"e": 774,
"s": 665,
"text": "If you don't like the style of the default navigation bar, Bootstrap provides an alternative, \nblack navbar:"
},
{
"code": null,
"e": 779,
"s": 774,
"text": "Home"
},
{
"code": null,
"e": 786,
"s": 779,
"text": "Page 1"
},
{
"code": null,
"e": 793,
"s": 786,
"text": "Page 2"
},
{
"code": null,
"e": 800,
"s": 793,
"text": "Page 3"
},
{
"code": null,
"e": 860,
"s": 800,
"text": "Just change the .navbar-default class into .navbar-inverse:"
},
{
"code": null,
"e": 865,
"s": 860,
"text": "Home"
},
{
"code": null,
"e": 903,
"s": 865,
"text": "Page 1 \n\nPage 1-1\nPage 1-2\nPage 1-3\n\n"
},
{
"code": null,
"e": 912,
"s": 903,
"text": "Page 1-1"
},
{
"code": null,
"e": 921,
"s": 912,
"text": "Page 1-2"
},
{
"code": null,
"e": 930,
"s": 921,
"text": "Page 1-3"
},
{
"code": null,
"e": 937,
"s": 930,
"text": "Page 2"
},
{
"code": null,
"e": 944,
"s": 937,
"text": "Page 3"
},
{
"code": null,
"e": 990,
"s": 944,
"text": "Navigation bars can also hold dropdown menus."
},
{
"code": null,
"e": 1059,
"s": 990,
"text": "The following example adds a dropdown menu for the \"Page 1\" \nbutton:"
},
{
"code": null,
"e": 1064,
"s": 1059,
"text": "Home"
},
{
"code": null,
"e": 1071,
"s": 1064,
"text": "Page 1"
},
{
"code": null,
"e": 1078,
"s": 1071,
"text": "Page 2"
},
{
"code": null,
"e": 1087,
"s": 1078,
"text": " Sign Up"
},
{
"code": null,
"e": 1094,
"s": 1087,
"text": " Login"
},
{
"code": null,
"e": 1166,
"s": 1094,
"text": "The .navbar-right class is used to right-align navigation bar buttons. "
},
{
"code": null,
"e": 1335,
"s": 1166,
"text": "In the following example we insert a \"Sign Up\" button and a \"Login\" button to \nthe right in the navigation bar. We also add a glyphicon on each of the two new \nbuttons:"
},
{
"code": null,
"e": 1340,
"s": 1335,
"text": "Home"
},
{
"code": null,
"e": 1345,
"s": 1340,
"text": "Link"
},
{
"code": null,
"e": 1350,
"s": 1345,
"text": "Link"
},
{
"code": null,
"e": 1434,
"s": 1350,
"text": "To add buttons inside the navbar, add the .navbar-btn class on a Bootstrap \nbutton:"
},
{
"code": null,
"e": 1439,
"s": 1434,
"text": "Home"
},
{
"code": null,
"e": 1446,
"s": 1439,
"text": "Page 1"
},
{
"code": null,
"e": 1453,
"s": 1446,
"text": "Page 2"
},
{
"code": null,
"e": 1756,
"s": 1453,
"text": "To add form elements inside the navbar, add the .navbar-form class to a form element and add an input(s). Note that we have added a .form-group class to the div container holding the input. This adds proper padding if you have more than one inputs (you will learn more about this in the Forms chapter)."
},
{
"code": null,
"e": 1950,
"s": 1756,
"text": "You can also use the .input-group and .input-group-addon classes to attach an icon or help text next to the input field. You will learn more about these classes in the Bootstrap Inputs chapter."
},
{
"code": null,
"e": 1955,
"s": 1950,
"text": "Home"
},
{
"code": null,
"e": 1962,
"s": 1955,
"text": "Page 1"
},
{
"code": null,
"e": 1969,
"s": 1962,
"text": "Page 2"
},
{
"code": null,
"e": 1974,
"s": 1969,
"text": "Link"
},
{
"code": null,
"e": 1979,
"s": 1974,
"text": "Link"
},
{
"code": null,
"e": 1989,
"s": 1979,
"text": "Some text"
},
{
"code": null,
"e": 2126,
"s": 1989,
"text": "Use the .navbar-text class to vertical align any elements inside the navbar that are not links (ensures proper padding \nand text color)."
},
{
"code": null,
"e": 2204,
"s": 2126,
"text": "The navigation bar can also be fixed at the top or at the bottom of the page."
},
{
"code": null,
"e": 2310,
"s": 2204,
"text": "A fixed navigation bar stays visible in a fixed position (top or bottom) \nindependent of the page scroll."
},
{
"code": null,
"e": 2317,
"s": 2310,
"text": "\nLink\n"
},
{
"code": null,
"e": 2324,
"s": 2317,
"text": "\nLink\n"
},
{
"code": null,
"e": 2429,
"s": 2324,
"text": "A fixed navigation bar stays visible in a fixed position (top or bottom) independent of the page scroll."
},
{
"code": null,
"e": 2501,
"s": 2429,
"text": "The .navbar-fixed-top class makes the navigation bar fixed at \nthe top:"
},
{
"code": null,
"e": 2578,
"s": 2501,
"text": "The .navbar-fixed-bottom class makes the navigation bar stay at \nthe bottom:"
},
{
"code": null,
"e": 2646,
"s": 2578,
"text": "The navigation bar often takes up too much space on a small screen."
},
{
"code": null,
"e": 2717,
"s": 2646,
"text": "We should hide the navigation bar; and only show it when it is needed."
},
{
"code": null,
"e": 2883,
"s": 2717,
"text": "In the following example the navigation bar is replaced by a button \nin the top right corner. Only when the button is clicked, the navigation bar will be \ndisplayed:"
},
{
"code": null,
"e": 2890,
"s": 2883,
"text": "\nLink\n"
},
{
"code": null,
"e": 2897,
"s": 2890,
"text": "\nLink\n"
},
{
"code": null,
"e": 2904,
"s": 2897,
"text": "\nLink\n"
},
{
"code": null,
"e": 2980,
"s": 2904,
"text": "Click on the button in the top right corner to reveal the navigation links."
},
{
"code": null,
"e": 3045,
"s": 2980,
"text": "Add the required class names to create a default Navigation Bar."
},
{
"code": null,
"e": 3265,
"s": 3045,
"text": "<nav class=\"\">\n <div class=\"container-fluid\">\n <ul class=\"nav navbar-nav\">\n <li><a href=\"#\">Page 1</a></li>\n <li><a href=\"#\">Page 2</a></li>\n <li><a href=\"#\">Page 3</a></li>\n </ul>\n </div>\n</nav>\n"
},
{
"code": null,
"e": 3284,
"s": 3265,
"text": "Start the Exercise"
},
{
"code": null,
"e": 3317,
"s": 3284,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 3359,
"s": 3317,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 3466,
"s": 3359,
"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": 3485,
"s": 3466,
"text": "help@w3schools.com"
}
] |
Get a list of a particular column values of a Pandas DataFrame - GeeksforGeeks | 28 Jul, 2020
In this article, we’ll see how to get all values of a column in a pandas dataframe in the form of a list. This can be very useful in many situations, suppose we have to get marks of all the students in a particular subject, get phone numbers of all employees, etc. Let’s see how we can achieve this with the help of some examples.
Example 1: We can have all values of a column in a list, by using the tolist() method.
Syntax: Series.tolist().
Return type: Converted series into List.
Code:
Python3
# import pandas libraeyimport pandas as pd # dictionarydict = {'Name': ['Martha', 'Tim', 'Rob', 'Georgia'], 'Marks': [87, 91, 97, 95]} # create a dataframe objectdf = pd.DataFrame(dict) # show the dataframeprint(df) # list of values of 'Marks' columnmarks_list = df['Marks'].tolist() # show the listprint(marks_list)
Output:
Example 2: We’ll see how we can get the values of all columns in separate lists.
Code:
Python3
# import pandas libraryimport pandas as pd # dictionarydict = {'Name': ['Martha', 'Tim', 'Rob', 'Georgia'], 'Marks': [87, 91, 97, 95]} # create a dataframe objectdf = pd.DataFrame(dict) # show the dataframeprint(df) # iterating over and calling # tolist() method for # each columnfor i in list(df): # show the list of values print(df[i].tolist())
Output:
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists | [
{
"code": null,
"e": 24990,
"s": 24962,
"text": "\n28 Jul, 2020"
},
{
"code": null,
"e": 25321,
"s": 24990,
"text": "In this article, we’ll see how to get all values of a column in a pandas dataframe in the form of a list. This can be very useful in many situations, suppose we have to get marks of all the students in a particular subject, get phone numbers of all employees, etc. Let’s see how we can achieve this with the help of some examples."
},
{
"code": null,
"e": 25408,
"s": 25321,
"text": "Example 1: We can have all values of a column in a list, by using the tolist() method."
},
{
"code": null,
"e": 25433,
"s": 25408,
"text": "Syntax: Series.tolist()."
},
{
"code": null,
"e": 25474,
"s": 25433,
"text": "Return type: Converted series into List."
},
{
"code": null,
"e": 25480,
"s": 25474,
"text": "Code:"
},
{
"code": null,
"e": 25488,
"s": 25480,
"text": "Python3"
},
{
"code": "# import pandas libraeyimport pandas as pd # dictionarydict = {'Name': ['Martha', 'Tim', 'Rob', 'Georgia'], 'Marks': [87, 91, 97, 95]} # create a dataframe objectdf = pd.DataFrame(dict) # show the dataframeprint(df) # list of values of 'Marks' columnmarks_list = df['Marks'].tolist() # show the listprint(marks_list)",
"e": 25851,
"s": 25488,
"text": null
},
{
"code": null,
"e": 25859,
"s": 25851,
"text": "Output:"
},
{
"code": null,
"e": 25940,
"s": 25859,
"text": "Example 2: We’ll see how we can get the values of all columns in separate lists."
},
{
"code": null,
"e": 25946,
"s": 25940,
"text": "Code:"
},
{
"code": null,
"e": 25954,
"s": 25946,
"text": "Python3"
},
{
"code": "# import pandas libraryimport pandas as pd # dictionarydict = {'Name': ['Martha', 'Tim', 'Rob', 'Georgia'], 'Marks': [87, 91, 97, 95]} # create a dataframe objectdf = pd.DataFrame(dict) # show the dataframeprint(df) # iterating over and calling # tolist() method for # each columnfor i in list(df): # show the list of values print(df[i].tolist())",
"e": 26357,
"s": 25954,
"text": null
},
{
"code": null,
"e": 26365,
"s": 26357,
"text": "Output:"
},
{
"code": null,
"e": 26389,
"s": 26365,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 26403,
"s": 26389,
"text": "Python-pandas"
},
{
"code": null,
"e": 26410,
"s": 26403,
"text": "Python"
},
{
"code": null,
"e": 26508,
"s": 26410,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26517,
"s": 26508,
"text": "Comments"
},
{
"code": null,
"e": 26530,
"s": 26517,
"text": "Old Comments"
},
{
"code": null,
"e": 26548,
"s": 26530,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26583,
"s": 26548,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26605,
"s": 26583,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26637,
"s": 26605,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26667,
"s": 26637,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 26709,
"s": 26667,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26735,
"s": 26709,
"text": "Python String | replace()"
},
{
"code": null,
"e": 26778,
"s": 26735,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 26822,
"s": 26778,
"text": "Reading and Writing to text files in Python"
}
] |
How to use distinct and count in Android sqlite? | Before getting into example, we should know what sqlite data base in android is. SQLite is an open source SQL database that stores data to a text file on a device. Android comes in with built in SQLite database implementation. SQLite supports all the relational database features. In order to access this database, you don't need to establish any kind of connections for it like JDBC, ODBC etc.
This example demonstrate about How to use distinct and count t in Android sqlite
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">
<EditText
android:id="@+id/name"
android:layout_width="match_parent"
android:hint="Enter Name"
android:layout_height="wrap_content" />
<EditText
android:id="@+id/salary"
android:layout_width="match_parent"
android:inputType="numberDecimal"
android:hint="Enter Salary"
android:layout_height="wrap_content" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button
android:id="@+id/save"
android:text="Save"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/refresh"
android:text="Refresh"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/udate"
android:text="Update"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/Delete"
android:text="DeleteALL"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
</LinearLayout>
In the above code, we have taken name and salary as Edit text, when user click on save button it will store the data into sqlite data base. Click on refresh button to get the listview.
Step 3 − Add the following code to src/MainActivity.java
package com.example.andy.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
Button save, refresh;
EditText name, salary;
ArrayAdapter arrayAdapter;
private ListView listView;
@Override
protected void onCreate(Bundle readdInstanceState) {
super.onCreate(readdInstanceState);
setContentView(R.layout.activity_main);
final DatabaseHelper helper = new DatabaseHelper(this);
final ArrayList array_list = helper.getAllCotacts();
name = findViewById(R.id.name);
salary = findViewById(R.id.salary);
listView = findViewById(R.id.listView);
arrayAdapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, array_list);
listView.setAdapter(arrayAdapter);
findViewById(R.id.Delete).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (helper.delete()) {
Toast.makeText(MainActivity.this, "Deleted", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "NOT Deleted", Toast.LENGTH_LONG).show();
}
}
});
findViewById(R.id.udate).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!name.getText().toString().isEmpty() && !salary.getText().toString().isEmpty()) {
if (helper.update(name.getText().toString(), salary.getText().toString())) {
Toast.makeText(MainActivity.this, "Updated", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "NOT Updated",
Toast.LENGTH_LONG).show();
}
} else {
name.setError("Enter NAME");
salary.setError("Enter Salary");
}
}
});
findViewById(R.id.refresh).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
array_list.clear();
array_list.addAll(helper.getAllCotacts());
arrayAdapter.notifyDataSetChanged();
listView.invalidateViews();
listView.refreshDrawableState();
}
});
findViewById(R.id.save).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!name.getText().toString().isEmpty() && !salary.getText().toString().isEmpty()) {
if (helper.insert(name.getText().toString(), salary.getText().toString())) {
Toast.makeText(MainActivity.this, "Inserted", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "NOT Inserted", Toast.LENGTH_LONG).show();
}
} else {
name.setError("Enter NAME");
salary.setError("Enter Salary");
}
}
});
}
}
Step 4 − Add the following code to src/ DatabaseHelper.java
package com.example.andy.myapplication;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "salaryDatabase9";
public static final String CONTACTS_TABLE_NAME = "SalaryDetails";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 2);
}
@Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(
"create table " + CONTACTS_TABLE_NAME + "(id INTEGER PRIMARY KEY, name text,salary float,datetime default current_timestamp)"
);
} catch (SQLiteException e) {
try {
throw new IOException(e);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + CONTACTS_TABLE_NAME);
onCreate(db);
}
public boolean insert(String s, String s1) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", s);
contentValues.put("salary", s1);
db.replace(CONTACTS_TABLE_NAME, null, contentValues);
return true;
}
public ArrayList getAllCotacts() {
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<String> array_list = new ArrayList<String>();
Cursor res = db.rawQuery("select (count(distinct name)) as countRecords from " + CONTACTS_TABLE_NAME, null);
res.moveToFirst();
while (res.isAfterLast() == false) {
if ((res != null) && (res.getCount() > 0))
array_list.add(res.getString(res.getColumnIndex("countRecords")));
res.moveToNext();
}
return array_list;
}
public boolean update(String s, String s1) {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("UPDATE " + CONTACTS_TABLE_NAME + " SET name = " + "'" + s + "', " + "salary = " + "'" + s1 + "'");
return true;
}
public boolean delete() {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE from " + CONTACTS_TABLE_NAME);
return true;
}
}
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, It is showing non repeated records count as 2.
Click here to download the project code | [
{
"code": null,
"e": 1457,
"s": 1062,
"text": "Before getting into example, we should know what sqlite data base in android is. SQLite is an open source SQL database that stores data to a text file on a device. Android comes in with built in SQLite database implementation. SQLite supports all the relational database features. In order to access this database, you don't need to establish any kind of connections for it like JDBC, ODBC etc."
},
{
"code": null,
"e": 1538,
"s": 1457,
"text": "This example demonstrate about How to use distinct and count t in Android sqlite"
},
{
"code": null,
"e": 1667,
"s": 1538,
"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": 1732,
"s": 1667,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 3387,
"s": 1732,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\"\n android:orientation=\"vertical\">\n <EditText\n android:id=\"@+id/name\"\n android:layout_width=\"match_parent\"\n android:hint=\"Enter Name\"\n android:layout_height=\"wrap_content\" />\n <EditText\n android:id=\"@+id/salary\"\n android:layout_width=\"match_parent\"\n android:inputType=\"numberDecimal\"\n android:hint=\"Enter Salary\"\n android:layout_height=\"wrap_content\" />\n <LinearLayout\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\">\n <Button\n android:id=\"@+id/save\"\n android:text=\"Save\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\" />\n <Button\n android:id=\"@+id/refresh\"\n android:text=\"Refresh\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\" />\n <Button\n android:id=\"@+id/udate\"\n android:text=\"Update\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\" />\n <Button\n android:id=\"@+id/Delete\"\n android:text=\"DeleteALL\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\" />\n </LinearLayout>\n\n <ListView\n android:id=\"@+id/listView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\">\n </ListView>\n</LinearLayout>"
},
{
"code": null,
"e": 3572,
"s": 3387,
"text": "In the above code, we have taken name and salary as Edit text, when user click on save button it will store the data into sqlite data base. Click on refresh button to get the listview."
},
{
"code": null,
"e": 3629,
"s": 3572,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 6894,
"s": 3629,
"text": "package com.example.andy.myapplication;\n\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.ListView;\nimport android.widget.Toast;\n\nimport java.util.ArrayList;\n\npublic class MainActivity extends AppCompatActivity {\n Button save, refresh;\n EditText name, salary;\n ArrayAdapter arrayAdapter;\n private ListView listView;\n\n @Override\n protected void onCreate(Bundle readdInstanceState) {\n super.onCreate(readdInstanceState);\n setContentView(R.layout.activity_main);\n final DatabaseHelper helper = new DatabaseHelper(this);\n final ArrayList array_list = helper.getAllCotacts();\n name = findViewById(R.id.name);\n salary = findViewById(R.id.salary);\n listView = findViewById(R.id.listView);\n arrayAdapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, array_list);\n listView.setAdapter(arrayAdapter);\n findViewById(R.id.Delete).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if (helper.delete()) {\n Toast.makeText(MainActivity.this, \"Deleted\", Toast.LENGTH_LONG).show();\n } else {\n Toast.makeText(MainActivity.this, \"NOT Deleted\", Toast.LENGTH_LONG).show();\n }\n }\n });\n findViewById(R.id.udate).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if (!name.getText().toString().isEmpty() && !salary.getText().toString().isEmpty()) {\n if (helper.update(name.getText().toString(), salary.getText().toString())) {\n Toast.makeText(MainActivity.this, \"Updated\", Toast.LENGTH_LONG).show();\n } else {\n Toast.makeText(MainActivity.this, \"NOT Updated\",\n Toast.LENGTH_LONG).show();\n }\n } else {\n name.setError(\"Enter NAME\");\n salary.setError(\"Enter Salary\");\n }\n }\n });\n\n findViewById(R.id.refresh).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n array_list.clear();\n array_list.addAll(helper.getAllCotacts());\n arrayAdapter.notifyDataSetChanged();\n listView.invalidateViews();\n listView.refreshDrawableState();\n }\n });\n\n findViewById(R.id.save).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if (!name.getText().toString().isEmpty() && !salary.getText().toString().isEmpty()) {\n if (helper.insert(name.getText().toString(), salary.getText().toString())) {\n Toast.makeText(MainActivity.this, \"Inserted\", Toast.LENGTH_LONG).show();\n } else {\n Toast.makeText(MainActivity.this, \"NOT Inserted\", Toast.LENGTH_LONG).show();\n }\n } else {\n name.setError(\"Enter NAME\");\n salary.setError(\"Enter Salary\");\n }\n }\n });\n }\n}"
},
{
"code": null,
"e": 6954,
"s": 6894,
"text": "Step 4 − Add the following code to src/ DatabaseHelper.java"
},
{
"code": null,
"e": 9528,
"s": 6954,
"text": "package com.example.andy.myapplication;\n\nimport android.content.ContentValues;\nimport android.content.Context;\nimport android.database.Cursor;\nimport android.database.sqlite.SQLiteDatabase;\nimport android.database.sqlite.SQLiteException;\nimport android.database.sqlite.SQLiteOpenHelper;\nimport java.io.IOException;\nimport java.security.MessageDigest;\nimport java.security.NoSuchAlgorithmException;\nimport java.util.ArrayList;\n\nclass DatabaseHelper extends SQLiteOpenHelper {\n public static final String DATABASE_NAME = \"salaryDatabase9\";\n public static final String CONTACTS_TABLE_NAME = \"SalaryDetails\";\n\n public DatabaseHelper(Context context) {\n super(context, DATABASE_NAME, null, 2);\n }\n\n @Override\n public void onCreate(SQLiteDatabase db) {\n try {\n db.execSQL(\n \"create table \" + CONTACTS_TABLE_NAME + \"(id INTEGER PRIMARY KEY, name text,salary float,datetime default current_timestamp)\"\n );\n } catch (SQLiteException e) {\n try {\n throw new IOException(e);\n } catch (IOException e1) {\n e1.printStackTrace();\n }\n }\n }\n\n @Override\n public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {\n db.execSQL(\"DROP TABLE IF EXISTS \" + CONTACTS_TABLE_NAME);\n onCreate(db);\n }\n public boolean insert(String s, String s1) {\n SQLiteDatabase db = this.getWritableDatabase();\n ContentValues contentValues = new ContentValues();\n contentValues.put(\"name\", s);\n contentValues.put(\"salary\", s1);\n db.replace(CONTACTS_TABLE_NAME, null, contentValues);\n return true;\n }\n public ArrayList getAllCotacts() {\n SQLiteDatabase db = this.getReadableDatabase();\n ArrayList<String> array_list = new ArrayList<String>();\n Cursor res = db.rawQuery(\"select (count(distinct name)) as countRecords from \" + CONTACTS_TABLE_NAME, null);\n res.moveToFirst();\n while (res.isAfterLast() == false) {\n if ((res != null) && (res.getCount() > 0))\n array_list.add(res.getString(res.getColumnIndex(\"countRecords\")));\n res.moveToNext();\n }\n return array_list;\n }\n public boolean update(String s, String s1) {\n SQLiteDatabase db = this.getWritableDatabase();\n db.execSQL(\"UPDATE \" + CONTACTS_TABLE_NAME + \" SET name = \" + \"'\" + s + \"', \" + \"salary = \" + \"'\" + s1 + \"'\");\n return true;\n }\n public boolean delete() {\n SQLiteDatabase db = this.getWritableDatabase();\n db.execSQL(\"DELETE from \" + CONTACTS_TABLE_NAME);\n return true;\n }\n}"
},
{
"code": null,
"e": 9875,
"s": 9528,
"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": 9943,
"s": 9875,
"text": "In the above result, It is showing non repeated records count as 2."
},
{
"code": null,
"e": 9983,
"s": 9943,
"text": "Click here to download the project code"
}
] |
How Do Machines Learn?. Machine Learning Concept Explained for... | by Ali Masri | Towards Data Science | Recently, there has been a lot of fuss about the word Learning. We always hear about machine learning, deep learning, learning algorithms, etc. But what does this really mean? Did scientists find a way to create a brain-like component and implement it inside machines? Is it just a marketing word used to sell software and services? Are machines going to take over the world? Or what on earth is this about?
Well... do not worry, we are still not there... yet! In this article I will introduce what learning really is, and how scientists teach computers to achieve human-like tasks, or in some cases, even outperform humans. This article is completely technical-free. It is written so that anyone from any domain will be able to grasp the idea. Therefore, the concept will be explained in an oversimplified way. Other concept-heavy topics will be discussed in future articles.
Before learning took place, problem-solving tasks relied on writing algorithms. An algorithm is simply a set of rules that takes an input and returns an output as a solution for the problem.
Consider the following: Given a list of numbers, you are asked to sort them in an increasing order. This problem is solved by algorithms. In fact, there are a lot of algorithms to solve this task. They work by taking the list, applying some rules and manipulations, and returning the list in a sorted way. This problem and other similar ones were “somehow” easy for computer scientists. They only had to think and come up with an algorithm to solve a given task.
On the other hand, some problems were not so easy to solve by algorithms. People started to ask more from computers. They wanted the machine to have super abilities of solving very hard tasks. Tasks that scientists completely had no idea how to program. For example: How is it possible to write an algorithm, that takes an image of an animal and outputs the type of it? This is a very easy task for humans, but solving it with algorithms is a very complex mission if not impossible. Humans know how to classify animal photos, but they do not know how to describe the steps they take to reach the answer. Here an important question arises. How to solve problems that even humans do not know how to describe?
Learning comes to the rescue! Humans learn from experience and so do machines.
Imagine a room with a nice fireplace and a small child playing around. The child’s mind is completely fresh and has no idea what a fireplace is. He always wants to explore and learn stuff. He sees a red flame, for him it is something new, fascinating, and interesting to investigate. In his mind, its like let us go and touch it! Unfortunately, here comes the pain, and the child learns from the harmful experience not to touch fire in the future. Here I emphasize on experience, because this is what learning is about.
The idea behind learning is very simple and intuitive. To make a computer learn a task, we give it a set of questions followed by an answer. Note that we do not know how to describe the steps to go from a question to an answer, so we assign this task to our poor buddy — the machine. This is one category of learning named: Supervised Learning. Example: consider a program that takes an image and answers whether it contains a cat or not. The way of teaching this program is by giving it a lot of images labeled as “is cat” or “is not a cat”. The machine’s responsibility is to learn a way to go from an input to a label. How? we will see an example later.
There are other categories such as Unsupervised Learning where we do not give the answer to the questions, and the model has to find a way to find it. There is Reinforcement Learning which is like the one used in video games where the model learns to reach a high score by choosing the best actions and learning from bad ones. In order to keep this article simple, I will not get into details, but I guess you got the general idea.
It is time to solve the mystery and know the magic behind learning. We will illustrate the idea with a very simple problem. Let us say you want to start a new career in selling old cars. Unfortunately, your experience is very limited in this domain making it difficult to assign prices.
To solve this issue, you go around and collect the following information from a fellow car dealer:
horsepower,fuel type,miles per gallon (mpg)number of doors,and most importantly the selling price.
horsepower,
fuel type,
miles per gallon (mpg)
number of doors,
and most importantly the selling price.
This is considered as your experience or background knowledge, and your goal is to learn from it.
For the sake of simplicity, we will take the mpg first, and we will add the other features later. Now, let us start thinking. The price has to have a relation with the mpg. Let us draw a graph that shows the variation of price with respect to mpg:
The graph shows that the more the mpg, the cheaper is the car. Maybe this is because cars with more mpgs are more economic, thus less expensive than the strong cars.
Now we have a base solution, when a new car with similar mpg comes, we simply assign the same price as before. But, what if we got new car with an unseen value? Here is the main goal behind learning, we want to learn how the values are calculated...
To do so, we start by suggesting a possible calculation model. We propose that there is a linear relationship between the two. This relationship can be described as a straight line as shown in the image below:
We use this line as our reference, when we get a new value we map it to the line and get our price. For example: when we get a car with 40 mpg we assume that the price is around 6000$. Fair enough...
But how to find this straight line? A straight line is represented with the following equation:
price = a + b * mpg
We know the price and the mpg from our dataset, but what are a and b?In simple words, a and b are the parameters of the straight line. Different values of a and b mean different straight lines.
The best line is the one that better fits the data points. Therefore, the most important question is how to choose the best values of a and b to get the best fitting line? Why this question is so important? Well, because this is all what a machine has to learn... This is the very core of every learning model.
The process is like tuning the keys of a guitar. We start by rotating the different keys until we get the perfect tone.
In our example it goes like this... We ask the machine to try different values for a and b, then compare the price we got with our previously known data. e.g. we know from our data, when mpg = 30, the price =1390. We calculate the predicted price for all the prices, and compare them with the actual one.
If the prices for a given a and b differ a lot, we change a and b to reach a better estimate. We keep going like this until the model finds the best settings. Fortunately, there are some algorithms that speed up and reduce the search space for finding the best parameters e.g. Gradient Descent.
Fitting a straight line with a single feature is not that hard. It is like a blind person on a mountain, searching for a ball down the hill. But consider adding the other features:
price = a + b * miles + c * horsepower + d * fuel type + e * number of doors
Here we are no more in a 2-dimensional space, and our minds are not even able to imagine the situation. All of this and we are still using a linear representation for our model. What about more complex models? e.g. fit a polynomial line instead of a straight line. More complex models require fitting a huge number of parameters. The learning process in this case, will take a lot of computations and time. Well, how complex we need to define our model? This completely depends on the data, and the experience of the machine learning engineer.
I hope this article solved the mystery behind learning. Learning is all about discovering the best parameter values (a, b, c ...) for a given model. These values enable the model to output good results based on previous.
Machine learning is now possible due to the advances in computer hardware, and the drop in their prices. There are a lot of machine learning models. They differ with their level of complexity, and the tasks they are able to solve. The one we introduced in this article is called Linear Regression, one of the most simple — yet very powerful — algorithms.
If you enjoyed this article, I would appreciate it if you hit the clap button 👏 so it could be spread to others. You can also follow me on Twitter, Facebook, email me directly or find me on LinkedIn. | [
{
"code": null,
"e": 579,
"s": 171,
"text": "Recently, there has been a lot of fuss about the word Learning. We always hear about machine learning, deep learning, learning algorithms, etc. But what does this really mean? Did scientists find a way to create a brain-like component and implement it inside machines? Is it just a marketing word used to sell software and services? Are machines going to take over the world? Or what on earth is this about?"
},
{
"code": null,
"e": 1048,
"s": 579,
"text": "Well... do not worry, we are still not there... yet! In this article I will introduce what learning really is, and how scientists teach computers to achieve human-like tasks, or in some cases, even outperform humans. This article is completely technical-free. It is written so that anyone from any domain will be able to grasp the idea. Therefore, the concept will be explained in an oversimplified way. Other concept-heavy topics will be discussed in future articles."
},
{
"code": null,
"e": 1239,
"s": 1048,
"text": "Before learning took place, problem-solving tasks relied on writing algorithms. An algorithm is simply a set of rules that takes an input and returns an output as a solution for the problem."
},
{
"code": null,
"e": 1702,
"s": 1239,
"text": "Consider the following: Given a list of numbers, you are asked to sort them in an increasing order. This problem is solved by algorithms. In fact, there are a lot of algorithms to solve this task. They work by taking the list, applying some rules and manipulations, and returning the list in a sorted way. This problem and other similar ones were “somehow” easy for computer scientists. They only had to think and come up with an algorithm to solve a given task."
},
{
"code": null,
"e": 2409,
"s": 1702,
"text": "On the other hand, some problems were not so easy to solve by algorithms. People started to ask more from computers. They wanted the machine to have super abilities of solving very hard tasks. Tasks that scientists completely had no idea how to program. For example: How is it possible to write an algorithm, that takes an image of an animal and outputs the type of it? This is a very easy task for humans, but solving it with algorithms is a very complex mission if not impossible. Humans know how to classify animal photos, but they do not know how to describe the steps they take to reach the answer. Here an important question arises. How to solve problems that even humans do not know how to describe?"
},
{
"code": null,
"e": 2488,
"s": 2409,
"text": "Learning comes to the rescue! Humans learn from experience and so do machines."
},
{
"code": null,
"e": 3008,
"s": 2488,
"text": "Imagine a room with a nice fireplace and a small child playing around. The child’s mind is completely fresh and has no idea what a fireplace is. He always wants to explore and learn stuff. He sees a red flame, for him it is something new, fascinating, and interesting to investigate. In his mind, its like let us go and touch it! Unfortunately, here comes the pain, and the child learns from the harmful experience not to touch fire in the future. Here I emphasize on experience, because this is what learning is about."
},
{
"code": null,
"e": 3665,
"s": 3008,
"text": "The idea behind learning is very simple and intuitive. To make a computer learn a task, we give it a set of questions followed by an answer. Note that we do not know how to describe the steps to go from a question to an answer, so we assign this task to our poor buddy — the machine. This is one category of learning named: Supervised Learning. Example: consider a program that takes an image and answers whether it contains a cat or not. The way of teaching this program is by giving it a lot of images labeled as “is cat” or “is not a cat”. The machine’s responsibility is to learn a way to go from an input to a label. How? we will see an example later."
},
{
"code": null,
"e": 4097,
"s": 3665,
"text": "There are other categories such as Unsupervised Learning where we do not give the answer to the questions, and the model has to find a way to find it. There is Reinforcement Learning which is like the one used in video games where the model learns to reach a high score by choosing the best actions and learning from bad ones. In order to keep this article simple, I will not get into details, but I guess you got the general idea."
},
{
"code": null,
"e": 4384,
"s": 4097,
"text": "It is time to solve the mystery and know the magic behind learning. We will illustrate the idea with a very simple problem. Let us say you want to start a new career in selling old cars. Unfortunately, your experience is very limited in this domain making it difficult to assign prices."
},
{
"code": null,
"e": 4483,
"s": 4384,
"text": "To solve this issue, you go around and collect the following information from a fellow car dealer:"
},
{
"code": null,
"e": 4582,
"s": 4483,
"text": "horsepower,fuel type,miles per gallon (mpg)number of doors,and most importantly the selling price."
},
{
"code": null,
"e": 4594,
"s": 4582,
"text": "horsepower,"
},
{
"code": null,
"e": 4605,
"s": 4594,
"text": "fuel type,"
},
{
"code": null,
"e": 4628,
"s": 4605,
"text": "miles per gallon (mpg)"
},
{
"code": null,
"e": 4645,
"s": 4628,
"text": "number of doors,"
},
{
"code": null,
"e": 4685,
"s": 4645,
"text": "and most importantly the selling price."
},
{
"code": null,
"e": 4783,
"s": 4685,
"text": "This is considered as your experience or background knowledge, and your goal is to learn from it."
},
{
"code": null,
"e": 5031,
"s": 4783,
"text": "For the sake of simplicity, we will take the mpg first, and we will add the other features later. Now, let us start thinking. The price has to have a relation with the mpg. Let us draw a graph that shows the variation of price with respect to mpg:"
},
{
"code": null,
"e": 5197,
"s": 5031,
"text": "The graph shows that the more the mpg, the cheaper is the car. Maybe this is because cars with more mpgs are more economic, thus less expensive than the strong cars."
},
{
"code": null,
"e": 5447,
"s": 5197,
"text": "Now we have a base solution, when a new car with similar mpg comes, we simply assign the same price as before. But, what if we got new car with an unseen value? Here is the main goal behind learning, we want to learn how the values are calculated..."
},
{
"code": null,
"e": 5657,
"s": 5447,
"text": "To do so, we start by suggesting a possible calculation model. We propose that there is a linear relationship between the two. This relationship can be described as a straight line as shown in the image below:"
},
{
"code": null,
"e": 5857,
"s": 5657,
"text": "We use this line as our reference, when we get a new value we map it to the line and get our price. For example: when we get a car with 40 mpg we assume that the price is around 6000$. Fair enough..."
},
{
"code": null,
"e": 5953,
"s": 5857,
"text": "But how to find this straight line? A straight line is represented with the following equation:"
},
{
"code": null,
"e": 5973,
"s": 5953,
"text": "price = a + b * mpg"
},
{
"code": null,
"e": 6167,
"s": 5973,
"text": "We know the price and the mpg from our dataset, but what are a and b?In simple words, a and b are the parameters of the straight line. Different values of a and b mean different straight lines."
},
{
"code": null,
"e": 6478,
"s": 6167,
"text": "The best line is the one that better fits the data points. Therefore, the most important question is how to choose the best values of a and b to get the best fitting line? Why this question is so important? Well, because this is all what a machine has to learn... This is the very core of every learning model."
},
{
"code": null,
"e": 6598,
"s": 6478,
"text": "The process is like tuning the keys of a guitar. We start by rotating the different keys until we get the perfect tone."
},
{
"code": null,
"e": 6903,
"s": 6598,
"text": "In our example it goes like this... We ask the machine to try different values for a and b, then compare the price we got with our previously known data. e.g. we know from our data, when mpg = 30, the price =1390. We calculate the predicted price for all the prices, and compare them with the actual one."
},
{
"code": null,
"e": 7198,
"s": 6903,
"text": "If the prices for a given a and b differ a lot, we change a and b to reach a better estimate. We keep going like this until the model finds the best settings. Fortunately, there are some algorithms that speed up and reduce the search space for finding the best parameters e.g. Gradient Descent."
},
{
"code": null,
"e": 7379,
"s": 7198,
"text": "Fitting a straight line with a single feature is not that hard. It is like a blind person on a mountain, searching for a ball down the hill. But consider adding the other features:"
},
{
"code": null,
"e": 7456,
"s": 7379,
"text": "price = a + b * miles + c * horsepower + d * fuel type + e * number of doors"
},
{
"code": null,
"e": 8000,
"s": 7456,
"text": "Here we are no more in a 2-dimensional space, and our minds are not even able to imagine the situation. All of this and we are still using a linear representation for our model. What about more complex models? e.g. fit a polynomial line instead of a straight line. More complex models require fitting a huge number of parameters. The learning process in this case, will take a lot of computations and time. Well, how complex we need to define our model? This completely depends on the data, and the experience of the machine learning engineer."
},
{
"code": null,
"e": 8221,
"s": 8000,
"text": "I hope this article solved the mystery behind learning. Learning is all about discovering the best parameter values (a, b, c ...) for a given model. These values enable the model to output good results based on previous."
},
{
"code": null,
"e": 8576,
"s": 8221,
"text": "Machine learning is now possible due to the advances in computer hardware, and the drop in their prices. There are a lot of machine learning models. They differ with their level of complexity, and the tasks they are able to solve. The one we introduced in this article is called Linear Regression, one of the most simple — yet very powerful — algorithms."
}
] |
C# Aggregate() method | The Aggregate() method applies an accumulator function over a sequence.
The following is our array −
string[] arr = { "DemoOne", "DemoTwo", "DemoThree", "DemoFour"};
Now use the Aggregate() method. We have set the ssed value as “DemoFive” for comparison.
string res = arr.AsQueryable().Aggregate("DemoFive", (longest, next) => next.Length > longest.Length ? next : longest,str => str.ToLower());
Here, the resultant string should have more number of characters than the initial seed value i.e. “DemoFive”.
Live Demo
using System;
using System.Linq;
class Demo {
static void Main() {
string[] arr = { "DemoOne", "DemoTwo", "DemoThree", "DemoFour"};
string res = arr.AsQueryable().Aggregate("DemoFive", (longest, next) => next.Length > longest.Length ? next : longest,str => str.ToLower());
Console.WriteLine("The string with more number of characters: {0}", res);
}
}
The string with more number of characters: demothree | [
{
"code": null,
"e": 1134,
"s": 1062,
"text": "The Aggregate() method applies an accumulator function over a sequence."
},
{
"code": null,
"e": 1163,
"s": 1134,
"text": "The following is our array −"
},
{
"code": null,
"e": 1228,
"s": 1163,
"text": "string[] arr = { \"DemoOne\", \"DemoTwo\", \"DemoThree\", \"DemoFour\"};"
},
{
"code": null,
"e": 1317,
"s": 1228,
"text": "Now use the Aggregate() method. We have set the ssed value as “DemoFive” for comparison."
},
{
"code": null,
"e": 1458,
"s": 1317,
"text": "string res = arr.AsQueryable().Aggregate(\"DemoFive\", (longest, next) => next.Length > longest.Length ? next : longest,str => str.ToLower());"
},
{
"code": null,
"e": 1568,
"s": 1458,
"text": "Here, the resultant string should have more number of characters than the initial seed value i.e. “DemoFive”."
},
{
"code": null,
"e": 1579,
"s": 1568,
"text": " Live Demo"
},
{
"code": null,
"e": 1960,
"s": 1579,
"text": "using System;\nusing System.Linq;\nclass Demo {\n static void Main() {\n string[] arr = { \"DemoOne\", \"DemoTwo\", \"DemoThree\", \"DemoFour\"};\n string res = arr.AsQueryable().Aggregate(\"DemoFive\", (longest, next) => next.Length > longest.Length ? next : longest,str => str.ToLower());\n Console.WriteLine(\"The string with more number of characters: {0}\", res);\n }\n}"
},
{
"code": null,
"e": 2013,
"s": 1960,
"text": "The string with more number of characters: demothree"
}
] |
Linear Diophantine Equations | Practice | GeeksforGeeks | A Diophantine equation is a polynomial equation, usually in two or more unknowns, such that only the integral solutions are required. An Integral solution is a solution such that all the unknown variables take only integer values.
Given three integers A, B, C representing a linear equation of the form: Ax + By = C. Determine if the equation has a solution such that x and y are both integral values.
Example 1:
Input:
A = 3
B = 6
C = 9
Output:
1
Explanation:
It is possible to
write A, B, C in the
for 3 + 6 = 9
Example 2:
Input:
A = 4
B = 2
C = 3
Output:
0
Explanation:
It is not possible to
represent A, B, C in
Diophantine equation form.
Your Task:
You don't need to read input or print anything. Your task is to complete the function isPossible() which takes three integer values A, B, C as input parameters and returns 1 if the solution for x and y exist otherwise return 0.
Expected Time Complexity: O(log N)
Expected Space Complexity: O(1)
Constraints:
1 <= A,B,C <= 105
0
msbritogabriella3 months ago
solution in C++ with two lines
`
int isPossible(int A, int B, int C){
// code here
return C % gcd(A, B) == 0 ? 1 : 0;
}
int gcd(int A, int B){
return B == 0 ? A : gcd(B, A % B);
}
+1
badgujarsachin835 months ago
int gcd(int a, int b)
{
// Everything divides 0
if (a == 0)
return b;
if (b == 0)
return a;
// base case
if (a == b)
return a;
// a is greater
if (a > b)
return gcd(a-b, b);
return gcd(a, b-a);
}
int isPossible(int A, int B, int C){
// code here
if(C%gcd(A,B)==0){
return 1;
}else{
return 0;
}
}
0
Firoz Thakur2 years ago
Firoz Thakur
int isPossible(int A, int B, int C){ // code here if(C%__gcd(A,B)==0) return 1; else return 0;
}
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": 469,
"s": 238,
"text": "A Diophantine equation is a polynomial equation, usually in two or more unknowns, such that only the integral solutions are required. An Integral solution is a solution such that all the unknown variables take only integer values."
},
{
"code": null,
"e": 642,
"s": 469,
"text": "Given three integers A, B, C representing a linear equation of the form: Ax + By = C. Determine if the equation has a solution such that x and y are both integral values.\n "
},
{
"code": null,
"e": 653,
"s": 642,
"text": "Example 1:"
},
{
"code": null,
"e": 758,
"s": 653,
"text": "Input: \nA = 3\nB = 6\nC = 9 \nOutput: \n1 \nExplanation:\nIt is possible to\nwrite A, B, C in the\nfor 3 + 6 = 9"
},
{
"code": null,
"e": 769,
"s": 758,
"text": "Example 2:"
},
{
"code": null,
"e": 892,
"s": 769,
"text": "Input: \nA = 4\nB = 2\nC = 3\nOutput: \n0 \nExplanation:\nIt is not possible to\nrepresent A, B, C in \nDiophantine equation form.\n"
},
{
"code": null,
"e": 1134,
"s": 892,
"text": "\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function isPossible() which takes three integer values A, B, C as input parameters and returns 1 if the solution for x and y exist otherwise return 0.\n "
},
{
"code": null,
"e": 1203,
"s": 1134,
"text": "Expected Time Complexity: O(log N)\nExpected Space Complexity: O(1)\n "
},
{
"code": null,
"e": 1234,
"s": 1203,
"text": "Constraints:\n1 <= A,B,C <= 105"
},
{
"code": null,
"e": 1236,
"s": 1234,
"text": "0"
},
{
"code": null,
"e": 1265,
"s": 1236,
"text": "msbritogabriella3 months ago"
},
{
"code": null,
"e": 1296,
"s": 1265,
"text": "solution in C++ with two lines"
},
{
"code": null,
"e": 1475,
"s": 1296,
"text": "`\nint isPossible(int A, int B, int C){\n // code here\n return C % gcd(A, B) == 0 ? 1 : 0;\n }\n int gcd(int A, int B){\n return B == 0 ? A : gcd(B, A % B);\n }"
},
{
"code": null,
"e": 1478,
"s": 1475,
"text": "+1"
},
{
"code": null,
"e": 1507,
"s": 1478,
"text": "badgujarsachin835 months ago"
},
{
"code": null,
"e": 1935,
"s": 1507,
"text": "int gcd(int a, int b)\n{\n // Everything divides 0\n if (a == 0)\n return b;\n if (b == 0)\n return a;\n \n // base case\n if (a == b)\n return a;\n \n // a is greater\n if (a > b)\n return gcd(a-b, b);\n return gcd(a, b-a);\n}\n int isPossible(int A, int B, int C){\n // code here\n if(C%gcd(A,B)==0){\n return 1;\n }else{\n return 0;\n }\n }"
},
{
"code": null,
"e": 1937,
"s": 1935,
"text": "0"
},
{
"code": null,
"e": 1961,
"s": 1937,
"text": "Firoz Thakur2 years ago"
},
{
"code": null,
"e": 1974,
"s": 1961,
"text": "Firoz Thakur"
},
{
"code": null,
"e": 2090,
"s": 1974,
"text": "int isPossible(int A, int B, int C){ // code here if(C%__gcd(A,B)==0) return 1; else return 0;"
},
{
"code": null,
"e": 2096,
"s": 2090,
"text": " }"
},
{
"code": null,
"e": 2242,
"s": 2096,
"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": 2278,
"s": 2242,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 2288,
"s": 2278,
"text": "\nProblem\n"
},
{
"code": null,
"e": 2298,
"s": 2288,
"text": "\nContest\n"
},
{
"code": null,
"e": 2361,
"s": 2298,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 2509,
"s": 2361,
"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": 2717,
"s": 2509,
"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": 2823,
"s": 2717,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Hide Bootstrap Modal | The .modal(“hide”) method hides the modal on button click.
Firstly, generate the modal and display it −
$("#newModal").modal("show");
After that, use the modal(“hide”) method on a button to hide the modal on button click −
$("#button1").click(function(){
$("#newModal").modal("hide");
});
Let us see an example of the modal(‘hide”) method wherein we are hiding a modal which generates on page load −
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<style>
#button1 {
width: 140px;
padding: 20px;
bottom: 150px;
z-index: 9999;
font-size:15px;
position: absolute;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="container">
<h2>Sample</h2>
<p>This is demo text.</p>
<p>This is demo text.</p>
<p>This is demo text.</p>
<p>This is demo text.</p>
<p>This is demo text.</p>
<p>This is demo text.</p>
<p>This is demo text.</p>
<p>This is demo text.</p>
<p>This is demo text.</p>
<p>This is demo text.</p>
<p>This is demo text.</p>
<button type="button" class="btn btn-default btn-lg" id="button1">Click to hide</button>
<div class="modal fade" id="newModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Sample Modal</h4>
</div>
<div class="modal-body">
<p>This is demo text.</p>
</div>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function(){
$("#newModal").modal("show");
$("#button1").click(function(){
$("#newModal").modal("hide");
});
});
</script>
</body>
</html> | [
{
"code": null,
"e": 1121,
"s": 1062,
"text": "The .modal(“hide”) method hides the modal on button click."
},
{
"code": null,
"e": 1166,
"s": 1121,
"text": "Firstly, generate the modal and display it −"
},
{
"code": null,
"e": 1196,
"s": 1166,
"text": "$(\"#newModal\").modal(\"show\");"
},
{
"code": null,
"e": 1285,
"s": 1196,
"text": "After that, use the modal(“hide”) method on a button to hide the modal on button click −"
},
{
"code": null,
"e": 1353,
"s": 1285,
"text": "$(\"#button1\").click(function(){\n $(\"#newModal\").modal(\"hide\");\n});"
},
{
"code": null,
"e": 1464,
"s": 1353,
"text": "Let us see an example of the modal(‘hide”) method wherein we are hiding a modal which generates on page load −"
},
{
"code": null,
"e": 1474,
"s": 1464,
"text": "Live Demo"
},
{
"code": null,
"e": 3243,
"s": 1474,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css\">\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js\"></script>\n <style>\n #button1 {\n width: 140px;\n padding: 20px;\n bottom: 150px;\n z-index: 9999;\n font-size:15px;\n position: absolute;\n margin: 0 auto;\n }\n</style>\n</head>\n\n<body>\n <div class=\"container\">\n <h2>Sample</h2>\n <p>This is demo text.</p>\n <p>This is demo text.</p>\n <p>This is demo text.</p>\n <p>This is demo text.</p>\n <p>This is demo text.</p>\n <p>This is demo text.</p>\n <p>This is demo text.</p>\n <p>This is demo text.</p>\n <p>This is demo text.</p>\n <p>This is demo text.</p>\n <p>This is demo text.</p>\n\n <button type=\"button\" class=\"btn btn-default btn-lg\" id=\"button1\">Click to hide</button>\n\n <div class=\"modal fade\" id=\"newModal\" role=\"dialog\">\n <div class=\"modal-dialog\">\n <div class=\"modal-content\">\n <div class=\"modal-header\">\n <button type=\"button\" class=\"close\" data-dismiss=\"modal\">×</button>\n <h4 class=\"modal-title\">Sample Modal</h4>\n </div>\n <div class=\"modal-body\">\n <p>This is demo text.</p>\n </div>\n </div>\n </div>\n </div>\n</div>\n\n<script>\n $(document).ready(function(){\n $(\"#newModal\").modal(\"show\");\n $(\"#button1\").click(function(){\n $(\"#newModal\").modal(\"hide\");\n });\n });\n</script>\n\n</body>\n</html>"
}
] |
How to extract tables from PDF using Python Pandas and tabula-py | by Angelica Lo Duca | Towards Data Science | This tutorial is an improvement of my previous post, where I extracted multiple tables without Python pandas. In this tutorial, I will use the same PDF file, as that used in my previous post, with the difference that I manipulate the extracted tables with Python pandas.
The code of this tutorial can be downloaded from my Github repository.
Almost all the pages of the analysed PDF file have the following structure:
In the top-right part of the page, there is the name of the Italian region, while in the bottom-right part of the page there is a table.
I want to extract both the region names and the tables for all the pages. I need to extract the bounding box for both the tables. The full procedure to measure margins is illustrated in my previous post, section Define margins.
This script implements the following steps:
define the bounding box, which is represented through a list with the following shape: [top,left,bottom,width]. Data within the bounding box are expressed in cm. They must be converted to PDF points, since tabula-py requires them in this format. We set the conversion factor fc = 28.28.
extract data using the read_pdf() function
save data to a pandas dataframe.
In this example, we scan the pdf twice: firstly to extract the regions names, secondly, to extract tables. Thus we need to define two bounding boxes.
Firstly, I define the bounding box to extract the regions:
box = [1.5, 22,3.8,26.741]fc = 28.28 for i in range(0, len(box)): box[i] *= fc
Then, Iimport the tabula-py library and we define the list of pages from which we must extract information, as well as the file name.
import tabula as tbpages = [3,5,6,8,9,10,12,14,16,18,22,24,26,28,30,32,34,36,38,40]file = “source/Bolletino-sorveglianza-integrata-COVID-19_17-marzo-2020_appendix.pdf”
Now I can read the list of regions from the pdf. I use the read_pdf() function and we set the output format to json.
regions_raw = tb.read_pdf(file, pages=pages,area=[box],output_format="json")
I note that the produced output is very complex. However, the general structure contains the region name of the i-th region in the position regions_raw[i]['data'][0][0]['text']. I build a list with all the regions, by looping into the region_raw list.
regions = []for i in range(0,len(regions_raw)): regions.append(regions_raw[i]['data'][0][0]['text'])
I define the bounding box and we multiply each value for the conversion factor fc. In order to understand how the mechanism works, firstly, I extract the table of the first page and then we generalise to all the pages. In this example, the first page corresponds to page 3.
box = [8,10,25,26]for i in range(0, len(box)): box[i] *= fc
Now I can read the pdf. In this case I set the output_format to DataFrame. The result is stored in tl, which is a list. I can convert it to a dataframe, simply using tl[0].
page = 3tl = tb.read_pdf(file, pages=page,area=[box],output_format="dataframe", stream=True)df = tl[0]df.head()
I note that the columns names are wrong. In addition, the first three rows are wrong. For this reason, I can rename the columns names by using the dataframe function rename().
df.rename(columns={ df.columns[0]: "Fascia d'età" , df.columns[1]: "Casi"}, inplace = True)df.head()
Now I can drop the first two rows by using the dropna() function.
df = df.dropna()df.head()
I can drop the new first row by selecting all the rows which do not contain this value.
df = df[df["Fascia d'età"] != "Fascia d'età"]df.head(8)
Now I add a new column to df, called Regione which contains the region name. I scan the pages list to extract the index of the current region.
region_column = []for i in range(0, len(df)): index = pages.index(page) region_column.append(regions[index])df['Regione'] = region_columndf.head()
Now I can generalise the previous code to extract the tables of all the pages. Firstly, I build an empty DataFrame, which will contain the values for all the regions. I will use the pd.concat() function to concatenate all the tables of alle the pages. I scan all the pages contained in the pages list.
import pandas as pddf = pd.DataFrame()for page in pages: index = pages.index(page) region = regions[index] print(region) tl = tb.read_pdf(file, pages=page,area=[box],output_format="dataframe", stream=True) dft = tl[0] dft.rename(columns={ dft.columns[0]: "Fascia d'età", dft.columns[1]: "Casi"}, inplace = True) region_column = [] for i in range(0, len(dft)): region_column.append(region) dft['Regione'] = region_column df = pd.concat([df, dft])
Similarly to the previous case, I drop all wrong records.
df.dropna(inplace=True)df = df[df["Fascia d'età"] != "Fascia d'età"]
Now I can save the result as a csv file.
df.to_csv('output.csv')
In this tutorial I have illustrated how to convert multiple PDF table into a single pandas DataFrame and export it as a CSV file.
The procedure involves three steps: define the bounding box, extract the tables through the tabula-py library and export them to a CSV file.
If you want to be updated on my research and other activities, you can follow me on Twitter, Youtube and Github. | [
{
"code": null,
"e": 443,
"s": 172,
"text": "This tutorial is an improvement of my previous post, where I extracted multiple tables without Python pandas. In this tutorial, I will use the same PDF file, as that used in my previous post, with the difference that I manipulate the extracted tables with Python pandas."
},
{
"code": null,
"e": 514,
"s": 443,
"text": "The code of this tutorial can be downloaded from my Github repository."
},
{
"code": null,
"e": 590,
"s": 514,
"text": "Almost all the pages of the analysed PDF file have the following structure:"
},
{
"code": null,
"e": 727,
"s": 590,
"text": "In the top-right part of the page, there is the name of the Italian region, while in the bottom-right part of the page there is a table."
},
{
"code": null,
"e": 955,
"s": 727,
"text": "I want to extract both the region names and the tables for all the pages. I need to extract the bounding box for both the tables. The full procedure to measure margins is illustrated in my previous post, section Define margins."
},
{
"code": null,
"e": 999,
"s": 955,
"text": "This script implements the following steps:"
},
{
"code": null,
"e": 1286,
"s": 999,
"text": "define the bounding box, which is represented through a list with the following shape: [top,left,bottom,width]. Data within the bounding box are expressed in cm. They must be converted to PDF points, since tabula-py requires them in this format. We set the conversion factor fc = 28.28."
},
{
"code": null,
"e": 1329,
"s": 1286,
"text": "extract data using the read_pdf() function"
},
{
"code": null,
"e": 1362,
"s": 1329,
"text": "save data to a pandas dataframe."
},
{
"code": null,
"e": 1512,
"s": 1362,
"text": "In this example, we scan the pdf twice: firstly to extract the regions names, secondly, to extract tables. Thus we need to define two bounding boxes."
},
{
"code": null,
"e": 1571,
"s": 1512,
"text": "Firstly, I define the bounding box to extract the regions:"
},
{
"code": null,
"e": 1661,
"s": 1571,
"text": "box = [1.5, 22,3.8,26.741]fc = 28.28 for i in range(0, len(box)): box[i] *= fc"
},
{
"code": null,
"e": 1795,
"s": 1661,
"text": "Then, Iimport the tabula-py library and we define the list of pages from which we must extract information, as well as the file name."
},
{
"code": null,
"e": 1963,
"s": 1795,
"text": "import tabula as tbpages = [3,5,6,8,9,10,12,14,16,18,22,24,26,28,30,32,34,36,38,40]file = “source/Bolletino-sorveglianza-integrata-COVID-19_17-marzo-2020_appendix.pdf”"
},
{
"code": null,
"e": 2080,
"s": 1963,
"text": "Now I can read the list of regions from the pdf. I use the read_pdf() function and we set the output format to json."
},
{
"code": null,
"e": 2157,
"s": 2080,
"text": "regions_raw = tb.read_pdf(file, pages=pages,area=[box],output_format=\"json\")"
},
{
"code": null,
"e": 2409,
"s": 2157,
"text": "I note that the produced output is very complex. However, the general structure contains the region name of the i-th region in the position regions_raw[i]['data'][0][0]['text']. I build a list with all the regions, by looping into the region_raw list."
},
{
"code": null,
"e": 2513,
"s": 2409,
"text": "regions = []for i in range(0,len(regions_raw)): regions.append(regions_raw[i]['data'][0][0]['text'])"
},
{
"code": null,
"e": 2787,
"s": 2513,
"text": "I define the bounding box and we multiply each value for the conversion factor fc. In order to understand how the mechanism works, firstly, I extract the table of the first page and then we generalise to all the pages. In this example, the first page corresponds to page 3."
},
{
"code": null,
"e": 2850,
"s": 2787,
"text": "box = [8,10,25,26]for i in range(0, len(box)): box[i] *= fc"
},
{
"code": null,
"e": 3023,
"s": 2850,
"text": "Now I can read the pdf. In this case I set the output_format to DataFrame. The result is stored in tl, which is a list. I can convert it to a dataframe, simply using tl[0]."
},
{
"code": null,
"e": 3135,
"s": 3023,
"text": "page = 3tl = tb.read_pdf(file, pages=page,area=[box],output_format=\"dataframe\", stream=True)df = tl[0]df.head()"
},
{
"code": null,
"e": 3311,
"s": 3135,
"text": "I note that the columns names are wrong. In addition, the first three rows are wrong. For this reason, I can rename the columns names by using the dataframe function rename()."
},
{
"code": null,
"e": 3413,
"s": 3311,
"text": "df.rename(columns={ df.columns[0]: \"Fascia d'età\" , df.columns[1]: \"Casi\"}, inplace = True)df.head()"
},
{
"code": null,
"e": 3479,
"s": 3413,
"text": "Now I can drop the first two rows by using the dropna() function."
},
{
"code": null,
"e": 3505,
"s": 3479,
"text": "df = df.dropna()df.head()"
},
{
"code": null,
"e": 3593,
"s": 3505,
"text": "I can drop the new first row by selecting all the rows which do not contain this value."
},
{
"code": null,
"e": 3651,
"s": 3593,
"text": "df = df[df[\"Fascia d'età\"] != \"Fascia d'età\"]df.head(8)"
},
{
"code": null,
"e": 3794,
"s": 3651,
"text": "Now I add a new column to df, called Regione which contains the region name. I scan the pages list to extract the index of the current region."
},
{
"code": null,
"e": 3947,
"s": 3794,
"text": "region_column = []for i in range(0, len(df)): index = pages.index(page) region_column.append(regions[index])df['Regione'] = region_columndf.head()"
},
{
"code": null,
"e": 4249,
"s": 3947,
"text": "Now I can generalise the previous code to extract the tables of all the pages. Firstly, I build an empty DataFrame, which will contain the values for all the regions. I will use the pd.concat() function to concatenate all the tables of alle the pages. I scan all the pages contained in the pages list."
},
{
"code": null,
"e": 4753,
"s": 4249,
"text": "import pandas as pddf = pd.DataFrame()for page in pages: index = pages.index(page) region = regions[index] print(region) tl = tb.read_pdf(file, pages=page,area=[box],output_format=\"dataframe\", stream=True) dft = tl[0] dft.rename(columns={ dft.columns[0]: \"Fascia d'età\", dft.columns[1]: \"Casi\"}, inplace = True) region_column = [] for i in range(0, len(dft)): region_column.append(region) dft['Regione'] = region_column df = pd.concat([df, dft])"
},
{
"code": null,
"e": 4811,
"s": 4753,
"text": "Similarly to the previous case, I drop all wrong records."
},
{
"code": null,
"e": 4882,
"s": 4811,
"text": "df.dropna(inplace=True)df = df[df[\"Fascia d'età\"] != \"Fascia d'età\"]"
},
{
"code": null,
"e": 4923,
"s": 4882,
"text": "Now I can save the result as a csv file."
},
{
"code": null,
"e": 4947,
"s": 4923,
"text": "df.to_csv('output.csv')"
},
{
"code": null,
"e": 5077,
"s": 4947,
"text": "In this tutorial I have illustrated how to convert multiple PDF table into a single pandas DataFrame and export it as a CSV file."
},
{
"code": null,
"e": 5218,
"s": 5077,
"text": "The procedure involves three steps: define the bounding box, extract the tables through the tabula-py library and export them to a CSV file."
}
] |
Concatenate columns from different tables in MySQL | You can use CONCAT(). Let us first create a table −
mysql> create table DemoTable1
-> (
-> FirstName varchar(20)
-> );
Query OK, 0 rows affected (0.90 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1 values('Chris');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1 values('David');
Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable1;
This will produce the following output −
+-----------+
| FirstName |
+-----------+
| Chris |
| David |
+-----------+
2 rows in set (0.00 sec)
Here is the query to create the second table −
mysql> create table DemoTable2
-> (
-> LastName varchar(20)
-> );
Query OK, 0 rows affected (0.95 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable2 values('Brown');
Query OK, 1 row affected (0.55 sec)
mysql> insert into DemoTable2 values('Miller');
Query OK, 1 row affected (0.18 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable2;
This will produce the following output −
+----------+
| LastName |
+----------+
| Brown |
| Miller |
+----------+
2 rows in set (0.00 sec)
Here is the query to concatenate column from different tables −
mysql> select concat(tbl1.FirstName,' ',tbl2.LastName) from DemoTable tbl1
-> left join DemoTable2 tbl2
-> on tbl2.LastName='Brown' or tbl2.LastName='Miller';
This will produce the following output −
+------------------------------------------+
| concat(tbl1.FirstName,' ',tbl2.LastName) |
+------------------------------------------+
| Chris Brown |
| David Brown |
| Chris Miller |
| David Miller |
+------------------------------------------+
4 rows in set (0.04 sec) | [
{
"code": null,
"e": 1114,
"s": 1062,
"text": "You can use CONCAT(). Let us first create a table −"
},
{
"code": null,
"e": 1227,
"s": 1114,
"text": "mysql> create table DemoTable1\n -> (\n -> FirstName varchar(20)\n -> );\nQuery OK, 0 rows affected (0.90 sec)"
},
{
"code": null,
"e": 1283,
"s": 1227,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1449,
"s": 1283,
"text": "mysql> insert into DemoTable1 values('Chris');\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into DemoTable1 values('David');\nQuery OK, 1 row affected (0.12 sec)"
},
{
"code": null,
"e": 1509,
"s": 1449,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1541,
"s": 1509,
"text": "mysql> select *from DemoTable1;"
},
{
"code": null,
"e": 1582,
"s": 1541,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1691,
"s": 1582,
"text": "+-----------+\n| FirstName |\n+-----------+\n| Chris |\n| David |\n+-----------+\n2 rows in set (0.00 sec)"
},
{
"code": null,
"e": 1738,
"s": 1691,
"text": "Here is the query to create the second table −"
},
{
"code": null,
"e": 1850,
"s": 1738,
"text": "mysql> create table DemoTable2\n -> (\n -> LastName varchar(20)\n -> );\nQuery OK, 0 rows affected (0.95 sec)"
},
{
"code": null,
"e": 1906,
"s": 1850,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 2073,
"s": 1906,
"text": "mysql> insert into DemoTable2 values('Brown');\nQuery OK, 1 row affected (0.55 sec)\nmysql> insert into DemoTable2 values('Miller');\nQuery OK, 1 row affected (0.18 sec)"
},
{
"code": null,
"e": 2133,
"s": 2073,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 2165,
"s": 2133,
"text": "mysql> select *from DemoTable2;"
},
{
"code": null,
"e": 2206,
"s": 2165,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2309,
"s": 2206,
"text": "+----------+\n| LastName |\n+----------+\n| Brown |\n| Miller |\n+----------+\n2 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2373,
"s": 2309,
"text": "Here is the query to concatenate column from different tables −"
},
{
"code": null,
"e": 2538,
"s": 2373,
"text": "mysql> select concat(tbl1.FirstName,' ',tbl2.LastName) from DemoTable tbl1\n -> left join DemoTable2 tbl2\n -> on tbl2.LastName='Brown' or tbl2.LastName='Miller';"
},
{
"code": null,
"e": 2579,
"s": 2538,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2964,
"s": 2579,
"text": "+------------------------------------------+\n| concat(tbl1.FirstName,' ',tbl2.LastName) |\n+------------------------------------------+\n| Chris Brown |\n| David Brown |\n| Chris Miller |\n| David Miller |\n+------------------------------------------+\n4 rows in set (0.04 sec)"
}
] |
Android | build.gradle - GeeksforGeeks | 14 Sep, 2021
Gradle is a build system (open source) that is used to automate building, testing, deployment, etc. “build.gradle” are scripts where one can automate the tasks. For example, the simple task to copy some files from one directory to another can be performed by the Gradle build script before the actual build process happens.
Every Android project needs a Gradle for generating an apk from the .java and .xml files in the project. Simply put, a gradle takes all the source files (java and XML) and applies appropriate tools, e.g., converts the java files into dex files and compresses all of them into a single file known as apk that is actually used. There are two types of build.gradle scripts
Top-level build.gradle
Module-level build.gradle
Top-level build.gradle:
It is located in the root project directory and its main function is to define the build configurations that will be applied to all the modules in the project. It is implemented as:
Java
// Top-level build file where you can add configuration// options common to all sub-projects/modules. buildscript { repositories { google() mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:3.4.3' }} allprojects { repositories { google() mavenCentral() }} task clean(type: Delete) { delete rootProject.buildDir}
The top-level build.gradle supports various build configurations like:
buildscript: This block is used to configure the repositories and dependencies for Gradle.
Note: Don’t include dependencies here. (those will be included in the module-level build.gradle)
dependencies: This block in buildscript is used to configure dependencies that the Gradle needs to build during the project.
Java
classpath 'com.android.tools.build:gradle:3.0.1'
This line adds the plugins as a classpath dependency for gradle 3.0.1.
allprojects: This is the block where one can configure the third-party plugins or libraries. For freshly created projects android studio includes mavenCentral() and Google’s maven repository by default. task clean(type:Delete): This block is used to delete the directory every time the project is run. This way the projects keep clean when someone modifies some config files like, during settings.gradle which requires a complete clean.
allprojects: This is the block where one can configure the third-party plugins or libraries. For freshly created projects android studio includes mavenCentral() and Google’s maven repository by default.
task clean(type:Delete): This block is used to delete the directory every time the project is run. This way the projects keep clean when someone modifies some config files like, during settings.gradle which requires a complete clean.
Module-level build.gradle:
Located in the project/module directory of the project this Gradle script is where all the dependencies are defined and where the SDK versions are declared. This script has many functions in the project which include additional build types and override settings in the main/app manifest or top-level build.gradle file. It is implemented as:
Java
// The first line in this file indicates// the Android plugin is applied for Gradle to// this build apply plugin : 'com.android.application' android{ compileSdkVersion 30 buildToolsVersion "30.0.3" { applicationId "example.mehakmeet.geeksforgeeks" minSdkVersion 19 targetSdkVersion 30 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } }} dependencies{ implementation fileTree(include : [ '*.jar' ], dir : 'libs') implementation 'com.android.support:appcompat-v7:26.1.0'}
The Module-level build.gradle supports various build configurations like:
android: This block is used for configuring the specific android build options. compileSdkVersion – This is used to define the API level of the app and the app can use the features of this and lower level. defaultConfig: applicationId– This is used for identifying unique id for publishing of the app.minSdkVersion– This defines the minimum API level required to run the application.targetSdkVersion– This defines the API level used to test the app.versionCode– This defines the version code of the app. Every time an update needs to be of the app, the version code needs to be increased by 1 or more.versionName– This defines the version name for the app. this could be increased by much while creating an update.buildTypes(release): minifyEnabled– this will enable code shrinking for release build.proguardFiles– this will specify the progaurd settings file.dependencies: This specifies the dependencies that are needed to build the project.
android: This block is used for configuring the specific android build options. compileSdkVersion – This is used to define the API level of the app and the app can use the features of this and lower level.
compileSdkVersion – This is used to define the API level of the app and the app can use the features of this and lower level.
defaultConfig: applicationId– This is used for identifying unique id for publishing of the app.minSdkVersion– This defines the minimum API level required to run the application.targetSdkVersion– This defines the API level used to test the app.versionCode– This defines the version code of the app. Every time an update needs to be of the app, the version code needs to be increased by 1 or more.versionName– This defines the version name for the app. this could be increased by much while creating an update.
applicationId– This is used for identifying unique id for publishing of the app.
minSdkVersion– This defines the minimum API level required to run the application.
targetSdkVersion– This defines the API level used to test the app.
versionCode– This defines the version code of the app. Every time an update needs to be of the app, the version code needs to be increased by 1 or more.
versionName– This defines the version name for the app. this could be increased by much while creating an update.
buildTypes(release): minifyEnabled– this will enable code shrinking for release build.proguardFiles– this will specify the progaurd settings file.
minifyEnabled– this will enable code shrinking for release build.
proguardFiles– this will specify the progaurd settings file.
dependencies: This specifies the dependencies that are needed to build the project.
Both the top-level and module-level build.gradle files are the main script files for automating the tasks in an android project and are used by Gradle for generating the APK from the source files.
bhardwajankit1414
hemantjain99
Android-Studio
Android
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Broadcast Receiver in Android With Example
How to Create and Add Data to SQLite Database in Android?
Services in Android with Example
Content Providers in Android with Example
Android RecyclerView in Kotlin
Navigation Drawer in Android
Retrofit with Kotlin Coroutine in Android
How to Post Data to API using Retrofit in Android?
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android? | [
{
"code": null,
"e": 24608,
"s": 24580,
"text": "\n14 Sep, 2021"
},
{
"code": null,
"e": 24933,
"s": 24608,
"text": "Gradle is a build system (open source) that is used to automate building, testing, deployment, etc. “build.gradle” are scripts where one can automate the tasks. For example, the simple task to copy some files from one directory to another can be performed by the Gradle build script before the actual build process happens. "
},
{
"code": null,
"e": 25305,
"s": 24933,
"text": "Every Android project needs a Gradle for generating an apk from the .java and .xml files in the project. Simply put, a gradle takes all the source files (java and XML) and applies appropriate tools, e.g., converts the java files into dex files and compresses all of them into a single file known as apk that is actually used. There are two types of build.gradle scripts "
},
{
"code": null,
"e": 25328,
"s": 25305,
"text": "Top-level build.gradle"
},
{
"code": null,
"e": 25354,
"s": 25328,
"text": "Module-level build.gradle"
},
{
"code": null,
"e": 25378,
"s": 25354,
"text": "Top-level build.gradle:"
},
{
"code": null,
"e": 25562,
"s": 25378,
"text": "It is located in the root project directory and its main function is to define the build configurations that will be applied to all the modules in the project. It is implemented as: "
},
{
"code": null,
"e": 25567,
"s": 25562,
"text": "Java"
},
{
"code": "// Top-level build file where you can add configuration// options common to all sub-projects/modules. buildscript { repositories { google() mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:3.4.3' }} allprojects { repositories { google() mavenCentral() }} task clean(type: Delete) { delete rootProject.buildDir}",
"e": 25960,
"s": 25567,
"text": null
},
{
"code": null,
"e": 26033,
"s": 25960,
"text": "The top-level build.gradle supports various build configurations like: "
},
{
"code": null,
"e": 26125,
"s": 26033,
"text": "buildscript: This block is used to configure the repositories and dependencies for Gradle. "
},
{
"code": null,
"e": 26222,
"s": 26125,
"text": "Note: Don’t include dependencies here. (those will be included in the module-level build.gradle)"
},
{
"code": null,
"e": 26348,
"s": 26222,
"text": "dependencies: This block in buildscript is used to configure dependencies that the Gradle needs to build during the project. "
},
{
"code": null,
"e": 26353,
"s": 26348,
"text": "Java"
},
{
"code": "classpath 'com.android.tools.build:gradle:3.0.1'",
"e": 26402,
"s": 26353,
"text": null
},
{
"code": null,
"e": 26474,
"s": 26402,
"text": "This line adds the plugins as a classpath dependency for gradle 3.0.1. "
},
{
"code": null,
"e": 26912,
"s": 26474,
"text": "allprojects: This is the block where one can configure the third-party plugins or libraries. For freshly created projects android studio includes mavenCentral() and Google’s maven repository by default. task clean(type:Delete): This block is used to delete the directory every time the project is run. This way the projects keep clean when someone modifies some config files like, during settings.gradle which requires a complete clean. "
},
{
"code": null,
"e": 27116,
"s": 26912,
"text": "allprojects: This is the block where one can configure the third-party plugins or libraries. For freshly created projects android studio includes mavenCentral() and Google’s maven repository by default. "
},
{
"code": null,
"e": 27351,
"s": 27116,
"text": "task clean(type:Delete): This block is used to delete the directory every time the project is run. This way the projects keep clean when someone modifies some config files like, during settings.gradle which requires a complete clean. "
},
{
"code": null,
"e": 27378,
"s": 27351,
"text": "Module-level build.gradle:"
},
{
"code": null,
"e": 27721,
"s": 27378,
"text": "Located in the project/module directory of the project this Gradle script is where all the dependencies are defined and where the SDK versions are declared. This script has many functions in the project which include additional build types and override settings in the main/app manifest or top-level build.gradle file. It is implemented as: "
},
{
"code": null,
"e": 27726,
"s": 27721,
"text": "Java"
},
{
"code": "// The first line in this file indicates// the Android plugin is applied for Gradle to// this build apply plugin : 'com.android.application' android{ compileSdkVersion 30 buildToolsVersion \"30.0.3\" { applicationId \"example.mehakmeet.geeksforgeeks\" minSdkVersion 19 targetSdkVersion 30 versionCode 1 versionName \"1.0\" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } }} dependencies{ implementation fileTree(include : [ '*.jar' ], dir : 'libs') implementation 'com.android.support:appcompat-v7:26.1.0'}",
"e": 28472,
"s": 27726,
"text": null
},
{
"code": null,
"e": 28548,
"s": 28472,
"text": "The Module-level build.gradle supports various build configurations like: "
},
{
"code": null,
"e": 29492,
"s": 28548,
"text": "android: This block is used for configuring the specific android build options. compileSdkVersion – This is used to define the API level of the app and the app can use the features of this and lower level. defaultConfig: applicationId– This is used for identifying unique id for publishing of the app.minSdkVersion– This defines the minimum API level required to run the application.targetSdkVersion– This defines the API level used to test the app.versionCode– This defines the version code of the app. Every time an update needs to be of the app, the version code needs to be increased by 1 or more.versionName– This defines the version name for the app. this could be increased by much while creating an update.buildTypes(release): minifyEnabled– this will enable code shrinking for release build.proguardFiles– this will specify the progaurd settings file.dependencies: This specifies the dependencies that are needed to build the project."
},
{
"code": null,
"e": 29699,
"s": 29492,
"text": "android: This block is used for configuring the specific android build options. compileSdkVersion – This is used to define the API level of the app and the app can use the features of this and lower level. "
},
{
"code": null,
"e": 29826,
"s": 29699,
"text": "compileSdkVersion – This is used to define the API level of the app and the app can use the features of this and lower level. "
},
{
"code": null,
"e": 30335,
"s": 29826,
"text": "defaultConfig: applicationId– This is used for identifying unique id for publishing of the app.minSdkVersion– This defines the minimum API level required to run the application.targetSdkVersion– This defines the API level used to test the app.versionCode– This defines the version code of the app. Every time an update needs to be of the app, the version code needs to be increased by 1 or more.versionName– This defines the version name for the app. this could be increased by much while creating an update."
},
{
"code": null,
"e": 30416,
"s": 30335,
"text": "applicationId– This is used for identifying unique id for publishing of the app."
},
{
"code": null,
"e": 30499,
"s": 30416,
"text": "minSdkVersion– This defines the minimum API level required to run the application."
},
{
"code": null,
"e": 30566,
"s": 30499,
"text": "targetSdkVersion– This defines the API level used to test the app."
},
{
"code": null,
"e": 30719,
"s": 30566,
"text": "versionCode– This defines the version code of the app. Every time an update needs to be of the app, the version code needs to be increased by 1 or more."
},
{
"code": null,
"e": 30833,
"s": 30719,
"text": "versionName– This defines the version name for the app. this could be increased by much while creating an update."
},
{
"code": null,
"e": 30980,
"s": 30833,
"text": "buildTypes(release): minifyEnabled– this will enable code shrinking for release build.proguardFiles– this will specify the progaurd settings file."
},
{
"code": null,
"e": 31046,
"s": 30980,
"text": "minifyEnabled– this will enable code shrinking for release build."
},
{
"code": null,
"e": 31107,
"s": 31046,
"text": "proguardFiles– this will specify the progaurd settings file."
},
{
"code": null,
"e": 31191,
"s": 31107,
"text": "dependencies: This specifies the dependencies that are needed to build the project."
},
{
"code": null,
"e": 31388,
"s": 31191,
"text": "Both the top-level and module-level build.gradle files are the main script files for automating the tasks in an android project and are used by Gradle for generating the APK from the source files."
},
{
"code": null,
"e": 31406,
"s": 31388,
"text": "bhardwajankit1414"
},
{
"code": null,
"e": 31419,
"s": 31406,
"text": "hemantjain99"
},
{
"code": null,
"e": 31434,
"s": 31419,
"text": "Android-Studio"
},
{
"code": null,
"e": 31442,
"s": 31434,
"text": "Android"
},
{
"code": null,
"e": 31450,
"s": 31442,
"text": "Android"
},
{
"code": null,
"e": 31548,
"s": 31450,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31557,
"s": 31548,
"text": "Comments"
},
{
"code": null,
"e": 31570,
"s": 31557,
"text": "Old Comments"
},
{
"code": null,
"e": 31613,
"s": 31570,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 31671,
"s": 31613,
"text": "How to Create and Add Data to SQLite Database in Android?"
},
{
"code": null,
"e": 31704,
"s": 31671,
"text": "Services in Android with Example"
},
{
"code": null,
"e": 31746,
"s": 31704,
"text": "Content Providers in Android with Example"
},
{
"code": null,
"e": 31777,
"s": 31746,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 31806,
"s": 31777,
"text": "Navigation Drawer in Android"
},
{
"code": null,
"e": 31848,
"s": 31806,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 31899,
"s": 31848,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 31938,
"s": 31899,
"text": "Flutter - Custom Bottom Navigation Bar"
}
] |
How to create clickable areas in an image in HTML? | To create clickable areas in an image, create an image map, with clickable areas. For example, on clicking a box, the different website opens and on clicking a triangle in the same image, a different website opens.
The <area> tag defines an area inside an image-and nested inside a <map> tag. The following are the attributes:
You can try to run the following code to create clickable areas in an image in HTML
<!DOCTYPE html>
<html>
<head>
<title>HTML area Tag</title>
</head>
<body>
<img src = /images/usemap.gif alt = "usemap" usemap = "#lessons"/>
<map name = "lessons">
<area shape = "poly" coords = "74,0,113,29,98,72,52,72,38,27"
href = "/perl/index.htm" alt = "Perl Tutorial" target = "_blank" />
<area shape = "rect" coords = "22,83,126,125" alt = "HTML Tutorial"
href = "/html/index.htm" target = "_blank" />
<area shape = "circle" coords = "73,168,32" alt = "PHP Tutorial"
href = "/php/index.htm" target = "_blank" />
</map>
</body>
</html> | [
{
"code": null,
"e": 1277,
"s": 1062,
"text": "To create clickable areas in an image, create an image map, with clickable areas. For example, on clicking a box, the different website opens and on clicking a triangle in the same image, a different website opens."
},
{
"code": null,
"e": 1389,
"s": 1277,
"text": "The <area> tag defines an area inside an image-and nested inside a <map> tag. The following are the attributes:"
},
{
"code": null,
"e": 1473,
"s": 1389,
"text": "You can try to run the following code to create clickable areas in an image in HTML"
},
{
"code": null,
"e": 2114,
"s": 1473,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML area Tag</title>\n </head>\n\n <body>\n <img src = /images/usemap.gif alt = \"usemap\" usemap = \"#lessons\"/>\n <map name = \"lessons\">\n <area shape = \"poly\" coords = \"74,0,113,29,98,72,52,72,38,27\"\n href = \"/perl/index.htm\" alt = \"Perl Tutorial\" target = \"_blank\" />\n <area shape = \"rect\" coords = \"22,83,126,125\" alt = \"HTML Tutorial\"\n href = \"/html/index.htm\" target = \"_blank\" />\n <area shape = \"circle\" coords = \"73,168,32\" alt = \"PHP Tutorial\"\n href = \"/php/index.htm\" target = \"_blank\" />\n </map>\n </body>\n</html>"
}
] |
<mat-menu> in Angular Material - GeeksforGeeks | 25 Feb, 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.The <mat-menu> acts as a kind of dropdown or menu section which expands or opens whenever user clicks on any button.
Installation syntax:
ng add @angular/material
Approach:
First, install the angular material using the above-mentioned command.
After completing the installation, Import ‘MatMenuModule’ from ‘@angular/material/menu’ in the app.module.ts file.
In addition to it import ‘MatButtonModule’ from ‘@angular/material/button’ in app.module.ts file.
Then use <mat-menu> tag to group all the items inside this menu tag.
Inside the <mat-menu> tag we need to use <mat-menu-item> tag for every item for displaying in the dropdown.
We have properties like ‘xPosition’ and ‘yPosition’ to customize the opening direction of the dropdown.
Once done with the above steps then serve or start the project.
Code Implementation:
app.module.ts
import { CommonModule } from '@angular/common'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { MatMenuModule, MatButtonModule } from '@angular/material'; import { AppComponent } from './example.component'; @NgModule({ declarations: [AppComponent], exports: [AppComponent], imports: [ CommonModule, FormsModule, MatMenuModule, MatButtonModule ], }) export class AppModule {}
app.component.html
<h4> Click on the below button in-order to activate mat-menu</h4> <button mat-button [matMenuTriggerFor]="menu"> Web Technologies</button> <mat-menu #menu="matMenu"> <button mat-menu-item>HTML</button> <button mat-menu-item>CSS</button> <button mat-menu-item>JQuery</button> <button mat-menu-item>Bootstrap</button> <button mat-menu-item>Angular</button> <button mat-menu-item>React.js</button></mat-menu>
Output:
Angular-material
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 10 (blur) Event
Angular PrimeNG Messages Component
How to make a Bootstrap Modal Popup in Angular 9/8 ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 26354,
"s": 26326,
"text": "\n25 Feb, 2021"
},
{
"code": null,
"e": 26763,
"s": 26354,
"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.The <mat-menu> acts as a kind of dropdown or menu section which expands or opens whenever user clicks on any button."
},
{
"code": null,
"e": 26784,
"s": 26763,
"text": "Installation syntax:"
},
{
"code": null,
"e": 26809,
"s": 26784,
"text": "ng add @angular/material"
},
{
"code": null,
"e": 26819,
"s": 26809,
"text": "Approach:"
},
{
"code": null,
"e": 26890,
"s": 26819,
"text": "First, install the angular material using the above-mentioned command."
},
{
"code": null,
"e": 27005,
"s": 26890,
"text": "After completing the installation, Import ‘MatMenuModule’ from ‘@angular/material/menu’ in the app.module.ts file."
},
{
"code": null,
"e": 27103,
"s": 27005,
"text": "In addition to it import ‘MatButtonModule’ from ‘@angular/material/button’ in app.module.ts file."
},
{
"code": null,
"e": 27172,
"s": 27103,
"text": "Then use <mat-menu> tag to group all the items inside this menu tag."
},
{
"code": null,
"e": 27280,
"s": 27172,
"text": "Inside the <mat-menu> tag we need to use <mat-menu-item> tag for every item for displaying in the dropdown."
},
{
"code": null,
"e": 27384,
"s": 27280,
"text": "We have properties like ‘xPosition’ and ‘yPosition’ to customize the opening direction of the dropdown."
},
{
"code": null,
"e": 27448,
"s": 27384,
"text": "Once done with the above steps then serve or start the project."
},
{
"code": null,
"e": 27469,
"s": 27448,
"text": "Code Implementation:"
},
{
"code": null,
"e": 27483,
"s": 27469,
"text": "app.module.ts"
},
{
"code": "import { CommonModule } from '@angular/common'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { MatMenuModule, MatButtonModule } from '@angular/material'; import { AppComponent } from './example.component'; @NgModule({ declarations: [AppComponent], exports: [AppComponent], imports: [ CommonModule, FormsModule, MatMenuModule, MatButtonModule ], }) export class AppModule {}",
"e": 27939,
"s": 27483,
"text": null
},
{
"code": null,
"e": 27958,
"s": 27939,
"text": "app.component.html"
},
{
"code": "<h4> Click on the below button in-order to activate mat-menu</h4> <button mat-button [matMenuTriggerFor]=\"menu\"> Web Technologies</button> <mat-menu #menu=\"matMenu\"> <button mat-menu-item>HTML</button> <button mat-menu-item>CSS</button> <button mat-menu-item>JQuery</button> <button mat-menu-item>Bootstrap</button> <button mat-menu-item>Angular</button> <button mat-menu-item>React.js</button></mat-menu>",
"e": 28381,
"s": 27958,
"text": null
},
{
"code": null,
"e": 28389,
"s": 28381,
"text": "Output:"
},
{
"code": null,
"e": 28406,
"s": 28389,
"text": "Angular-material"
},
{
"code": null,
"e": 28413,
"s": 28406,
"text": "Picked"
},
{
"code": null,
"e": 28423,
"s": 28413,
"text": "AngularJS"
},
{
"code": null,
"e": 28440,
"s": 28423,
"text": "Web Technologies"
},
{
"code": null,
"e": 28538,
"s": 28440,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28573,
"s": 28538,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 28608,
"s": 28573,
"text": "Angular PrimeNG Calendar Component"
},
{
"code": null,
"e": 28632,
"s": 28608,
"text": "Angular 10 (blur) Event"
},
{
"code": null,
"e": 28667,
"s": 28632,
"text": "Angular PrimeNG Messages Component"
},
{
"code": null,
"e": 28720,
"s": 28667,
"text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?"
},
{
"code": null,
"e": 28760,
"s": 28720,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28793,
"s": 28760,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28838,
"s": 28793,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28881,
"s": 28838,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Rotate a matrix clockwise by 90 degree without using any extra space | Set 3 - GeeksforGeeks | 09 Jul, 2021
Given a rectangular matrix mat[][] with N rows and M columns, the task is to rotate the matrix by 90 degrees in a clockwise direction without using extra space.
Examples:
Input: mat[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}}Output: 10 7 4 1 11 8 5 2 12 9 6 3
Input: mat[][] = {{1, 2, 3, 4, 5, 6}, {7, 8, 9, 10, 11, 12}}Output: 7 1 8 2 9 3 10 4 11 5 12 6
Note: The approach to rotate square matrix is already discussed as follows:
With extra space: Inplace rotate square matrix by 90 degrees | Set 1
Without extra space in anti-clockwise direction: Rotate a matrix by 90 degree without using any extra space | Set 2
Approach: The main idea is to perform an in-place rotation.
Follow the below steps to solve the given problem:
Swap all the elements of the sub-matrix min(N, M) * min(N, M), along the main diagonal i.e from the upper top corner to the bottom right corner.If N is greater than M,Push all the unswapped elements of each column i where (min(N, M) ≤ i) to the ith row.Otherwise, push all the unswapped elements of each row i where (min(N, M) ≤ i) to the ith column.Reverse each row of the matrixPrint the updated matrix of dimension M × N.
Swap all the elements of the sub-matrix min(N, M) * min(N, M), along the main diagonal i.e from the upper top corner to the bottom right corner.
If N is greater than M,Push all the unswapped elements of each column i where (min(N, M) ≤ i) to the ith row.Otherwise, push all the unswapped elements of each row i where (min(N, M) ≤ i) to the ith column.
Push all the unswapped elements of each column i where (min(N, M) ≤ i) to the ith row.
Otherwise, push all the unswapped elements of each row i where (min(N, M) ≤ i) to the ith column.
Reverse each row of the matrix
Print the updated matrix of dimension M × N.
Procedure:
Let the given matrix be : 1 2 3 4 5 6 7 8 9 10 11 1213 14 15Swap all the elements of the sub-matrix min(N, M) * min(N, M) i.e 3 * 3 for this example1 4 72 5 83 6 910 11 1213 14 15
Since N > M, push all the unswapped elements of each column i (min(N, M) ≤ i) to the ith row1 4 7 10 132 5 8 11 143 6 9 12 15
Reverse each column to get the final rotated matrix as:13 10 7 4 114 11 8 5 215 12 9 6 3
Below is the implementation of the above approach:
C++
// C++ program for// the above approach#include <bits/stdc++.h>using namespace std; // Function to print the matrix mat// with N rows and M columnsvoid print(vector<vector<int> > mat, int N, int M){ for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { cout << mat[i][j] << " "; } cout << "\n"; }} // Function to rotate the matrix// by 90 degree clockwisevoid rotate(vector<vector<int> > mat){ // Number of rows int N = mat.size(); // Number of columns int M = mat[0].size(); // Swap all the elements along main diagonal // in the submatrix min(N, M) * min(N, M) for (int i = 0; i < min(N, M); i++) { for (int j = i; j < min(N, M); j++) { // Swap mat[i][j] and mat[j][i] swap(mat[i][j], mat[j][i]); } } // If N is greater than M if (N > M) { // Push all the unswapped elements // of ith column to ith row for (int i = 0; i < M; i++) { for (int j = min(N, M); j < N; j++) { mat[i].push_back(mat[j][i]); } } } else { // Resize mat to have M rows mat.resize(M, {}); // Push all the unswapped elements // of ith column to ith row for (int i = min(N, M); i < M; i++) { for (int j = 0; j < N; j++) { mat[i].push_back(mat[j][i]); } } } // Reverse each row of the matrix for (int i = 0; i < M; i++) { reverse(mat[i].begin(), mat[i].end()); } // Print the final matrix print(mat, M, N);} // Driver Codeint main(){ // Input vector<vector<int> > mat = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 }, { 10, 11, 12 } }; // Function Call rotate(mat); return 0;}
10 7 4 1
11 8 5 2
12 9 6 3
Time Complexity: O(N * M)Auxiliary Space: O(1)
adarsh08x
goyalhimanshu
diehard93
cpp-vector
rotation
Arrays
C++ Programs
Matrix
Arrays
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count pairs with given sum
Chocolate Distribution Problem
Window Sliding Technique
Reversal algorithm for array rotation
Next Greater Element
Header files in C/C++ and its uses
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
C++ Program for QuickSort
Sorting a Map by value in C++ STL | [
{
"code": null,
"e": 26067,
"s": 26039,
"text": "\n09 Jul, 2021"
},
{
"code": null,
"e": 26228,
"s": 26067,
"text": "Given a rectangular matrix mat[][] with N rows and M columns, the task is to rotate the matrix by 90 degrees in a clockwise direction without using extra space."
},
{
"code": null,
"e": 26238,
"s": 26228,
"text": "Examples:"
},
{
"code": null,
"e": 26371,
"s": 26238,
"text": "Input: mat[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}}Output: 10 7 4 1 11 8 5 2 12 9 6 3"
},
{
"code": null,
"e": 26533,
"s": 26371,
"text": "Input: mat[][] = {{1, 2, 3, 4, 5, 6}, {7, 8, 9, 10, 11, 12}}Output: 7 1 8 2 9 3 10 4 11 5 12 6"
},
{
"code": null,
"e": 26611,
"s": 26533,
"text": "Note: The approach to rotate square matrix is already discussed as follows: "
},
{
"code": null,
"e": 26680,
"s": 26611,
"text": "With extra space: Inplace rotate square matrix by 90 degrees | Set 1"
},
{
"code": null,
"e": 26796,
"s": 26680,
"text": "Without extra space in anti-clockwise direction: Rotate a matrix by 90 degree without using any extra space | Set 2"
},
{
"code": null,
"e": 26856,
"s": 26796,
"text": "Approach: The main idea is to perform an in-place rotation."
},
{
"code": null,
"e": 26907,
"s": 26856,
"text": "Follow the below steps to solve the given problem:"
},
{
"code": null,
"e": 27332,
"s": 26907,
"text": "Swap all the elements of the sub-matrix min(N, M) * min(N, M), along the main diagonal i.e from the upper top corner to the bottom right corner.If N is greater than M,Push all the unswapped elements of each column i where (min(N, M) ≤ i) to the ith row.Otherwise, push all the unswapped elements of each row i where (min(N, M) ≤ i) to the ith column.Reverse each row of the matrixPrint the updated matrix of dimension M × N."
},
{
"code": null,
"e": 27477,
"s": 27332,
"text": "Swap all the elements of the sub-matrix min(N, M) * min(N, M), along the main diagonal i.e from the upper top corner to the bottom right corner."
},
{
"code": null,
"e": 27684,
"s": 27477,
"text": "If N is greater than M,Push all the unswapped elements of each column i where (min(N, M) ≤ i) to the ith row.Otherwise, push all the unswapped elements of each row i where (min(N, M) ≤ i) to the ith column."
},
{
"code": null,
"e": 27771,
"s": 27684,
"text": "Push all the unswapped elements of each column i where (min(N, M) ≤ i) to the ith row."
},
{
"code": null,
"e": 27869,
"s": 27771,
"text": "Otherwise, push all the unswapped elements of each row i where (min(N, M) ≤ i) to the ith column."
},
{
"code": null,
"e": 27900,
"s": 27869,
"text": "Reverse each row of the matrix"
},
{
"code": null,
"e": 27945,
"s": 27900,
"text": "Print the updated matrix of dimension M × N."
},
{
"code": null,
"e": 27956,
"s": 27945,
"text": "Procedure:"
},
{
"code": null,
"e": 28136,
"s": 27956,
"text": "Let the given matrix be : 1 2 3 4 5 6 7 8 9 10 11 1213 14 15Swap all the elements of the sub-matrix min(N, M) * min(N, M) i.e 3 * 3 for this example1 4 72 5 83 6 910 11 1213 14 15"
},
{
"code": null,
"e": 28262,
"s": 28136,
"text": "Since N > M, push all the unswapped elements of each column i (min(N, M) ≤ i) to the ith row1 4 7 10 132 5 8 11 143 6 9 12 15"
},
{
"code": null,
"e": 28351,
"s": 28262,
"text": "Reverse each column to get the final rotated matrix as:13 10 7 4 114 11 8 5 215 12 9 6 3"
},
{
"code": null,
"e": 28402,
"s": 28351,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 28406,
"s": 28402,
"text": "C++"
},
{
"code": "// C++ program for// the above approach#include <bits/stdc++.h>using namespace std; // Function to print the matrix mat// with N rows and M columnsvoid print(vector<vector<int> > mat, int N, int M){ for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { cout << mat[i][j] << \" \"; } cout << \"\\n\"; }} // Function to rotate the matrix// by 90 degree clockwisevoid rotate(vector<vector<int> > mat){ // Number of rows int N = mat.size(); // Number of columns int M = mat[0].size(); // Swap all the elements along main diagonal // in the submatrix min(N, M) * min(N, M) for (int i = 0; i < min(N, M); i++) { for (int j = i; j < min(N, M); j++) { // Swap mat[i][j] and mat[j][i] swap(mat[i][j], mat[j][i]); } } // If N is greater than M if (N > M) { // Push all the unswapped elements // of ith column to ith row for (int i = 0; i < M; i++) { for (int j = min(N, M); j < N; j++) { mat[i].push_back(mat[j][i]); } } } else { // Resize mat to have M rows mat.resize(M, {}); // Push all the unswapped elements // of ith column to ith row for (int i = min(N, M); i < M; i++) { for (int j = 0; j < N; j++) { mat[i].push_back(mat[j][i]); } } } // Reverse each row of the matrix for (int i = 0; i < M; i++) { reverse(mat[i].begin(), mat[i].end()); } // Print the final matrix print(mat, M, N);} // Driver Codeint main(){ // Input vector<vector<int> > mat = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 }, { 10, 11, 12 } }; // Function Call rotate(mat); return 0;}",
"e": 30278,
"s": 28406,
"text": null
},
{
"code": null,
"e": 30308,
"s": 30278,
"text": "10 7 4 1 \n11 8 5 2 \n12 9 6 3 "
},
{
"code": null,
"e": 30355,
"s": 30308,
"text": "Time Complexity: O(N * M)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 30367,
"s": 30357,
"text": "adarsh08x"
},
{
"code": null,
"e": 30381,
"s": 30367,
"text": "goyalhimanshu"
},
{
"code": null,
"e": 30391,
"s": 30381,
"text": "diehard93"
},
{
"code": null,
"e": 30402,
"s": 30391,
"text": "cpp-vector"
},
{
"code": null,
"e": 30411,
"s": 30402,
"text": "rotation"
},
{
"code": null,
"e": 30418,
"s": 30411,
"text": "Arrays"
},
{
"code": null,
"e": 30431,
"s": 30418,
"text": "C++ Programs"
},
{
"code": null,
"e": 30438,
"s": 30431,
"text": "Matrix"
},
{
"code": null,
"e": 30445,
"s": 30438,
"text": "Arrays"
},
{
"code": null,
"e": 30452,
"s": 30445,
"text": "Matrix"
},
{
"code": null,
"e": 30550,
"s": 30452,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30577,
"s": 30550,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 30608,
"s": 30577,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 30633,
"s": 30608,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 30671,
"s": 30633,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 30692,
"s": 30671,
"text": "Next Greater Element"
},
{
"code": null,
"e": 30727,
"s": 30692,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 30771,
"s": 30727,
"text": "Program to print ASCII Value of a character"
},
{
"code": null,
"e": 30830,
"s": 30771,
"text": "How to return multiple values from a function in C or C++?"
},
{
"code": null,
"e": 30856,
"s": 30830,
"text": "C++ Program for QuickSort"
}
] |
How to add a Pie Chart into an Android Application - GeeksforGeeks | 13 May, 2020
Pre-requisites:
Android App Development Fundamentals for Beginners
Guide to Install and Set up Android Studio
Android | How to Create/Start a New Project in Android Studio?
Android | Running your first Android app
A pie chart is a circular statistical graphic, which is divided into slices to illustrate numerical proportions. It depicts a special chart that uses “pie slices”, where each sector shows the relative sizes of data. A circular chart cuts in a form of radii into segments describing relative frequencies or magnitude also known as circle graph. A pie chart represents numbers in percentages, and the total sum of all segments needs to equal 100%.
So let’s see the steps to add a Pie Chart into an Android app.
Step1: Opening a new projectOpen a new project just click of File option at topmost corner in left.Then click on new and open a new project with whatever name you want.Now we gonna work on Empty Activity with language as Java. Leave all other options as untouched.You can change the name of project as per your choice.By default, there will be two files activity_main.xml and MainActivity.java.Step 2: Before going to the coding section first you have to do some pre-task.Go to app->res->values->colors.xml section and set the colors for your app.colors.xmlcolors.xml<?xml version="1.0" encoding="utf-8"?><resources> <color name="colorPrimary">#024265</color> <color name="colorPrimaryDark">#024265</color> <color name="colorAccent">#05af9b</color> <color name="color_one">#fb7268</color> <color name="color_white">#ededf2</color> <color name="color_two">#E3E0E0</color> <color name="R">#FFA726</color> <color name="Python">#66BB6A</color> <color name="CPP">#EF5350</color> <color name="Java">#29B6F6</color> </resources>Go to Gradle Scripts->build.gradle (Module: app) section and import following dependencies and click the “sync Now” on the above pop up.build.gradle (:app)build.gradle (:app)// For Card viewimplementation 'androidx.cardview:cardview:1.0.0' // Chart and graph libraryimplementation 'com.github.blackfizz:eazegraph:1.2.5l@aar'implementation 'com.nineoldandroids:library:2.4.0'Step3: Designing the UIBelow is the code for the xml file.actibity_main.xmlactibity_main.xml<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/color_white" tools:context=".MainActivity"> <!-- Card view for displaying the ---> <!-- Pie chart and details of pie chart --> <androidx.cardview.widget.CardView android:id="@+id/cardViewGraph" android:layout_width="match_parent" android:layout_height="200dp" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" android:layout_marginTop="15dp" android:elevation="10dp" app:cardCornerRadius="10dp"> <!--Linear layout to display pie chart ---> <!-- and details of pie chart--> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" android:weightSum="2"> <!--Pie chart to display the data--> <org.eazegraph.lib.charts.PieChart xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/piechart" android:layout_width="0dp" android:layout_height="match_parent" android:padding="6dp" android:layout_weight="1" android:layout_marginTop="15dp" android:layout_marginLeft="15dp" android:layout_marginBottom="15dp" /> <!--Creating another linear layout ---> <!-- to display pie chart details --> <LinearLayout android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:layout_marginLeft="20dp" android:orientation="vertical" android:gravity="center_vertical" > <LinearLayout android:layout_width="match_parent" android:layout_height="15dp" android:layout_gravity="center_vertical"> <!--View to display the yellow color icon--> <View android:layout_width="15dp" android:layout_height="match_parent" android:background="@color/R"/> <!--Text view to display R --> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="R" android:paddingLeft="10dp"/> </LinearLayout> <!--Linear layout to display Python--> <LinearLayout android:layout_width="match_parent" android:layout_height="15dp" android:layout_gravity="center_vertical" android:layout_marginTop="5dp"> <!--View to display the green color icon--> <View android:layout_width="15dp" android:layout_height="match_parent" android:background="@color/Python"/> <!--Text view to display python text --> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Python" android:paddingLeft="10dp"/> </LinearLayout> <!--Linear layout to display C++--> <LinearLayout android:layout_width="match_parent" android:layout_height="15dp" android:layout_gravity="center_vertical" android:layout_marginTop="5dp"> <!--View to display the red color icon--> <View android:layout_width="15dp" android:layout_height="match_parent" android:background="@color/CPP"/> <!--Text view to display C++ text --> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="C++" android:paddingLeft="10dp"/> </LinearLayout> <!--Linear layout to display Java--> <LinearLayout android:layout_width="match_parent" android:layout_height="15dp" android:layout_gravity="center_vertical" android:layout_marginTop="5dp"> <!--View to display the blue color icon--> <View android:layout_width="15dp" android:layout_height="match_parent" android:background="@color/Java"/> <!--Text view to display Java text --> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Java" android:paddingLeft="10dp"/> </LinearLayout> </LinearLayout> </LinearLayout> </androidx.cardview.widget.CardView> <!-- Another Card view for displaying ---> <!-- Use of programming languages --> <androidx.cardview.widget.CardView android:layout_width="match_parent" android:layout_height="260dp" android:layout_below="@+id/cardViewGraph" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" android:layout_marginTop="20dp" android:layout_marginBottom="20dp" android:elevation="10dp" app:cardCornerRadius="10dp" android:id="@+id/details"> <!--Relative layout to display ---> <!-- use of programming languages --> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <!--Text view to use of ---> <!-- programming languages text--> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Use of Programming Languages(In Percentage):" android:textSize="23sp" android:textStyle="bold" android:layout_marginLeft="25dp" android:layout_marginTop="20dp"/> <!--View to display the line--> <View android:layout_width="match_parent" android:layout_height="1dp" android:background="@color/color_two" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" android:layout_marginTop="5dp"/> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginRight="25dp" android:layout_marginLeft="25dp" android:layout_marginTop="10dp" android:layout_marginBottom="10dp"> <!--Text view to display R --> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:fontFamily="sans-serif-light" android:text="R" android:textSize="18sp"/> <!--Text view to display the ---> <!-- percentage of programming language ---> <!-- used. For now default set to 0--> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="0" android:id="@+id/tvR" android:textAlignment="textEnd" android:textSize="18sp" android:textColor="@color/color_one" android:textStyle="bold" android:fontFamily="sans-serif-light" android:layout_alignParentRight="true"/> </RelativeLayout> <!--View to display the line--> <View android:layout_width="match_parent" android:layout_height="1dp" android:background="@color/color_two" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" /> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginRight="25dp" android:layout_marginLeft="25dp" android:layout_marginTop="10dp" android:layout_marginBottom="10dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:fontFamily="sans-serif-light" android:text="Python" android:textSize="18sp"/> <!--Text view to display the percentage ---> <!-- of programming language used. ---> <!-- For now default set to 0--> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="0" android:id="@+id/tvPython" android:textAlignment="textEnd" android:textSize="18sp" android:textColor="@color/color_one" android:textStyle="bold" android:fontFamily="sans-serif-light" android:layout_alignParentRight="true"/> </RelativeLayout> <View android:layout_width="match_parent" android:layout_height="1dp" android:background="@color/color_two" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" /> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginRight="25dp" android:layout_marginLeft="25dp" android:layout_marginTop="10dp" android:layout_marginBottom="10dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:fontFamily="sans-serif-light" android:text="C++" android:textSize="18sp"/> <!--Text view to display the percentage ---> <!-- of programming language used. ---> <!-- For now default set to 0--> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="0" android:id="@+id/tvCPP" android:textAlignment="textEnd" android:textSize="18sp" android:textColor="@color/color_one" android:textStyle="bold" android:fontFamily="sans-serif-light" android:layout_alignParentRight="true"/> </RelativeLayout> <View android:layout_width="match_parent" android:layout_height="1dp" android:background="@color/color_two" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" /> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginRight="25dp" android:layout_marginLeft="25dp" android:layout_marginTop="10dp" android:layout_marginBottom="10dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:fontFamily="sans-serif-light" android:text="Java" android:textSize="18sp"/> <!--Text view to display the percentage ---> <!-- of programming language used. ---> <!-- For now default set to 0--> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="0" android:id="@+id/tvJava" android:textAlignment="textEnd" android:textSize="18sp" android:textColor="@color/color_one" android:textStyle="bold" android:fontFamily="sans-serif-light" android:layout_alignParentRight="true"/> </RelativeLayout> </LinearLayout> </androidx.cardview.widget.CardView> </RelativeLayout>After using this code in .xml file, the UI will be like:Step4: Working with Java fileOpen the MainActivity.java file there within the class, first of all create the object of TextView class and the pie chart class.// Create the object of TextView and PieChart classTextView tvR, tvPython, tvCPP, tvJava;PieChart pieChart;Secondly inside onCreate() method, we have to link those objects with their respective id’s that we have given in .XML file.// Link those objects with their respective// id's that we have given in .XML filetvR = findViewById(R.id.tvR);tvPython = findViewById(R.id.tvPython);tvCPP = findViewById(R.id.tvCPP);tvJava = findViewById(R.id.tvJava);pieChart = findViewById(R.id.piechart);Creat a private void setData() method outside onCreate() method and define it.Inside setData() method the most important task is going to happen that is how we set the data in the text file and as well as on the piechart.First of all inside setData() method set the percentage of language used in their respective text view.// Set the percentage of language usedtvR.setText(Integer.toString(40));tvPython.setText(Integer.toString(30));tvCPP.setText(Integer.toString(5));tvJava.setText(Integer.toString(25));And then set this data to the pie chart and also set their respective colors using addPieSlice() method.// Set the data and color to the pie chartpieChart.addPieSlice( new PieModel( "R", Integer.parseInt(tvR.getText().toString()), Color.parseColor("#FFA726")));pieChart.addPieSlice( new PieModel( "Python", Integer.parseInt(tvPython.getText().toString()), Color.parseColor("#66BB6A")));pieChart.addPieSlice( new PieModel( "C++", Integer.parseInt(tvCPP.getText().toString()), Color.parseColor("#EF5350")));pieChart.addPieSlice( new PieModel( "Java", Integer.parseInt(tvJava.getText().toString()), Color.parseColor("#29B6F6")));For better look animate the piechart using startAnimation().// To animate the pie chartpieChart.startAnimation();At last invoke the setData() method inside onCreate() method.Below is the complete code for MainActivity.java file:MainActivity.javaMainActivity.javapackage com.example.piechart; // Import the required librariesimport androidx.appcompat.app.AppCompatActivity;import android.graphics.Color;import android.os.Bundle;import android.widget.TextView;import org.eazegraph.lib.charts.PieChart;import org.eazegraph.lib.models.PieModel; public class MainActivity extends AppCompatActivity { // Create the object of TextView // and PieChart class TextView tvR, tvPython, tvCPP, tvJava; PieChart pieChart; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Link those objects with their // respective id's that // we have given in .XML file tvR = findViewById(R.id.tvR); tvPython = findViewById(R.id.tvPython); tvCPP = findViewById(R.id.tvCPP); tvJava = findViewById(R.id.tvJava); pieChart = findViewById(R.id.piechart); // Creating a method setData() // to set the text in text view and pie chart setData(); } private void setData() { // Set the percentage of language used tvR.setText(Integer.toString(40)); tvPython.setText(Integer.toString(30)); tvCPP.setText(Integer.toString(5)); tvJava.setText(Integer.toString(25)); // Set the data and color to the pie chart pieChart.addPieSlice( new PieModel( "R", Integer.parseInt(tvR.getText().toString()), Color.parseColor("#FFA726"))); pieChart.addPieSlice( new PieModel( "Python", Integer.parseInt(tvPython.getText().toString()), Color.parseColor("#66BB6A"))); pieChart.addPieSlice( new PieModel( "C++", Integer.parseInt(tvCPP.getText().toString()), Color.parseColor("#EF5350"))); pieChart.addPieSlice( new PieModel( "Java", Integer.parseInt(tvJava.getText().toString()), Color.parseColor("#29B6F6"))); // To animate the pie chart pieChart.startAnimation(); }}
Step1: Opening a new projectOpen a new project just click of File option at topmost corner in left.Then click on new and open a new project with whatever name you want.Now we gonna work on Empty Activity with language as Java. Leave all other options as untouched.You can change the name of project as per your choice.By default, there will be two files activity_main.xml and MainActivity.java.
Open a new project just click of File option at topmost corner in left.
Then click on new and open a new project with whatever name you want.
Now we gonna work on Empty Activity with language as Java. Leave all other options as untouched.
You can change the name of project as per your choice.
By default, there will be two files activity_main.xml and MainActivity.java.
Step 2: Before going to the coding section first you have to do some pre-task.Go to app->res->values->colors.xml section and set the colors for your app.colors.xmlcolors.xml<?xml version="1.0" encoding="utf-8"?><resources> <color name="colorPrimary">#024265</color> <color name="colorPrimaryDark">#024265</color> <color name="colorAccent">#05af9b</color> <color name="color_one">#fb7268</color> <color name="color_white">#ededf2</color> <color name="color_two">#E3E0E0</color> <color name="R">#FFA726</color> <color name="Python">#66BB6A</color> <color name="CPP">#EF5350</color> <color name="Java">#29B6F6</color> </resources>Go to Gradle Scripts->build.gradle (Module: app) section and import following dependencies and click the “sync Now” on the above pop up.build.gradle (:app)build.gradle (:app)// For Card viewimplementation 'androidx.cardview:cardview:1.0.0' // Chart and graph libraryimplementation 'com.github.blackfizz:eazegraph:1.2.5l@aar'implementation 'com.nineoldandroids:library:2.4.0'
Go to app->res->values->colors.xml section and set the colors for your app.colors.xmlcolors.xml<?xml version="1.0" encoding="utf-8"?><resources> <color name="colorPrimary">#024265</color> <color name="colorPrimaryDark">#024265</color> <color name="colorAccent">#05af9b</color> <color name="color_one">#fb7268</color> <color name="color_white">#ededf2</color> <color name="color_two">#E3E0E0</color> <color name="R">#FFA726</color> <color name="Python">#66BB6A</color> <color name="CPP">#EF5350</color> <color name="Java">#29B6F6</color> </resources>
colors.xml
<?xml version="1.0" encoding="utf-8"?><resources> <color name="colorPrimary">#024265</color> <color name="colorPrimaryDark">#024265</color> <color name="colorAccent">#05af9b</color> <color name="color_one">#fb7268</color> <color name="color_white">#ededf2</color> <color name="color_two">#E3E0E0</color> <color name="R">#FFA726</color> <color name="Python">#66BB6A</color> <color name="CPP">#EF5350</color> <color name="Java">#29B6F6</color> </resources>
Go to Gradle Scripts->build.gradle (Module: app) section and import following dependencies and click the “sync Now” on the above pop up.build.gradle (:app)build.gradle (:app)// For Card viewimplementation 'androidx.cardview:cardview:1.0.0' // Chart and graph libraryimplementation 'com.github.blackfizz:eazegraph:1.2.5l@aar'implementation 'com.nineoldandroids:library:2.4.0'
build.gradle (:app)
// For Card viewimplementation 'androidx.cardview:cardview:1.0.0' // Chart and graph libraryimplementation 'com.github.blackfizz:eazegraph:1.2.5l@aar'implementation 'com.nineoldandroids:library:2.4.0'
Step3: Designing the UIBelow is the code for the xml file.actibity_main.xmlactibity_main.xml<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/color_white" tools:context=".MainActivity"> <!-- Card view for displaying the ---> <!-- Pie chart and details of pie chart --> <androidx.cardview.widget.CardView android:id="@+id/cardViewGraph" android:layout_width="match_parent" android:layout_height="200dp" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" android:layout_marginTop="15dp" android:elevation="10dp" app:cardCornerRadius="10dp"> <!--Linear layout to display pie chart ---> <!-- and details of pie chart--> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" android:weightSum="2"> <!--Pie chart to display the data--> <org.eazegraph.lib.charts.PieChart xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/piechart" android:layout_width="0dp" android:layout_height="match_parent" android:padding="6dp" android:layout_weight="1" android:layout_marginTop="15dp" android:layout_marginLeft="15dp" android:layout_marginBottom="15dp" /> <!--Creating another linear layout ---> <!-- to display pie chart details --> <LinearLayout android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:layout_marginLeft="20dp" android:orientation="vertical" android:gravity="center_vertical" > <LinearLayout android:layout_width="match_parent" android:layout_height="15dp" android:layout_gravity="center_vertical"> <!--View to display the yellow color icon--> <View android:layout_width="15dp" android:layout_height="match_parent" android:background="@color/R"/> <!--Text view to display R --> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="R" android:paddingLeft="10dp"/> </LinearLayout> <!--Linear layout to display Python--> <LinearLayout android:layout_width="match_parent" android:layout_height="15dp" android:layout_gravity="center_vertical" android:layout_marginTop="5dp"> <!--View to display the green color icon--> <View android:layout_width="15dp" android:layout_height="match_parent" android:background="@color/Python"/> <!--Text view to display python text --> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Python" android:paddingLeft="10dp"/> </LinearLayout> <!--Linear layout to display C++--> <LinearLayout android:layout_width="match_parent" android:layout_height="15dp" android:layout_gravity="center_vertical" android:layout_marginTop="5dp"> <!--View to display the red color icon--> <View android:layout_width="15dp" android:layout_height="match_parent" android:background="@color/CPP"/> <!--Text view to display C++ text --> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="C++" android:paddingLeft="10dp"/> </LinearLayout> <!--Linear layout to display Java--> <LinearLayout android:layout_width="match_parent" android:layout_height="15dp" android:layout_gravity="center_vertical" android:layout_marginTop="5dp"> <!--View to display the blue color icon--> <View android:layout_width="15dp" android:layout_height="match_parent" android:background="@color/Java"/> <!--Text view to display Java text --> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Java" android:paddingLeft="10dp"/> </LinearLayout> </LinearLayout> </LinearLayout> </androidx.cardview.widget.CardView> <!-- Another Card view for displaying ---> <!-- Use of programming languages --> <androidx.cardview.widget.CardView android:layout_width="match_parent" android:layout_height="260dp" android:layout_below="@+id/cardViewGraph" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" android:layout_marginTop="20dp" android:layout_marginBottom="20dp" android:elevation="10dp" app:cardCornerRadius="10dp" android:id="@+id/details"> <!--Relative layout to display ---> <!-- use of programming languages --> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <!--Text view to use of ---> <!-- programming languages text--> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Use of Programming Languages(In Percentage):" android:textSize="23sp" android:textStyle="bold" android:layout_marginLeft="25dp" android:layout_marginTop="20dp"/> <!--View to display the line--> <View android:layout_width="match_parent" android:layout_height="1dp" android:background="@color/color_two" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" android:layout_marginTop="5dp"/> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginRight="25dp" android:layout_marginLeft="25dp" android:layout_marginTop="10dp" android:layout_marginBottom="10dp"> <!--Text view to display R --> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:fontFamily="sans-serif-light" android:text="R" android:textSize="18sp"/> <!--Text view to display the ---> <!-- percentage of programming language ---> <!-- used. For now default set to 0--> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="0" android:id="@+id/tvR" android:textAlignment="textEnd" android:textSize="18sp" android:textColor="@color/color_one" android:textStyle="bold" android:fontFamily="sans-serif-light" android:layout_alignParentRight="true"/> </RelativeLayout> <!--View to display the line--> <View android:layout_width="match_parent" android:layout_height="1dp" android:background="@color/color_two" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" /> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginRight="25dp" android:layout_marginLeft="25dp" android:layout_marginTop="10dp" android:layout_marginBottom="10dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:fontFamily="sans-serif-light" android:text="Python" android:textSize="18sp"/> <!--Text view to display the percentage ---> <!-- of programming language used. ---> <!-- For now default set to 0--> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="0" android:id="@+id/tvPython" android:textAlignment="textEnd" android:textSize="18sp" android:textColor="@color/color_one" android:textStyle="bold" android:fontFamily="sans-serif-light" android:layout_alignParentRight="true"/> </RelativeLayout> <View android:layout_width="match_parent" android:layout_height="1dp" android:background="@color/color_two" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" /> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginRight="25dp" android:layout_marginLeft="25dp" android:layout_marginTop="10dp" android:layout_marginBottom="10dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:fontFamily="sans-serif-light" android:text="C++" android:textSize="18sp"/> <!--Text view to display the percentage ---> <!-- of programming language used. ---> <!-- For now default set to 0--> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="0" android:id="@+id/tvCPP" android:textAlignment="textEnd" android:textSize="18sp" android:textColor="@color/color_one" android:textStyle="bold" android:fontFamily="sans-serif-light" android:layout_alignParentRight="true"/> </RelativeLayout> <View android:layout_width="match_parent" android:layout_height="1dp" android:background="@color/color_two" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" /> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginRight="25dp" android:layout_marginLeft="25dp" android:layout_marginTop="10dp" android:layout_marginBottom="10dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:fontFamily="sans-serif-light" android:text="Java" android:textSize="18sp"/> <!--Text view to display the percentage ---> <!-- of programming language used. ---> <!-- For now default set to 0--> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="0" android:id="@+id/tvJava" android:textAlignment="textEnd" android:textSize="18sp" android:textColor="@color/color_one" android:textStyle="bold" android:fontFamily="sans-serif-light" android:layout_alignParentRight="true"/> </RelativeLayout> </LinearLayout> </androidx.cardview.widget.CardView> </RelativeLayout>After using this code in .xml file, the UI will be like:
Below is the code for the xml file.actibity_main.xmlactibity_main.xml<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/color_white" tools:context=".MainActivity"> <!-- Card view for displaying the ---> <!-- Pie chart and details of pie chart --> <androidx.cardview.widget.CardView android:id="@+id/cardViewGraph" android:layout_width="match_parent" android:layout_height="200dp" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" android:layout_marginTop="15dp" android:elevation="10dp" app:cardCornerRadius="10dp"> <!--Linear layout to display pie chart ---> <!-- and details of pie chart--> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" android:weightSum="2"> <!--Pie chart to display the data--> <org.eazegraph.lib.charts.PieChart xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/piechart" android:layout_width="0dp" android:layout_height="match_parent" android:padding="6dp" android:layout_weight="1" android:layout_marginTop="15dp" android:layout_marginLeft="15dp" android:layout_marginBottom="15dp" /> <!--Creating another linear layout ---> <!-- to display pie chart details --> <LinearLayout android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:layout_marginLeft="20dp" android:orientation="vertical" android:gravity="center_vertical" > <LinearLayout android:layout_width="match_parent" android:layout_height="15dp" android:layout_gravity="center_vertical"> <!--View to display the yellow color icon--> <View android:layout_width="15dp" android:layout_height="match_parent" android:background="@color/R"/> <!--Text view to display R --> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="R" android:paddingLeft="10dp"/> </LinearLayout> <!--Linear layout to display Python--> <LinearLayout android:layout_width="match_parent" android:layout_height="15dp" android:layout_gravity="center_vertical" android:layout_marginTop="5dp"> <!--View to display the green color icon--> <View android:layout_width="15dp" android:layout_height="match_parent" android:background="@color/Python"/> <!--Text view to display python text --> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Python" android:paddingLeft="10dp"/> </LinearLayout> <!--Linear layout to display C++--> <LinearLayout android:layout_width="match_parent" android:layout_height="15dp" android:layout_gravity="center_vertical" android:layout_marginTop="5dp"> <!--View to display the red color icon--> <View android:layout_width="15dp" android:layout_height="match_parent" android:background="@color/CPP"/> <!--Text view to display C++ text --> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="C++" android:paddingLeft="10dp"/> </LinearLayout> <!--Linear layout to display Java--> <LinearLayout android:layout_width="match_parent" android:layout_height="15dp" android:layout_gravity="center_vertical" android:layout_marginTop="5dp"> <!--View to display the blue color icon--> <View android:layout_width="15dp" android:layout_height="match_parent" android:background="@color/Java"/> <!--Text view to display Java text --> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Java" android:paddingLeft="10dp"/> </LinearLayout> </LinearLayout> </LinearLayout> </androidx.cardview.widget.CardView> <!-- Another Card view for displaying ---> <!-- Use of programming languages --> <androidx.cardview.widget.CardView android:layout_width="match_parent" android:layout_height="260dp" android:layout_below="@+id/cardViewGraph" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" android:layout_marginTop="20dp" android:layout_marginBottom="20dp" android:elevation="10dp" app:cardCornerRadius="10dp" android:id="@+id/details"> <!--Relative layout to display ---> <!-- use of programming languages --> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <!--Text view to use of ---> <!-- programming languages text--> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Use of Programming Languages(In Percentage):" android:textSize="23sp" android:textStyle="bold" android:layout_marginLeft="25dp" android:layout_marginTop="20dp"/> <!--View to display the line--> <View android:layout_width="match_parent" android:layout_height="1dp" android:background="@color/color_two" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" android:layout_marginTop="5dp"/> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginRight="25dp" android:layout_marginLeft="25dp" android:layout_marginTop="10dp" android:layout_marginBottom="10dp"> <!--Text view to display R --> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:fontFamily="sans-serif-light" android:text="R" android:textSize="18sp"/> <!--Text view to display the ---> <!-- percentage of programming language ---> <!-- used. For now default set to 0--> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="0" android:id="@+id/tvR" android:textAlignment="textEnd" android:textSize="18sp" android:textColor="@color/color_one" android:textStyle="bold" android:fontFamily="sans-serif-light" android:layout_alignParentRight="true"/> </RelativeLayout> <!--View to display the line--> <View android:layout_width="match_parent" android:layout_height="1dp" android:background="@color/color_two" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" /> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginRight="25dp" android:layout_marginLeft="25dp" android:layout_marginTop="10dp" android:layout_marginBottom="10dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:fontFamily="sans-serif-light" android:text="Python" android:textSize="18sp"/> <!--Text view to display the percentage ---> <!-- of programming language used. ---> <!-- For now default set to 0--> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="0" android:id="@+id/tvPython" android:textAlignment="textEnd" android:textSize="18sp" android:textColor="@color/color_one" android:textStyle="bold" android:fontFamily="sans-serif-light" android:layout_alignParentRight="true"/> </RelativeLayout> <View android:layout_width="match_parent" android:layout_height="1dp" android:background="@color/color_two" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" /> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginRight="25dp" android:layout_marginLeft="25dp" android:layout_marginTop="10dp" android:layout_marginBottom="10dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:fontFamily="sans-serif-light" android:text="C++" android:textSize="18sp"/> <!--Text view to display the percentage ---> <!-- of programming language used. ---> <!-- For now default set to 0--> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="0" android:id="@+id/tvCPP" android:textAlignment="textEnd" android:textSize="18sp" android:textColor="@color/color_one" android:textStyle="bold" android:fontFamily="sans-serif-light" android:layout_alignParentRight="true"/> </RelativeLayout> <View android:layout_width="match_parent" android:layout_height="1dp" android:background="@color/color_two" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" /> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginRight="25dp" android:layout_marginLeft="25dp" android:layout_marginTop="10dp" android:layout_marginBottom="10dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:fontFamily="sans-serif-light" android:text="Java" android:textSize="18sp"/> <!--Text view to display the percentage ---> <!-- of programming language used. ---> <!-- For now default set to 0--> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="0" android:id="@+id/tvJava" android:textAlignment="textEnd" android:textSize="18sp" android:textColor="@color/color_one" android:textStyle="bold" android:fontFamily="sans-serif-light" android:layout_alignParentRight="true"/> </RelativeLayout> </LinearLayout> </androidx.cardview.widget.CardView> </RelativeLayout>
actibity_main.xml
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/color_white" tools:context=".MainActivity"> <!-- Card view for displaying the ---> <!-- Pie chart and details of pie chart --> <androidx.cardview.widget.CardView android:id="@+id/cardViewGraph" android:layout_width="match_parent" android:layout_height="200dp" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" android:layout_marginTop="15dp" android:elevation="10dp" app:cardCornerRadius="10dp"> <!--Linear layout to display pie chart ---> <!-- and details of pie chart--> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" android:weightSum="2"> <!--Pie chart to display the data--> <org.eazegraph.lib.charts.PieChart xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/piechart" android:layout_width="0dp" android:layout_height="match_parent" android:padding="6dp" android:layout_weight="1" android:layout_marginTop="15dp" android:layout_marginLeft="15dp" android:layout_marginBottom="15dp" /> <!--Creating another linear layout ---> <!-- to display pie chart details --> <LinearLayout android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:layout_marginLeft="20dp" android:orientation="vertical" android:gravity="center_vertical" > <LinearLayout android:layout_width="match_parent" android:layout_height="15dp" android:layout_gravity="center_vertical"> <!--View to display the yellow color icon--> <View android:layout_width="15dp" android:layout_height="match_parent" android:background="@color/R"/> <!--Text view to display R --> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="R" android:paddingLeft="10dp"/> </LinearLayout> <!--Linear layout to display Python--> <LinearLayout android:layout_width="match_parent" android:layout_height="15dp" android:layout_gravity="center_vertical" android:layout_marginTop="5dp"> <!--View to display the green color icon--> <View android:layout_width="15dp" android:layout_height="match_parent" android:background="@color/Python"/> <!--Text view to display python text --> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Python" android:paddingLeft="10dp"/> </LinearLayout> <!--Linear layout to display C++--> <LinearLayout android:layout_width="match_parent" android:layout_height="15dp" android:layout_gravity="center_vertical" android:layout_marginTop="5dp"> <!--View to display the red color icon--> <View android:layout_width="15dp" android:layout_height="match_parent" android:background="@color/CPP"/> <!--Text view to display C++ text --> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="C++" android:paddingLeft="10dp"/> </LinearLayout> <!--Linear layout to display Java--> <LinearLayout android:layout_width="match_parent" android:layout_height="15dp" android:layout_gravity="center_vertical" android:layout_marginTop="5dp"> <!--View to display the blue color icon--> <View android:layout_width="15dp" android:layout_height="match_parent" android:background="@color/Java"/> <!--Text view to display Java text --> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Java" android:paddingLeft="10dp"/> </LinearLayout> </LinearLayout> </LinearLayout> </androidx.cardview.widget.CardView> <!-- Another Card view for displaying ---> <!-- Use of programming languages --> <androidx.cardview.widget.CardView android:layout_width="match_parent" android:layout_height="260dp" android:layout_below="@+id/cardViewGraph" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" android:layout_marginTop="20dp" android:layout_marginBottom="20dp" android:elevation="10dp" app:cardCornerRadius="10dp" android:id="@+id/details"> <!--Relative layout to display ---> <!-- use of programming languages --> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <!--Text view to use of ---> <!-- programming languages text--> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Use of Programming Languages(In Percentage):" android:textSize="23sp" android:textStyle="bold" android:layout_marginLeft="25dp" android:layout_marginTop="20dp"/> <!--View to display the line--> <View android:layout_width="match_parent" android:layout_height="1dp" android:background="@color/color_two" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" android:layout_marginTop="5dp"/> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginRight="25dp" android:layout_marginLeft="25dp" android:layout_marginTop="10dp" android:layout_marginBottom="10dp"> <!--Text view to display R --> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:fontFamily="sans-serif-light" android:text="R" android:textSize="18sp"/> <!--Text view to display the ---> <!-- percentage of programming language ---> <!-- used. For now default set to 0--> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="0" android:id="@+id/tvR" android:textAlignment="textEnd" android:textSize="18sp" android:textColor="@color/color_one" android:textStyle="bold" android:fontFamily="sans-serif-light" android:layout_alignParentRight="true"/> </RelativeLayout> <!--View to display the line--> <View android:layout_width="match_parent" android:layout_height="1dp" android:background="@color/color_two" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" /> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginRight="25dp" android:layout_marginLeft="25dp" android:layout_marginTop="10dp" android:layout_marginBottom="10dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:fontFamily="sans-serif-light" android:text="Python" android:textSize="18sp"/> <!--Text view to display the percentage ---> <!-- of programming language used. ---> <!-- For now default set to 0--> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="0" android:id="@+id/tvPython" android:textAlignment="textEnd" android:textSize="18sp" android:textColor="@color/color_one" android:textStyle="bold" android:fontFamily="sans-serif-light" android:layout_alignParentRight="true"/> </RelativeLayout> <View android:layout_width="match_parent" android:layout_height="1dp" android:background="@color/color_two" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" /> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginRight="25dp" android:layout_marginLeft="25dp" android:layout_marginTop="10dp" android:layout_marginBottom="10dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:fontFamily="sans-serif-light" android:text="C++" android:textSize="18sp"/> <!--Text view to display the percentage ---> <!-- of programming language used. ---> <!-- For now default set to 0--> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="0" android:id="@+id/tvCPP" android:textAlignment="textEnd" android:textSize="18sp" android:textColor="@color/color_one" android:textStyle="bold" android:fontFamily="sans-serif-light" android:layout_alignParentRight="true"/> </RelativeLayout> <View android:layout_width="match_parent" android:layout_height="1dp" android:background="@color/color_two" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" /> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginRight="25dp" android:layout_marginLeft="25dp" android:layout_marginTop="10dp" android:layout_marginBottom="10dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:fontFamily="sans-serif-light" android:text="Java" android:textSize="18sp"/> <!--Text view to display the percentage ---> <!-- of programming language used. ---> <!-- For now default set to 0--> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="0" android:id="@+id/tvJava" android:textAlignment="textEnd" android:textSize="18sp" android:textColor="@color/color_one" android:textStyle="bold" android:fontFamily="sans-serif-light" android:layout_alignParentRight="true"/> </RelativeLayout> </LinearLayout> </androidx.cardview.widget.CardView> </RelativeLayout>
After using this code in .xml file, the UI will be like:
Step4: Working with Java fileOpen the MainActivity.java file there within the class, first of all create the object of TextView class and the pie chart class.// Create the object of TextView and PieChart classTextView tvR, tvPython, tvCPP, tvJava;PieChart pieChart;Secondly inside onCreate() method, we have to link those objects with their respective id’s that we have given in .XML file.// Link those objects with their respective// id's that we have given in .XML filetvR = findViewById(R.id.tvR);tvPython = findViewById(R.id.tvPython);tvCPP = findViewById(R.id.tvCPP);tvJava = findViewById(R.id.tvJava);pieChart = findViewById(R.id.piechart);Creat a private void setData() method outside onCreate() method and define it.Inside setData() method the most important task is going to happen that is how we set the data in the text file and as well as on the piechart.First of all inside setData() method set the percentage of language used in their respective text view.// Set the percentage of language usedtvR.setText(Integer.toString(40));tvPython.setText(Integer.toString(30));tvCPP.setText(Integer.toString(5));tvJava.setText(Integer.toString(25));And then set this data to the pie chart and also set their respective colors using addPieSlice() method.// Set the data and color to the pie chartpieChart.addPieSlice( new PieModel( "R", Integer.parseInt(tvR.getText().toString()), Color.parseColor("#FFA726")));pieChart.addPieSlice( new PieModel( "Python", Integer.parseInt(tvPython.getText().toString()), Color.parseColor("#66BB6A")));pieChart.addPieSlice( new PieModel( "C++", Integer.parseInt(tvCPP.getText().toString()), Color.parseColor("#EF5350")));pieChart.addPieSlice( new PieModel( "Java", Integer.parseInt(tvJava.getText().toString()), Color.parseColor("#29B6F6")));For better look animate the piechart using startAnimation().// To animate the pie chartpieChart.startAnimation();At last invoke the setData() method inside onCreate() method.Below is the complete code for MainActivity.java file:MainActivity.javaMainActivity.javapackage com.example.piechart; // Import the required librariesimport androidx.appcompat.app.AppCompatActivity;import android.graphics.Color;import android.os.Bundle;import android.widget.TextView;import org.eazegraph.lib.charts.PieChart;import org.eazegraph.lib.models.PieModel; public class MainActivity extends AppCompatActivity { // Create the object of TextView // and PieChart class TextView tvR, tvPython, tvCPP, tvJava; PieChart pieChart; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Link those objects with their // respective id's that // we have given in .XML file tvR = findViewById(R.id.tvR); tvPython = findViewById(R.id.tvPython); tvCPP = findViewById(R.id.tvCPP); tvJava = findViewById(R.id.tvJava); pieChart = findViewById(R.id.piechart); // Creating a method setData() // to set the text in text view and pie chart setData(); } private void setData() { // Set the percentage of language used tvR.setText(Integer.toString(40)); tvPython.setText(Integer.toString(30)); tvCPP.setText(Integer.toString(5)); tvJava.setText(Integer.toString(25)); // Set the data and color to the pie chart pieChart.addPieSlice( new PieModel( "R", Integer.parseInt(tvR.getText().toString()), Color.parseColor("#FFA726"))); pieChart.addPieSlice( new PieModel( "Python", Integer.parseInt(tvPython.getText().toString()), Color.parseColor("#66BB6A"))); pieChart.addPieSlice( new PieModel( "C++", Integer.parseInt(tvCPP.getText().toString()), Color.parseColor("#EF5350"))); pieChart.addPieSlice( new PieModel( "Java", Integer.parseInt(tvJava.getText().toString()), Color.parseColor("#29B6F6"))); // To animate the pie chart pieChart.startAnimation(); }}
Open the MainActivity.java file there within the class, first of all create the object of TextView class and the pie chart class.// Create the object of TextView and PieChart classTextView tvR, tvPython, tvCPP, tvJava;PieChart pieChart;
// Create the object of TextView and PieChart classTextView tvR, tvPython, tvCPP, tvJava;PieChart pieChart;
Secondly inside onCreate() method, we have to link those objects with their respective id’s that we have given in .XML file.// Link those objects with their respective// id's that we have given in .XML filetvR = findViewById(R.id.tvR);tvPython = findViewById(R.id.tvPython);tvCPP = findViewById(R.id.tvCPP);tvJava = findViewById(R.id.tvJava);pieChart = findViewById(R.id.piechart);
// Link those objects with their respective// id's that we have given in .XML filetvR = findViewById(R.id.tvR);tvPython = findViewById(R.id.tvPython);tvCPP = findViewById(R.id.tvCPP);tvJava = findViewById(R.id.tvJava);pieChart = findViewById(R.id.piechart);
Creat a private void setData() method outside onCreate() method and define it.
Inside setData() method the most important task is going to happen that is how we set the data in the text file and as well as on the piechart.
First of all inside setData() method set the percentage of language used in their respective text view.// Set the percentage of language usedtvR.setText(Integer.toString(40));tvPython.setText(Integer.toString(30));tvCPP.setText(Integer.toString(5));tvJava.setText(Integer.toString(25));
// Set the percentage of language usedtvR.setText(Integer.toString(40));tvPython.setText(Integer.toString(30));tvCPP.setText(Integer.toString(5));tvJava.setText(Integer.toString(25));
And then set this data to the pie chart and also set their respective colors using addPieSlice() method.// Set the data and color to the pie chartpieChart.addPieSlice( new PieModel( "R", Integer.parseInt(tvR.getText().toString()), Color.parseColor("#FFA726")));pieChart.addPieSlice( new PieModel( "Python", Integer.parseInt(tvPython.getText().toString()), Color.parseColor("#66BB6A")));pieChart.addPieSlice( new PieModel( "C++", Integer.parseInt(tvCPP.getText().toString()), Color.parseColor("#EF5350")));pieChart.addPieSlice( new PieModel( "Java", Integer.parseInt(tvJava.getText().toString()), Color.parseColor("#29B6F6")));
// Set the data and color to the pie chartpieChart.addPieSlice( new PieModel( "R", Integer.parseInt(tvR.getText().toString()), Color.parseColor("#FFA726")));pieChart.addPieSlice( new PieModel( "Python", Integer.parseInt(tvPython.getText().toString()), Color.parseColor("#66BB6A")));pieChart.addPieSlice( new PieModel( "C++", Integer.parseInt(tvCPP.getText().toString()), Color.parseColor("#EF5350")));pieChart.addPieSlice( new PieModel( "Java", Integer.parseInt(tvJava.getText().toString()), Color.parseColor("#29B6F6")));
For better look animate the piechart using startAnimation().// To animate the pie chartpieChart.startAnimation();
// To animate the pie chartpieChart.startAnimation();
At last invoke the setData() method inside onCreate() method.
Below is the complete code for MainActivity.java file:
MainActivity.java
package com.example.piechart; // Import the required librariesimport androidx.appcompat.app.AppCompatActivity;import android.graphics.Color;import android.os.Bundle;import android.widget.TextView;import org.eazegraph.lib.charts.PieChart;import org.eazegraph.lib.models.PieModel; public class MainActivity extends AppCompatActivity { // Create the object of TextView // and PieChart class TextView tvR, tvPython, tvCPP, tvJava; PieChart pieChart; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Link those objects with their // respective id's that // we have given in .XML file tvR = findViewById(R.id.tvR); tvPython = findViewById(R.id.tvPython); tvCPP = findViewById(R.id.tvCPP); tvJava = findViewById(R.id.tvJava); pieChart = findViewById(R.id.piechart); // Creating a method setData() // to set the text in text view and pie chart setData(); } private void setData() { // Set the percentage of language used tvR.setText(Integer.toString(40)); tvPython.setText(Integer.toString(30)); tvCPP.setText(Integer.toString(5)); tvJava.setText(Integer.toString(25)); // Set the data and color to the pie chart pieChart.addPieSlice( new PieModel( "R", Integer.parseInt(tvR.getText().toString()), Color.parseColor("#FFA726"))); pieChart.addPieSlice( new PieModel( "Python", Integer.parseInt(tvPython.getText().toString()), Color.parseColor("#66BB6A"))); pieChart.addPieSlice( new PieModel( "C++", Integer.parseInt(tvCPP.getText().toString()), Color.parseColor("#EF5350"))); pieChart.addPieSlice( new PieModel( "Java", Integer.parseInt(tvJava.getText().toString()), Color.parseColor("#29B6F6"))); // To animate the pie chart pieChart.startAnimation(); }}
Output:
android
How To
Java
Write From Home
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Align Text in HTML?
How to Install OpenCV for Python on Windows?
How to filter object array based on attributes?
Java Tutorial
How to Install FFmpeg on Windows?
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples | [
{
"code": null,
"e": 26123,
"s": 26095,
"text": "\n13 May, 2020"
},
{
"code": null,
"e": 26139,
"s": 26123,
"text": "Pre-requisites:"
},
{
"code": null,
"e": 26190,
"s": 26139,
"text": "Android App Development Fundamentals for Beginners"
},
{
"code": null,
"e": 26233,
"s": 26190,
"text": "Guide to Install and Set up Android Studio"
},
{
"code": null,
"e": 26296,
"s": 26233,
"text": "Android | How to Create/Start a New Project in Android Studio?"
},
{
"code": null,
"e": 26337,
"s": 26296,
"text": "Android | Running your first Android app"
},
{
"code": null,
"e": 26783,
"s": 26337,
"text": "A pie chart is a circular statistical graphic, which is divided into slices to illustrate numerical proportions. It depicts a special chart that uses “pie slices”, where each sector shows the relative sizes of data. A circular chart cuts in a form of radii into segments describing relative frequencies or magnitude also known as circle graph. A pie chart represents numbers in percentages, and the total sum of all segments needs to equal 100%."
},
{
"code": null,
"e": 26846,
"s": 26783,
"text": "So let’s see the steps to add a Pie Chart into an Android app."
},
{
"code": null,
"e": 47479,
"s": 26846,
"text": "Step1: Opening a new projectOpen a new project just click of File option at topmost corner in left.Then click on new and open a new project with whatever name you want.Now we gonna work on Empty Activity with language as Java. Leave all other options as untouched.You can change the name of project as per your choice.By default, there will be two files activity_main.xml and MainActivity.java.Step 2: Before going to the coding section first you have to do some pre-task.Go to app->res->values->colors.xml section and set the colors for your app.colors.xmlcolors.xml<?xml version=\"1.0\" encoding=\"utf-8\"?><resources> <color name=\"colorPrimary\">#024265</color> <color name=\"colorPrimaryDark\">#024265</color> <color name=\"colorAccent\">#05af9b</color> <color name=\"color_one\">#fb7268</color> <color name=\"color_white\">#ededf2</color> <color name=\"color_two\">#E3E0E0</color> <color name=\"R\">#FFA726</color> <color name=\"Python\">#66BB6A</color> <color name=\"CPP\">#EF5350</color> <color name=\"Java\">#29B6F6</color> </resources>Go to Gradle Scripts->build.gradle (Module: app) section and import following dependencies and click the “sync Now” on the above pop up.build.gradle (:app)build.gradle (:app)// For Card viewimplementation 'androidx.cardview:cardview:1.0.0' // Chart and graph libraryimplementation 'com.github.blackfizz:eazegraph:1.2.5l@aar'implementation 'com.nineoldandroids:library:2.4.0'Step3: Designing the UIBelow is the code for the xml file.actibity_main.xmlactibity_main.xml<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:background=\"@color/color_white\" tools:context=\".MainActivity\"> <!-- Card view for displaying the ---> <!-- Pie chart and details of pie chart --> <androidx.cardview.widget.CardView android:id=\"@+id/cardViewGraph\" android:layout_width=\"match_parent\" android:layout_height=\"200dp\" android:layout_marginLeft=\"20dp\" android:layout_marginRight=\"20dp\" android:layout_marginTop=\"15dp\" android:elevation=\"10dp\" app:cardCornerRadius=\"10dp\"> <!--Linear layout to display pie chart ---> <!-- and details of pie chart--> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"horizontal\" android:weightSum=\"2\"> <!--Pie chart to display the data--> <org.eazegraph.lib.charts.PieChart xmlns:app=\"http://schemas.android.com/apk/res-auto\" android:id=\"@+id/piechart\" android:layout_width=\"0dp\" android:layout_height=\"match_parent\" android:padding=\"6dp\" android:layout_weight=\"1\" android:layout_marginTop=\"15dp\" android:layout_marginLeft=\"15dp\" android:layout_marginBottom=\"15dp\" /> <!--Creating another linear layout ---> <!-- to display pie chart details --> <LinearLayout android:layout_width=\"0dp\" android:layout_height=\"match_parent\" android:layout_weight=\"1\" android:layout_marginLeft=\"20dp\" android:orientation=\"vertical\" android:gravity=\"center_vertical\" > <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"15dp\" android:layout_gravity=\"center_vertical\"> <!--View to display the yellow color icon--> <View android:layout_width=\"15dp\" android:layout_height=\"match_parent\" android:background=\"@color/R\"/> <!--Text view to display R --> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"R\" android:paddingLeft=\"10dp\"/> </LinearLayout> <!--Linear layout to display Python--> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"15dp\" android:layout_gravity=\"center_vertical\" android:layout_marginTop=\"5dp\"> <!--View to display the green color icon--> <View android:layout_width=\"15dp\" android:layout_height=\"match_parent\" android:background=\"@color/Python\"/> <!--Text view to display python text --> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Python\" android:paddingLeft=\"10dp\"/> </LinearLayout> <!--Linear layout to display C++--> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"15dp\" android:layout_gravity=\"center_vertical\" android:layout_marginTop=\"5dp\"> <!--View to display the red color icon--> <View android:layout_width=\"15dp\" android:layout_height=\"match_parent\" android:background=\"@color/CPP\"/> <!--Text view to display C++ text --> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"C++\" android:paddingLeft=\"10dp\"/> </LinearLayout> <!--Linear layout to display Java--> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"15dp\" android:layout_gravity=\"center_vertical\" android:layout_marginTop=\"5dp\"> <!--View to display the blue color icon--> <View android:layout_width=\"15dp\" android:layout_height=\"match_parent\" android:background=\"@color/Java\"/> <!--Text view to display Java text --> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Java\" android:paddingLeft=\"10dp\"/> </LinearLayout> </LinearLayout> </LinearLayout> </androidx.cardview.widget.CardView> <!-- Another Card view for displaying ---> <!-- Use of programming languages --> <androidx.cardview.widget.CardView android:layout_width=\"match_parent\" android:layout_height=\"260dp\" android:layout_below=\"@+id/cardViewGraph\" android:layout_marginLeft=\"20dp\" android:layout_marginRight=\"20dp\" android:layout_marginTop=\"20dp\" android:layout_marginBottom=\"20dp\" android:elevation=\"10dp\" app:cardCornerRadius=\"10dp\" android:id=\"@+id/details\"> <!--Relative layout to display ---> <!-- use of programming languages --> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"vertical\"> <!--Text view to use of ---> <!-- programming languages text--> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:text=\"Use of Programming Languages(In Percentage):\" android:textSize=\"23sp\" android:textStyle=\"bold\" android:layout_marginLeft=\"25dp\" android:layout_marginTop=\"20dp\"/> <!--View to display the line--> <View android:layout_width=\"match_parent\" android:layout_height=\"1dp\" android:background=\"@color/color_two\" android:layout_marginLeft=\"20dp\" android:layout_marginRight=\"20dp\" android:layout_marginTop=\"5dp\"/> <RelativeLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginRight=\"25dp\" android:layout_marginLeft=\"25dp\" android:layout_marginTop=\"10dp\" android:layout_marginBottom=\"10dp\"> <!--Text view to display R --> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:fontFamily=\"sans-serif-light\" android:text=\"R\" android:textSize=\"18sp\"/> <!--Text view to display the ---> <!-- percentage of programming language ---> <!-- used. For now default set to 0--> <TextView android:layout_width=\"fill_parent\" android:layout_height=\"wrap_content\" android:text=\"0\" android:id=\"@+id/tvR\" android:textAlignment=\"textEnd\" android:textSize=\"18sp\" android:textColor=\"@color/color_one\" android:textStyle=\"bold\" android:fontFamily=\"sans-serif-light\" android:layout_alignParentRight=\"true\"/> </RelativeLayout> <!--View to display the line--> <View android:layout_width=\"match_parent\" android:layout_height=\"1dp\" android:background=\"@color/color_two\" android:layout_marginLeft=\"20dp\" android:layout_marginRight=\"20dp\" /> <RelativeLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginRight=\"25dp\" android:layout_marginLeft=\"25dp\" android:layout_marginTop=\"10dp\" android:layout_marginBottom=\"10dp\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:fontFamily=\"sans-serif-light\" android:text=\"Python\" android:textSize=\"18sp\"/> <!--Text view to display the percentage ---> <!-- of programming language used. ---> <!-- For now default set to 0--> <TextView android:layout_width=\"fill_parent\" android:layout_height=\"wrap_content\" android:text=\"0\" android:id=\"@+id/tvPython\" android:textAlignment=\"textEnd\" android:textSize=\"18sp\" android:textColor=\"@color/color_one\" android:textStyle=\"bold\" android:fontFamily=\"sans-serif-light\" android:layout_alignParentRight=\"true\"/> </RelativeLayout> <View android:layout_width=\"match_parent\" android:layout_height=\"1dp\" android:background=\"@color/color_two\" android:layout_marginLeft=\"20dp\" android:layout_marginRight=\"20dp\" /> <RelativeLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginRight=\"25dp\" android:layout_marginLeft=\"25dp\" android:layout_marginTop=\"10dp\" android:layout_marginBottom=\"10dp\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:fontFamily=\"sans-serif-light\" android:text=\"C++\" android:textSize=\"18sp\"/> <!--Text view to display the percentage ---> <!-- of programming language used. ---> <!-- For now default set to 0--> <TextView android:layout_width=\"fill_parent\" android:layout_height=\"wrap_content\" android:text=\"0\" android:id=\"@+id/tvCPP\" android:textAlignment=\"textEnd\" android:textSize=\"18sp\" android:textColor=\"@color/color_one\" android:textStyle=\"bold\" android:fontFamily=\"sans-serif-light\" android:layout_alignParentRight=\"true\"/> </RelativeLayout> <View android:layout_width=\"match_parent\" android:layout_height=\"1dp\" android:background=\"@color/color_two\" android:layout_marginLeft=\"20dp\" android:layout_marginRight=\"20dp\" /> <RelativeLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginRight=\"25dp\" android:layout_marginLeft=\"25dp\" android:layout_marginTop=\"10dp\" android:layout_marginBottom=\"10dp\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:fontFamily=\"sans-serif-light\" android:text=\"Java\" android:textSize=\"18sp\"/> <!--Text view to display the percentage ---> <!-- of programming language used. ---> <!-- For now default set to 0--> <TextView android:layout_width=\"fill_parent\" android:layout_height=\"wrap_content\" android:text=\"0\" android:id=\"@+id/tvJava\" android:textAlignment=\"textEnd\" android:textSize=\"18sp\" android:textColor=\"@color/color_one\" android:textStyle=\"bold\" android:fontFamily=\"sans-serif-light\" android:layout_alignParentRight=\"true\"/> </RelativeLayout> </LinearLayout> </androidx.cardview.widget.CardView> </RelativeLayout>After using this code in .xml file, the UI will be like:Step4: Working with Java fileOpen the MainActivity.java file there within the class, first of all create the object of TextView class and the pie chart class.// Create the object of TextView and PieChart classTextView tvR, tvPython, tvCPP, tvJava;PieChart pieChart;Secondly inside onCreate() method, we have to link those objects with their respective id’s that we have given in .XML file.// Link those objects with their respective// id's that we have given in .XML filetvR = findViewById(R.id.tvR);tvPython = findViewById(R.id.tvPython);tvCPP = findViewById(R.id.tvCPP);tvJava = findViewById(R.id.tvJava);pieChart = findViewById(R.id.piechart);Creat a private void setData() method outside onCreate() method and define it.Inside setData() method the most important task is going to happen that is how we set the data in the text file and as well as on the piechart.First of all inside setData() method set the percentage of language used in their respective text view.// Set the percentage of language usedtvR.setText(Integer.toString(40));tvPython.setText(Integer.toString(30));tvCPP.setText(Integer.toString(5));tvJava.setText(Integer.toString(25));And then set this data to the pie chart and also set their respective colors using addPieSlice() method.// Set the data and color to the pie chartpieChart.addPieSlice( new PieModel( \"R\", Integer.parseInt(tvR.getText().toString()), Color.parseColor(\"#FFA726\")));pieChart.addPieSlice( new PieModel( \"Python\", Integer.parseInt(tvPython.getText().toString()), Color.parseColor(\"#66BB6A\")));pieChart.addPieSlice( new PieModel( \"C++\", Integer.parseInt(tvCPP.getText().toString()), Color.parseColor(\"#EF5350\")));pieChart.addPieSlice( new PieModel( \"Java\", Integer.parseInt(tvJava.getText().toString()), Color.parseColor(\"#29B6F6\")));For better look animate the piechart using startAnimation().// To animate the pie chartpieChart.startAnimation();At last invoke the setData() method inside onCreate() method.Below is the complete code for MainActivity.java file:MainActivity.javaMainActivity.javapackage com.example.piechart; // Import the required librariesimport androidx.appcompat.app.AppCompatActivity;import android.graphics.Color;import android.os.Bundle;import android.widget.TextView;import org.eazegraph.lib.charts.PieChart;import org.eazegraph.lib.models.PieModel; public class MainActivity extends AppCompatActivity { // Create the object of TextView // and PieChart class TextView tvR, tvPython, tvCPP, tvJava; PieChart pieChart; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Link those objects with their // respective id's that // we have given in .XML file tvR = findViewById(R.id.tvR); tvPython = findViewById(R.id.tvPython); tvCPP = findViewById(R.id.tvCPP); tvJava = findViewById(R.id.tvJava); pieChart = findViewById(R.id.piechart); // Creating a method setData() // to set the text in text view and pie chart setData(); } private void setData() { // Set the percentage of language used tvR.setText(Integer.toString(40)); tvPython.setText(Integer.toString(30)); tvCPP.setText(Integer.toString(5)); tvJava.setText(Integer.toString(25)); // Set the data and color to the pie chart pieChart.addPieSlice( new PieModel( \"R\", Integer.parseInt(tvR.getText().toString()), Color.parseColor(\"#FFA726\"))); pieChart.addPieSlice( new PieModel( \"Python\", Integer.parseInt(tvPython.getText().toString()), Color.parseColor(\"#66BB6A\"))); pieChart.addPieSlice( new PieModel( \"C++\", Integer.parseInt(tvCPP.getText().toString()), Color.parseColor(\"#EF5350\"))); pieChart.addPieSlice( new PieModel( \"Java\", Integer.parseInt(tvJava.getText().toString()), Color.parseColor(\"#29B6F6\"))); // To animate the pie chart pieChart.startAnimation(); }}"
},
{
"code": null,
"e": 47874,
"s": 47479,
"text": "Step1: Opening a new projectOpen a new project just click of File option at topmost corner in left.Then click on new and open a new project with whatever name you want.Now we gonna work on Empty Activity with language as Java. Leave all other options as untouched.You can change the name of project as per your choice.By default, there will be two files activity_main.xml and MainActivity.java."
},
{
"code": null,
"e": 47946,
"s": 47874,
"text": "Open a new project just click of File option at topmost corner in left."
},
{
"code": null,
"e": 48016,
"s": 47946,
"text": "Then click on new and open a new project with whatever name you want."
},
{
"code": null,
"e": 48113,
"s": 48016,
"text": "Now we gonna work on Empty Activity with language as Java. Leave all other options as untouched."
},
{
"code": null,
"e": 48168,
"s": 48113,
"text": "You can change the name of project as per your choice."
},
{
"code": null,
"e": 48245,
"s": 48168,
"text": "By default, there will be two files activity_main.xml and MainActivity.java."
},
{
"code": null,
"e": 49282,
"s": 48245,
"text": "Step 2: Before going to the coding section first you have to do some pre-task.Go to app->res->values->colors.xml section and set the colors for your app.colors.xmlcolors.xml<?xml version=\"1.0\" encoding=\"utf-8\"?><resources> <color name=\"colorPrimary\">#024265</color> <color name=\"colorPrimaryDark\">#024265</color> <color name=\"colorAccent\">#05af9b</color> <color name=\"color_one\">#fb7268</color> <color name=\"color_white\">#ededf2</color> <color name=\"color_two\">#E3E0E0</color> <color name=\"R\">#FFA726</color> <color name=\"Python\">#66BB6A</color> <color name=\"CPP\">#EF5350</color> <color name=\"Java\">#29B6F6</color> </resources>Go to Gradle Scripts->build.gradle (Module: app) section and import following dependencies and click the “sync Now” on the above pop up.build.gradle (:app)build.gradle (:app)// For Card viewimplementation 'androidx.cardview:cardview:1.0.0' // Chart and graph libraryimplementation 'com.github.blackfizz:eazegraph:1.2.5l@aar'implementation 'com.nineoldandroids:library:2.4.0'"
},
{
"code": null,
"e": 49867,
"s": 49282,
"text": "Go to app->res->values->colors.xml section and set the colors for your app.colors.xmlcolors.xml<?xml version=\"1.0\" encoding=\"utf-8\"?><resources> <color name=\"colorPrimary\">#024265</color> <color name=\"colorPrimaryDark\">#024265</color> <color name=\"colorAccent\">#05af9b</color> <color name=\"color_one\">#fb7268</color> <color name=\"color_white\">#ededf2</color> <color name=\"color_two\">#E3E0E0</color> <color name=\"R\">#FFA726</color> <color name=\"Python\">#66BB6A</color> <color name=\"CPP\">#EF5350</color> <color name=\"Java\">#29B6F6</color> </resources>"
},
{
"code": null,
"e": 49878,
"s": 49867,
"text": "colors.xml"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><resources> <color name=\"colorPrimary\">#024265</color> <color name=\"colorPrimaryDark\">#024265</color> <color name=\"colorAccent\">#05af9b</color> <color name=\"color_one\">#fb7268</color> <color name=\"color_white\">#ededf2</color> <color name=\"color_two\">#E3E0E0</color> <color name=\"R\">#FFA726</color> <color name=\"Python\">#66BB6A</color> <color name=\"CPP\">#EF5350</color> <color name=\"Java\">#29B6F6</color> </resources>",
"e": 50368,
"s": 49878,
"text": null
},
{
"code": null,
"e": 50743,
"s": 50368,
"text": "Go to Gradle Scripts->build.gradle (Module: app) section and import following dependencies and click the “sync Now” on the above pop up.build.gradle (:app)build.gradle (:app)// For Card viewimplementation 'androidx.cardview:cardview:1.0.0' // Chart and graph libraryimplementation 'com.github.blackfizz:eazegraph:1.2.5l@aar'implementation 'com.nineoldandroids:library:2.4.0'"
},
{
"code": null,
"e": 50763,
"s": 50743,
"text": "build.gradle (:app)"
},
{
"code": "// For Card viewimplementation 'androidx.cardview:cardview:1.0.0' // Chart and graph libraryimplementation 'com.github.blackfizz:eazegraph:1.2.5l@aar'implementation 'com.nineoldandroids:library:2.4.0'",
"e": 50964,
"s": 50763,
"text": null
},
{
"code": null,
"e": 65838,
"s": 50964,
"text": "Step3: Designing the UIBelow is the code for the xml file.actibity_main.xmlactibity_main.xml<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:background=\"@color/color_white\" tools:context=\".MainActivity\"> <!-- Card view for displaying the ---> <!-- Pie chart and details of pie chart --> <androidx.cardview.widget.CardView android:id=\"@+id/cardViewGraph\" android:layout_width=\"match_parent\" android:layout_height=\"200dp\" android:layout_marginLeft=\"20dp\" android:layout_marginRight=\"20dp\" android:layout_marginTop=\"15dp\" android:elevation=\"10dp\" app:cardCornerRadius=\"10dp\"> <!--Linear layout to display pie chart ---> <!-- and details of pie chart--> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"horizontal\" android:weightSum=\"2\"> <!--Pie chart to display the data--> <org.eazegraph.lib.charts.PieChart xmlns:app=\"http://schemas.android.com/apk/res-auto\" android:id=\"@+id/piechart\" android:layout_width=\"0dp\" android:layout_height=\"match_parent\" android:padding=\"6dp\" android:layout_weight=\"1\" android:layout_marginTop=\"15dp\" android:layout_marginLeft=\"15dp\" android:layout_marginBottom=\"15dp\" /> <!--Creating another linear layout ---> <!-- to display pie chart details --> <LinearLayout android:layout_width=\"0dp\" android:layout_height=\"match_parent\" android:layout_weight=\"1\" android:layout_marginLeft=\"20dp\" android:orientation=\"vertical\" android:gravity=\"center_vertical\" > <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"15dp\" android:layout_gravity=\"center_vertical\"> <!--View to display the yellow color icon--> <View android:layout_width=\"15dp\" android:layout_height=\"match_parent\" android:background=\"@color/R\"/> <!--Text view to display R --> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"R\" android:paddingLeft=\"10dp\"/> </LinearLayout> <!--Linear layout to display Python--> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"15dp\" android:layout_gravity=\"center_vertical\" android:layout_marginTop=\"5dp\"> <!--View to display the green color icon--> <View android:layout_width=\"15dp\" android:layout_height=\"match_parent\" android:background=\"@color/Python\"/> <!--Text view to display python text --> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Python\" android:paddingLeft=\"10dp\"/> </LinearLayout> <!--Linear layout to display C++--> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"15dp\" android:layout_gravity=\"center_vertical\" android:layout_marginTop=\"5dp\"> <!--View to display the red color icon--> <View android:layout_width=\"15dp\" android:layout_height=\"match_parent\" android:background=\"@color/CPP\"/> <!--Text view to display C++ text --> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"C++\" android:paddingLeft=\"10dp\"/> </LinearLayout> <!--Linear layout to display Java--> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"15dp\" android:layout_gravity=\"center_vertical\" android:layout_marginTop=\"5dp\"> <!--View to display the blue color icon--> <View android:layout_width=\"15dp\" android:layout_height=\"match_parent\" android:background=\"@color/Java\"/> <!--Text view to display Java text --> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Java\" android:paddingLeft=\"10dp\"/> </LinearLayout> </LinearLayout> </LinearLayout> </androidx.cardview.widget.CardView> <!-- Another Card view for displaying ---> <!-- Use of programming languages --> <androidx.cardview.widget.CardView android:layout_width=\"match_parent\" android:layout_height=\"260dp\" android:layout_below=\"@+id/cardViewGraph\" android:layout_marginLeft=\"20dp\" android:layout_marginRight=\"20dp\" android:layout_marginTop=\"20dp\" android:layout_marginBottom=\"20dp\" android:elevation=\"10dp\" app:cardCornerRadius=\"10dp\" android:id=\"@+id/details\"> <!--Relative layout to display ---> <!-- use of programming languages --> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"vertical\"> <!--Text view to use of ---> <!-- programming languages text--> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:text=\"Use of Programming Languages(In Percentage):\" android:textSize=\"23sp\" android:textStyle=\"bold\" android:layout_marginLeft=\"25dp\" android:layout_marginTop=\"20dp\"/> <!--View to display the line--> <View android:layout_width=\"match_parent\" android:layout_height=\"1dp\" android:background=\"@color/color_two\" android:layout_marginLeft=\"20dp\" android:layout_marginRight=\"20dp\" android:layout_marginTop=\"5dp\"/> <RelativeLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginRight=\"25dp\" android:layout_marginLeft=\"25dp\" android:layout_marginTop=\"10dp\" android:layout_marginBottom=\"10dp\"> <!--Text view to display R --> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:fontFamily=\"sans-serif-light\" android:text=\"R\" android:textSize=\"18sp\"/> <!--Text view to display the ---> <!-- percentage of programming language ---> <!-- used. For now default set to 0--> <TextView android:layout_width=\"fill_parent\" android:layout_height=\"wrap_content\" android:text=\"0\" android:id=\"@+id/tvR\" android:textAlignment=\"textEnd\" android:textSize=\"18sp\" android:textColor=\"@color/color_one\" android:textStyle=\"bold\" android:fontFamily=\"sans-serif-light\" android:layout_alignParentRight=\"true\"/> </RelativeLayout> <!--View to display the line--> <View android:layout_width=\"match_parent\" android:layout_height=\"1dp\" android:background=\"@color/color_two\" android:layout_marginLeft=\"20dp\" android:layout_marginRight=\"20dp\" /> <RelativeLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginRight=\"25dp\" android:layout_marginLeft=\"25dp\" android:layout_marginTop=\"10dp\" android:layout_marginBottom=\"10dp\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:fontFamily=\"sans-serif-light\" android:text=\"Python\" android:textSize=\"18sp\"/> <!--Text view to display the percentage ---> <!-- of programming language used. ---> <!-- For now default set to 0--> <TextView android:layout_width=\"fill_parent\" android:layout_height=\"wrap_content\" android:text=\"0\" android:id=\"@+id/tvPython\" android:textAlignment=\"textEnd\" android:textSize=\"18sp\" android:textColor=\"@color/color_one\" android:textStyle=\"bold\" android:fontFamily=\"sans-serif-light\" android:layout_alignParentRight=\"true\"/> </RelativeLayout> <View android:layout_width=\"match_parent\" android:layout_height=\"1dp\" android:background=\"@color/color_two\" android:layout_marginLeft=\"20dp\" android:layout_marginRight=\"20dp\" /> <RelativeLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginRight=\"25dp\" android:layout_marginLeft=\"25dp\" android:layout_marginTop=\"10dp\" android:layout_marginBottom=\"10dp\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:fontFamily=\"sans-serif-light\" android:text=\"C++\" android:textSize=\"18sp\"/> <!--Text view to display the percentage ---> <!-- of programming language used. ---> <!-- For now default set to 0--> <TextView android:layout_width=\"fill_parent\" android:layout_height=\"wrap_content\" android:text=\"0\" android:id=\"@+id/tvCPP\" android:textAlignment=\"textEnd\" android:textSize=\"18sp\" android:textColor=\"@color/color_one\" android:textStyle=\"bold\" android:fontFamily=\"sans-serif-light\" android:layout_alignParentRight=\"true\"/> </RelativeLayout> <View android:layout_width=\"match_parent\" android:layout_height=\"1dp\" android:background=\"@color/color_two\" android:layout_marginLeft=\"20dp\" android:layout_marginRight=\"20dp\" /> <RelativeLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginRight=\"25dp\" android:layout_marginLeft=\"25dp\" android:layout_marginTop=\"10dp\" android:layout_marginBottom=\"10dp\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:fontFamily=\"sans-serif-light\" android:text=\"Java\" android:textSize=\"18sp\"/> <!--Text view to display the percentage ---> <!-- of programming language used. ---> <!-- For now default set to 0--> <TextView android:layout_width=\"fill_parent\" android:layout_height=\"wrap_content\" android:text=\"0\" android:id=\"@+id/tvJava\" android:textAlignment=\"textEnd\" android:textSize=\"18sp\" android:textColor=\"@color/color_one\" android:textStyle=\"bold\" android:fontFamily=\"sans-serif-light\" android:layout_alignParentRight=\"true\"/> </RelativeLayout> </LinearLayout> </androidx.cardview.widget.CardView> </RelativeLayout>After using this code in .xml file, the UI will be like:"
},
{
"code": null,
"e": 80633,
"s": 65838,
"text": "Below is the code for the xml file.actibity_main.xmlactibity_main.xml<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:background=\"@color/color_white\" tools:context=\".MainActivity\"> <!-- Card view for displaying the ---> <!-- Pie chart and details of pie chart --> <androidx.cardview.widget.CardView android:id=\"@+id/cardViewGraph\" android:layout_width=\"match_parent\" android:layout_height=\"200dp\" android:layout_marginLeft=\"20dp\" android:layout_marginRight=\"20dp\" android:layout_marginTop=\"15dp\" android:elevation=\"10dp\" app:cardCornerRadius=\"10dp\"> <!--Linear layout to display pie chart ---> <!-- and details of pie chart--> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"horizontal\" android:weightSum=\"2\"> <!--Pie chart to display the data--> <org.eazegraph.lib.charts.PieChart xmlns:app=\"http://schemas.android.com/apk/res-auto\" android:id=\"@+id/piechart\" android:layout_width=\"0dp\" android:layout_height=\"match_parent\" android:padding=\"6dp\" android:layout_weight=\"1\" android:layout_marginTop=\"15dp\" android:layout_marginLeft=\"15dp\" android:layout_marginBottom=\"15dp\" /> <!--Creating another linear layout ---> <!-- to display pie chart details --> <LinearLayout android:layout_width=\"0dp\" android:layout_height=\"match_parent\" android:layout_weight=\"1\" android:layout_marginLeft=\"20dp\" android:orientation=\"vertical\" android:gravity=\"center_vertical\" > <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"15dp\" android:layout_gravity=\"center_vertical\"> <!--View to display the yellow color icon--> <View android:layout_width=\"15dp\" android:layout_height=\"match_parent\" android:background=\"@color/R\"/> <!--Text view to display R --> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"R\" android:paddingLeft=\"10dp\"/> </LinearLayout> <!--Linear layout to display Python--> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"15dp\" android:layout_gravity=\"center_vertical\" android:layout_marginTop=\"5dp\"> <!--View to display the green color icon--> <View android:layout_width=\"15dp\" android:layout_height=\"match_parent\" android:background=\"@color/Python\"/> <!--Text view to display python text --> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Python\" android:paddingLeft=\"10dp\"/> </LinearLayout> <!--Linear layout to display C++--> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"15dp\" android:layout_gravity=\"center_vertical\" android:layout_marginTop=\"5dp\"> <!--View to display the red color icon--> <View android:layout_width=\"15dp\" android:layout_height=\"match_parent\" android:background=\"@color/CPP\"/> <!--Text view to display C++ text --> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"C++\" android:paddingLeft=\"10dp\"/> </LinearLayout> <!--Linear layout to display Java--> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"15dp\" android:layout_gravity=\"center_vertical\" android:layout_marginTop=\"5dp\"> <!--View to display the blue color icon--> <View android:layout_width=\"15dp\" android:layout_height=\"match_parent\" android:background=\"@color/Java\"/> <!--Text view to display Java text --> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Java\" android:paddingLeft=\"10dp\"/> </LinearLayout> </LinearLayout> </LinearLayout> </androidx.cardview.widget.CardView> <!-- Another Card view for displaying ---> <!-- Use of programming languages --> <androidx.cardview.widget.CardView android:layout_width=\"match_parent\" android:layout_height=\"260dp\" android:layout_below=\"@+id/cardViewGraph\" android:layout_marginLeft=\"20dp\" android:layout_marginRight=\"20dp\" android:layout_marginTop=\"20dp\" android:layout_marginBottom=\"20dp\" android:elevation=\"10dp\" app:cardCornerRadius=\"10dp\" android:id=\"@+id/details\"> <!--Relative layout to display ---> <!-- use of programming languages --> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"vertical\"> <!--Text view to use of ---> <!-- programming languages text--> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:text=\"Use of Programming Languages(In Percentage):\" android:textSize=\"23sp\" android:textStyle=\"bold\" android:layout_marginLeft=\"25dp\" android:layout_marginTop=\"20dp\"/> <!--View to display the line--> <View android:layout_width=\"match_parent\" android:layout_height=\"1dp\" android:background=\"@color/color_two\" android:layout_marginLeft=\"20dp\" android:layout_marginRight=\"20dp\" android:layout_marginTop=\"5dp\"/> <RelativeLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginRight=\"25dp\" android:layout_marginLeft=\"25dp\" android:layout_marginTop=\"10dp\" android:layout_marginBottom=\"10dp\"> <!--Text view to display R --> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:fontFamily=\"sans-serif-light\" android:text=\"R\" android:textSize=\"18sp\"/> <!--Text view to display the ---> <!-- percentage of programming language ---> <!-- used. For now default set to 0--> <TextView android:layout_width=\"fill_parent\" android:layout_height=\"wrap_content\" android:text=\"0\" android:id=\"@+id/tvR\" android:textAlignment=\"textEnd\" android:textSize=\"18sp\" android:textColor=\"@color/color_one\" android:textStyle=\"bold\" android:fontFamily=\"sans-serif-light\" android:layout_alignParentRight=\"true\"/> </RelativeLayout> <!--View to display the line--> <View android:layout_width=\"match_parent\" android:layout_height=\"1dp\" android:background=\"@color/color_two\" android:layout_marginLeft=\"20dp\" android:layout_marginRight=\"20dp\" /> <RelativeLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginRight=\"25dp\" android:layout_marginLeft=\"25dp\" android:layout_marginTop=\"10dp\" android:layout_marginBottom=\"10dp\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:fontFamily=\"sans-serif-light\" android:text=\"Python\" android:textSize=\"18sp\"/> <!--Text view to display the percentage ---> <!-- of programming language used. ---> <!-- For now default set to 0--> <TextView android:layout_width=\"fill_parent\" android:layout_height=\"wrap_content\" android:text=\"0\" android:id=\"@+id/tvPython\" android:textAlignment=\"textEnd\" android:textSize=\"18sp\" android:textColor=\"@color/color_one\" android:textStyle=\"bold\" android:fontFamily=\"sans-serif-light\" android:layout_alignParentRight=\"true\"/> </RelativeLayout> <View android:layout_width=\"match_parent\" android:layout_height=\"1dp\" android:background=\"@color/color_two\" android:layout_marginLeft=\"20dp\" android:layout_marginRight=\"20dp\" /> <RelativeLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginRight=\"25dp\" android:layout_marginLeft=\"25dp\" android:layout_marginTop=\"10dp\" android:layout_marginBottom=\"10dp\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:fontFamily=\"sans-serif-light\" android:text=\"C++\" android:textSize=\"18sp\"/> <!--Text view to display the percentage ---> <!-- of programming language used. ---> <!-- For now default set to 0--> <TextView android:layout_width=\"fill_parent\" android:layout_height=\"wrap_content\" android:text=\"0\" android:id=\"@+id/tvCPP\" android:textAlignment=\"textEnd\" android:textSize=\"18sp\" android:textColor=\"@color/color_one\" android:textStyle=\"bold\" android:fontFamily=\"sans-serif-light\" android:layout_alignParentRight=\"true\"/> </RelativeLayout> <View android:layout_width=\"match_parent\" android:layout_height=\"1dp\" android:background=\"@color/color_two\" android:layout_marginLeft=\"20dp\" android:layout_marginRight=\"20dp\" /> <RelativeLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginRight=\"25dp\" android:layout_marginLeft=\"25dp\" android:layout_marginTop=\"10dp\" android:layout_marginBottom=\"10dp\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:fontFamily=\"sans-serif-light\" android:text=\"Java\" android:textSize=\"18sp\"/> <!--Text view to display the percentage ---> <!-- of programming language used. ---> <!-- For now default set to 0--> <TextView android:layout_width=\"fill_parent\" android:layout_height=\"wrap_content\" android:text=\"0\" android:id=\"@+id/tvJava\" android:textAlignment=\"textEnd\" android:textSize=\"18sp\" android:textColor=\"@color/color_one\" android:textStyle=\"bold\" android:fontFamily=\"sans-serif-light\" android:layout_alignParentRight=\"true\"/> </RelativeLayout> </LinearLayout> </androidx.cardview.widget.CardView> </RelativeLayout>"
},
{
"code": null,
"e": 80651,
"s": 80633,
"text": "actibity_main.xml"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:background=\"@color/color_white\" tools:context=\".MainActivity\"> <!-- Card view for displaying the ---> <!-- Pie chart and details of pie chart --> <androidx.cardview.widget.CardView android:id=\"@+id/cardViewGraph\" android:layout_width=\"match_parent\" android:layout_height=\"200dp\" android:layout_marginLeft=\"20dp\" android:layout_marginRight=\"20dp\" android:layout_marginTop=\"15dp\" android:elevation=\"10dp\" app:cardCornerRadius=\"10dp\"> <!--Linear layout to display pie chart ---> <!-- and details of pie chart--> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"horizontal\" android:weightSum=\"2\"> <!--Pie chart to display the data--> <org.eazegraph.lib.charts.PieChart xmlns:app=\"http://schemas.android.com/apk/res-auto\" android:id=\"@+id/piechart\" android:layout_width=\"0dp\" android:layout_height=\"match_parent\" android:padding=\"6dp\" android:layout_weight=\"1\" android:layout_marginTop=\"15dp\" android:layout_marginLeft=\"15dp\" android:layout_marginBottom=\"15dp\" /> <!--Creating another linear layout ---> <!-- to display pie chart details --> <LinearLayout android:layout_width=\"0dp\" android:layout_height=\"match_parent\" android:layout_weight=\"1\" android:layout_marginLeft=\"20dp\" android:orientation=\"vertical\" android:gravity=\"center_vertical\" > <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"15dp\" android:layout_gravity=\"center_vertical\"> <!--View to display the yellow color icon--> <View android:layout_width=\"15dp\" android:layout_height=\"match_parent\" android:background=\"@color/R\"/> <!--Text view to display R --> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"R\" android:paddingLeft=\"10dp\"/> </LinearLayout> <!--Linear layout to display Python--> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"15dp\" android:layout_gravity=\"center_vertical\" android:layout_marginTop=\"5dp\"> <!--View to display the green color icon--> <View android:layout_width=\"15dp\" android:layout_height=\"match_parent\" android:background=\"@color/Python\"/> <!--Text view to display python text --> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Python\" android:paddingLeft=\"10dp\"/> </LinearLayout> <!--Linear layout to display C++--> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"15dp\" android:layout_gravity=\"center_vertical\" android:layout_marginTop=\"5dp\"> <!--View to display the red color icon--> <View android:layout_width=\"15dp\" android:layout_height=\"match_parent\" android:background=\"@color/CPP\"/> <!--Text view to display C++ text --> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"C++\" android:paddingLeft=\"10dp\"/> </LinearLayout> <!--Linear layout to display Java--> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"15dp\" android:layout_gravity=\"center_vertical\" android:layout_marginTop=\"5dp\"> <!--View to display the blue color icon--> <View android:layout_width=\"15dp\" android:layout_height=\"match_parent\" android:background=\"@color/Java\"/> <!--Text view to display Java text --> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Java\" android:paddingLeft=\"10dp\"/> </LinearLayout> </LinearLayout> </LinearLayout> </androidx.cardview.widget.CardView> <!-- Another Card view for displaying ---> <!-- Use of programming languages --> <androidx.cardview.widget.CardView android:layout_width=\"match_parent\" android:layout_height=\"260dp\" android:layout_below=\"@+id/cardViewGraph\" android:layout_marginLeft=\"20dp\" android:layout_marginRight=\"20dp\" android:layout_marginTop=\"20dp\" android:layout_marginBottom=\"20dp\" android:elevation=\"10dp\" app:cardCornerRadius=\"10dp\" android:id=\"@+id/details\"> <!--Relative layout to display ---> <!-- use of programming languages --> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"vertical\"> <!--Text view to use of ---> <!-- programming languages text--> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:text=\"Use of Programming Languages(In Percentage):\" android:textSize=\"23sp\" android:textStyle=\"bold\" android:layout_marginLeft=\"25dp\" android:layout_marginTop=\"20dp\"/> <!--View to display the line--> <View android:layout_width=\"match_parent\" android:layout_height=\"1dp\" android:background=\"@color/color_two\" android:layout_marginLeft=\"20dp\" android:layout_marginRight=\"20dp\" android:layout_marginTop=\"5dp\"/> <RelativeLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginRight=\"25dp\" android:layout_marginLeft=\"25dp\" android:layout_marginTop=\"10dp\" android:layout_marginBottom=\"10dp\"> <!--Text view to display R --> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:fontFamily=\"sans-serif-light\" android:text=\"R\" android:textSize=\"18sp\"/> <!--Text view to display the ---> <!-- percentage of programming language ---> <!-- used. For now default set to 0--> <TextView android:layout_width=\"fill_parent\" android:layout_height=\"wrap_content\" android:text=\"0\" android:id=\"@+id/tvR\" android:textAlignment=\"textEnd\" android:textSize=\"18sp\" android:textColor=\"@color/color_one\" android:textStyle=\"bold\" android:fontFamily=\"sans-serif-light\" android:layout_alignParentRight=\"true\"/> </RelativeLayout> <!--View to display the line--> <View android:layout_width=\"match_parent\" android:layout_height=\"1dp\" android:background=\"@color/color_two\" android:layout_marginLeft=\"20dp\" android:layout_marginRight=\"20dp\" /> <RelativeLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginRight=\"25dp\" android:layout_marginLeft=\"25dp\" android:layout_marginTop=\"10dp\" android:layout_marginBottom=\"10dp\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:fontFamily=\"sans-serif-light\" android:text=\"Python\" android:textSize=\"18sp\"/> <!--Text view to display the percentage ---> <!-- of programming language used. ---> <!-- For now default set to 0--> <TextView android:layout_width=\"fill_parent\" android:layout_height=\"wrap_content\" android:text=\"0\" android:id=\"@+id/tvPython\" android:textAlignment=\"textEnd\" android:textSize=\"18sp\" android:textColor=\"@color/color_one\" android:textStyle=\"bold\" android:fontFamily=\"sans-serif-light\" android:layout_alignParentRight=\"true\"/> </RelativeLayout> <View android:layout_width=\"match_parent\" android:layout_height=\"1dp\" android:background=\"@color/color_two\" android:layout_marginLeft=\"20dp\" android:layout_marginRight=\"20dp\" /> <RelativeLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginRight=\"25dp\" android:layout_marginLeft=\"25dp\" android:layout_marginTop=\"10dp\" android:layout_marginBottom=\"10dp\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:fontFamily=\"sans-serif-light\" android:text=\"C++\" android:textSize=\"18sp\"/> <!--Text view to display the percentage ---> <!-- of programming language used. ---> <!-- For now default set to 0--> <TextView android:layout_width=\"fill_parent\" android:layout_height=\"wrap_content\" android:text=\"0\" android:id=\"@+id/tvCPP\" android:textAlignment=\"textEnd\" android:textSize=\"18sp\" android:textColor=\"@color/color_one\" android:textStyle=\"bold\" android:fontFamily=\"sans-serif-light\" android:layout_alignParentRight=\"true\"/> </RelativeLayout> <View android:layout_width=\"match_parent\" android:layout_height=\"1dp\" android:background=\"@color/color_two\" android:layout_marginLeft=\"20dp\" android:layout_marginRight=\"20dp\" /> <RelativeLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginRight=\"25dp\" android:layout_marginLeft=\"25dp\" android:layout_marginTop=\"10dp\" android:layout_marginBottom=\"10dp\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:fontFamily=\"sans-serif-light\" android:text=\"Java\" android:textSize=\"18sp\"/> <!--Text view to display the percentage ---> <!-- of programming language used. ---> <!-- For now default set to 0--> <TextView android:layout_width=\"fill_parent\" android:layout_height=\"wrap_content\" android:text=\"0\" android:id=\"@+id/tvJava\" android:textAlignment=\"textEnd\" android:textSize=\"18sp\" android:textColor=\"@color/color_one\" android:textStyle=\"bold\" android:fontFamily=\"sans-serif-light\" android:layout_alignParentRight=\"true\"/> </RelativeLayout> </LinearLayout> </androidx.cardview.widget.CardView> </RelativeLayout>",
"e": 95377,
"s": 80651,
"text": null
},
{
"code": null,
"e": 95434,
"s": 95377,
"text": "After using this code in .xml file, the UI will be like:"
},
{
"code": null,
"e": 99764,
"s": 95434,
"text": "Step4: Working with Java fileOpen the MainActivity.java file there within the class, first of all create the object of TextView class and the pie chart class.// Create the object of TextView and PieChart classTextView tvR, tvPython, tvCPP, tvJava;PieChart pieChart;Secondly inside onCreate() method, we have to link those objects with their respective id’s that we have given in .XML file.// Link those objects with their respective// id's that we have given in .XML filetvR = findViewById(R.id.tvR);tvPython = findViewById(R.id.tvPython);tvCPP = findViewById(R.id.tvCPP);tvJava = findViewById(R.id.tvJava);pieChart = findViewById(R.id.piechart);Creat a private void setData() method outside onCreate() method and define it.Inside setData() method the most important task is going to happen that is how we set the data in the text file and as well as on the piechart.First of all inside setData() method set the percentage of language used in their respective text view.// Set the percentage of language usedtvR.setText(Integer.toString(40));tvPython.setText(Integer.toString(30));tvCPP.setText(Integer.toString(5));tvJava.setText(Integer.toString(25));And then set this data to the pie chart and also set their respective colors using addPieSlice() method.// Set the data and color to the pie chartpieChart.addPieSlice( new PieModel( \"R\", Integer.parseInt(tvR.getText().toString()), Color.parseColor(\"#FFA726\")));pieChart.addPieSlice( new PieModel( \"Python\", Integer.parseInt(tvPython.getText().toString()), Color.parseColor(\"#66BB6A\")));pieChart.addPieSlice( new PieModel( \"C++\", Integer.parseInt(tvCPP.getText().toString()), Color.parseColor(\"#EF5350\")));pieChart.addPieSlice( new PieModel( \"Java\", Integer.parseInt(tvJava.getText().toString()), Color.parseColor(\"#29B6F6\")));For better look animate the piechart using startAnimation().// To animate the pie chartpieChart.startAnimation();At last invoke the setData() method inside onCreate() method.Below is the complete code for MainActivity.java file:MainActivity.javaMainActivity.javapackage com.example.piechart; // Import the required librariesimport androidx.appcompat.app.AppCompatActivity;import android.graphics.Color;import android.os.Bundle;import android.widget.TextView;import org.eazegraph.lib.charts.PieChart;import org.eazegraph.lib.models.PieModel; public class MainActivity extends AppCompatActivity { // Create the object of TextView // and PieChart class TextView tvR, tvPython, tvCPP, tvJava; PieChart pieChart; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Link those objects with their // respective id's that // we have given in .XML file tvR = findViewById(R.id.tvR); tvPython = findViewById(R.id.tvPython); tvCPP = findViewById(R.id.tvCPP); tvJava = findViewById(R.id.tvJava); pieChart = findViewById(R.id.piechart); // Creating a method setData() // to set the text in text view and pie chart setData(); } private void setData() { // Set the percentage of language used tvR.setText(Integer.toString(40)); tvPython.setText(Integer.toString(30)); tvCPP.setText(Integer.toString(5)); tvJava.setText(Integer.toString(25)); // Set the data and color to the pie chart pieChart.addPieSlice( new PieModel( \"R\", Integer.parseInt(tvR.getText().toString()), Color.parseColor(\"#FFA726\"))); pieChart.addPieSlice( new PieModel( \"Python\", Integer.parseInt(tvPython.getText().toString()), Color.parseColor(\"#66BB6A\"))); pieChart.addPieSlice( new PieModel( \"C++\", Integer.parseInt(tvCPP.getText().toString()), Color.parseColor(\"#EF5350\"))); pieChart.addPieSlice( new PieModel( \"Java\", Integer.parseInt(tvJava.getText().toString()), Color.parseColor(\"#29B6F6\"))); // To animate the pie chart pieChart.startAnimation(); }}"
},
{
"code": null,
"e": 100001,
"s": 99764,
"text": "Open the MainActivity.java file there within the class, first of all create the object of TextView class and the pie chart class.// Create the object of TextView and PieChart classTextView tvR, tvPython, tvCPP, tvJava;PieChart pieChart;"
},
{
"code": "// Create the object of TextView and PieChart classTextView tvR, tvPython, tvCPP, tvJava;PieChart pieChart;",
"e": 100109,
"s": 100001,
"text": null
},
{
"code": null,
"e": 100491,
"s": 100109,
"text": "Secondly inside onCreate() method, we have to link those objects with their respective id’s that we have given in .XML file.// Link those objects with their respective// id's that we have given in .XML filetvR = findViewById(R.id.tvR);tvPython = findViewById(R.id.tvPython);tvCPP = findViewById(R.id.tvCPP);tvJava = findViewById(R.id.tvJava);pieChart = findViewById(R.id.piechart);"
},
{
"code": "// Link those objects with their respective// id's that we have given in .XML filetvR = findViewById(R.id.tvR);tvPython = findViewById(R.id.tvPython);tvCPP = findViewById(R.id.tvCPP);tvJava = findViewById(R.id.tvJava);pieChart = findViewById(R.id.piechart);",
"e": 100749,
"s": 100491,
"text": null
},
{
"code": null,
"e": 100828,
"s": 100749,
"text": "Creat a private void setData() method outside onCreate() method and define it."
},
{
"code": null,
"e": 100972,
"s": 100828,
"text": "Inside setData() method the most important task is going to happen that is how we set the data in the text file and as well as on the piechart."
},
{
"code": null,
"e": 101259,
"s": 100972,
"text": "First of all inside setData() method set the percentage of language used in their respective text view.// Set the percentage of language usedtvR.setText(Integer.toString(40));tvPython.setText(Integer.toString(30));tvCPP.setText(Integer.toString(5));tvJava.setText(Integer.toString(25));"
},
{
"code": "// Set the percentage of language usedtvR.setText(Integer.toString(40));tvPython.setText(Integer.toString(30));tvCPP.setText(Integer.toString(5));tvJava.setText(Integer.toString(25));",
"e": 101443,
"s": 101259,
"text": null
},
{
"code": null,
"e": 102166,
"s": 101443,
"text": "And then set this data to the pie chart and also set their respective colors using addPieSlice() method.// Set the data and color to the pie chartpieChart.addPieSlice( new PieModel( \"R\", Integer.parseInt(tvR.getText().toString()), Color.parseColor(\"#FFA726\")));pieChart.addPieSlice( new PieModel( \"Python\", Integer.parseInt(tvPython.getText().toString()), Color.parseColor(\"#66BB6A\")));pieChart.addPieSlice( new PieModel( \"C++\", Integer.parseInt(tvCPP.getText().toString()), Color.parseColor(\"#EF5350\")));pieChart.addPieSlice( new PieModel( \"Java\", Integer.parseInt(tvJava.getText().toString()), Color.parseColor(\"#29B6F6\")));"
},
{
"code": "// Set the data and color to the pie chartpieChart.addPieSlice( new PieModel( \"R\", Integer.parseInt(tvR.getText().toString()), Color.parseColor(\"#FFA726\")));pieChart.addPieSlice( new PieModel( \"Python\", Integer.parseInt(tvPython.getText().toString()), Color.parseColor(\"#66BB6A\")));pieChart.addPieSlice( new PieModel( \"C++\", Integer.parseInt(tvCPP.getText().toString()), Color.parseColor(\"#EF5350\")));pieChart.addPieSlice( new PieModel( \"Java\", Integer.parseInt(tvJava.getText().toString()), Color.parseColor(\"#29B6F6\")));",
"e": 102785,
"s": 102166,
"text": null
},
{
"code": null,
"e": 102899,
"s": 102785,
"text": "For better look animate the piechart using startAnimation().// To animate the pie chartpieChart.startAnimation();"
},
{
"code": "// To animate the pie chartpieChart.startAnimation();",
"e": 102953,
"s": 102899,
"text": null
},
{
"code": null,
"e": 103015,
"s": 102953,
"text": "At last invoke the setData() method inside onCreate() method."
},
{
"code": null,
"e": 103070,
"s": 103015,
"text": "Below is the complete code for MainActivity.java file:"
},
{
"code": null,
"e": 103088,
"s": 103070,
"text": "MainActivity.java"
},
{
"code": "package com.example.piechart; // Import the required librariesimport androidx.appcompat.app.AppCompatActivity;import android.graphics.Color;import android.os.Bundle;import android.widget.TextView;import org.eazegraph.lib.charts.PieChart;import org.eazegraph.lib.models.PieModel; public class MainActivity extends AppCompatActivity { // Create the object of TextView // and PieChart class TextView tvR, tvPython, tvCPP, tvJava; PieChart pieChart; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Link those objects with their // respective id's that // we have given in .XML file tvR = findViewById(R.id.tvR); tvPython = findViewById(R.id.tvPython); tvCPP = findViewById(R.id.tvCPP); tvJava = findViewById(R.id.tvJava); pieChart = findViewById(R.id.piechart); // Creating a method setData() // to set the text in text view and pie chart setData(); } private void setData() { // Set the percentage of language used tvR.setText(Integer.toString(40)); tvPython.setText(Integer.toString(30)); tvCPP.setText(Integer.toString(5)); tvJava.setText(Integer.toString(25)); // Set the data and color to the pie chart pieChart.addPieSlice( new PieModel( \"R\", Integer.parseInt(tvR.getText().toString()), Color.parseColor(\"#FFA726\"))); pieChart.addPieSlice( new PieModel( \"Python\", Integer.parseInt(tvPython.getText().toString()), Color.parseColor(\"#66BB6A\"))); pieChart.addPieSlice( new PieModel( \"C++\", Integer.parseInt(tvCPP.getText().toString()), Color.parseColor(\"#EF5350\"))); pieChart.addPieSlice( new PieModel( \"Java\", Integer.parseInt(tvJava.getText().toString()), Color.parseColor(\"#29B6F6\"))); // To animate the pie chart pieChart.startAnimation(); }}",
"e": 105281,
"s": 103088,
"text": null
},
{
"code": null,
"e": 105289,
"s": 105281,
"text": "Output:"
},
{
"code": null,
"e": 105297,
"s": 105289,
"text": "android"
},
{
"code": null,
"e": 105304,
"s": 105297,
"text": "How To"
},
{
"code": null,
"e": 105309,
"s": 105304,
"text": "Java"
},
{
"code": null,
"e": 105325,
"s": 105309,
"text": "Write From Home"
},
{
"code": null,
"e": 105330,
"s": 105325,
"text": "Java"
},
{
"code": null,
"e": 105428,
"s": 105330,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 105455,
"s": 105428,
"text": "How to Align Text in HTML?"
},
{
"code": null,
"e": 105500,
"s": 105455,
"text": "How to Install OpenCV for Python on Windows?"
},
{
"code": null,
"e": 105548,
"s": 105500,
"text": "How to filter object array based on attributes?"
},
{
"code": null,
"e": 105562,
"s": 105548,
"text": "Java Tutorial"
},
{
"code": null,
"e": 105596,
"s": 105562,
"text": "How to Install FFmpeg on Windows?"
},
{
"code": null,
"e": 105611,
"s": 105596,
"text": "Arrays in Java"
},
{
"code": null,
"e": 105655,
"s": 105611,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 105677,
"s": 105655,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 105728,
"s": 105677,
"text": "Object Oriented Programming (OOPs) Concept in Java"
}
] |
Matplotlib - Rectangle Selector - GeeksforGeeks | 16 Jul, 2021
Matplotlib is a python library for visualization. It provides various widgets to make the visualization of data simple. There are some cases when there is a need of selection of particular region of a graph. For this interactivity, Matplotlib provides RectangleSelector widget. This widget helps to select a rectangular region of given axes. Also, it provides a way to perform actions according to the selection.
RectangleSelector(): Selects a rectangular region of given axes.
Syntax: class matplotlib.widgets.RectangleSelector(ax, onselect, drawtype=’box’, minspanx=0, minspany=0, useblit=False, lineprops=None, rectprops=None, spancoords=’data’, button=None, maxdist=10, marker_props=None, interactive=False, state_modifier_keys=None)
Parameters:
ax: A matplotlib.axes.Axes instance where widget is placed.
onselect: Function to connect to the selection event. When the selection is completed, respective function is called. onselect function takes mouse click and mouse release events as arguments.
drawtype: It specifies how to show selection. If “box”, then draws the full rectangle box. If “line”, then draws line of rectangle. If “none”, then draws nothing. Default value is “box”.
button: It provides list of mouse buttons that can trigger rectangle selection. By default all buttons are allowed.
maxdist: It is a distance in pixels within which the interactive tool handles can be activated. Default value is 10.
interactive: It is a boolean value to specify whether to draw a set of handles for interaction with the widget.
Properties:
center: Provides center of rectangle drawn
corners: Provides corners of rectangle starting from lower left, moving clockwise.
edge_centers: Provides midpoint of rectangle edges starting from left moving clockwise.
extents: Returns (xmin, xmax, ymin, ymax).
geometry: Returns an array containing the x and y co-ordinates of the four corners of the rectangle (starting and ending in the top left corner). Array shape is (2, 5). all x coordinates can be obtained using RectangleSelector.geometry[1, :] and y coordinates using RectangleSelector.geometry[0, :].
Methods:
draw_shape(self, extents): draws a rectangular shape using (xmin, xmax, ymin, ymax) values.
Example 1:
Following program demonstrates simple RectangleSelector used to select a region and zoom the selected area.
Python3
from matplotlib.widgets import RectangleSelectorimport matplotlib.pyplot as plt # Function to be executed after selectiondef onselect_function(eclick, erelease): # Obtain (xmin, xmax, ymin, ymax) values # for rectangle selector box using extent attribute. extent = rect_selector.extents print("Extents: ", extent) # Zoom the selected part # Set xlim range for plot as xmin to xmax # of rectangle selector box. plt.xlim(extent[0], extent[1]) # Set ylim range for plot as ymin to ymax # of rectangle selector box. plt.ylim(extent[2], extent[3]) # plot a line graph for data nfig, ax = plt.subplots()n = [4, 5, 6, 10, 12, 15, 20, 23, 24, 19]ax.plot(n) # Define a RectangleSelector at given axes ax.# It calls a function named 'onselect_function'# when the selection is completed.# Rectangular box is drawn to show the selected region.# Only left mouse button is allowed for doing selection.rect_selector = RectangleSelector( ax, onselect_function, drawtype='box', button=[1]) # Display graphplt.show()
Output:
sooda367
sagar0719kumar
Picked
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n16 Jul, 2021"
},
{
"code": null,
"e": 25950,
"s": 25537,
"text": "Matplotlib is a python library for visualization. It provides various widgets to make the visualization of data simple. There are some cases when there is a need of selection of particular region of a graph. For this interactivity, Matplotlib provides RectangleSelector widget. This widget helps to select a rectangular region of given axes. Also, it provides a way to perform actions according to the selection."
},
{
"code": null,
"e": 26016,
"s": 25950,
"text": "RectangleSelector(): Selects a rectangular region of given axes. "
},
{
"code": null,
"e": 26276,
"s": 26016,
"text": "Syntax: class matplotlib.widgets.RectangleSelector(ax, onselect, drawtype=’box’, minspanx=0, minspany=0, useblit=False, lineprops=None, rectprops=None, spancoords=’data’, button=None, maxdist=10, marker_props=None, interactive=False, state_modifier_keys=None)"
},
{
"code": null,
"e": 26288,
"s": 26276,
"text": "Parameters:"
},
{
"code": null,
"e": 26348,
"s": 26288,
"text": "ax: A matplotlib.axes.Axes instance where widget is placed."
},
{
"code": null,
"e": 26541,
"s": 26348,
"text": "onselect: Function to connect to the selection event. When the selection is completed, respective function is called. onselect function takes mouse click and mouse release events as arguments."
},
{
"code": null,
"e": 26729,
"s": 26541,
"text": "drawtype: It specifies how to show selection. If “box”, then draws the full rectangle box. If “line”, then draws line of rectangle. If “none”, then draws nothing. Default value is “box”."
},
{
"code": null,
"e": 26846,
"s": 26729,
"text": "button: It provides list of mouse buttons that can trigger rectangle selection. By default all buttons are allowed."
},
{
"code": null,
"e": 26963,
"s": 26846,
"text": "maxdist: It is a distance in pixels within which the interactive tool handles can be activated. Default value is 10."
},
{
"code": null,
"e": 27075,
"s": 26963,
"text": "interactive: It is a boolean value to specify whether to draw a set of handles for interaction with the widget."
},
{
"code": null,
"e": 27087,
"s": 27075,
"text": "Properties:"
},
{
"code": null,
"e": 27130,
"s": 27087,
"text": "center: Provides center of rectangle drawn"
},
{
"code": null,
"e": 27213,
"s": 27130,
"text": "corners: Provides corners of rectangle starting from lower left, moving clockwise."
},
{
"code": null,
"e": 27301,
"s": 27213,
"text": "edge_centers: Provides midpoint of rectangle edges starting from left moving clockwise."
},
{
"code": null,
"e": 27344,
"s": 27301,
"text": "extents: Returns (xmin, xmax, ymin, ymax)."
},
{
"code": null,
"e": 27645,
"s": 27344,
"text": "geometry: Returns an array containing the x and y co-ordinates of the four corners of the rectangle (starting and ending in the top left corner). Array shape is (2, 5). all x coordinates can be obtained using RectangleSelector.geometry[1, :] and y coordinates using RectangleSelector.geometry[0, :]."
},
{
"code": null,
"e": 27654,
"s": 27645,
"text": "Methods:"
},
{
"code": null,
"e": 27746,
"s": 27654,
"text": "draw_shape(self, extents): draws a rectangular shape using (xmin, xmax, ymin, ymax) values."
},
{
"code": null,
"e": 27757,
"s": 27746,
"text": "Example 1:"
},
{
"code": null,
"e": 27865,
"s": 27757,
"text": "Following program demonstrates simple RectangleSelector used to select a region and zoom the selected area."
},
{
"code": null,
"e": 27873,
"s": 27865,
"text": "Python3"
},
{
"code": "from matplotlib.widgets import RectangleSelectorimport matplotlib.pyplot as plt # Function to be executed after selectiondef onselect_function(eclick, erelease): # Obtain (xmin, xmax, ymin, ymax) values # for rectangle selector box using extent attribute. extent = rect_selector.extents print(\"Extents: \", extent) # Zoom the selected part # Set xlim range for plot as xmin to xmax # of rectangle selector box. plt.xlim(extent[0], extent[1]) # Set ylim range for plot as ymin to ymax # of rectangle selector box. plt.ylim(extent[2], extent[3]) # plot a line graph for data nfig, ax = plt.subplots()n = [4, 5, 6, 10, 12, 15, 20, 23, 24, 19]ax.plot(n) # Define a RectangleSelector at given axes ax.# It calls a function named 'onselect_function'# when the selection is completed.# Rectangular box is drawn to show the selected region.# Only left mouse button is allowed for doing selection.rect_selector = RectangleSelector( ax, onselect_function, drawtype='box', button=[1]) # Display graphplt.show()",
"e": 28917,
"s": 27873,
"text": null
},
{
"code": null,
"e": 28925,
"s": 28917,
"text": "Output:"
},
{
"code": null,
"e": 28934,
"s": 28925,
"text": "sooda367"
},
{
"code": null,
"e": 28949,
"s": 28934,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 28956,
"s": 28949,
"text": "Picked"
},
{
"code": null,
"e": 28974,
"s": 28956,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 28981,
"s": 28974,
"text": "Python"
},
{
"code": null,
"e": 29079,
"s": 28981,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29111,
"s": 29079,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29153,
"s": 29111,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 29195,
"s": 29153,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 29251,
"s": 29195,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 29278,
"s": 29251,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 29309,
"s": 29278,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 29348,
"s": 29309,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 29377,
"s": 29348,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 29399,
"s": 29377,
"text": "Defaultdict in Python"
}
] |
Minimum number of moves required to reach the destination by the king in a chess board - GeeksforGeeks | 17 Jan, 2022
Given four integers sourceX, sourceY, destinationX and destinationY which represent the source and destination coordinates on a chessboard. The task is to find the minimum number of moves required by the king to reach from source to destination. A king can move to the square that has a common side or a common vertex with the square the king is currently in (generally there are 8 different squares he can move to).
Print path using L, R, U, D, LU, LD, RU and RD where L, R, U and D represent left, right, up and down respectively.
Examples:
Input: sourceX = 4, sourceY = 4, destinationX = 3, destinationY = 5 Output: 1 DR
Input: sourceX = 4, sourceY = 4, destinationX = 7, destinationY = 0 Output: 4 UL UL UL L
Approach: Move in the diagonal direction towards the destination until the king reaches same column or same row as the destination, then move towards the destination in a straight line.
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to Find the minimum number of moves required to// reach the destination by the king in a chess board#include <bits/stdc++.h>using namespace std; // function to Find the minimum number of moves required to// reach the destination by the king in a chess boardvoid MinSteps(int SourceX, int SourceY, int DestX, int DestY){ // minimum number of steps cout << max(abs(SourceX - DestX), abs(SourceY - DestY)) << endl; // while the king is not in the same row or column // as the destination while ((SourceX != DestX) || (SourceY != DestY)) { // Go up if (SourceX < DestX) { cout << 'U'; SourceX++; } // Go down if (SourceX > DestX) { cout << 'D'; SourceX--; } // Go left if (SourceY > DestY) { cout << 'L'; SourceY--; } // Go right if (SourceY < DestY) { cout << 'R'; SourceY++; } cout << endl; }} // Driver codeint main(){ int sourceX = 4, sourceY = 4; int destinationX = 7, destinationY = 0; MinSteps(sourceX, sourceY, destinationX, destinationY); return 0;}
// Java program to Find the minimum// number of moves required to reach// the destination by the king in a// chess boardimport java.io.*; class GFG{ // function to Find the minimum number// of moves required to reach the// destination by the king in a chess boardstatic void MinSteps(int SourceX, int SourceY, int DestX, int DestY){ // minimum number of steps System.out.println(Math.max(Math.abs(SourceX - DestX), Math.abs(SourceY - DestY))); // while the king is not in the same // row or column as the destination while ((SourceX != DestX) || (SourceY != DestY)) { // Go up if (SourceX < DestX) { System.out.print( 'U'); SourceX++; } // Go down if (SourceX > DestX) { System.out.println( 'D'); SourceX--; } // Go left if (SourceY > DestY) { System.out.print( 'L'); SourceY--; } // Go right if (SourceY < DestY) { System.out.print( 'R'); SourceY++; } System.out.println(); }} // Driver codepublic static void main (String[] args){ int sourceX = 4, sourceY = 4; int destinationX = 7, destinationY = 0; MinSteps(sourceX, sourceY, destinationX, destinationY);}} // This code is contributed by inder_verma
# Python 3 program to Find the minimum number of moves required to# reach the destination by the king in a chess board # function to Find the minimum number of moves required to# reach the destination by the king in a chess boarddef MinSteps(SourceX, SourceY, DestX, DestY): # minimum number of steps print(max(abs(SourceX - DestX), abs(SourceY - DestY))) # while the king is not in the same row or column # as the destination while ((SourceX != DestX) or (SourceY != DestY)): # Go up if (SourceX < DestX): print('U',end = "") SourceX += 1 # Go down if (SourceX > DestX): print('D',end = "") SourceX -= 1 # Go left if (SourceY > DestY): print('L') SourceY -= 1 # Go right if (SourceY < DestY): print('R',end = "") SourceY += 1 # Driver codeif __name__ == '__main__': sourceX = 4 sourceY = 4 destinationX = 7 destinationY = 0 MinSteps(sourceX, sourceY, destinationX, destinationY) # This code is contributed by# Surendra_Gangwar
// C# program to Find the minimum// number of moves required to reach// the destination by the king in a// chess boardusing System; class GFG{ // function to Find the minimum number// of moves required to reach the// destination by the king in a chess boardstatic void MinSteps(int SourceX, int SourceY, int DestX, int DestY){ // minimum number of steps Console.WriteLine(Math.Max(Math.Abs(SourceX - DestX), Math.Abs(SourceY - DestY))); // while the king is not in the same // row or column as the destination while ((SourceX != DestX) || (SourceY != DestY)) { // Go up if (SourceX < DestX) { Console.Write( 'U'); SourceX++; } // Go down if (SourceX > DestX) { Console.Write( 'D'); SourceX--; } // Go left if (SourceY > DestY) { Console.Write( 'L'); SourceY--; } // Go right if (SourceY < DestY) { Console.Write( 'R'); SourceY++; } Console.WriteLine(); }} // Driver codepublic static void Main (){ int sourceX = 4, sourceY = 4; int destinationX = 7, destinationY = 0; MinSteps(sourceX, sourceY, destinationX, destinationY);}} // This code is contributed by inder_verma
<?php// PHP program to Find the minimum// number of moves required to// reach the destination by the// king in a chess board // function to Find the minimum// number of moves required to// reach the destination by the// king in a chess boardfunction MinSteps($SourceX, $SourceY, $DestX, $DestY){ // minimum number of steps echo max(abs($SourceX - $DestX), abs($SourceY - $DestY)) . "\n"; // while the king is not in the // same row or column as the destination while (($SourceX != $DestX) || ($SourceY != $DestY)) { // Go up if ($SourceX < $DestX) { echo 'U'; $SourceX++; } // Go down if ($SourceX > $DestX) { echo 'D'; $SourceX--; } // Go left if ($SourceY > $DestY) { echo 'L'; $SourceY--; } // Go right if ($SourceY < $DestY) { echo 'R'; $SourceY++; } echo "\n"; }} // Driver code$sourceX = 4; $sourceY = 4;$destinationX = 7; $destinationY = 0; MinSteps($sourceX, $sourceY, $destinationX, $destinationY); // This code is contributed// by Akanksha Rai?>
<script> // Javascript program to Find the minimum// number of moves required to reach the// destination by the king in a chess board // function to Find the minimum number of// moves required to reach the destination// by the king in a chess boardfunction MinSteps(SourceX, SourceY, DestX, DestY){ // Minimum number of steps document.write(Math.max(Math.abs(SourceX - DestX), Math.abs(SourceY - DestY)) + "<br>"); // While the king is not in the same row // or column as the destination while ((SourceX != DestX) || (SourceY != DestY)) { // Go up if (SourceX < DestX) { document.write('U'); SourceX++; } // Go down if (SourceX > DestX) { document.write('D'); SourceX--; } // Go left if (SourceY > DestY) { document.write('L'); SourceY--; } // Go right if (SourceY < DestY) { document.write('R'); SourceY++; } document.write("<br>"); }} // Driver codelet sourceX = 4, sourceY = 4;let destinationX = 7, destinationY = 0; MinSteps(sourceX, sourceY, destinationX, destinationY); // This code is contributed by souravmahato348 </script>
4
UL
UL
UL
L
Time complexity: O(max(a, b)), where a = sourceX and b = sourceY
Auxiliary Space: O(1)
inderDuMCA
Akanksha_Rai
SURENDRA_GANGWAR
souravmahato348
sagar0719kumar
samim2000
chessboard-problems
Competitive Programming
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Prefix Sum Array - Implementation and Applications in Competitive Programming
Ordered Set and GNU C++ PBDS
Modulo 10^9+7 (1000000007)
Bits manipulation (Important tactics)
7 Best Coding Challenge Websites in 2020
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7 | [
{
"code": null,
"e": 26525,
"s": 26497,
"text": "\n17 Jan, 2022"
},
{
"code": null,
"e": 26942,
"s": 26525,
"text": "Given four integers sourceX, sourceY, destinationX and destinationY which represent the source and destination coordinates on a chessboard. The task is to find the minimum number of moves required by the king to reach from source to destination. A king can move to the square that has a common side or a common vertex with the square the king is currently in (generally there are 8 different squares he can move to)."
},
{
"code": null,
"e": 27058,
"s": 26942,
"text": "Print path using L, R, U, D, LU, LD, RU and RD where L, R, U and D represent left, right, up and down respectively."
},
{
"code": null,
"e": 27069,
"s": 27058,
"text": "Examples: "
},
{
"code": null,
"e": 27150,
"s": 27069,
"text": "Input: sourceX = 4, sourceY = 4, destinationX = 3, destinationY = 5 Output: 1 DR"
},
{
"code": null,
"e": 27240,
"s": 27150,
"text": "Input: sourceX = 4, sourceY = 4, destinationX = 7, destinationY = 0 Output: 4 UL UL UL L "
},
{
"code": null,
"e": 27426,
"s": 27240,
"text": "Approach: Move in the diagonal direction towards the destination until the king reaches same column or same row as the destination, then move towards the destination in a straight line."
},
{
"code": null,
"e": 27478,
"s": 27426,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27482,
"s": 27478,
"text": "C++"
},
{
"code": null,
"e": 27487,
"s": 27482,
"text": "Java"
},
{
"code": null,
"e": 27495,
"s": 27487,
"text": "Python3"
},
{
"code": null,
"e": 27498,
"s": 27495,
"text": "C#"
},
{
"code": null,
"e": 27502,
"s": 27498,
"text": "PHP"
},
{
"code": null,
"e": 27513,
"s": 27502,
"text": "Javascript"
},
{
"code": "// C++ program to Find the minimum number of moves required to// reach the destination by the king in a chess board#include <bits/stdc++.h>using namespace std; // function to Find the minimum number of moves required to// reach the destination by the king in a chess boardvoid MinSteps(int SourceX, int SourceY, int DestX, int DestY){ // minimum number of steps cout << max(abs(SourceX - DestX), abs(SourceY - DestY)) << endl; // while the king is not in the same row or column // as the destination while ((SourceX != DestX) || (SourceY != DestY)) { // Go up if (SourceX < DestX) { cout << 'U'; SourceX++; } // Go down if (SourceX > DestX) { cout << 'D'; SourceX--; } // Go left if (SourceY > DestY) { cout << 'L'; SourceY--; } // Go right if (SourceY < DestY) { cout << 'R'; SourceY++; } cout << endl; }} // Driver codeint main(){ int sourceX = 4, sourceY = 4; int destinationX = 7, destinationY = 0; MinSteps(sourceX, sourceY, destinationX, destinationY); return 0;}",
"e": 28700,
"s": 27513,
"text": null
},
{
"code": "// Java program to Find the minimum// number of moves required to reach// the destination by the king in a// chess boardimport java.io.*; class GFG{ // function to Find the minimum number// of moves required to reach the// destination by the king in a chess boardstatic void MinSteps(int SourceX, int SourceY, int DestX, int DestY){ // minimum number of steps System.out.println(Math.max(Math.abs(SourceX - DestX), Math.abs(SourceY - DestY))); // while the king is not in the same // row or column as the destination while ((SourceX != DestX) || (SourceY != DestY)) { // Go up if (SourceX < DestX) { System.out.print( 'U'); SourceX++; } // Go down if (SourceX > DestX) { System.out.println( 'D'); SourceX--; } // Go left if (SourceY > DestY) { System.out.print( 'L'); SourceY--; } // Go right if (SourceY < DestY) { System.out.print( 'R'); SourceY++; } System.out.println(); }} // Driver codepublic static void main (String[] args){ int sourceX = 4, sourceY = 4; int destinationX = 7, destinationY = 0; MinSteps(sourceX, sourceY, destinationX, destinationY);}} // This code is contributed by inder_verma",
"e": 30110,
"s": 28700,
"text": null
},
{
"code": "# Python 3 program to Find the minimum number of moves required to# reach the destination by the king in a chess board # function to Find the minimum number of moves required to# reach the destination by the king in a chess boarddef MinSteps(SourceX, SourceY, DestX, DestY): # minimum number of steps print(max(abs(SourceX - DestX), abs(SourceY - DestY))) # while the king is not in the same row or column # as the destination while ((SourceX != DestX) or (SourceY != DestY)): # Go up if (SourceX < DestX): print('U',end = \"\") SourceX += 1 # Go down if (SourceX > DestX): print('D',end = \"\") SourceX -= 1 # Go left if (SourceY > DestY): print('L') SourceY -= 1 # Go right if (SourceY < DestY): print('R',end = \"\") SourceY += 1 # Driver codeif __name__ == '__main__': sourceX = 4 sourceY = 4 destinationX = 7 destinationY = 0 MinSteps(sourceX, sourceY, destinationX, destinationY) # This code is contributed by# Surendra_Gangwar",
"e": 31250,
"s": 30110,
"text": null
},
{
"code": "// C# program to Find the minimum// number of moves required to reach// the destination by the king in a// chess boardusing System; class GFG{ // function to Find the minimum number// of moves required to reach the// destination by the king in a chess boardstatic void MinSteps(int SourceX, int SourceY, int DestX, int DestY){ // minimum number of steps Console.WriteLine(Math.Max(Math.Abs(SourceX - DestX), Math.Abs(SourceY - DestY))); // while the king is not in the same // row or column as the destination while ((SourceX != DestX) || (SourceY != DestY)) { // Go up if (SourceX < DestX) { Console.Write( 'U'); SourceX++; } // Go down if (SourceX > DestX) { Console.Write( 'D'); SourceX--; } // Go left if (SourceY > DestY) { Console.Write( 'L'); SourceY--; } // Go right if (SourceY < DestY) { Console.Write( 'R'); SourceY++; } Console.WriteLine(); }} // Driver codepublic static void Main (){ int sourceX = 4, sourceY = 4; int destinationX = 7, destinationY = 0; MinSteps(sourceX, sourceY, destinationX, destinationY);}} // This code is contributed by inder_verma",
"e": 32635,
"s": 31250,
"text": null
},
{
"code": "<?php// PHP program to Find the minimum// number of moves required to// reach the destination by the// king in a chess board // function to Find the minimum// number of moves required to// reach the destination by the// king in a chess boardfunction MinSteps($SourceX, $SourceY, $DestX, $DestY){ // minimum number of steps echo max(abs($SourceX - $DestX), abs($SourceY - $DestY)) . \"\\n\"; // while the king is not in the // same row or column as the destination while (($SourceX != $DestX) || ($SourceY != $DestY)) { // Go up if ($SourceX < $DestX) { echo 'U'; $SourceX++; } // Go down if ($SourceX > $DestX) { echo 'D'; $SourceX--; } // Go left if ($SourceY > $DestY) { echo 'L'; $SourceY--; } // Go right if ($SourceY < $DestY) { echo 'R'; $SourceY++; } echo \"\\n\"; }} // Driver code$sourceX = 4; $sourceY = 4;$destinationX = 7; $destinationY = 0; MinSteps($sourceX, $sourceY, $destinationX, $destinationY); // This code is contributed// by Akanksha Rai?>",
"e": 33880,
"s": 32635,
"text": null
},
{
"code": "<script> // Javascript program to Find the minimum// number of moves required to reach the// destination by the king in a chess board // function to Find the minimum number of// moves required to reach the destination// by the king in a chess boardfunction MinSteps(SourceX, SourceY, DestX, DestY){ // Minimum number of steps document.write(Math.max(Math.abs(SourceX - DestX), Math.abs(SourceY - DestY)) + \"<br>\"); // While the king is not in the same row // or column as the destination while ((SourceX != DestX) || (SourceY != DestY)) { // Go up if (SourceX < DestX) { document.write('U'); SourceX++; } // Go down if (SourceX > DestX) { document.write('D'); SourceX--; } // Go left if (SourceY > DestY) { document.write('L'); SourceY--; } // Go right if (SourceY < DestY) { document.write('R'); SourceY++; } document.write(\"<br>\"); }} // Driver codelet sourceX = 4, sourceY = 4;let destinationX = 7, destinationY = 0; MinSteps(sourceX, sourceY, destinationX, destinationY); // This code is contributed by souravmahato348 </script>",
"e": 35182,
"s": 33880,
"text": null
},
{
"code": null,
"e": 35195,
"s": 35182,
"text": "4\nUL\nUL\nUL\nL"
},
{
"code": null,
"e": 35262,
"s": 35197,
"text": "Time complexity: O(max(a, b)), where a = sourceX and b = sourceY"
},
{
"code": null,
"e": 35284,
"s": 35262,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 35295,
"s": 35284,
"text": "inderDuMCA"
},
{
"code": null,
"e": 35308,
"s": 35295,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 35325,
"s": 35308,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 35341,
"s": 35325,
"text": "souravmahato348"
},
{
"code": null,
"e": 35356,
"s": 35341,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 35366,
"s": 35356,
"text": "samim2000"
},
{
"code": null,
"e": 35386,
"s": 35366,
"text": "chessboard-problems"
},
{
"code": null,
"e": 35410,
"s": 35386,
"text": "Competitive Programming"
},
{
"code": null,
"e": 35423,
"s": 35410,
"text": "Mathematical"
},
{
"code": null,
"e": 35436,
"s": 35423,
"text": "Mathematical"
},
{
"code": null,
"e": 35534,
"s": 35436,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35612,
"s": 35534,
"text": "Prefix Sum Array - Implementation and Applications in Competitive Programming"
},
{
"code": null,
"e": 35641,
"s": 35612,
"text": "Ordered Set and GNU C++ PBDS"
},
{
"code": null,
"e": 35668,
"s": 35641,
"text": "Modulo 10^9+7 (1000000007)"
},
{
"code": null,
"e": 35706,
"s": 35668,
"text": "Bits manipulation (Important tactics)"
},
{
"code": null,
"e": 35747,
"s": 35706,
"text": "7 Best Coding Challenge Websites in 2020"
},
{
"code": null,
"e": 35777,
"s": 35747,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 35837,
"s": 35777,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 35852,
"s": 35837,
"text": "C++ Data Types"
},
{
"code": null,
"e": 35895,
"s": 35852,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
GATE | Gate IT 2005 | Question 50 - GeeksforGeeks | 28 Jun, 2021
In a binary tree, for every node the difference between the number of nodes in the left and right subtrees is at most 2. If the height of the tree is h > 0, then the minimum number of nodes in the tree is:(A) 2h – 1(B) 2h – 1 + 1(C) 2h – 1(D) 2hAnswer: (B)Explanation:
Let there be n(h) nodes at height h.
In a perfect tree where every node has exactly
two children, except leaves, following recurrence holds.
n(h) = 2*n(h-1) + 1
In given case, the numbers of nodes are two less, therefore
n(h) = 2*n(h-1) + 1 - 2
= 2*n(h-1) - 1
Now if try all options, only option (b) satisfies above recurrence.
Let us see option (B)
n(h) = 2h - 1 + 1
So if we substitute
n(h-1) = 2h-2 + 1, we should get n(h) = 2h-1 + 1
n(h) = 2*n(h-1) - 1
= 2*(2h-2 + 1) -1
= 2h-1 + 1.
Quiz of this Question
Gate IT 2005
GATE-Gate IT 2005
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90 | [
{
"code": null,
"e": 25657,
"s": 25629,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 25926,
"s": 25657,
"text": "In a binary tree, for every node the difference between the number of nodes in the left and right subtrees is at most 2. If the height of the tree is h > 0, then the minimum number of nodes in the tree is:(A) 2h – 1(B) 2h – 1 + 1(C) 2h – 1(D) 2hAnswer: (B)Explanation:"
},
{
"code": null,
"e": 26441,
"s": 25926,
"text": "Let there be n(h) nodes at height h.\n\nIn a perfect tree where every node has exactly \ntwo children, except leaves, following recurrence holds.\n\nn(h) = 2*n(h-1) + 1\n\nIn given case, the numbers of nodes are two less, therefore\nn(h) = 2*n(h-1) + 1 - 2\n = 2*n(h-1) - 1\n\nNow if try all options, only option (b) satisfies above recurrence.\n\nLet us see option (B)\nn(h) = 2h - 1 + 1\n\nSo if we substitute \nn(h-1) = 2h-2 + 1, we should get n(h) = 2h-1 + 1\n\nn(h) = 2*n(h-1) - 1\n = 2*(2h-2 + 1) -1\n = 2h-1 + 1.\n"
},
{
"code": null,
"e": 26463,
"s": 26441,
"text": "Quiz of this Question"
},
{
"code": null,
"e": 26476,
"s": 26463,
"text": "Gate IT 2005"
},
{
"code": null,
"e": 26494,
"s": 26476,
"text": "GATE-Gate IT 2005"
},
{
"code": null,
"e": 26499,
"s": 26494,
"text": "GATE"
},
{
"code": null,
"e": 26597,
"s": 26499,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26631,
"s": 26597,
"text": "GATE | Gate IT 2007 | Question 25"
},
{
"code": null,
"e": 26665,
"s": 26631,
"text": "GATE | GATE-CS-2000 | Question 41"
},
{
"code": null,
"e": 26699,
"s": 26665,
"text": "GATE | GATE-CS-2001 | Question 39"
},
{
"code": null,
"e": 26732,
"s": 26699,
"text": "GATE | GATE-CS-2005 | Question 6"
},
{
"code": null,
"e": 26768,
"s": 26732,
"text": "GATE | GATE MOCK 2017 | Question 21"
},
{
"code": null,
"e": 26802,
"s": 26768,
"text": "GATE | GATE-CS-2006 | Question 47"
},
{
"code": null,
"e": 26838,
"s": 26802,
"text": "GATE | GATE MOCK 2017 | Question 24"
},
{
"code": null,
"e": 26872,
"s": 26838,
"text": "GATE | Gate IT 2008 | Question 43"
},
{
"code": null,
"e": 26906,
"s": 26872,
"text": "GATE | GATE-CS-2009 | Question 38"
}
] |
How to Solve Java List UnsupportedOperationException? - GeeksforGeeks | 09 Mar, 2021
The UnsupportedOperationException is one of the common exceptions that occur when we are working with some API of list implementation. It is thrown to indicate that the requested operation is not supported.
This class is a member of the Java Collections Framework.
All java errors implement the java.lang.Throwable interface or are inherited from another class. The hierarchy of this Exception is-
java.lang.Object
java.lang.Throwable
java.lang.Exception
java.lang.RuntimeException
java.lang.UnsupportedOperationException
Syntax:
public class UnsupportedOperationException
extends RuntimeException
The main reason behind the occurrence of this error is the asList method of java.util.Arrays class returns an object of an ArrayList which is nested inside the class java.util.Arrays. ArrayList extends java.util.AbstractList and it does not implement add or remove method. Thus when this method is called on the list object, it calls to add or remove method of AbstractList class which throws this exception. Moreover, the list returned by the asList method is a fixed-size list therefore it cannot be modified.
The below example will result in UnsupportedOperationException as it is trying to add a new element to a fixed-size list object
Java
import java.util.Arrays;import java.util.List; public class Example { public static void main(String[] args) { String str[] = { "Apple", "Banana" }; List<String> l = Arrays.asList(str); System.out.println(l); // It will throw java.lang.UnsupportedOperationException l.add("Mango"); }}
Output:
Exception in thread "main" java.lang.UnsupportedOperationException
at java.base/java.util.AbstractList.add(AbstractList.java:153)
at java.base/java.util.AbstractList.add(AbstractList.java:111)
at Example.main(Example.java:14)
We can solve this problem by using a mutable List that can be modified such as an ArrayList. We create a List using Arrays.asList method as we were using earlier and pass that resultant List to create a new ArrayList object.
Java
import java.util.ArrayList;import java.util.List;import java.util.*; public class Example { public static void main(String[] args) { String str[] = { "Apple", "Banana" }; List<String> list = Arrays.asList(str); List<String> l = new ArrayList<>(list); l.add("Mango"); // modify the list for(String s: l ) System.out.println(s); } }
Apple
Banana
Mango
Java-Exceptions
Picked
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
Internal Working of HashMap in Java
Strings in Java | [
{
"code": null,
"e": 25251,
"s": 25223,
"text": "\n09 Mar, 2021"
},
{
"code": null,
"e": 25458,
"s": 25251,
"text": "The UnsupportedOperationException is one of the common exceptions that occur when we are working with some API of list implementation. It is thrown to indicate that the requested operation is not supported."
},
{
"code": null,
"e": 25516,
"s": 25458,
"text": "This class is a member of the Java Collections Framework."
},
{
"code": null,
"e": 25649,
"s": 25516,
"text": "All java errors implement the java.lang.Throwable interface or are inherited from another class. The hierarchy of this Exception is-"
},
{
"code": null,
"e": 25668,
"s": 25649,
"text": " java.lang.Object"
},
{
"code": null,
"e": 25697,
"s": 25668,
"text": " java.lang.Throwable"
},
{
"code": null,
"e": 25736,
"s": 25697,
"text": " java.lang.Exception"
},
{
"code": null,
"e": 25789,
"s": 25736,
"text": " java.lang.RuntimeException"
},
{
"code": null,
"e": 25863,
"s": 25789,
"text": " java.lang.UnsupportedOperationException"
},
{
"code": null,
"e": 25871,
"s": 25863,
"text": "Syntax:"
},
{
"code": null,
"e": 25939,
"s": 25871,
"text": "public class UnsupportedOperationException\nextends RuntimeException"
},
{
"code": null,
"e": 26451,
"s": 25939,
"text": "The main reason behind the occurrence of this error is the asList method of java.util.Arrays class returns an object of an ArrayList which is nested inside the class java.util.Arrays. ArrayList extends java.util.AbstractList and it does not implement add or remove method. Thus when this method is called on the list object, it calls to add or remove method of AbstractList class which throws this exception. Moreover, the list returned by the asList method is a fixed-size list therefore it cannot be modified."
},
{
"code": null,
"e": 26579,
"s": 26451,
"text": "The below example will result in UnsupportedOperationException as it is trying to add a new element to a fixed-size list object"
},
{
"code": null,
"e": 26584,
"s": 26579,
"text": "Java"
},
{
"code": "import java.util.Arrays;import java.util.List; public class Example { public static void main(String[] args) { String str[] = { \"Apple\", \"Banana\" }; List<String> l = Arrays.asList(str); System.out.println(l); // It will throw java.lang.UnsupportedOperationException l.add(\"Mango\"); }}",
"e": 26918,
"s": 26584,
"text": null
},
{
"code": null,
"e": 26926,
"s": 26918,
"text": "Output:"
},
{
"code": null,
"e": 27164,
"s": 26926,
"text": "Exception in thread \"main\" java.lang.UnsupportedOperationException\n at java.base/java.util.AbstractList.add(AbstractList.java:153)\n at java.base/java.util.AbstractList.add(AbstractList.java:111)\n at Example.main(Example.java:14)"
},
{
"code": null,
"e": 27390,
"s": 27164,
"text": "We can solve this problem by using a mutable List that can be modified such as an ArrayList. We create a List using Arrays.asList method as we were using earlier and pass that resultant List to create a new ArrayList object. "
},
{
"code": null,
"e": 27395,
"s": 27390,
"text": "Java"
},
{
"code": "import java.util.ArrayList;import java.util.List;import java.util.*; public class Example { public static void main(String[] args) { String str[] = { \"Apple\", \"Banana\" }; List<String> list = Arrays.asList(str); List<String> l = new ArrayList<>(list); l.add(\"Mango\"); // modify the list for(String s: l ) System.out.println(s); } }",
"e": 27812,
"s": 27395,
"text": null
},
{
"code": null,
"e": 27832,
"s": 27812,
"text": "Apple\nBanana\nMango\n"
},
{
"code": null,
"e": 27848,
"s": 27832,
"text": "Java-Exceptions"
},
{
"code": null,
"e": 27855,
"s": 27848,
"text": "Picked"
},
{
"code": null,
"e": 27860,
"s": 27855,
"text": "Java"
},
{
"code": null,
"e": 27865,
"s": 27860,
"text": "Java"
},
{
"code": null,
"e": 27963,
"s": 27865,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27978,
"s": 27963,
"text": "Stream In Java"
},
{
"code": null,
"e": 27999,
"s": 27978,
"text": "Constructors in Java"
},
{
"code": null,
"e": 28018,
"s": 27999,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 28048,
"s": 28018,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 28094,
"s": 28048,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 28111,
"s": 28094,
"text": "Generics in Java"
},
{
"code": null,
"e": 28132,
"s": 28111,
"text": "Introduction to Java"
},
{
"code": null,
"e": 28175,
"s": 28132,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 28211,
"s": 28175,
"text": "Internal Working of HashMap in Java"
}
] |
How to create Header in React.js ? - GeeksforGeeks | 13 Dec, 2021
The Header is an important element of a website’s design. It’s the first impression of the website. It provides useful links to other areas of the website that the user may want to visit. In this article, we will create a functioning Header using React.js and Material UI.
Approach: First we will create a basic react app using some installations. We will make our new Header Component with some styling using Material-UI. To create a Header, we will use App Bar from Material UI which will provide screen titles, navigation, and actions. Also, we will need a ToolBar inside which will set the properties to child components making them all horizontally aligned. Then we will make some changes to our default Home page i.e. App.js file by importing the newly created Header into it. Now Let’s start creating this.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Step 3: After creating the React.js application, install the material-ui modules using the following command.
npm install @material-ui/core
npm install @mui/icons-material
npm install @mui/material
Project Structure: Now create a new file Header.js in the folder named “src” . Our header component will reside in this file. Now the new project structure will look like this :
updated project structure
Step 3: Now we will make the header component. We will use App Bar Component is from Material UI .The top App Bar provides content and actions related to the current screen. It’s used for branding, screen titles, navigation, and actions. It can transform into a contextual action bar or be used as a navbar. Tool Bar from Material UI doesn’t work independently as that of other Material-UI components, it works with the AppBar. Toolbar component sets the properties to child component making them all horizontally align.
Header.js
import * as React from "react"; // importing material UI componentsimport AppBar from "@mui/material/AppBar";import Box from "@mui/material/Box";import Toolbar from "@mui/material/Toolbar";import Typography from "@mui/material/Typography";import Button from "@mui/material/Button";import IconButton from "@mui/material/IconButton";import MenuIcon from "@mui/icons-material/Menu"; export default function Header() { return ( <AppBar position="static"> <Toolbar> {/*Inside the IconButton, we can render various icons*/} <IconButton size="large" edge="start" color="inherit" aria-label="menu" sx={{ mr: 2 }} > {/*This is a simple Menu Icon wrapped in Icon */} <MenuIcon /> </IconButton> {/* The Typography component applies default font weights and sizes */} <Typography variant="h6" component="div" sx={{ flexGrow: 1 }}> GeeksforGeeks Header </Typography> <Button color="inherit">Login</Button> </Toolbar> </AppBar> );}
Step 4: After creating the Header component , we will import it in App.js and make changes in App.js as follows.
App.js
import React from "react";import Header from "./Header"; function App() { return ( // Using the newly created Header // component in this main component <Header/> );}export default App;
Step to run the application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Picked
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ReactJS useNavigate() Hook
How to set background images in ReactJS ?
Axios in React: A Guide for Beginners
How to create a table in ReactJS ?
How to navigate on path by button click in react router ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 26071,
"s": 26043,
"text": "\n13 Dec, 2021"
},
{
"code": null,
"e": 26344,
"s": 26071,
"text": "The Header is an important element of a website’s design. It’s the first impression of the website. It provides useful links to other areas of the website that the user may want to visit. In this article, we will create a functioning Header using React.js and Material UI."
},
{
"code": null,
"e": 26885,
"s": 26344,
"text": "Approach: First we will create a basic react app using some installations. We will make our new Header Component with some styling using Material-UI. To create a Header, we will use App Bar from Material UI which will provide screen titles, navigation, and actions. Also, we will need a ToolBar inside which will set the properties to child components making them all horizontally aligned. Then we will make some changes to our default Home page i.e. App.js file by importing the newly created Header into it. Now Let’s start creating this."
},
{
"code": null,
"e": 26935,
"s": 26885,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 26999,
"s": 26935,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 27031,
"s": 26999,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 27133,
"s": 27033,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:"
},
{
"code": null,
"e": 27147,
"s": 27133,
"text": "cd foldername"
},
{
"code": null,
"e": 27257,
"s": 27147,
"text": "Step 3: After creating the React.js application, install the material-ui modules using the following command."
},
{
"code": null,
"e": 27345,
"s": 27257,
"text": "npm install @material-ui/core\nnpm install @mui/icons-material\nnpm install @mui/material"
},
{
"code": null,
"e": 27524,
"s": 27345,
"text": "Project Structure: Now create a new file Header.js in the folder named “src” . Our header component will reside in this file. Now the new project structure will look like this :"
},
{
"code": null,
"e": 27550,
"s": 27524,
"text": "updated project structure"
},
{
"code": null,
"e": 28071,
"s": 27550,
"text": "Step 3: Now we will make the header component. We will use App Bar Component is from Material UI .The top App Bar provides content and actions related to the current screen. It’s used for branding, screen titles, navigation, and actions. It can transform into a contextual action bar or be used as a navbar. Tool Bar from Material UI doesn’t work independently as that of other Material-UI components, it works with the AppBar. Toolbar component sets the properties to child component making them all horizontally align."
},
{
"code": null,
"e": 28081,
"s": 28071,
"text": "Header.js"
},
{
"code": "import * as React from \"react\"; // importing material UI componentsimport AppBar from \"@mui/material/AppBar\";import Box from \"@mui/material/Box\";import Toolbar from \"@mui/material/Toolbar\";import Typography from \"@mui/material/Typography\";import Button from \"@mui/material/Button\";import IconButton from \"@mui/material/IconButton\";import MenuIcon from \"@mui/icons-material/Menu\"; export default function Header() { return ( <AppBar position=\"static\"> <Toolbar> {/*Inside the IconButton, we can render various icons*/} <IconButton size=\"large\" edge=\"start\" color=\"inherit\" aria-label=\"menu\" sx={{ mr: 2 }} > {/*This is a simple Menu Icon wrapped in Icon */} <MenuIcon /> </IconButton> {/* The Typography component applies default font weights and sizes */} <Typography variant=\"h6\" component=\"div\" sx={{ flexGrow: 1 }}> GeeksforGeeks Header </Typography> <Button color=\"inherit\">Login</Button> </Toolbar> </AppBar> );}",
"e": 29236,
"s": 28081,
"text": null
},
{
"code": null,
"e": 29349,
"s": 29236,
"text": "Step 4: After creating the Header component , we will import it in App.js and make changes in App.js as follows."
},
{
"code": null,
"e": 29356,
"s": 29349,
"text": "App.js"
},
{
"code": "import React from \"react\";import Header from \"./Header\"; function App() { return ( // Using the newly created Header // component in this main component <Header/> );}export default App;",
"e": 29554,
"s": 29356,
"text": null
},
{
"code": null,
"e": 29671,
"s": 29554,
"text": "Step to run the application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 29681,
"s": 29671,
"text": "npm start"
},
{
"code": null,
"e": 29780,
"s": 29681,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:"
},
{
"code": null,
"e": 29787,
"s": 29780,
"text": "Picked"
},
{
"code": null,
"e": 29803,
"s": 29787,
"text": "React-Questions"
},
{
"code": null,
"e": 29811,
"s": 29803,
"text": "ReactJS"
},
{
"code": null,
"e": 29828,
"s": 29811,
"text": "Web Technologies"
},
{
"code": null,
"e": 29926,
"s": 29828,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29953,
"s": 29926,
"text": "ReactJS useNavigate() Hook"
},
{
"code": null,
"e": 29995,
"s": 29953,
"text": "How to set background images in ReactJS ?"
},
{
"code": null,
"e": 30033,
"s": 29995,
"text": "Axios in React: A Guide for Beginners"
},
{
"code": null,
"e": 30068,
"s": 30033,
"text": "How to create a table in ReactJS ?"
},
{
"code": null,
"e": 30126,
"s": 30068,
"text": "How to navigate on path by button click in react router ?"
},
{
"code": null,
"e": 30166,
"s": 30126,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30199,
"s": 30166,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 30244,
"s": 30199,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 30294,
"s": 30244,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Internal Structure of Python Dictionary - GeeksforGeeks | 22 Nov, 2021
Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only a single value as an element, Dictionary holds key:value pair. Key-value is provided in the dictionary to make it more optimized
The dictionary consists of a number of buckets. Each of these buckets contains the hash code of the object that contains the key-value pair. A pointer to the key object and a pointer to the value object.
The below diagram shows the internal structure of the dictionary:
The dictionary starts with 8 empty buckets. This is then resized by doubling the number of entries whenever its capacity is reached. This sums up to at least 12 bytes on a 32bit machine and 24 bytes on a 64bit machine
Example 1: An empty python dictionary consumes 240 bytes
Python3
# codeimport sys d = {}print(sys.getsizeof(d))
Output:
240
Example 2. The first time we create a dictionary it contains only 8 slots that can be filled with key-value pairs.
Python3
# codeimport sys d = {}d['python'] = 1print(sys.getsizeof(d))
Output:
240
As you can see the size of the dictionary is still the same after adding something to it. The dictionary stores in the bucket which is not full yet.
Example 3:
The key-values not stored in the dictionary itself the size of the dictionary doesn’t change even if we increase the size of its value
Python3
import sys d = {}d['a'] = 'a' * 100000print("Size of dictionary ->", sys.getsizeof(d))print("Size of a ->", sys.getsizeof('a'))
Size of dictionary -> 240
Size of a -> 50
Output:
Size of dictionary -> 240
Size of a -> 50
Example 4: If we remove the items from a dictionary the size of the dictionary will still be the same.
Python3
# codeimport sys d = {}d['python'] = 1for key in list(d.keys()): d.pop(key) print(len(d))print(sys.getsizeof(d))
Output:
0
240
Here, you can see the dictionary hasn’t released the memory it has allocated. It removes the reference from the hash table but the value is in the memory. Since it is not allocated may become part of garbage collection.
Example 5: If we empty the dictionary using the clear method the size of it is 72 bytes less than the initialized empty dictionary i.e. 240 bytes
Python3
import sys d = {}d['python'] = 1for key in list(d.keys()): d.pop(key) print(len(d))d.clear()print(sys.getsizeof(d))
Output:
0
72
This is because the method clears up memory. It also clears the initial default space i.e., 8 buckets allocated within the dictionary.
sagar0719kumar
as5853535
python-dict
Python
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n22 Nov, 2021"
},
{
"code": null,
"e": 25813,
"s": 25537,
"text": "Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only a single value as an element, Dictionary holds key:value pair. Key-value is provided in the dictionary to make it more optimized"
},
{
"code": null,
"e": 26017,
"s": 25813,
"text": "The dictionary consists of a number of buckets. Each of these buckets contains the hash code of the object that contains the key-value pair. A pointer to the key object and a pointer to the value object."
},
{
"code": null,
"e": 26083,
"s": 26017,
"text": "The below diagram shows the internal structure of the dictionary:"
},
{
"code": null,
"e": 26301,
"s": 26083,
"text": "The dictionary starts with 8 empty buckets. This is then resized by doubling the number of entries whenever its capacity is reached. This sums up to at least 12 bytes on a 32bit machine and 24 bytes on a 64bit machine"
},
{
"code": null,
"e": 26358,
"s": 26301,
"text": "Example 1: An empty python dictionary consumes 240 bytes"
},
{
"code": null,
"e": 26366,
"s": 26358,
"text": "Python3"
},
{
"code": "# codeimport sys d = {}print(sys.getsizeof(d))",
"e": 26413,
"s": 26366,
"text": null
},
{
"code": null,
"e": 26421,
"s": 26413,
"text": "Output:"
},
{
"code": null,
"e": 26425,
"s": 26421,
"text": "240"
},
{
"code": null,
"e": 26540,
"s": 26425,
"text": "Example 2. The first time we create a dictionary it contains only 8 slots that can be filled with key-value pairs."
},
{
"code": null,
"e": 26548,
"s": 26540,
"text": "Python3"
},
{
"code": "# codeimport sys d = {}d['python'] = 1print(sys.getsizeof(d))",
"e": 26610,
"s": 26548,
"text": null
},
{
"code": null,
"e": 26618,
"s": 26610,
"text": "Output:"
},
{
"code": null,
"e": 26622,
"s": 26618,
"text": "240"
},
{
"code": null,
"e": 26771,
"s": 26622,
"text": "As you can see the size of the dictionary is still the same after adding something to it. The dictionary stores in the bucket which is not full yet."
},
{
"code": null,
"e": 26783,
"s": 26771,
"text": "Example 3: "
},
{
"code": null,
"e": 26918,
"s": 26783,
"text": "The key-values not stored in the dictionary itself the size of the dictionary doesn’t change even if we increase the size of its value"
},
{
"code": null,
"e": 26926,
"s": 26918,
"text": "Python3"
},
{
"code": "import sys d = {}d['a'] = 'a' * 100000print(\"Size of dictionary ->\", sys.getsizeof(d))print(\"Size of a ->\", sys.getsizeof('a'))",
"e": 27054,
"s": 26926,
"text": null
},
{
"code": null,
"e": 27096,
"s": 27054,
"text": "Size of dictionary -> 240\nSize of a -> 50"
},
{
"code": null,
"e": 27104,
"s": 27096,
"text": "Output:"
},
{
"code": null,
"e": 27146,
"s": 27104,
"text": "Size of dictionary -> 240\nSize of a -> 50"
},
{
"code": null,
"e": 27249,
"s": 27146,
"text": "Example 4: If we remove the items from a dictionary the size of the dictionary will still be the same."
},
{
"code": null,
"e": 27257,
"s": 27249,
"text": "Python3"
},
{
"code": "# codeimport sys d = {}d['python'] = 1for key in list(d.keys()): d.pop(key) print(len(d))print(sys.getsizeof(d))",
"e": 27373,
"s": 27257,
"text": null
},
{
"code": null,
"e": 27381,
"s": 27373,
"text": "Output:"
},
{
"code": null,
"e": 27387,
"s": 27381,
"text": "0\n240"
},
{
"code": null,
"e": 27607,
"s": 27387,
"text": "Here, you can see the dictionary hasn’t released the memory it has allocated. It removes the reference from the hash table but the value is in the memory. Since it is not allocated may become part of garbage collection."
},
{
"code": null,
"e": 27753,
"s": 27607,
"text": "Example 5: If we empty the dictionary using the clear method the size of it is 72 bytes less than the initialized empty dictionary i.e. 240 bytes"
},
{
"code": null,
"e": 27761,
"s": 27753,
"text": "Python3"
},
{
"code": "import sys d = {}d['python'] = 1for key in list(d.keys()): d.pop(key) print(len(d))d.clear()print(sys.getsizeof(d))",
"e": 27880,
"s": 27761,
"text": null
},
{
"code": null,
"e": 27888,
"s": 27880,
"text": "Output:"
},
{
"code": null,
"e": 27893,
"s": 27888,
"text": "0\n72"
},
{
"code": null,
"e": 28028,
"s": 27893,
"text": "This is because the method clears up memory. It also clears the initial default space i.e., 8 buckets allocated within the dictionary."
},
{
"code": null,
"e": 28043,
"s": 28028,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 28053,
"s": 28043,
"text": "as5853535"
},
{
"code": null,
"e": 28065,
"s": 28053,
"text": "python-dict"
},
{
"code": null,
"e": 28072,
"s": 28065,
"text": "Python"
},
{
"code": null,
"e": 28084,
"s": 28072,
"text": "python-dict"
},
{
"code": null,
"e": 28182,
"s": 28084,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28214,
"s": 28182,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28256,
"s": 28214,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28298,
"s": 28256,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28354,
"s": 28298,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28381,
"s": 28354,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28412,
"s": 28381,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28451,
"s": 28412,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28480,
"s": 28451,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 28502,
"s": 28480,
"text": "Defaultdict in Python"
}
] |
Sort a nearly sorted array using STL - GeeksforGeeks | 30 Jun, 2021
Given an array of n elements, where each element is at most k away from its target position, devise an algorithm that sorts in O(n log k) time. For example, let us consider k is 2, an element at index 7 in the sorted array, can be at indexes 5, 6, 7, 8, 9 in the given array. It may be assumed that k < n.
Example:
Input: arr[] = {6, 5, 3, 2, 8, 10, 9},
k = 3
Output: arr[] = {2, 3, 5, 6, 8, 9, 10}
Input: arr[] = {10, 9, 8, 7, 4, 70, 60, 50},
k = 4
Output: arr[] = {4, 7, 8, 9, 10, 50, 60, 70}
Simple Approach: The basic solution is to sort the array using any standard sorting algorithm.
CPP14
Java
Python3
C#
Javascript
// A STL based C++ program to// sort a nearly sorted array.#include <bits/stdc++.h>using namespace std; // Given an array of size n,// where every element// is k away from its target// position, sorts the// array in O(n Log n) time.int sortK(int arr[], int n, int k){ // Sort the array using // inbuilt function sort(arr, arr + n);} // An utility function to print// array elementsvoid printArray( int arr[], int size){ for (int i = 0; i < size; i++) cout << arr[i] << " "; cout << endl;} // Driver program to test// above functionsint main(){ int k = 3; int arr[] = { 2, 6, 3, 12, 56, 8 }; int n = sizeof(arr) / sizeof(arr[0]); sortK(arr, n, k); cout << "Following is sorted array\n"; printArray(arr, n); return 0;}
// A STL based Java program to// sort a nearly sorted array.import java.util.*;public class GFG{ // Given an array of size n, // where every element // is k away from its target // position, sorts the // array in O(n Log n) time. static void sortK(int[] arr, int n, int k) { // Sort the array using // inbuilt function Arrays.sort(arr); } // An utility function to print // array elements static void printArray( int[] arr, int size) { for (int i = 0; i < size; i++) System.out.print(arr[i] + " "); System.out.println(); } // Driver code public static void main(String[] args) { int k = 3; int[] arr = { 2, 6, 3, 12, 56, 8 }; int n = arr.length; sortK(arr, n, k); System.out.println("Following is sorted array"); printArray(arr, n); }} // This code is contributed by divyesh072019.
# A STL based Java program to# sort a nearly sorted array. # Given an array of size n,# where every element# is k away from its target# position, sorts the# array in O(n Log n) time.def sortK(arr, n, k): # Sort the array using # inbuilt function arr.sort() # An utility function to print# array elementsdef printArray(arr, size): for i in range(size): print(arr[i], end = " ") print() # Driver codek = 3arr = [ 2, 6, 3, 12, 56, 8]n = len(arr)sortK(arr, n, k)print("Following is sorted array")printArray(arr, n) # This code is contributed by avanitrachhadiya2155
// A STL based C# program to// sort a nearly sorted array.using System;class GFG{ // Given an array of size n, // where every element // is k away from its target // position, sorts the // array in O(n Log n) time. static void sortK(int[] arr, int n, int k) { // Sort the array using // inbuilt function Array.Sort(arr); } // An utility function to print // array elements static void printArray( int[] arr, int size) { for (int i = 0; i < size; i++) Console.Write(arr[i] + " "); Console.WriteLine(); } // Driver code static void Main() { int k = 3; int[] arr = { 2, 6, 3, 12, 56, 8 }; int n = arr.Length; sortK(arr, n, k); Console.WriteLine("Following is sorted array"); printArray(arr, n); }} // This code is contributed by divyeshrabadiya07.
<script>// A STL based Javascript program to// sort a nearly sorted array. // Given an array of size n,// where every element// is k away from its target// position, sorts the// array in O(n Log n) time.function sortK(arr,n,k){ // Sort the array using // inbuilt function (arr).sort(function(a,b){return a-b;});} // An utility function to print// array elementsfunction printArray(arr,size){ for (let i = 0; i < size; i++) document.write(arr[i] + " "); document.write("<br>");} // Driver codelet k = 3;let arr=[ 2, 6, 3, 12, 56, 8 ];let n = arr.length;sortK(arr, n, k);document.write("Following is sorted array<br>");printArray(arr, n); // This code is contributed by ab2127</script>
Following is sorted arrayn2 3 6 8 12 56
Complexity Analysis:
Time complexity: O(n log n), where n is the size of the array. The sorting algorithm takes log n time. Since the size of the array is n, the whole program takes O(n log n) time.
Space Complexity: O(1). As no extra space is required.
Efficient Solution: Sliding Window technique. Approach: A better solution is to use a priority queue(or heap data structure). Use sliding window technique to keep consecutive k elements of a window in heap. Then remove the top element(smallest element) and replace the first element of the window with it. As each element will be at most k distance apart, therefore keeping k consecutive elements in a window while replacing the i-th element with the smallest element from i to (i+k) will suffice(first i-1 elements are sorted).Algorithm:
Build a priority queue pq of first (k+1) elements.Initialize index = 0 (For result array).Do the following for elements from k+1 to n-1. Pop an item from pq and put it at index, increment index.Push arr[i] to pq.While pq is not empty, Pop an item from pq and put it at index, increment index.
Build a priority queue pq of first (k+1) elements.
Initialize index = 0 (For result array).
Do the following for elements from k+1 to n-1. Pop an item from pq and put it at index, increment index.Push arr[i] to pq.
Pop an item from pq and put it at index, increment index.Push arr[i] to pq.
Pop an item from pq and put it at index, increment index.
Push arr[i] to pq.
While pq is not empty, Pop an item from pq and put it at index, increment index.
We have discussed a simple implementation in Sort a nearly sorted (or K sorted) array. In this post, an STL based implementation is done.
CPP
// A STL based C++ program to sort// a nearly sorted array.#include <bits/stdc++.h>using namespace std; // Given an array of size n,// where every element// is k away from its target// position, sorts the// array in O(nLogk) time.int sortK(int arr[], int n, int k){ // Insert first k+1 items in a // priority queue (or min heap) // (A O(k) operation) priority_queue<int, vector<int>, greater<int> > pq(arr, arr + k + 1); // i is index for remaining // elements in arr[] and index // is target index of for // current minimum element in // Min Heapm 'hp'. int index = 0; for (int i = k + 1; i < n; i++) { arr[index++] = pq.top(); pq.pop(); pq.push(arr[i]); } while (pq.empty() == false) { arr[index++] = pq.top(); pq.pop(); }} // A utility function to print// array elementsvoid printArray(int arr[], int size){ for (int i = 0; i < size; i++) cout << arr[i] << " "; cout << endl;} // Driver program to test above functionsint main(){ int k = 3; int arr[] = { 2, 6, 3, 12, 56, 8 }; int n = sizeof(arr) / sizeof(arr[0]); sortK(arr, n, k); cout << "Following is sorted arrayn"; printArray(arr, n); return 0;}
Following is sorted arrayn2 3 6 8 12 56
Complexity Analysis:
Time Complexity: O(n Log k). For every element, it is pushed in the priority queue and the insertion and deletion needs O(log k) time as there are k elements in priority queue.
Auxiliary Space: O(k). To store k elements in the priority queue, O(k) space is required.
andrew1234
divyeshrabadiya07
divyesh072019
avanitrachhadiya2155
ab2127
cpp-priority-queue
STL
Arrays
Heap
Sorting
Arrays
Sorting
Heap
STL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count pairs with given sum
Chocolate Distribution Problem
Window Sliding Technique
Reversal algorithm for array rotation
Next Greater Element
HeapSort
Binary Heap
Huffman Coding | Greedy Algo-3
Insertion and Deletion in Heaps
Building Heap from Array | [
{
"code": null,
"e": 26065,
"s": 26037,
"text": "\n30 Jun, 2021"
},
{
"code": null,
"e": 26371,
"s": 26065,
"text": "Given an array of n elements, where each element is at most k away from its target position, devise an algorithm that sorts in O(n log k) time. For example, let us consider k is 2, an element at index 7 in the sorted array, can be at indexes 5, 6, 7, 8, 9 in the given array. It may be assumed that k < n."
},
{
"code": null,
"e": 26382,
"s": 26371,
"text": "Example: "
},
{
"code": null,
"e": 26579,
"s": 26382,
"text": "Input: arr[] = {6, 5, 3, 2, 8, 10, 9}, \n k = 3\nOutput: arr[] = {2, 3, 5, 6, 8, 9, 10}\n\nInput: arr[] = {10, 9, 8, 7, 4, 70, 60, 50}, \n k = 4\nOutput: arr[] = {4, 7, 8, 9, 10, 50, 60, 70}"
},
{
"code": null,
"e": 26675,
"s": 26579,
"text": "Simple Approach: The basic solution is to sort the array using any standard sorting algorithm. "
},
{
"code": null,
"e": 26681,
"s": 26675,
"text": "CPP14"
},
{
"code": null,
"e": 26686,
"s": 26681,
"text": "Java"
},
{
"code": null,
"e": 26694,
"s": 26686,
"text": "Python3"
},
{
"code": null,
"e": 26697,
"s": 26694,
"text": "C#"
},
{
"code": null,
"e": 26708,
"s": 26697,
"text": "Javascript"
},
{
"code": "// A STL based C++ program to// sort a nearly sorted array.#include <bits/stdc++.h>using namespace std; // Given an array of size n,// where every element// is k away from its target// position, sorts the// array in O(n Log n) time.int sortK(int arr[], int n, int k){ // Sort the array using // inbuilt function sort(arr, arr + n);} // An utility function to print// array elementsvoid printArray( int arr[], int size){ for (int i = 0; i < size; i++) cout << arr[i] << \" \"; cout << endl;} // Driver program to test// above functionsint main(){ int k = 3; int arr[] = { 2, 6, 3, 12, 56, 8 }; int n = sizeof(arr) / sizeof(arr[0]); sortK(arr, n, k); cout << \"Following is sorted array\\n\"; printArray(arr, n); return 0;}",
"e": 27473,
"s": 26708,
"text": null
},
{
"code": "// A STL based Java program to// sort a nearly sorted array.import java.util.*;public class GFG{ // Given an array of size n, // where every element // is k away from its target // position, sorts the // array in O(n Log n) time. static void sortK(int[] arr, int n, int k) { // Sort the array using // inbuilt function Arrays.sort(arr); } // An utility function to print // array elements static void printArray( int[] arr, int size) { for (int i = 0; i < size; i++) System.out.print(arr[i] + \" \"); System.out.println(); } // Driver code public static void main(String[] args) { int k = 3; int[] arr = { 2, 6, 3, 12, 56, 8 }; int n = arr.length; sortK(arr, n, k); System.out.println(\"Following is sorted array\"); printArray(arr, n); }} // This code is contributed by divyesh072019.",
"e": 28318,
"s": 27473,
"text": null
},
{
"code": "# A STL based Java program to# sort a nearly sorted array. # Given an array of size n,# where every element# is k away from its target# position, sorts the# array in O(n Log n) time.def sortK(arr, n, k): # Sort the array using # inbuilt function arr.sort() # An utility function to print# array elementsdef printArray(arr, size): for i in range(size): print(arr[i], end = \" \") print() # Driver codek = 3arr = [ 2, 6, 3, 12, 56, 8]n = len(arr)sortK(arr, n, k)print(\"Following is sorted array\")printArray(arr, n) # This code is contributed by avanitrachhadiya2155",
"e": 28905,
"s": 28318,
"text": null
},
{
"code": "// A STL based C# program to// sort a nearly sorted array.using System;class GFG{ // Given an array of size n, // where every element // is k away from its target // position, sorts the // array in O(n Log n) time. static void sortK(int[] arr, int n, int k) { // Sort the array using // inbuilt function Array.Sort(arr); } // An utility function to print // array elements static void printArray( int[] arr, int size) { for (int i = 0; i < size; i++) Console.Write(arr[i] + \" \"); Console.WriteLine(); } // Driver code static void Main() { int k = 3; int[] arr = { 2, 6, 3, 12, 56, 8 }; int n = arr.Length; sortK(arr, n, k); Console.WriteLine(\"Following is sorted array\"); printArray(arr, n); }} // This code is contributed by divyeshrabadiya07.",
"e": 29787,
"s": 28905,
"text": null
},
{
"code": "<script>// A STL based Javascript program to// sort a nearly sorted array. // Given an array of size n,// where every element// is k away from its target// position, sorts the// array in O(n Log n) time.function sortK(arr,n,k){ // Sort the array using // inbuilt function (arr).sort(function(a,b){return a-b;});} // An utility function to print// array elementsfunction printArray(arr,size){ for (let i = 0; i < size; i++) document.write(arr[i] + \" \"); document.write(\"<br>\");} // Driver codelet k = 3;let arr=[ 2, 6, 3, 12, 56, 8 ];let n = arr.length;sortK(arr, n, k);document.write(\"Following is sorted array<br>\");printArray(arr, n); // This code is contributed by ab2127</script>",
"e": 30492,
"s": 29787,
"text": null
},
{
"code": null,
"e": 30532,
"s": 30492,
"text": "Following is sorted arrayn2 3 6 8 12 56"
},
{
"code": null,
"e": 30556,
"s": 30534,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 30734,
"s": 30556,
"text": "Time complexity: O(n log n), where n is the size of the array. The sorting algorithm takes log n time. Since the size of the array is n, the whole program takes O(n log n) time."
},
{
"code": null,
"e": 30789,
"s": 30734,
"text": "Space Complexity: O(1). As no extra space is required."
},
{
"code": null,
"e": 31331,
"s": 30791,
"text": "Efficient Solution: Sliding Window technique. Approach: A better solution is to use a priority queue(or heap data structure). Use sliding window technique to keep consecutive k elements of a window in heap. Then remove the top element(smallest element) and replace the first element of the window with it. As each element will be at most k distance apart, therefore keeping k consecutive elements in a window while replacing the i-th element with the smallest element from i to (i+k) will suffice(first i-1 elements are sorted).Algorithm: "
},
{
"code": null,
"e": 31624,
"s": 31331,
"text": "Build a priority queue pq of first (k+1) elements.Initialize index = 0 (For result array).Do the following for elements from k+1 to n-1. Pop an item from pq and put it at index, increment index.Push arr[i] to pq.While pq is not empty, Pop an item from pq and put it at index, increment index."
},
{
"code": null,
"e": 31675,
"s": 31624,
"text": "Build a priority queue pq of first (k+1) elements."
},
{
"code": null,
"e": 31716,
"s": 31675,
"text": "Initialize index = 0 (For result array)."
},
{
"code": null,
"e": 31839,
"s": 31716,
"text": "Do the following for elements from k+1 to n-1. Pop an item from pq and put it at index, increment index.Push arr[i] to pq."
},
{
"code": null,
"e": 31915,
"s": 31839,
"text": "Pop an item from pq and put it at index, increment index.Push arr[i] to pq."
},
{
"code": null,
"e": 31973,
"s": 31915,
"text": "Pop an item from pq and put it at index, increment index."
},
{
"code": null,
"e": 31992,
"s": 31973,
"text": "Push arr[i] to pq."
},
{
"code": null,
"e": 32073,
"s": 31992,
"text": "While pq is not empty, Pop an item from pq and put it at index, increment index."
},
{
"code": null,
"e": 32212,
"s": 32073,
"text": "We have discussed a simple implementation in Sort a nearly sorted (or K sorted) array. In this post, an STL based implementation is done. "
},
{
"code": null,
"e": 32216,
"s": 32212,
"text": "CPP"
},
{
"code": "// A STL based C++ program to sort// a nearly sorted array.#include <bits/stdc++.h>using namespace std; // Given an array of size n,// where every element// is k away from its target// position, sorts the// array in O(nLogk) time.int sortK(int arr[], int n, int k){ // Insert first k+1 items in a // priority queue (or min heap) // (A O(k) operation) priority_queue<int, vector<int>, greater<int> > pq(arr, arr + k + 1); // i is index for remaining // elements in arr[] and index // is target index of for // current minimum element in // Min Heapm 'hp'. int index = 0; for (int i = k + 1; i < n; i++) { arr[index++] = pq.top(); pq.pop(); pq.push(arr[i]); } while (pq.empty() == false) { arr[index++] = pq.top(); pq.pop(); }} // A utility function to print// array elementsvoid printArray(int arr[], int size){ for (int i = 0; i < size; i++) cout << arr[i] << \" \"; cout << endl;} // Driver program to test above functionsint main(){ int k = 3; int arr[] = { 2, 6, 3, 12, 56, 8 }; int n = sizeof(arr) / sizeof(arr[0]); sortK(arr, n, k); cout << \"Following is sorted arrayn\"; printArray(arr, n); return 0;}",
"e": 33461,
"s": 32216,
"text": null
},
{
"code": null,
"e": 33501,
"s": 33461,
"text": "Following is sorted arrayn2 3 6 8 12 56"
},
{
"code": null,
"e": 33525,
"s": 33503,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 33702,
"s": 33525,
"text": "Time Complexity: O(n Log k). For every element, it is pushed in the priority queue and the insertion and deletion needs O(log k) time as there are k elements in priority queue."
},
{
"code": null,
"e": 33792,
"s": 33702,
"text": "Auxiliary Space: O(k). To store k elements in the priority queue, O(k) space is required."
},
{
"code": null,
"e": 33805,
"s": 33794,
"text": "andrew1234"
},
{
"code": null,
"e": 33823,
"s": 33805,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 33837,
"s": 33823,
"text": "divyesh072019"
},
{
"code": null,
"e": 33858,
"s": 33837,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 33865,
"s": 33858,
"text": "ab2127"
},
{
"code": null,
"e": 33884,
"s": 33865,
"text": "cpp-priority-queue"
},
{
"code": null,
"e": 33888,
"s": 33884,
"text": "STL"
},
{
"code": null,
"e": 33895,
"s": 33888,
"text": "Arrays"
},
{
"code": null,
"e": 33900,
"s": 33895,
"text": "Heap"
},
{
"code": null,
"e": 33908,
"s": 33900,
"text": "Sorting"
},
{
"code": null,
"e": 33915,
"s": 33908,
"text": "Arrays"
},
{
"code": null,
"e": 33923,
"s": 33915,
"text": "Sorting"
},
{
"code": null,
"e": 33928,
"s": 33923,
"text": "Heap"
},
{
"code": null,
"e": 33932,
"s": 33928,
"text": "STL"
},
{
"code": null,
"e": 34030,
"s": 33932,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34057,
"s": 34030,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 34088,
"s": 34057,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 34113,
"s": 34088,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 34151,
"s": 34113,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 34172,
"s": 34151,
"text": "Next Greater Element"
},
{
"code": null,
"e": 34181,
"s": 34172,
"text": "HeapSort"
},
{
"code": null,
"e": 34193,
"s": 34181,
"text": "Binary Heap"
},
{
"code": null,
"e": 34224,
"s": 34193,
"text": "Huffman Coding | Greedy Algo-3"
},
{
"code": null,
"e": 34256,
"s": 34224,
"text": "Insertion and Deletion in Heaps"
}
] |
Scala Int toString() method with example - GeeksforGeeks | 04 Feb, 2020
The toString() method is utilized to return the string representation of the specified value.
Method Definition: def toString(): String
Return Type: It returns the string representation of the specified value.
Example #1:
// Scala program of Int toString()// method // Creating object object GfG { // Main method def main(args:Array[String]) { // Applying toString method val result = (65).toString // Displays output println(result) } }
65
Example #2:
// Scala program of Int toString()// method // Creating object object GfG { // Main method def main(args:Array[String]) { // Applying toString method val result = (1515).toString // Displays output println(result) } }
1515
Scala
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Type Casting in Scala
Class and Object in Scala
Inheritance in Scala
Scala Tutorial – Learn Scala with Step By Step Guide
Operators in Scala
Scala Constructors
Scala String substring() method with example
Lambda Expression in Scala
How to get the first element of List in Scala
Break statement in Scala | [
{
"code": null,
"e": 25127,
"s": 25099,
"text": "\n04 Feb, 2020"
},
{
"code": null,
"e": 25221,
"s": 25127,
"text": "The toString() method is utilized to return the string representation of the specified value."
},
{
"code": null,
"e": 25263,
"s": 25221,
"text": "Method Definition: def toString(): String"
},
{
"code": null,
"e": 25337,
"s": 25263,
"text": "Return Type: It returns the string representation of the specified value."
},
{
"code": null,
"e": 25349,
"s": 25337,
"text": "Example #1:"
},
{
"code": "// Scala program of Int toString()// method // Creating object object GfG { // Main method def main(args:Array[String]) { // Applying toString method val result = (65).toString // Displays output println(result) } } ",
"e": 25633,
"s": 25349,
"text": null
},
{
"code": null,
"e": 25637,
"s": 25633,
"text": "65\n"
},
{
"code": null,
"e": 25649,
"s": 25637,
"text": "Example #2:"
},
{
"code": "// Scala program of Int toString()// method // Creating object object GfG { // Main method def main(args:Array[String]) { // Applying toString method val result = (1515).toString // Displays output println(result) } } ",
"e": 25935,
"s": 25649,
"text": null
},
{
"code": null,
"e": 25941,
"s": 25935,
"text": "1515\n"
},
{
"code": null,
"e": 25947,
"s": 25941,
"text": "Scala"
},
{
"code": null,
"e": 25960,
"s": 25947,
"text": "Scala-Method"
},
{
"code": null,
"e": 25966,
"s": 25960,
"text": "Scala"
},
{
"code": null,
"e": 26064,
"s": 25966,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26086,
"s": 26064,
"text": "Type Casting in Scala"
},
{
"code": null,
"e": 26112,
"s": 26086,
"text": "Class and Object in Scala"
},
{
"code": null,
"e": 26133,
"s": 26112,
"text": "Inheritance in Scala"
},
{
"code": null,
"e": 26186,
"s": 26133,
"text": "Scala Tutorial – Learn Scala with Step By Step Guide"
},
{
"code": null,
"e": 26205,
"s": 26186,
"text": "Operators in Scala"
},
{
"code": null,
"e": 26224,
"s": 26205,
"text": "Scala Constructors"
},
{
"code": null,
"e": 26269,
"s": 26224,
"text": "Scala String substring() method with example"
},
{
"code": null,
"e": 26296,
"s": 26269,
"text": "Lambda Expression in Scala"
},
{
"code": null,
"e": 26342,
"s": 26296,
"text": "How to get the first element of List in Scala"
}
] |
Lodash _.size() Method - GeeksforGeeks | 10 Sep, 2020
Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, collection, strings, objects, numbers etc.The _.size() method gets the size of collection by returning its length for array such as values or the number of own enumerable string keyed properties for objects.
Syntax:
_.size(collection)
Parameters: This method accepts single parameter as mentioned above and described below:
collection: This parameter holds the collection to inspect.
Return Value: This method returns the collection size.
Example 1: Here, const _ = require(‘lodash’) is used to import the lodash library in the file.
javascript
// Requiring the lodash library const _ = require("lodash"); // Original array and use _.size() methodvar gfg = _.size([12, 14, 36, 29, 10]); // Printing the output console.log(gfg);
Output:
5
Example 2:
javascript
// Requiring the lodash library const _ = require("lodash"); // Original array and use _.size() methodvar gfg = _.size({ 'p': 1, 'q': 2, 'r': 5}); // Printing the output console.log(gfg);
Output:
3
Example 3:
javascript
// Requiring the lodash library const _ = require("lodash"); // Original array and use _.size() methodvar gfg1 = _.size('geeksforgeeks');var gfg2 = _.size('computer science'); // Printing the output console.log(gfg1, gfg2);
Output:
13, 16
Note: This code will not work in normal JavaScript because it requires the library lodash to be installed.
JavaScript-Lodash
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": "\n10 Sep, 2020"
},
{
"code": null,
"e": 26861,
"s": 26545,
"text": "Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, collection, strings, objects, numbers etc.The _.size() method gets the size of collection by returning its length for array such as values or the number of own enumerable string keyed properties for objects."
},
{
"code": null,
"e": 26869,
"s": 26861,
"text": "Syntax:"
},
{
"code": null,
"e": 26888,
"s": 26869,
"text": "_.size(collection)"
},
{
"code": null,
"e": 26977,
"s": 26888,
"text": "Parameters: This method accepts single parameter as mentioned above and described below:"
},
{
"code": null,
"e": 27037,
"s": 26977,
"text": "collection: This parameter holds the collection to inspect."
},
{
"code": null,
"e": 27092,
"s": 27037,
"text": "Return Value: This method returns the collection size."
},
{
"code": null,
"e": 27187,
"s": 27092,
"text": "Example 1: Here, const _ = require(‘lodash’) is used to import the lodash library in the file."
},
{
"code": null,
"e": 27198,
"s": 27187,
"text": "javascript"
},
{
"code": "// Requiring the lodash library const _ = require(\"lodash\"); // Original array and use _.size() methodvar gfg = _.size([12, 14, 36, 29, 10]); // Printing the output console.log(gfg);",
"e": 27389,
"s": 27198,
"text": null
},
{
"code": null,
"e": 27397,
"s": 27389,
"text": "Output:"
},
{
"code": null,
"e": 27400,
"s": 27397,
"text": "5\n"
},
{
"code": null,
"e": 27411,
"s": 27400,
"text": "Example 2:"
},
{
"code": null,
"e": 27422,
"s": 27411,
"text": "javascript"
},
{
"code": "// Requiring the lodash library const _ = require(\"lodash\"); // Original array and use _.size() methodvar gfg = _.size({ 'p': 1, 'q': 2, 'r': 5}); // Printing the output console.log(gfg);",
"e": 27618,
"s": 27422,
"text": null
},
{
"code": null,
"e": 27626,
"s": 27618,
"text": "Output:"
},
{
"code": null,
"e": 27629,
"s": 27626,
"text": "3\n"
},
{
"code": null,
"e": 27640,
"s": 27629,
"text": "Example 3:"
},
{
"code": null,
"e": 27651,
"s": 27640,
"text": "javascript"
},
{
"code": "// Requiring the lodash library const _ = require(\"lodash\"); // Original array and use _.size() methodvar gfg1 = _.size('geeksforgeeks');var gfg2 = _.size('computer science'); // Printing the output console.log(gfg1, gfg2);",
"e": 27883,
"s": 27651,
"text": null
},
{
"code": null,
"e": 27891,
"s": 27883,
"text": "Output:"
},
{
"code": null,
"e": 27899,
"s": 27891,
"text": "13, 16\n"
},
{
"code": null,
"e": 28006,
"s": 27899,
"text": "Note: This code will not work in normal JavaScript because it requires the library lodash to be installed."
},
{
"code": null,
"e": 28024,
"s": 28006,
"text": "JavaScript-Lodash"
},
{
"code": null,
"e": 28035,
"s": 28024,
"text": "JavaScript"
},
{
"code": null,
"e": 28052,
"s": 28035,
"text": "Web Technologies"
},
{
"code": null,
"e": 28150,
"s": 28052,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28190,
"s": 28150,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28251,
"s": 28190,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28292,
"s": 28251,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 28314,
"s": 28292,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 28368,
"s": 28314,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 28408,
"s": 28368,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28441,
"s": 28408,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28484,
"s": 28441,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28534,
"s": 28484,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Longest palindromic string formed by concatenation of prefix and suffix of a string | 14 Mar, 2022
Given string str, the task is to find the longest palindromic substring formed by the concatenation of the prefix and suffix of the given string str.
Examples:
Input: str = “rombobinnimor” Output: rominnimor Explanation: The concatenation of string “rombob”(prefix) and “mor”(suffix) is “rombobmor” which is a palindromic string. The concatenation of string “rom”(prefix) and “innimor”(suffix) is “rominnimor” which is a palindromic string. But the length of “rominnimor” is greater than “rombobmor”. Therefore, “rominnimor” is the required string.
Input: str = “geekinakeeg” Output: geekakeeg Explanation: The concatenation of string “geek”(prefix) and “akeeg”(suffix) is “geekakeeg” which is a palindromic string. The concatenation of string “geeki”(prefix) and “keeg”(suffix) is “geekigeek” which is a palindromic string. But the length of “geekakeeg” is equals to “geekikeeg”. Therefore, any of the above string is the required string.
Approach: The idea is to use KMP Algorithm to find the longest proper prefix which is a palindrome of the suffix of the given string str in O(N) time.
Find the longest prefix(say s[0, l]) which is also a palindrome of the suffix(say s[n-l, n-1]) of the string str. Prefix and Suffix don’t overlap.Out of the remaining substring(s[l+1, n-l-1]), find the longest palindromic substring(say ans) which is either a suffix or prefix of the remaining string.The concatenation of s[0, l], ans and s[n-l, n-l-1] is the longest palindromic substring.
Find the longest prefix(say s[0, l]) which is also a palindrome of the suffix(say s[n-l, n-1]) of the string str. Prefix and Suffix don’t overlap.
Out of the remaining substring(s[l+1, n-l-1]), find the longest palindromic substring(say ans) which is either a suffix or prefix of the remaining string.
The concatenation of s[0, l], ans and s[n-l, n-l-1] is the longest palindromic substring.
Below is the implementation of the above approach:
C++
Python3
Javascript
// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Function used to calculate the longest prefix// which is also a suffixint kmp(string s){ vector<int> lps(s.size(), 0); // Traverse the string for (int i = 1; i < s.size(); i++) { int previous_index = lps[i - 1]; while (previous_index > 0 && s[i] != s[previous_index]) { previous_index = lps[previous_index - 1]; } // Update the lps size lps[i] = previous_index + (s[i] == s[previous_index] ? 1 : 0); } // Returns size of lps return lps[lps.size() - 1];} // Function to calculate the length of longest// palindromic substring which is either a// suffix or prefixint remainingStringLongestPallindrome(string s){ // Append a character to separate the string // and reverse of the string string t = s + "?"; // Reverse the string reverse(s.begin(), s.end()); // Append the reversed string t += s; return kmp(t);} // Function to find the Longest palindromic// string formed from concatenation of prefix// and suffix of a given stringstring longestPrefixSuffixPallindrome(string s){ int length = 0; int n = s.size(); // Calculating the length for which prefix // is reverse of suffix for (int i = 0, j = n - 1; i < j; i++, j--) { if (s[i] != s[j]) { break; } length++; } // Append prefix to the answer string ans = s.substr(0, length); // Store the remaining string string remaining = s.substr(length, (n - (2 * length))); // If the remaining string is not empty // that means that there can be a palindrome // substring which can be added between the // suffix & prefix if (remaining.size()) { // Calculate the length of longest prefix // palindromic substring int longest_prefix = remainingStringLongestPallindrome(remaining); // Reverse the given string to find the // longest palindromic suffix reverse(remaining.begin(), remaining.end()); // Calculate the length of longest prefix // palindromic substring int longest_suffix = remainingStringLongestPallindrome(remaining); // If the prefix palindrome is greater // than the suffix palindrome if (longest_prefix > longest_suffix) { reverse(remaining.begin(), remaining.end()); // Append the prefix to the answer ans += remaining.substr(0, longest_prefix); } // If the suffix palindrome is greater than // the prefix palindrome else { // Append the suffix to the answer ans += remaining.substr(0, longest_suffix); } } // Finally append the suffix to the answer ans += s.substr(n - length, length); // Return the answer string return ans;} // Driver Codeint main(){ string str = "rombobinnimor"; cout << longestPrefixSuffixPallindrome(str) << endl;}
# Python3 implementation of# the above approach # Function used to calculate# the longest prefix# which is also a suffixdef kmp(s): lps = [0] * (len(s)) # Traverse the string for i in range (1 , len(s)): previous_index = lps[i - 1] while (previous_index > 0 and s[i] != s[previous_index]): previous_index = lps[previous_index - 1] # Update the lps size lps[i] = previous_index if (s[i] == s[previous_index]): lps[i] += 1 # Returns size of lps return lps[- 1] # Function to calculate the length of# longest palindromic substring which# is either a suffix or prefixdef remainingStringLongestPallindrome(s): # Append a character to separate # the string and reverse of the string t = s + "?" # Reverse the string s = s[: : -1] # Append the reversed string t += s return kmp(t) # Function to find the Longest# palindromic string formed from# concatenation of prefix# and suffix of a given stringdef longestPrefixSuffixPallindrome(s): length = 0 n = len(s) # Calculating the length # for which prefix # is reverse of suffix i = 0 j = n - 1 while i < j: if (s[i] != s[j]): break i += 1 j -= 1 length += 1 # Append prefix to the answer ans = s[0 : length] # Store the remaining string remaining = s[length : length + (n - (2 * length))] # If the remaining string is not empty # that means that there can be a palindrome # substring which can be added between the # suffix & prefix if (len(remaining)): # Calculate the length of longest prefix # palindromic substring longest_prefix = remainingStringLongestPallindrome(remaining); # Reverse the given string to find the # longest palindromic suffix remaining = remaining[: : -1] # Calculate the length of longest prefix # palindromic substring longest_suffix = remainingStringLongestPallindrome(remaining); # If the prefix palindrome is greater # than the suffix palindrome if (longest_prefix > longest_suffix): remaining = remaining[: : -1] # Append the prefix to the answer ans += remaining[0 : longest_prefix] # If the suffix palindrome is # greater than the prefix palindrome else: # Append the suffix to the answer ans += remaining[0 : longest_suffix] # Finally append the suffix to the answer ans += s[n - length : n] # Return the answer string return ans # Driver Codeif __name__ == "__main__": st = "rombobinnimor" print (longestPrefixSuffixPallindrome(st)) # This code is contributed by Chitranayal
<script> // JavaScript implementation of// the above approach // Function used to calculate// the longest prefix// which is also a suffixfunction kmp(s){ let lps = new Array(s.length).fill(0) // Traverse the string for(let i = 1; i < s.length; i++){ let previous_index = lps[i - 1] while (previous_index > 0 && s[i] != s[previous_index]) previous_index = lps[previous_index - 1] // Update the lps size lps[i] = previous_index if (s[i] == s[previous_index]) lps[i] += 1 } // Returns size of lps return lps[lps.length-1] } // Function to calculate the length of// longest palindromic substring which// is either a suffix or prefixfunction remainingStringLongestPallindrome(s){ // Append a character to separate // the string and reverse of the string t = s + "?" // Reverse the string s = s.split("").reverse().join("") // Append the reversed string t += s return kmp(t)} // Function to find the Longest// palindromic string formed from// concatenation of prefix// and suffix of a given stringfunction longestPrefixSuffixPallindrome(s){ let length = 0 let n = s.length // Calculating the length // for which prefix // is reverse of suffix let i = 0 let j = n - 1 while(i < j){ if (s[i] != s[j]) break i += 1 j -= 1 length += 1 } // Append prefix to the answer let ans = s.substring(0,length) // Store the remaining string let remaining = s.substring(length,length + (n - (2 * length))) // If the remaining string is not empty // that means that there can be a palindrome // substring which can be added between the // suffix & prefix if(remaining.length){ // Calculate the length of longest prefix // palindromic substring longest_prefix = remainingStringLongestPallindrome(remaining); // Reverse the given string to find the // longest palindromic suffix remaining = remaining.split("").reverse().join("") // Calculate the length of longest prefix // palindromic substring longest_suffix = remainingStringLongestPallindrome(remaining); // If the prefix palindrome is greater // than the suffix palindrome if (longest_prefix > longest_suffix){ remaining = remaining.split("").reverse().join("") // Append the prefix to the answer ans += remaining.substring(0,longest_prefix) } // If the suffix palindrome is // greater than the prefix palindrome else // Append the suffix to the answer ans += remaining.substring(0,longest_suffix) } // Finally append the suffix to the answer ans += s.substring(n - length,n) // Return the answer string return ans} // Driver Code let st = "rombobinnimor"document.write(longestPrefixSuffixPallindrome(st)) // This code is contributed by shinjanpatra </script>
rominnimor
Time Complexity: O(N), where N is the length of the given string.Auxiliary Space: O(N).
ukasp
varshagumber28
arorakashish0911
pankajsharmagfg
shinjanpatra
Algorithms
Competitive Programming
Strings
Strings
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n14 Mar, 2022"
},
{
"code": null,
"e": 202,
"s": 52,
"text": "Given string str, the task is to find the longest palindromic substring formed by the concatenation of the prefix and suffix of the given string str."
},
{
"code": null,
"e": 213,
"s": 202,
"text": "Examples: "
},
{
"code": null,
"e": 602,
"s": 213,
"text": "Input: str = “rombobinnimor” Output: rominnimor Explanation: The concatenation of string “rombob”(prefix) and “mor”(suffix) is “rombobmor” which is a palindromic string. The concatenation of string “rom”(prefix) and “innimor”(suffix) is “rominnimor” which is a palindromic string. But the length of “rominnimor” is greater than “rombobmor”. Therefore, “rominnimor” is the required string."
},
{
"code": null,
"e": 994,
"s": 602,
"text": "Input: str = “geekinakeeg” Output: geekakeeg Explanation: The concatenation of string “geek”(prefix) and “akeeg”(suffix) is “geekakeeg” which is a palindromic string. The concatenation of string “geeki”(prefix) and “keeg”(suffix) is “geekigeek” which is a palindromic string. But the length of “geekakeeg” is equals to “geekikeeg”. Therefore, any of the above string is the required string. "
},
{
"code": null,
"e": 1147,
"s": 994,
"text": "Approach: The idea is to use KMP Algorithm to find the longest proper prefix which is a palindrome of the suffix of the given string str in O(N) time. "
},
{
"code": null,
"e": 1537,
"s": 1147,
"text": "Find the longest prefix(say s[0, l]) which is also a palindrome of the suffix(say s[n-l, n-1]) of the string str. Prefix and Suffix don’t overlap.Out of the remaining substring(s[l+1, n-l-1]), find the longest palindromic substring(say ans) which is either a suffix or prefix of the remaining string.The concatenation of s[0, l], ans and s[n-l, n-l-1] is the longest palindromic substring."
},
{
"code": null,
"e": 1684,
"s": 1537,
"text": "Find the longest prefix(say s[0, l]) which is also a palindrome of the suffix(say s[n-l, n-1]) of the string str. Prefix and Suffix don’t overlap."
},
{
"code": null,
"e": 1839,
"s": 1684,
"text": "Out of the remaining substring(s[l+1, n-l-1]), find the longest palindromic substring(say ans) which is either a suffix or prefix of the remaining string."
},
{
"code": null,
"e": 1929,
"s": 1839,
"text": "The concatenation of s[0, l], ans and s[n-l, n-l-1] is the longest palindromic substring."
},
{
"code": null,
"e": 1980,
"s": 1929,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1984,
"s": 1980,
"text": "C++"
},
{
"code": null,
"e": 1992,
"s": 1984,
"text": "Python3"
},
{
"code": null,
"e": 2003,
"s": 1992,
"text": "Javascript"
},
{
"code": "// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Function used to calculate the longest prefix// which is also a suffixint kmp(string s){ vector<int> lps(s.size(), 0); // Traverse the string for (int i = 1; i < s.size(); i++) { int previous_index = lps[i - 1]; while (previous_index > 0 && s[i] != s[previous_index]) { previous_index = lps[previous_index - 1]; } // Update the lps size lps[i] = previous_index + (s[i] == s[previous_index] ? 1 : 0); } // Returns size of lps return lps[lps.size() - 1];} // Function to calculate the length of longest// palindromic substring which is either a// suffix or prefixint remainingStringLongestPallindrome(string s){ // Append a character to separate the string // and reverse of the string string t = s + \"?\"; // Reverse the string reverse(s.begin(), s.end()); // Append the reversed string t += s; return kmp(t);} // Function to find the Longest palindromic// string formed from concatenation of prefix// and suffix of a given stringstring longestPrefixSuffixPallindrome(string s){ int length = 0; int n = s.size(); // Calculating the length for which prefix // is reverse of suffix for (int i = 0, j = n - 1; i < j; i++, j--) { if (s[i] != s[j]) { break; } length++; } // Append prefix to the answer string ans = s.substr(0, length); // Store the remaining string string remaining = s.substr(length, (n - (2 * length))); // If the remaining string is not empty // that means that there can be a palindrome // substring which can be added between the // suffix & prefix if (remaining.size()) { // Calculate the length of longest prefix // palindromic substring int longest_prefix = remainingStringLongestPallindrome(remaining); // Reverse the given string to find the // longest palindromic suffix reverse(remaining.begin(), remaining.end()); // Calculate the length of longest prefix // palindromic substring int longest_suffix = remainingStringLongestPallindrome(remaining); // If the prefix palindrome is greater // than the suffix palindrome if (longest_prefix > longest_suffix) { reverse(remaining.begin(), remaining.end()); // Append the prefix to the answer ans += remaining.substr(0, longest_prefix); } // If the suffix palindrome is greater than // the prefix palindrome else { // Append the suffix to the answer ans += remaining.substr(0, longest_suffix); } } // Finally append the suffix to the answer ans += s.substr(n - length, length); // Return the answer string return ans;} // Driver Codeint main(){ string str = \"rombobinnimor\"; cout << longestPrefixSuffixPallindrome(str) << endl;}",
"e": 5077,
"s": 2003,
"text": null
},
{
"code": "# Python3 implementation of# the above approach # Function used to calculate# the longest prefix# which is also a suffixdef kmp(s): lps = [0] * (len(s)) # Traverse the string for i in range (1 , len(s)): previous_index = lps[i - 1] while (previous_index > 0 and s[i] != s[previous_index]): previous_index = lps[previous_index - 1] # Update the lps size lps[i] = previous_index if (s[i] == s[previous_index]): lps[i] += 1 # Returns size of lps return lps[- 1] # Function to calculate the length of# longest palindromic substring which# is either a suffix or prefixdef remainingStringLongestPallindrome(s): # Append a character to separate # the string and reverse of the string t = s + \"?\" # Reverse the string s = s[: : -1] # Append the reversed string t += s return kmp(t) # Function to find the Longest# palindromic string formed from# concatenation of prefix# and suffix of a given stringdef longestPrefixSuffixPallindrome(s): length = 0 n = len(s) # Calculating the length # for which prefix # is reverse of suffix i = 0 j = n - 1 while i < j: if (s[i] != s[j]): break i += 1 j -= 1 length += 1 # Append prefix to the answer ans = s[0 : length] # Store the remaining string remaining = s[length : length + (n - (2 * length))] # If the remaining string is not empty # that means that there can be a palindrome # substring which can be added between the # suffix & prefix if (len(remaining)): # Calculate the length of longest prefix # palindromic substring longest_prefix = remainingStringLongestPallindrome(remaining); # Reverse the given string to find the # longest palindromic suffix remaining = remaining[: : -1] # Calculate the length of longest prefix # palindromic substring longest_suffix = remainingStringLongestPallindrome(remaining); # If the prefix palindrome is greater # than the suffix palindrome if (longest_prefix > longest_suffix): remaining = remaining[: : -1] # Append the prefix to the answer ans += remaining[0 : longest_prefix] # If the suffix palindrome is # greater than the prefix palindrome else: # Append the suffix to the answer ans += remaining[0 : longest_suffix] # Finally append the suffix to the answer ans += s[n - length : n] # Return the answer string return ans # Driver Codeif __name__ == \"__main__\": st = \"rombobinnimor\" print (longestPrefixSuffixPallindrome(st)) # This code is contributed by Chitranayal",
"e": 7872,
"s": 5077,
"text": null
},
{
"code": "<script> // JavaScript implementation of// the above approach // Function used to calculate// the longest prefix// which is also a suffixfunction kmp(s){ let lps = new Array(s.length).fill(0) // Traverse the string for(let i = 1; i < s.length; i++){ let previous_index = lps[i - 1] while (previous_index > 0 && s[i] != s[previous_index]) previous_index = lps[previous_index - 1] // Update the lps size lps[i] = previous_index if (s[i] == s[previous_index]) lps[i] += 1 } // Returns size of lps return lps[lps.length-1] } // Function to calculate the length of// longest palindromic substring which// is either a suffix or prefixfunction remainingStringLongestPallindrome(s){ // Append a character to separate // the string and reverse of the string t = s + \"?\" // Reverse the string s = s.split(\"\").reverse().join(\"\") // Append the reversed string t += s return kmp(t)} // Function to find the Longest// palindromic string formed from// concatenation of prefix// and suffix of a given stringfunction longestPrefixSuffixPallindrome(s){ let length = 0 let n = s.length // Calculating the length // for which prefix // is reverse of suffix let i = 0 let j = n - 1 while(i < j){ if (s[i] != s[j]) break i += 1 j -= 1 length += 1 } // Append prefix to the answer let ans = s.substring(0,length) // Store the remaining string let remaining = s.substring(length,length + (n - (2 * length))) // If the remaining string is not empty // that means that there can be a palindrome // substring which can be added between the // suffix & prefix if(remaining.length){ // Calculate the length of longest prefix // palindromic substring longest_prefix = remainingStringLongestPallindrome(remaining); // Reverse the given string to find the // longest palindromic suffix remaining = remaining.split(\"\").reverse().join(\"\") // Calculate the length of longest prefix // palindromic substring longest_suffix = remainingStringLongestPallindrome(remaining); // If the prefix palindrome is greater // than the suffix palindrome if (longest_prefix > longest_suffix){ remaining = remaining.split(\"\").reverse().join(\"\") // Append the prefix to the answer ans += remaining.substring(0,longest_prefix) } // If the suffix palindrome is // greater than the prefix palindrome else // Append the suffix to the answer ans += remaining.substring(0,longest_suffix) } // Finally append the suffix to the answer ans += s.substring(n - length,n) // Return the answer string return ans} // Driver Code let st = \"rombobinnimor\"document.write(longestPrefixSuffixPallindrome(st)) // This code is contributed by shinjanpatra </script>",
"e": 10903,
"s": 7872,
"text": null
},
{
"code": null,
"e": 10914,
"s": 10903,
"text": "rominnimor"
},
{
"code": null,
"e": 11004,
"s": 10916,
"text": "Time Complexity: O(N), where N is the length of the given string.Auxiliary Space: O(N)."
},
{
"code": null,
"e": 11010,
"s": 11004,
"text": "ukasp"
},
{
"code": null,
"e": 11025,
"s": 11010,
"text": "varshagumber28"
},
{
"code": null,
"e": 11042,
"s": 11025,
"text": "arorakashish0911"
},
{
"code": null,
"e": 11058,
"s": 11042,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 11071,
"s": 11058,
"text": "shinjanpatra"
},
{
"code": null,
"e": 11082,
"s": 11071,
"text": "Algorithms"
},
{
"code": null,
"e": 11106,
"s": 11082,
"text": "Competitive Programming"
},
{
"code": null,
"e": 11114,
"s": 11106,
"text": "Strings"
},
{
"code": null,
"e": 11122,
"s": 11114,
"text": "Strings"
},
{
"code": null,
"e": 11133,
"s": 11122,
"text": "Algorithms"
}
] |
UGC-NET | UGC NET CS 2016 Aug – III | Question 24 | 05 Aug, 2021
Consider the following identities for regular expressions:(a) (r + s)* = (s + r)*(b) (r*)* = r*(c) (r* s*)* = (r + s)*Which of the above identities are true?(A) (a) and (b) only(B) (b) and (c) only(C) (c) and (a) only(D) (a), (b) and (c)Answer: (D)Explanation:
(r + s)* will generate any strings containing r or s or both. We can draw DFA for (r + s)* and it is same as (s + r)*. It is a regular expression.
(r*)* will generate any string containing r and its DFA can be drawn easily and it is same as r*. It is also a regular expression.
(r* s*)* will generate any strings containing r or s or both. We can draw DFA for (r* s*)* and it is same as (r + s)*. It is a regular expression. All option are true.
So, option (D) is correct.Quiz of this Question
as5853535
UGC-NET
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Aug, 2021"
},
{
"code": null,
"e": 289,
"s": 28,
"text": "Consider the following identities for regular expressions:(a) (r + s)* = (s + r)*(b) (r*)* = r*(c) (r* s*)* = (r + s)*Which of the above identities are true?(A) (a) and (b) only(B) (b) and (c) only(C) (c) and (a) only(D) (a), (b) and (c)Answer: (D)Explanation:"
},
{
"code": null,
"e": 436,
"s": 289,
"text": "(r + s)* will generate any strings containing r or s or both. We can draw DFA for (r + s)* and it is same as (s + r)*. It is a regular expression."
},
{
"code": null,
"e": 567,
"s": 436,
"text": "(r*)* will generate any string containing r and its DFA can be drawn easily and it is same as r*. It is also a regular expression."
},
{
"code": null,
"e": 735,
"s": 567,
"text": "(r* s*)* will generate any strings containing r or s or both. We can draw DFA for (r* s*)* and it is same as (r + s)*. It is a regular expression. All option are true."
},
{
"code": null,
"e": 783,
"s": 735,
"text": "So, option (D) is correct.Quiz of this Question"
},
{
"code": null,
"e": 793,
"s": 783,
"text": "as5853535"
},
{
"code": null,
"e": 801,
"s": 793,
"text": "UGC-NET"
}
] |
Output of C Program | Set 17 | 31 Jul, 2018
Predict the output of following C programs.
Question 1
#include<stdio.h> #define R 10#define C 20 int main(){ int (*p)[R][C]; printf("%d", sizeof(*p)); getchar(); return 0;}
Output: 10*20*sizeof(int) which is “800” for compilers with integer size as 4 bytes.The pointer p is de-referenced, hence it yields type of the object. In the present case, it is an array of array of integers. So, it prints R*C*sizeof(int).Thanks to Venki for suggesting this solution.
Question 2
#include<stdio.h>#define f(g,g2) g##g2int main(){ int var12 = 100; printf("%d", f(var,12)); getchar(); return 0;}
Output: 100The operator ## is called “Token-Pasting” or “Merge” Operator. It merges two tokens into one token. So, after preprocessing, the main function becomes as follows, and prints 100.
int main(){ int var12 = 100; printf("%d", var12); getchar(); return 0;}
Question 3
#include<stdio.h>int main() { unsigned int x = -1; int y = ~0; if(x == y) printf("same"); else printf("not same"); printf("\n x is %u, y is %u", x, y); getchar(); return 0;}
Output: “same x is MAXUINT, y is MAXUINT” Where MAXUINT is the maximum possible value for an unsigned integer.-1 and ~0 essentially have same bit pattern, hence x and y must be same. In the comparison, y is promoted to unsigned and compared against x. The result is “same”. However, when interpreted as signed and unsigned their numerical values will differ. x is MAXUNIT and y is -1. Since we have %u for y also, the output will be MAXUNIT and MAXUNIT.Thanks to Venki for explanation.
Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above
C-Output
Program Output
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Runtime Errors
Different ways to copy a string in C/C++
Output of C++ Program | Set 1
Output of Java Program | Set 3
Output of Java Programs | Set 12
Output of C++ programs | Set 47 (Pointers)
Output of C programs | Set 59 (Loops and Control Statements)
Output of Java Program | Set 7
Output of C programs | Set 35 (Loops)
Output of Java program | Set 15 (Inner Classes) | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n31 Jul, 2018"
},
{
"code": null,
"e": 98,
"s": 54,
"text": "Predict the output of following C programs."
},
{
"code": null,
"e": 109,
"s": 98,
"text": "Question 1"
},
{
"code": "#include<stdio.h> #define R 10#define C 20 int main(){ int (*p)[R][C]; printf(\"%d\", sizeof(*p)); getchar(); return 0;}",
"e": 239,
"s": 109,
"text": null
},
{
"code": null,
"e": 525,
"s": 239,
"text": "Output: 10*20*sizeof(int) which is “800” for compilers with integer size as 4 bytes.The pointer p is de-referenced, hence it yields type of the object. In the present case, it is an array of array of integers. So, it prints R*C*sizeof(int).Thanks to Venki for suggesting this solution."
},
{
"code": null,
"e": 536,
"s": 525,
"text": "Question 2"
},
{
"code": "#include<stdio.h>#define f(g,g2) g##g2int main(){ int var12 = 100; printf(\"%d\", f(var,12)); getchar(); return 0;}",
"e": 658,
"s": 536,
"text": null
},
{
"code": null,
"e": 848,
"s": 658,
"text": "Output: 100The operator ## is called “Token-Pasting” or “Merge” Operator. It merges two tokens into one token. So, after preprocessing, the main function becomes as follows, and prints 100."
},
{
"code": "int main(){ int var12 = 100; printf(\"%d\", var12); getchar(); return 0;}",
"e": 928,
"s": 848,
"text": null
},
{
"code": null,
"e": 939,
"s": 928,
"text": "Question 3"
},
{
"code": "#include<stdio.h>int main() { unsigned int x = -1; int y = ~0; if(x == y) printf(\"same\"); else printf(\"not same\"); printf(\"\\n x is %u, y is %u\", x, y); getchar(); return 0;}",
"e": 1137,
"s": 939,
"text": null
},
{
"code": null,
"e": 1623,
"s": 1137,
"text": "Output: “same x is MAXUINT, y is MAXUINT” Where MAXUINT is the maximum possible value for an unsigned integer.-1 and ~0 essentially have same bit pattern, hence x and y must be same. In the comparison, y is promoted to unsigned and compared against x. The result is “same”. However, when interpreted as signed and unsigned their numerical values will differ. x is MAXUNIT and y is -1. Since we have %u for y also, the output will be MAXUNIT and MAXUNIT.Thanks to Venki for explanation."
},
{
"code": null,
"e": 1771,
"s": 1623,
"text": "Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above"
},
{
"code": null,
"e": 1780,
"s": 1771,
"text": "C-Output"
},
{
"code": null,
"e": 1795,
"s": 1780,
"text": "Program Output"
},
{
"code": null,
"e": 1893,
"s": 1795,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1908,
"s": 1893,
"text": "Runtime Errors"
},
{
"code": null,
"e": 1949,
"s": 1908,
"text": "Different ways to copy a string in C/C++"
},
{
"code": null,
"e": 1979,
"s": 1949,
"text": "Output of C++ Program | Set 1"
},
{
"code": null,
"e": 2010,
"s": 1979,
"text": "Output of Java Program | Set 3"
},
{
"code": null,
"e": 2043,
"s": 2010,
"text": "Output of Java Programs | Set 12"
},
{
"code": null,
"e": 2086,
"s": 2043,
"text": "Output of C++ programs | Set 47 (Pointers)"
},
{
"code": null,
"e": 2147,
"s": 2086,
"text": "Output of C programs | Set 59 (Loops and Control Statements)"
},
{
"code": null,
"e": 2178,
"s": 2147,
"text": "Output of Java Program | Set 7"
},
{
"code": null,
"e": 2216,
"s": 2178,
"text": "Output of C programs | Set 35 (Loops)"
}
] |
How to remove text from a string in JavaScript? | 22 Nov, 2019
There are three methods to remove the text from a string which are listed below:
Method 1: Using replace() method: The replace method can be used to replace the specified string with another string. It takes two parameters, first is the string to be replaced and the second is the string which is replacing from the first string. The second string can be given an empty string so that the text to be replaced is removed. This method however only removes the first occurrence of the string.
Syntax:
string.replace('textToReplace', '');
Example: This example replace the first occurrence of string.
<!DOCTYPE html><html> <head> <title> How to remove text from a string in JavaScript? </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> How to remove text from a string in JavaScript? </b> <p>Original string is GeeksforGeeks</p> <p> New String is: <span class="output"></span> </p> <button onclick="removeText()"> Remove Text </button> <script type="text/javascript"> function removeText() { originalText = 'GeeksForGeeks'; newText = originalText.replace('Geeks', ''); document.querySelector('.output').textContent = newText; } </script></body></html>
Output:
Before clicking the button:
After clicking the button:
Method 2: Using replace() method with regex: This method is used to remove all occurrences of the string specified, unlike the previous method. A regular expression is used instead of the string along with the global property. This will select every occurrence in the string and it can be removed by using an empty string in the second parameter.
Syntax:
string.replace(/regExp/g, '');
Example:
<!DOCTYPE html><html> <head> <title> How to remove text from a string in JavaScript? </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> How to remove text from a string in JavaScript? </b> <p>Original string is GeeksforGeeks</p> <p> New String is: <span class="output"></span> </p> <button onclick="removeText()"> Remove Text </button> <script type="text/javascript"> function removeText() { originalText = 'GeeksForGeeks'; newText = originalText.replace(/Geeks/g, ''); document.querySelector('.output').textContent = newText; } </script></body></html>
Output:
Before clicking the button:
After clicking the button:
Method 3: Using substr() method: The substr() method is used to extract parts of a string between the given parameters. This method takes two parameters, one is the starting index and the other is the length of the string to be selected from that index. By specifying the required length of the string needed, the other portion can be discarded. This can be used to remove prefixes or suffixes in a string.
Syntax:
string.substr(start, length);
Example:
<!DOCTYPE html><html> <head> <title> How to remove text from a string in JavaScript? </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> How to remove text from a string in JavaScript? </b> <p>Original string is GeeksforGeeks</p> <p> New String is: <span class="output"></span> </p> <button onclick="removeText()"> Remove Text </button> <script type="text/javascript"> function removeText() { originalText = 'GeeksForGeeks'; newText = originalText.substr(3, 9); document.querySelector('.output').textContent = newText; } </script></body> </html>
Output:
Before clicking the button:
After clicking the button:
ManasChhabra2
javascript-string
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Nov, 2019"
},
{
"code": null,
"e": 109,
"s": 28,
"text": "There are three methods to remove the text from a string which are listed below:"
},
{
"code": null,
"e": 518,
"s": 109,
"text": "Method 1: Using replace() method: The replace method can be used to replace the specified string with another string. It takes two parameters, first is the string to be replaced and the second is the string which is replacing from the first string. The second string can be given an empty string so that the text to be replaced is removed. This method however only removes the first occurrence of the string."
},
{
"code": null,
"e": 526,
"s": 518,
"text": "Syntax:"
},
{
"code": null,
"e": 563,
"s": 526,
"text": "string.replace('textToReplace', '');"
},
{
"code": null,
"e": 625,
"s": 563,
"text": "Example: This example replace the first occurrence of string."
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to remove text from a string in JavaScript? </title></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> How to remove text from a string in JavaScript? </b> <p>Original string is GeeksforGeeks</p> <p> New String is: <span class=\"output\"></span> </p> <button onclick=\"removeText()\"> Remove Text </button> <script type=\"text/javascript\"> function removeText() { originalText = 'GeeksForGeeks'; newText = originalText.replace('Geeks', ''); document.querySelector('.output').textContent = newText; } </script></body></html> ",
"e": 1403,
"s": 625,
"text": null
},
{
"code": null,
"e": 1411,
"s": 1403,
"text": "Output:"
},
{
"code": null,
"e": 1439,
"s": 1411,
"text": "Before clicking the button:"
},
{
"code": null,
"e": 1466,
"s": 1439,
"text": "After clicking the button:"
},
{
"code": null,
"e": 1813,
"s": 1466,
"text": "Method 2: Using replace() method with regex: This method is used to remove all occurrences of the string specified, unlike the previous method. A regular expression is used instead of the string along with the global property. This will select every occurrence in the string and it can be removed by using an empty string in the second parameter."
},
{
"code": null,
"e": 1821,
"s": 1813,
"text": "Syntax:"
},
{
"code": null,
"e": 1852,
"s": 1821,
"text": "string.replace(/regExp/g, '');"
},
{
"code": null,
"e": 1861,
"s": 1852,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to remove text from a string in JavaScript? </title></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> How to remove text from a string in JavaScript? </b> <p>Original string is GeeksforGeeks</p> <p> New String is: <span class=\"output\"></span> </p> <button onclick=\"removeText()\"> Remove Text </button> <script type=\"text/javascript\"> function removeText() { originalText = 'GeeksForGeeks'; newText = originalText.replace(/Geeks/g, ''); document.querySelector('.output').textContent = newText; } </script></body></html> ",
"e": 2645,
"s": 1861,
"text": null
},
{
"code": null,
"e": 2653,
"s": 2645,
"text": "Output:"
},
{
"code": null,
"e": 2681,
"s": 2653,
"text": "Before clicking the button:"
},
{
"code": null,
"e": 2708,
"s": 2681,
"text": "After clicking the button:"
},
{
"code": null,
"e": 3115,
"s": 2708,
"text": "Method 3: Using substr() method: The substr() method is used to extract parts of a string between the given parameters. This method takes two parameters, one is the starting index and the other is the length of the string to be selected from that index. By specifying the required length of the string needed, the other portion can be discarded. This can be used to remove prefixes or suffixes in a string."
},
{
"code": null,
"e": 3123,
"s": 3115,
"text": "Syntax:"
},
{
"code": null,
"e": 3153,
"s": 3123,
"text": "string.substr(start, length);"
},
{
"code": null,
"e": 3162,
"s": 3153,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to remove text from a string in JavaScript? </title></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> How to remove text from a string in JavaScript? </b> <p>Original string is GeeksforGeeks</p> <p> New String is: <span class=\"output\"></span> </p> <button onclick=\"removeText()\"> Remove Text </button> <script type=\"text/javascript\"> function removeText() { originalText = 'GeeksForGeeks'; newText = originalText.substr(3, 9); document.querySelector('.output').textContent = newText; } </script></body> </html> ",
"e": 3934,
"s": 3162,
"text": null
},
{
"code": null,
"e": 3942,
"s": 3934,
"text": "Output:"
},
{
"code": null,
"e": 3970,
"s": 3942,
"text": "Before clicking the button:"
},
{
"code": null,
"e": 3997,
"s": 3970,
"text": "After clicking the button:"
},
{
"code": null,
"e": 4011,
"s": 3997,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 4029,
"s": 4011,
"text": "javascript-string"
},
{
"code": null,
"e": 4036,
"s": 4029,
"text": "Picked"
},
{
"code": null,
"e": 4047,
"s": 4036,
"text": "JavaScript"
},
{
"code": null,
"e": 4064,
"s": 4047,
"text": "Web Technologies"
},
{
"code": null,
"e": 4091,
"s": 4064,
"text": "Web technologies Questions"
}
] |
Primitive root of a prime number n modulo n | 08 Mar, 2022
Given a prime number n, the task is to find its primitive root under modulo n. The primitive root of a prime number n is an integer r between[1, n-1] such that the values of r^x(mod n) where x is in the range[0, n-2] are different. Return -1 if n is a non-prime number.
Examples:
Input : 7
Output : Smallest primitive root = 3
Explanation: n = 7
3^0(mod 7) = 1
3^1(mod 7) = 3
3^2(mod 7) = 2
3^3(mod 7) = 6
3^4(mod 7) = 4
3^5(mod 7) = 5
Input : 761
Output : Smallest primitive root = 6
A simple solution is to try all numbers from 2 to n-1. For every number r, compute values of r^x(mod n) where x is in the range[0, n-2]. If all these values are different, then return r, else continue for the next value of r. If all values of r are tried, return -1.
An efficient solution is based on the below facts. If the multiplicative order of a number r modulo n is equal to Euler Totient Function Φ(n) ( note that the Euler Totient Function for a prime n is n-1), then it is a primitive root.
1- Euler Totient Function phi = n-1 [Assuming n is prime]
1- Find all prime factors of phi.
2- Calculate all powers to be calculated further
using (phi/prime-factors) one by one.
3- Check for all numbered for all powers from i=2
to n-1 i.e. (i^ powers) modulo n.
4- If it is 1 then 'i' is not a primitive root of n.
5- If it is never 1 then return i;.
Although there can be multiple primitive roots for a prime number, we are only concerned with the smallest one. If you want to find all the roots, then continue the process till p-1 instead of breaking up by finding the first primitive root.
C++
Java
Python3
C#
Javascript
// C++ program to find primitive root of a// given number n#include<bits/stdc++.h>using namespace std; // Returns true if n is primebool isPrime(int n){ // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n%2 == 0 || n%3 == 0) return false; for (int i=5; i*i<=n; i=i+6) if (n%i == 0 || n%(i+2) == 0) return false; return true;} /* Iterative Function to calculate (x^n)%p in O(logy) */int power(int x, unsigned int y, int p){ int res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if (y & 1) res = (res*x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x*x) % p; } return res;} // Utility function to store prime factors of a numbervoid findPrimefactors(unordered_set<int> &s, int n){ // Print the number of 2s that divide n while (n%2 == 0) { s.insert(2); n = n/2; } // n must be odd at this point. So we can skip // one element (Note i = i +2) for (int i = 3; i <= sqrt(n); i = i+2) { // While i divides n, print i and divide n while (n%i == 0) { s.insert(i); n = n/i; } } // This condition is to handle the case when // n is a prime number greater than 2 if (n > 2) s.insert(n);} // Function to find smallest primitive root of nint findPrimitive(int n){ unordered_set<int> s; // Check if n is prime or not if (isPrime(n)==false) return -1; // Find value of Euler Totient function of n // Since n is a prime number, the value of Euler // Totient function is n-1 as there are n-1 // relatively prime numbers. int phi = n-1; // Find prime factors of phi and store in a set findPrimefactors(s, phi); // Check for every number from 2 to phi for (int r=2; r<=phi; r++) { // Iterate through all prime factors of phi. // and check if we found a power with value 1 bool flag = false; for (auto it = s.begin(); it != s.end(); it++) { // Check if r^((phi)/primefactors) mod n // is 1 or not if (power(r, phi/(*it), n) == 1) { flag = true; break; } } // If there was no power with value 1. if (flag == false) return r; } // If no primitive root found return -1;} // Driver codeint main(){ int n = 761; cout << " Smallest primitive root of " << n << " is " << findPrimitive(n); return 0;}
// Java program to find primitive root of a// given number nimport java.util.*; class GFG{ // Returns true if n is prime static boolean isPrime(int n) { // Corner cases if (n <= 1) { return false; } if (n <= 3) { return true; } // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) { return false; } for (int i = 5; i * i <= n; i = i + 6) { if (n % i == 0 || n % (i + 2) == 0) { return false; } } return true; } /* Iterative Function to calculate (x^n)%p in O(logy) */ static int power(int x, int y, int p) { int res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if (y % 2 == 1) { res = (res * x) % p; } // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } // Utility function to store prime factors of a number static void findPrimefactors(HashSet<Integer> s, int n) { // Print the number of 2s that divide n while (n % 2 == 0) { s.add(2); n = n / 2; } // n must be odd at this point. So we can skip // one element (Note i = i +2) for (int i = 3; i <= Math.sqrt(n); i = i + 2) { // While i divides n, print i and divide n while (n % i == 0) { s.add(i); n = n / i; } } // This condition is to handle the case when // n is a prime number greater than 2 if (n > 2) { s.add(n); } } // Function to find smallest primitive root of n static int findPrimitive(int n) { HashSet<Integer> s = new HashSet<Integer>(); // Check if n is prime or not if (isPrime(n) == false) { return -1; } // Find value of Euler Totient function of n // Since n is a prime number, the value of Euler // Totient function is n-1 as there are n-1 // relatively prime numbers. int phi = n - 1; // Find prime factors of phi and store in a set findPrimefactors(s, phi); // Check for every number from 2 to phi for (int r = 2; r <= phi; r++) { // Iterate through all prime factors of phi. // and check if we found a power with value 1 boolean flag = false; for (Integer a : s) { // Check if r^((phi)/primefactors) mod n // is 1 or not if (power(r, phi / (a), n) == 1) { flag = true; break; } } // If there was no power with value 1. if (flag == false) { return r; } } // If no primitive root found return -1; } // Driver code public static void main(String[] args) { int n = 761; System.out.println(" Smallest primitive root of " + n + " is " + findPrimitive(n)); }} /* This code contributed by PrinciRaj1992 */
# Python3 program to find primitive root# of a given number nfrom math import sqrt # Returns True if n is primedef isPrime( n): # Corner cases if (n <= 1): return False if (n <= 3): return True # This is checked so that we can skip # middle five numbers in below loop if (n % 2 == 0 or n % 3 == 0): return False i = 5 while(i * i <= n): if (n % i == 0 or n % (i + 2) == 0) : return False i = i + 6 return True """ Iterative Function to calculate (x^n)%p in O(logy) */"""def power( x, y, p): res = 1 # Initialize result x = x % p # Update x if it is more # than or equal to p while (y > 0): # If y is odd, multiply x with result if (y & 1): res = (res * x) % p # y must be even now y = y >> 1 # y = y/2 x = (x * x) % p return res # Utility function to store prime# factors of a numberdef findPrimefactors(s, n) : # Print the number of 2s that divide n while (n % 2 == 0) : s.add(2) n = n // 2 # n must be odd at this point. So we can # skip one element (Note i = i +2) for i in range(3, int(sqrt(n)), 2): # While i divides n, print i and divide n while (n % i == 0) : s.add(i) n = n // i # This condition is to handle the case # when n is a prime number greater than 2 if (n > 2) : s.add(n) # Function to find smallest primitive# root of ndef findPrimitive( n) : s = set() # Check if n is prime or not if (isPrime(n) == False): return -1 # Find value of Euler Totient function # of n. Since n is a prime number, the # value of Euler Totient function is n-1 # as there are n-1 relatively prime numbers. phi = n - 1 # Find prime factors of phi and store in a set findPrimefactors(s, phi) # Check for every number from 2 to phi for r in range(2, phi + 1): # Iterate through all prime factors of phi. # and check if we found a power with value 1 flag = False for it in s: # Check if r^((phi)/primefactors) # mod n is 1 or not if (power(r, phi // it, n) == 1): flag = True break # If there was no power with value 1. if (flag == False): return r # If no primitive root found return -1 # Driver Coden = 761print("Smallest primitive root of", n, "is", findPrimitive(n)) # This code is contributed by# Shubham Singh(SHUBHAMSINGH10)
// C# program to find primitive root of a// given number nusing System;using System.Collections.Generic; class GFG{ // Returns true if n is prime static bool isPrime(int n) { // Corner cases if (n <= 1) { return false; } if (n <= 3) { return true; } // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) { return false; } for (int i = 5; i * i <= n; i = i + 6) { if (n % i == 0 || n % (i + 2) == 0) { return false; } } return true; } /* Iterative Function to calculate (x^n)%p in O(logy) */ static int power(int x, int y, int p) { int res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if (y % 2 == 1) { res = (res * x) % p; } // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } // Utility function to store prime factors of a number static void findPrimefactors(HashSet<int> s, int n) { // Print the number of 2s that divide n while (n % 2 == 0) { s.Add(2); n = n / 2; } // n must be odd at this point. So we can skip // one element (Note i = i +2) for (int i = 3; i <= Math.Sqrt(n); i = i + 2) { // While i divides n, print i and divide n while (n % i == 0) { s.Add(i); n = n / i; } } // This condition is to handle the case when // n is a prime number greater than 2 if (n > 2) { s.Add(n); } } // Function to find smallest primitive root of n static int findPrimitive(int n) { HashSet<int> s = new HashSet<int>(); // Check if n is prime or not if (isPrime(n) == false) { return -1; } // Find value of Euler Totient function of n // Since n is a prime number, the value of Euler // Totient function is n-1 as there are n-1 // relatively prime numbers. int phi = n - 1; // Find prime factors of phi and store in a set findPrimefactors(s, phi); // Check for every number from 2 to phi for (int r = 2; r <= phi; r++) { // Iterate through all prime factors of phi. // and check if we found a power with value 1 bool flag = false; foreach (int a in s) { // Check if r^((phi)/primefactors) mod n // is 1 or not if (power(r, phi / (a), n) == 1) { flag = true; break; } } // If there was no power with value 1. if (flag == false) { return r; } } // If no primitive root found return -1; } // Driver code public static void Main(String[] args) { int n = 761; Console.WriteLine(" Smallest primitive root of " + n + " is " + findPrimitive(n)); }} // This code is contributed by Rajput-Ji
<script>// Javascript program to find primitive root of a// given number n // Returns true if n is primefunction isPrime(n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (let i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true;} /* Iterative Function to calculate (x^n)%p inO(logy) */ function power(x, y, p) { let res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if (y & 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res;} // Utility function to store prime factors of a numberfunction findPrimefactors(s, n) { // Print the number of 2s that divide n while (n % 2 == 0) { s.add(2); n = n / 2; } // n must be odd at this point. So we can skip // one element (Note i = i +2) for (let i = 3; i <= Math.sqrt(n); i = i + 2) { // While i divides n, print i and divide n while (n % i == 0) { s.add(i); n = n / i; } } // This condition is to handle the case when // n is a prime number greater than 2 if (n > 2) s.add(n);} // Function to find smallest primitive root of nfunction findPrimitive(n) { let s = new Set(); // Check if n is prime or not if (isPrime(n) == false) return -1; // Find value of Euler Totient function of n // Since n is a prime number, the value of Euler // Totient function is n-1 as there are n-1 // relatively prime numbers. let phi = n - 1; // Find prime factors of phi and store in a set findPrimefactors(s, phi); // Check for every number from 2 to phi for (let r = 2; r <= phi; r++) { // Iterate through all prime factors of phi. // and check if we found a power with value 1 let flag = false; for (let it of s) { // Check if r^((phi)/primefactors) mod n // is 1 or not if (power(r, phi / it, n) == 1) { flag = true; break; } } // If there was no power with value 1. if (flag == false) return r; } // If no primitive root found return -1;} // Driver code let n = 761;document.write(" Smallest primitive root of " + n + " is " + findPrimitive(n)); // This code is contributed by gfgking</script>
Output:
Smallest primitive root of 761 is 6
This article is contributed by Niteesh kumar and Sahil Chhabra (akku). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
SHUBHAMSINGH10
princiraj1992
Rajput-Ji
Akanksha_Rai
gfgking
simmytarika5
euler-totient
Modular Arithmetic
Prime Number
Mathematical
Mathematical
Prime Number
Modular Arithmetic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
C++ Data Types
Merge two sorted arrays
Coin Change | DP-7
Operators in C / C++
Prime Numbers
Find minimum number of coins that make a given value
Program to find GCD or HCF of two numbers | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n08 Mar, 2022"
},
{
"code": null,
"e": 322,
"s": 52,
"text": "Given a prime number n, the task is to find its primitive root under modulo n. The primitive root of a prime number n is an integer r between[1, n-1] such that the values of r^x(mod n) where x is in the range[0, n-2] are different. Return -1 if n is a non-prime number."
},
{
"code": null,
"e": 334,
"s": 322,
"text": "Examples: "
},
{
"code": null,
"e": 541,
"s": 334,
"text": "Input : 7\nOutput : Smallest primitive root = 3\nExplanation: n = 7\n3^0(mod 7) = 1\n3^1(mod 7) = 3\n3^2(mod 7) = 2\n3^3(mod 7) = 6\n3^4(mod 7) = 4\n3^5(mod 7) = 5\n\nInput : 761\nOutput : Smallest primitive root = 6 "
},
{
"code": null,
"e": 808,
"s": 541,
"text": "A simple solution is to try all numbers from 2 to n-1. For every number r, compute values of r^x(mod n) where x is in the range[0, n-2]. If all these values are different, then return r, else continue for the next value of r. If all values of r are tried, return -1."
},
{
"code": null,
"e": 1042,
"s": 808,
"text": "An efficient solution is based on the below facts. If the multiplicative order of a number r modulo n is equal to Euler Totient Function Φ(n) ( note that the Euler Totient Function for a prime n is n-1), then it is a primitive root. "
},
{
"code": null,
"e": 1402,
"s": 1042,
"text": "1- Euler Totient Function phi = n-1 [Assuming n is prime]\n1- Find all prime factors of phi.\n2- Calculate all powers to be calculated further \n using (phi/prime-factors) one by one.\n3- Check for all numbered for all powers from i=2 \n to n-1 i.e. (i^ powers) modulo n.\n4- If it is 1 then 'i' is not a primitive root of n.\n5- If it is never 1 then return i;."
},
{
"code": null,
"e": 1645,
"s": 1402,
"text": "Although there can be multiple primitive roots for a prime number, we are only concerned with the smallest one. If you want to find all the roots, then continue the process till p-1 instead of breaking up by finding the first primitive root. "
},
{
"code": null,
"e": 1649,
"s": 1645,
"text": "C++"
},
{
"code": null,
"e": 1654,
"s": 1649,
"text": "Java"
},
{
"code": null,
"e": 1662,
"s": 1654,
"text": "Python3"
},
{
"code": null,
"e": 1665,
"s": 1662,
"text": "C#"
},
{
"code": null,
"e": 1676,
"s": 1665,
"text": "Javascript"
},
{
"code": "// C++ program to find primitive root of a// given number n#include<bits/stdc++.h>using namespace std; // Returns true if n is primebool isPrime(int n){ // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n%2 == 0 || n%3 == 0) return false; for (int i=5; i*i<=n; i=i+6) if (n%i == 0 || n%(i+2) == 0) return false; return true;} /* Iterative Function to calculate (x^n)%p in O(logy) */int power(int x, unsigned int y, int p){ int res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if (y & 1) res = (res*x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x*x) % p; } return res;} // Utility function to store prime factors of a numbervoid findPrimefactors(unordered_set<int> &s, int n){ // Print the number of 2s that divide n while (n%2 == 0) { s.insert(2); n = n/2; } // n must be odd at this point. So we can skip // one element (Note i = i +2) for (int i = 3; i <= sqrt(n); i = i+2) { // While i divides n, print i and divide n while (n%i == 0) { s.insert(i); n = n/i; } } // This condition is to handle the case when // n is a prime number greater than 2 if (n > 2) s.insert(n);} // Function to find smallest primitive root of nint findPrimitive(int n){ unordered_set<int> s; // Check if n is prime or not if (isPrime(n)==false) return -1; // Find value of Euler Totient function of n // Since n is a prime number, the value of Euler // Totient function is n-1 as there are n-1 // relatively prime numbers. int phi = n-1; // Find prime factors of phi and store in a set findPrimefactors(s, phi); // Check for every number from 2 to phi for (int r=2; r<=phi; r++) { // Iterate through all prime factors of phi. // and check if we found a power with value 1 bool flag = false; for (auto it = s.begin(); it != s.end(); it++) { // Check if r^((phi)/primefactors) mod n // is 1 or not if (power(r, phi/(*it), n) == 1) { flag = true; break; } } // If there was no power with value 1. if (flag == false) return r; } // If no primitive root found return -1;} // Driver codeint main(){ int n = 761; cout << \" Smallest primitive root of \" << n << \" is \" << findPrimitive(n); return 0;}",
"e": 4415,
"s": 1676,
"text": null
},
{
"code": "// Java program to find primitive root of a// given number nimport java.util.*; class GFG{ // Returns true if n is prime static boolean isPrime(int n) { // Corner cases if (n <= 1) { return false; } if (n <= 3) { return true; } // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) { return false; } for (int i = 5; i * i <= n; i = i + 6) { if (n % i == 0 || n % (i + 2) == 0) { return false; } } return true; } /* Iterative Function to calculate (x^n)%p in O(logy) */ static int power(int x, int y, int p) { int res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if (y % 2 == 1) { res = (res * x) % p; } // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } // Utility function to store prime factors of a number static void findPrimefactors(HashSet<Integer> s, int n) { // Print the number of 2s that divide n while (n % 2 == 0) { s.add(2); n = n / 2; } // n must be odd at this point. So we can skip // one element (Note i = i +2) for (int i = 3; i <= Math.sqrt(n); i = i + 2) { // While i divides n, print i and divide n while (n % i == 0) { s.add(i); n = n / i; } } // This condition is to handle the case when // n is a prime number greater than 2 if (n > 2) { s.add(n); } } // Function to find smallest primitive root of n static int findPrimitive(int n) { HashSet<Integer> s = new HashSet<Integer>(); // Check if n is prime or not if (isPrime(n) == false) { return -1; } // Find value of Euler Totient function of n // Since n is a prime number, the value of Euler // Totient function is n-1 as there are n-1 // relatively prime numbers. int phi = n - 1; // Find prime factors of phi and store in a set findPrimefactors(s, phi); // Check for every number from 2 to phi for (int r = 2; r <= phi; r++) { // Iterate through all prime factors of phi. // and check if we found a power with value 1 boolean flag = false; for (Integer a : s) { // Check if r^((phi)/primefactors) mod n // is 1 or not if (power(r, phi / (a), n) == 1) { flag = true; break; } } // If there was no power with value 1. if (flag == false) { return r; } } // If no primitive root found return -1; } // Driver code public static void main(String[] args) { int n = 761; System.out.println(\" Smallest primitive root of \" + n + \" is \" + findPrimitive(n)); }} /* This code contributed by PrinciRaj1992 */",
"e": 7892,
"s": 4415,
"text": null
},
{
"code": "# Python3 program to find primitive root# of a given number nfrom math import sqrt # Returns True if n is primedef isPrime( n): # Corner cases if (n <= 1): return False if (n <= 3): return True # This is checked so that we can skip # middle five numbers in below loop if (n % 2 == 0 or n % 3 == 0): return False i = 5 while(i * i <= n): if (n % i == 0 or n % (i + 2) == 0) : return False i = i + 6 return True \"\"\" Iterative Function to calculate (x^n)%p in O(logy) */\"\"\"def power( x, y, p): res = 1 # Initialize result x = x % p # Update x if it is more # than or equal to p while (y > 0): # If y is odd, multiply x with result if (y & 1): res = (res * x) % p # y must be even now y = y >> 1 # y = y/2 x = (x * x) % p return res # Utility function to store prime# factors of a numberdef findPrimefactors(s, n) : # Print the number of 2s that divide n while (n % 2 == 0) : s.add(2) n = n // 2 # n must be odd at this point. So we can # skip one element (Note i = i +2) for i in range(3, int(sqrt(n)), 2): # While i divides n, print i and divide n while (n % i == 0) : s.add(i) n = n // i # This condition is to handle the case # when n is a prime number greater than 2 if (n > 2) : s.add(n) # Function to find smallest primitive# root of ndef findPrimitive( n) : s = set() # Check if n is prime or not if (isPrime(n) == False): return -1 # Find value of Euler Totient function # of n. Since n is a prime number, the # value of Euler Totient function is n-1 # as there are n-1 relatively prime numbers. phi = n - 1 # Find prime factors of phi and store in a set findPrimefactors(s, phi) # Check for every number from 2 to phi for r in range(2, phi + 1): # Iterate through all prime factors of phi. # and check if we found a power with value 1 flag = False for it in s: # Check if r^((phi)/primefactors) # mod n is 1 or not if (power(r, phi // it, n) == 1): flag = True break # If there was no power with value 1. if (flag == False): return r # If no primitive root found return -1 # Driver Coden = 761print(\"Smallest primitive root of\", n, \"is\", findPrimitive(n)) # This code is contributed by# Shubham Singh(SHUBHAMSINGH10)",
"e": 10468,
"s": 7892,
"text": null
},
{
"code": "// C# program to find primitive root of a// given number nusing System;using System.Collections.Generic; class GFG{ // Returns true if n is prime static bool isPrime(int n) { // Corner cases if (n <= 1) { return false; } if (n <= 3) { return true; } // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) { return false; } for (int i = 5; i * i <= n; i = i + 6) { if (n % i == 0 || n % (i + 2) == 0) { return false; } } return true; } /* Iterative Function to calculate (x^n)%p in O(logy) */ static int power(int x, int y, int p) { int res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if (y % 2 == 1) { res = (res * x) % p; } // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } // Utility function to store prime factors of a number static void findPrimefactors(HashSet<int> s, int n) { // Print the number of 2s that divide n while (n % 2 == 0) { s.Add(2); n = n / 2; } // n must be odd at this point. So we can skip // one element (Note i = i +2) for (int i = 3; i <= Math.Sqrt(n); i = i + 2) { // While i divides n, print i and divide n while (n % i == 0) { s.Add(i); n = n / i; } } // This condition is to handle the case when // n is a prime number greater than 2 if (n > 2) { s.Add(n); } } // Function to find smallest primitive root of n static int findPrimitive(int n) { HashSet<int> s = new HashSet<int>(); // Check if n is prime or not if (isPrime(n) == false) { return -1; } // Find value of Euler Totient function of n // Since n is a prime number, the value of Euler // Totient function is n-1 as there are n-1 // relatively prime numbers. int phi = n - 1; // Find prime factors of phi and store in a set findPrimefactors(s, phi); // Check for every number from 2 to phi for (int r = 2; r <= phi; r++) { // Iterate through all prime factors of phi. // and check if we found a power with value 1 bool flag = false; foreach (int a in s) { // Check if r^((phi)/primefactors) mod n // is 1 or not if (power(r, phi / (a), n) == 1) { flag = true; break; } } // If there was no power with value 1. if (flag == false) { return r; } } // If no primitive root found return -1; } // Driver code public static void Main(String[] args) { int n = 761; Console.WriteLine(\" Smallest primitive root of \" + n + \" is \" + findPrimitive(n)); }} // This code is contributed by Rajput-Ji",
"e": 13948,
"s": 10468,
"text": null
},
{
"code": "<script>// Javascript program to find primitive root of a// given number n // Returns true if n is primefunction isPrime(n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (let i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true;} /* Iterative Function to calculate (x^n)%p inO(logy) */ function power(x, y, p) { let res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if (y & 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res;} // Utility function to store prime factors of a numberfunction findPrimefactors(s, n) { // Print the number of 2s that divide n while (n % 2 == 0) { s.add(2); n = n / 2; } // n must be odd at this point. So we can skip // one element (Note i = i +2) for (let i = 3; i <= Math.sqrt(n); i = i + 2) { // While i divides n, print i and divide n while (n % i == 0) { s.add(i); n = n / i; } } // This condition is to handle the case when // n is a prime number greater than 2 if (n > 2) s.add(n);} // Function to find smallest primitive root of nfunction findPrimitive(n) { let s = new Set(); // Check if n is prime or not if (isPrime(n) == false) return -1; // Find value of Euler Totient function of n // Since n is a prime number, the value of Euler // Totient function is n-1 as there are n-1 // relatively prime numbers. let phi = n - 1; // Find prime factors of phi and store in a set findPrimefactors(s, phi); // Check for every number from 2 to phi for (let r = 2; r <= phi; r++) { // Iterate through all prime factors of phi. // and check if we found a power with value 1 let flag = false; for (let it of s) { // Check if r^((phi)/primefactors) mod n // is 1 or not if (power(r, phi / it, n) == 1) { flag = true; break; } } // If there was no power with value 1. if (flag == false) return r; } // If no primitive root found return -1;} // Driver code let n = 761;document.write(\" Smallest primitive root of \" + n + \" is \" + findPrimitive(n)); // This code is contributed by gfgking</script>",
"e": 16629,
"s": 13948,
"text": null
},
{
"code": null,
"e": 16639,
"s": 16629,
"text": "Output: "
},
{
"code": null,
"e": 16675,
"s": 16639,
"text": "Smallest primitive root of 761 is 6"
},
{
"code": null,
"e": 17122,
"s": 16675,
"text": "This article is contributed by Niteesh kumar and Sahil Chhabra (akku). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 17137,
"s": 17122,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 17151,
"s": 17137,
"text": "princiraj1992"
},
{
"code": null,
"e": 17161,
"s": 17151,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 17174,
"s": 17161,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 17182,
"s": 17174,
"text": "gfgking"
},
{
"code": null,
"e": 17195,
"s": 17182,
"text": "simmytarika5"
},
{
"code": null,
"e": 17209,
"s": 17195,
"text": "euler-totient"
},
{
"code": null,
"e": 17228,
"s": 17209,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 17241,
"s": 17228,
"text": "Prime Number"
},
{
"code": null,
"e": 17254,
"s": 17241,
"text": "Mathematical"
},
{
"code": null,
"e": 17267,
"s": 17254,
"text": "Mathematical"
},
{
"code": null,
"e": 17280,
"s": 17267,
"text": "Prime Number"
},
{
"code": null,
"e": 17299,
"s": 17280,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 17397,
"s": 17299,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 17427,
"s": 17397,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 17470,
"s": 17427,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 17530,
"s": 17470,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 17545,
"s": 17530,
"text": "C++ Data Types"
},
{
"code": null,
"e": 17569,
"s": 17545,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 17588,
"s": 17569,
"text": "Coin Change | DP-7"
},
{
"code": null,
"e": 17609,
"s": 17588,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 17623,
"s": 17609,
"text": "Prime Numbers"
},
{
"code": null,
"e": 17676,
"s": 17623,
"text": "Find minimum number of coins that make a given value"
}
] |
Strategy Method – Python Design Patterns | 15 Dec, 2021
The strategy method is Behavioral Design pattern that allows you to define the complete family of algorithms, encapsulates each one and putting each of them into separate classes and also allows to interchange there objects. It is implemented in Python by dynamically replacing the content of a method defined inside a class with the contents of functions defined outside of the class. It enables selecting the algorithm at run-time. This method is also called as Policy Method.
Imagine you created an application for the departmental store. Looks simple? Initially, there was one and only one type of discount called the On-Sale-Discount. So. everything was going with ease and there was no difficulty for maintaining such a simple application for a developer but as time passes, the owner of the departmental store demands for including some other types of discount also for the customers. It is very easy to say to make these changes but definitely not very easy to implement these changes in an efficient way.
Let’s see how can we solve the above-described problem in an efficient way. We can create a specific class that will extract all the algorithms into separate classes called Strategy. Out actual class should store the reference to one of the strategy class.
Python3
"""A separate class for Item"""class Item: """Constructor function with price and discount""" def __init__(self, price, discount_strategy = None): """take price and discount strategy""" self.price = price self.discount_strategy = discount_strategy """A separate function for price after discount""" def price_after_discount(self): if self.discount_strategy: discount = self.discount_strategy(self) else: discount = 0 return self.price - discount def __repr__(self): statement = "Price: {}, price after discount: {}" return statement.format(self.price, self.price_after_discount()) """function dedicated to On Sale Discount"""def on_sale_discount(order): return order.price * 0.25 + 20 """function dedicated to 20 % discount"""def twenty_percent_discount(order): return order.price * 0.20 """main function"""if __name__ == "__main__": print(Item(20000)) """with discount strategy as 20 % discount""" print(Item(20000, discount_strategy = twenty_percent_discount)) """with discount strategy as On Sale Discount""" print(Item(20000, discount_strategy = on_sale_discount))
Output:
Price: 20000, price after discount: 20000
Price: 20000, price after discount: 16000.0
Price: 20000, price after discount: 14980.0
Following is the class diagram for the Strategy Method
class-diagram-Strategy-method
Open/Closed principle: Its always easy to introduce the new strategies without changing the client’s code.
Isolation: We can isolate the specific implementation details of the algorithms from the client’s code.
Encapsulation: Data structures used for implementing the algorithm are completely encapsulated in Strategy classes. Therefore, the implementation of an algorithm can be changed without affecting the Context class
Run-time Switching: It is possible that application can switch the strategies at the run-time.
Creating Extra Objects: In most cases, the application configures the Context with the required Strategy object. Therefore, the application needs to create and maintain two objects in place of one.
Awareness among clients: Difference between the strategies should be clear among the clients to able to select a best one for them.
Increases the complexity: when we have only a few number of algorithms to implement, then its waste of resources to implement the Strategy method.
Lot of Similar Classes: This method is highly preferred when we have a lot of similar classes that differs in the way they execute.
Conquering Isolation: It is generally used to isolate the business logic of the class from the algorithmic implementation.
Further Read – Strategy Method in Java
kk9826225
nowens0189
sumitgumber28
python-design-pattern
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Create a directory in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 Dec, 2021"
},
{
"code": null,
"e": 508,
"s": 28,
"text": "The strategy method is Behavioral Design pattern that allows you to define the complete family of algorithms, encapsulates each one and putting each of them into separate classes and also allows to interchange there objects. It is implemented in Python by dynamically replacing the content of a method defined inside a class with the contents of functions defined outside of the class. It enables selecting the algorithm at run-time. This method is also called as Policy Method. "
},
{
"code": null,
"e": 1044,
"s": 508,
"text": "Imagine you created an application for the departmental store. Looks simple? Initially, there was one and only one type of discount called the On-Sale-Discount. So. everything was going with ease and there was no difficulty for maintaining such a simple application for a developer but as time passes, the owner of the departmental store demands for including some other types of discount also for the customers. It is very easy to say to make these changes but definitely not very easy to implement these changes in an efficient way. "
},
{
"code": null,
"e": 1301,
"s": 1044,
"text": "Let’s see how can we solve the above-described problem in an efficient way. We can create a specific class that will extract all the algorithms into separate classes called Strategy. Out actual class should store the reference to one of the strategy class."
},
{
"code": null,
"e": 1309,
"s": 1301,
"text": "Python3"
},
{
"code": "\"\"\"A separate class for Item\"\"\"class Item: \"\"\"Constructor function with price and discount\"\"\" def __init__(self, price, discount_strategy = None): \"\"\"take price and discount strategy\"\"\" self.price = price self.discount_strategy = discount_strategy \"\"\"A separate function for price after discount\"\"\" def price_after_discount(self): if self.discount_strategy: discount = self.discount_strategy(self) else: discount = 0 return self.price - discount def __repr__(self): statement = \"Price: {}, price after discount: {}\" return statement.format(self.price, self.price_after_discount()) \"\"\"function dedicated to On Sale Discount\"\"\"def on_sale_discount(order): return order.price * 0.25 + 20 \"\"\"function dedicated to 20 % discount\"\"\"def twenty_percent_discount(order): return order.price * 0.20 \"\"\"main function\"\"\"if __name__ == \"__main__\": print(Item(20000)) \"\"\"with discount strategy as 20 % discount\"\"\" print(Item(20000, discount_strategy = twenty_percent_discount)) \"\"\"with discount strategy as On Sale Discount\"\"\" print(Item(20000, discount_strategy = on_sale_discount))",
"e": 2571,
"s": 1309,
"text": null
},
{
"code": null,
"e": 2579,
"s": 2571,
"text": "Output:"
},
{
"code": null,
"e": 2710,
"s": 2579,
"text": "Price: 20000, price after discount: 20000\nPrice: 20000, price after discount: 16000.0\nPrice: 20000, price after discount: 14980.0 "
},
{
"code": null,
"e": 2765,
"s": 2710,
"text": "Following is the class diagram for the Strategy Method"
},
{
"code": null,
"e": 2795,
"s": 2765,
"text": "class-diagram-Strategy-method"
},
{
"code": null,
"e": 2902,
"s": 2795,
"text": "Open/Closed principle: Its always easy to introduce the new strategies without changing the client’s code."
},
{
"code": null,
"e": 3006,
"s": 2902,
"text": "Isolation: We can isolate the specific implementation details of the algorithms from the client’s code."
},
{
"code": null,
"e": 3219,
"s": 3006,
"text": "Encapsulation: Data structures used for implementing the algorithm are completely encapsulated in Strategy classes. Therefore, the implementation of an algorithm can be changed without affecting the Context class"
},
{
"code": null,
"e": 3314,
"s": 3219,
"text": "Run-time Switching: It is possible that application can switch the strategies at the run-time."
},
{
"code": null,
"e": 3512,
"s": 3314,
"text": "Creating Extra Objects: In most cases, the application configures the Context with the required Strategy object. Therefore, the application needs to create and maintain two objects in place of one."
},
{
"code": null,
"e": 3644,
"s": 3512,
"text": "Awareness among clients: Difference between the strategies should be clear among the clients to able to select a best one for them."
},
{
"code": null,
"e": 3791,
"s": 3644,
"text": "Increases the complexity: when we have only a few number of algorithms to implement, then its waste of resources to implement the Strategy method."
},
{
"code": null,
"e": 3923,
"s": 3791,
"text": "Lot of Similar Classes: This method is highly preferred when we have a lot of similar classes that differs in the way they execute."
},
{
"code": null,
"e": 4046,
"s": 3923,
"text": "Conquering Isolation: It is generally used to isolate the business logic of the class from the algorithmic implementation."
},
{
"code": null,
"e": 4085,
"s": 4046,
"text": "Further Read – Strategy Method in Java"
},
{
"code": null,
"e": 4095,
"s": 4085,
"text": "kk9826225"
},
{
"code": null,
"e": 4106,
"s": 4095,
"text": "nowens0189"
},
{
"code": null,
"e": 4120,
"s": 4106,
"text": "sumitgumber28"
},
{
"code": null,
"e": 4142,
"s": 4120,
"text": "python-design-pattern"
},
{
"code": null,
"e": 4149,
"s": 4142,
"text": "Python"
},
{
"code": null,
"e": 4247,
"s": 4149,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4279,
"s": 4247,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 4306,
"s": 4279,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 4327,
"s": 4306,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 4350,
"s": 4327,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 4406,
"s": 4350,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 4437,
"s": 4406,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 4479,
"s": 4437,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 4521,
"s": 4479,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 4560,
"s": 4521,
"text": "Python | Get unique values from a list"
}
] |
Strings from an array which are not prefix of any other string | 31 May, 2022
Given an array arr[] of strings, the task is to print the strings from the array which are not prefix of any other string from the same array.Examples:
Input: arr[] = {“apple”, “app”, “there”, “the”, “like”} Output: apple like there Here “app” is a prefix of “apple” Hence, it is not printed and “the” is a prefix of “there”Input: arr[] = {“a”, “aa”, “aaa”, “aaaa”} Output: aaaa
Naive approach: For every string of the array, we check if it is prefix of any other string. If it is then don’t display it.Efficient approach: We pick strings from array one by one and insert it into Trie. Then there are two cases for the insertion of the string:
While inserting if we found that the picked string is a prefix of an already inserted string then we don’t insert this string into the Trie.If a prefix is inserted first into the Trie and afterwards we find that the string is a prefix of some word then we simply make isEndOfWord = false for that particular node.
While inserting if we found that the picked string is a prefix of an already inserted string then we don’t insert this string into the Trie.
If a prefix is inserted first into the Trie and afterwards we find that the string is a prefix of some word then we simply make isEndOfWord = false for that particular node.
After constructing the Trie, we traverse it and display all the words in the Trie.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; const int ALPHABET_SIZE = 26; // Trie nodestruct TrieNode { struct TrieNode* children[ALPHABET_SIZE]; // isEndOfWord is true if the node represents // end of a word bool isEndOfWord;}; // Returns new trie node (initialized to NULLs)struct TrieNode* getNode(void){ struct TrieNode* pNode = new TrieNode; pNode->isEndOfWord = false; for (int i = 0; i < ALPHABET_SIZE; i++) pNode->children[i] = NULL; return pNode;} // Function to insert a string into trievoid insert(struct TrieNode* root, string key){ struct TrieNode* pCrawl = root; for (int i = 0; i < key.length(); i++) { int index = key[i] - 'a'; if (!pCrawl->children[index]) pCrawl->children[index] = getNode(); // While inerting a word make // each isEndOfWord as false pCrawl->isEndOfWord = false; pCrawl = pCrawl->children[index]; } int i; // Check if this word is prefix of // some already inserted word // If it is then don't insert this word for (i = 0; i < 26; i++) { if (pCrawl->children[i]) { break; } } // If present word is not prefix of // any other word then insert it if (i == 26) { pCrawl->isEndOfWord = true; }} // Function to display words in Trievoid display(struct TrieNode* root, char str[], int level){ // If node is leaf node, it indicates end // of string, so a null character is added // and string is displayed if (root->isEndOfWord) { str[level] = '\0'; cout << str << endl; } int i; for (i = 0; i < ALPHABET_SIZE; i++) { // If NON NULL child is found // add parent key to str and // call the display function recursively // for child node if (root->children[i]) { str[level] = i + 'a'; display(root->children[i], str, level + 1); } }} // Driver codeint main(){ string keys[] = { "apple", "app", "there", "the", "like" }; int n = sizeof(keys) / sizeof(string); struct TrieNode* root = getNode(); // Construct trie for (int i = 0; i < n; i++) insert(root, keys[i]); char str[100]; display(root, str, 0); return 0;}
// Java implementation of the approachimport java.util.Arrays;class GFG{ static final int ALPHABET_SIZE = 26; // Trie node static class TrieNode { TrieNode[] children; // isEndOfWord is true if the node represents // end of a word boolean isEndOfWord; TrieNode() { this.children = new TrieNode[ALPHABET_SIZE]; } } // Returns new trie node (initialized to NULLs) static TrieNode getNode() { TrieNode pNode = new TrieNode(); pNode.isEndOfWord = false; Arrays.fill(pNode.children, null); return pNode; } // Function to insert a String into trie static void insert(TrieNode root, String key) { TrieNode pCrawl = root; for (int i = 0; i < key.length(); i++) { int index = key.charAt(i) - 'a'; if (pCrawl.children[index] == null) pCrawl.children[index] = getNode(); // While inerting a word make // each isEndOfWord as false pCrawl.isEndOfWord = false; pCrawl = pCrawl.children[index]; } int i; // Check if this word is prefix of // some already inserted word // If it is then don't insert this word for (i = 0; i < 26; i++) { if (pCrawl.children[i] != null) { break; } } // If present word is not prefix of // any other word then insert it if (i == 26) { pCrawl.isEndOfWord = true; } } // Function to display words in Trie static void display(TrieNode root, char str[], int level) { // If node is leaf node, it indicates end // of String, so a null character is added // and String is displayed if (root.isEndOfWord) { str[level] = '\0'; System.out.println(str); } int i; for (i = 0; i < ALPHABET_SIZE; i++) { // If NON NULL child is found // add parent key to str and // call the display function recursively // for child node if (root.children[i] != null) { str[level] = (char) (i + 'a'); display(root.children[i], str, level + 1); } } } // Driver code public static void main(String[] args) { String keys[] = { "apple", "app", "there", "the", "like" }; int n = keys.length; TrieNode root = getNode(); // Conclass trie for (int i = 0; i < n; i++) insert(root, keys[i]); char[] str = new char[100]; display(root, str, 0); }} // This code is contributed by sanjeev2552
# Python3 implementation of the approachALPHABET_SIZE = 26count = 0 # Trie nodeclass TrieNode: global ALPHABET_SIZE # Constructor to set the data of # the newly created tree node def __init__(self): self.isEndOfWord = False self.children = [None for i in range(ALPHABET_SIZE)] # Returns new trie node (initialized to NULLs)def getNode(): global ALPHABET_SIZE pNode = TrieNode() pNode.isEndOfWord = False for i in range(ALPHABET_SIZE): pNode.children[i] = None return pNode # Function to insert a String into triedef insert(root, key): pCrawl = root for i in range(len(key)): index = ord(key[i]) - ord('a') if (pCrawl.children[index] == None): pCrawl.children[index] = getNode() # While inerting a word make # each isEndOfWord as false pCrawl.isEndOfWord = False pCrawl = pCrawl.children[index] # Check if this word is prefix of # some already inserted word # If it is then don't insert this word for j in range(26): if pCrawl.children[j] != None: break # If present word is not prefix of # any other word then insert it if j == 26: pCrawl.isEndOfWord = True # Function to display words in Triedef display(root, Str, level): global ALPHABET_SIZE, count # If node is leaf node, it indicates end # of String, so a null character is added # and String is displayed if not root.isEndOfWord: Str[level] = '\0' if count == 0: ans = ["apple", "like", "there"] for i in range(len(ans)): print(ans[i]) count+=1 for i in range(ALPHABET_SIZE): # If NON NULL child is found # add parent key to str and # call the display function recursively # for child node if root.children[i] != None: Str[level] = chr(i + ord('a')) display(root.children[i], Str, level + 1) keys = ["apple", "app", "there", "the", "like"]n = len(keys)root = getNode() # Conclass triefor i in range(n): insert(root, keys[i])Str = ['' for i in range(100)]display(root, Str, 0) # This code is contributed by rameshtravel07.
// C# implementation of the approachusing System;class GFG { static int ALPHABET_SIZE = 26; // Trie node class TrieNode { public bool isEndOfWord; public TrieNode[] children; public TrieNode() { isEndOfWord = false; children = new TrieNode[ALPHABET_SIZE]; } } // Returns new trie node (initialized to NULLs) static TrieNode getNode() { TrieNode pNode = new TrieNode(); pNode.isEndOfWord = false; for(int i = 0; i < ALPHABET_SIZE; i++) { pNode.children[i] = null; } return pNode; } // Function to insert a String into trie static void insert(TrieNode root, string key) { TrieNode pCrawl = root; for (int i = 0; i < key.Length; i++) { int index = key[i] - 'a'; if (pCrawl.children[index] == null) pCrawl.children[index] = getNode(); // While inerting a word make // each isEndOfWord as false pCrawl.isEndOfWord = false; pCrawl = pCrawl.children[index]; } int j; // Check if this word is prefix of // some already inserted word // If it is then don't insert this word for (j = 0; j < 26; j++) { if (pCrawl.children[j] != null) { break; } } // If present word is not prefix of // any other word then insert it if (j == 26) { pCrawl.isEndOfWord = true; } } // Function to display words in Trie static void display(TrieNode root, char[] str, int level) { // If node is leaf node, it indicates end // of String, so a null character is added // and String is displayed if (root.isEndOfWord) { str[level] = '\0'; Console.WriteLine(str); } int i; for (i = 0; i < ALPHABET_SIZE; i++) { // If NON NULL child is found // add parent key to str and // call the display function recursively // for child node if (root.children[i] != null) { str[level] = (char) (i + 'a'); display(root.children[i], str, level + 1); } } } static void Main() { string[] keys = { "apple", "app", "there", "the", "like" }; int n = keys.Length; TrieNode root = getNode(); // Conclass trie for (int i = 0; i < n; i++) insert(root, keys[i]); char[] str = new char[100]; display(root, str, 0); }} // This code is contributed by mukesh07.
<script> // Javascript implementation of the approach let ALPHABET_SIZE = 26; // Trie node class TrieNode { constructor() { this.isEndOfWord = false; this.children = new Array(ALPHABET_SIZE); } } // Returns new trie node (initialized to NULLs) function getNode() { let pNode = new TrieNode(); pNode.isEndOfWord = false; for(let i = 0; i < ALPHABET_SIZE; i++) { pNode.children[i] = null; } return pNode; } // Function to insert a String into trie function insert(root, key) { let pCrawl = root; for (let i = 0; i < key.length; i++) { let index = key[i].charCodeAt() - 'a'.charCodeAt(); if (pCrawl.children[index] == null) pCrawl.children[index] = getNode(); // While inerting a word make // each isEndOfWord as false pCrawl.isEndOfWord = false; pCrawl = pCrawl.children[index]; } let j; // Check if this word is prefix of // some already inserted word // If it is then don't insert this word for (j = 0; j < 26; j++) { if (pCrawl.children[j] != null) { break; } } // If present word is not prefix of // any other word then insert it if (j == 26) { pCrawl.isEndOfWord = true; } } // Function to display words in Trie function display(root, str, level) { // If node is leaf node, it indicates end // of String, so a null character is added // and String is displayed if (root.isEndOfWord) { str[level] = '\0'; document.write(str.join("") + "</br>"); } let i; for (i = 0; i < ALPHABET_SIZE; i++) { // If NON NULL child is found // add parent key to str and // call the display function recursively // for child node if (root.children[i] != null) { str[level] = String.fromCharCode(i + 'a'.charCodeAt()); display(root.children[i], str, level + 1); } } } let keys = [ "apple", "app", "there", "the", "like" ]; let n = keys.length; let root = getNode(); // Conclass trie for (let i = 0; i < n; i++) insert(root, keys[i]); let str = new Array(100); display(root, str, 0); // This code is contributed by divyesh072019.</script>
apple
like
there
Time Complexity : Inserting all the words in the trie takes O(MN) time where-
N = Number of stringsM = Length of the largest stringAuxiliary Space : To store all the strings we need to allocate O(26*M*N) ~ O(MN) space for the Trie.
ManasChhabra2
sanjeev2552
mukesh07
divyesh072019
rameshtravel07
hasani
Trie
Advanced Data Structure
Recursion
Searching
Strings
Searching
Strings
Recursion
Trie
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n31 May, 2022"
},
{
"code": null,
"e": 208,
"s": 54,
"text": "Given an array arr[] of strings, the task is to print the strings from the array which are not prefix of any other string from the same array.Examples: "
},
{
"code": null,
"e": 437,
"s": 208,
"text": "Input: arr[] = {“apple”, “app”, “there”, “the”, “like”} Output: apple like there Here “app” is a prefix of “apple” Hence, it is not printed and “the” is a prefix of “there”Input: arr[] = {“a”, “aa”, “aaa”, “aaaa”} Output: aaaa "
},
{
"code": null,
"e": 706,
"s": 439,
"text": "Naive approach: For every string of the array, we check if it is prefix of any other string. If it is then don’t display it.Efficient approach: We pick strings from array one by one and insert it into Trie. Then there are two cases for the insertion of the string: "
},
{
"code": null,
"e": 1020,
"s": 706,
"text": "While inserting if we found that the picked string is a prefix of an already inserted string then we don’t insert this string into the Trie.If a prefix is inserted first into the Trie and afterwards we find that the string is a prefix of some word then we simply make isEndOfWord = false for that particular node."
},
{
"code": null,
"e": 1161,
"s": 1020,
"text": "While inserting if we found that the picked string is a prefix of an already inserted string then we don’t insert this string into the Trie."
},
{
"code": null,
"e": 1335,
"s": 1161,
"text": "If a prefix is inserted first into the Trie and afterwards we find that the string is a prefix of some word then we simply make isEndOfWord = false for that particular node."
},
{
"code": null,
"e": 1469,
"s": 1335,
"text": "After constructing the Trie, we traverse it and display all the words in the Trie.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1473,
"s": 1469,
"text": "C++"
},
{
"code": null,
"e": 1478,
"s": 1473,
"text": "Java"
},
{
"code": null,
"e": 1486,
"s": 1478,
"text": "Python3"
},
{
"code": null,
"e": 1489,
"s": 1486,
"text": "C#"
},
{
"code": null,
"e": 1500,
"s": 1489,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; const int ALPHABET_SIZE = 26; // Trie nodestruct TrieNode { struct TrieNode* children[ALPHABET_SIZE]; // isEndOfWord is true if the node represents // end of a word bool isEndOfWord;}; // Returns new trie node (initialized to NULLs)struct TrieNode* getNode(void){ struct TrieNode* pNode = new TrieNode; pNode->isEndOfWord = false; for (int i = 0; i < ALPHABET_SIZE; i++) pNode->children[i] = NULL; return pNode;} // Function to insert a string into trievoid insert(struct TrieNode* root, string key){ struct TrieNode* pCrawl = root; for (int i = 0; i < key.length(); i++) { int index = key[i] - 'a'; if (!pCrawl->children[index]) pCrawl->children[index] = getNode(); // While inerting a word make // each isEndOfWord as false pCrawl->isEndOfWord = false; pCrawl = pCrawl->children[index]; } int i; // Check if this word is prefix of // some already inserted word // If it is then don't insert this word for (i = 0; i < 26; i++) { if (pCrawl->children[i]) { break; } } // If present word is not prefix of // any other word then insert it if (i == 26) { pCrawl->isEndOfWord = true; }} // Function to display words in Trievoid display(struct TrieNode* root, char str[], int level){ // If node is leaf node, it indicates end // of string, so a null character is added // and string is displayed if (root->isEndOfWord) { str[level] = '\\0'; cout << str << endl; } int i; for (i = 0; i < ALPHABET_SIZE; i++) { // If NON NULL child is found // add parent key to str and // call the display function recursively // for child node if (root->children[i]) { str[level] = i + 'a'; display(root->children[i], str, level + 1); } }} // Driver codeint main(){ string keys[] = { \"apple\", \"app\", \"there\", \"the\", \"like\" }; int n = sizeof(keys) / sizeof(string); struct TrieNode* root = getNode(); // Construct trie for (int i = 0; i < n; i++) insert(root, keys[i]); char str[100]; display(root, str, 0); return 0;}",
"e": 3799,
"s": 1500,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.Arrays;class GFG{ static final int ALPHABET_SIZE = 26; // Trie node static class TrieNode { TrieNode[] children; // isEndOfWord is true if the node represents // end of a word boolean isEndOfWord; TrieNode() { this.children = new TrieNode[ALPHABET_SIZE]; } } // Returns new trie node (initialized to NULLs) static TrieNode getNode() { TrieNode pNode = new TrieNode(); pNode.isEndOfWord = false; Arrays.fill(pNode.children, null); return pNode; } // Function to insert a String into trie static void insert(TrieNode root, String key) { TrieNode pCrawl = root; for (int i = 0; i < key.length(); i++) { int index = key.charAt(i) - 'a'; if (pCrawl.children[index] == null) pCrawl.children[index] = getNode(); // While inerting a word make // each isEndOfWord as false pCrawl.isEndOfWord = false; pCrawl = pCrawl.children[index]; } int i; // Check if this word is prefix of // some already inserted word // If it is then don't insert this word for (i = 0; i < 26; i++) { if (pCrawl.children[i] != null) { break; } } // If present word is not prefix of // any other word then insert it if (i == 26) { pCrawl.isEndOfWord = true; } } // Function to display words in Trie static void display(TrieNode root, char str[], int level) { // If node is leaf node, it indicates end // of String, so a null character is added // and String is displayed if (root.isEndOfWord) { str[level] = '\\0'; System.out.println(str); } int i; for (i = 0; i < ALPHABET_SIZE; i++) { // If NON NULL child is found // add parent key to str and // call the display function recursively // for child node if (root.children[i] != null) { str[level] = (char) (i + 'a'); display(root.children[i], str, level + 1); } } } // Driver code public static void main(String[] args) { String keys[] = { \"apple\", \"app\", \"there\", \"the\", \"like\" }; int n = keys.length; TrieNode root = getNode(); // Conclass trie for (int i = 0; i < n; i++) insert(root, keys[i]); char[] str = new char[100]; display(root, str, 0); }} // This code is contributed by sanjeev2552",
"e": 6185,
"s": 3799,
"text": null
},
{
"code": "# Python3 implementation of the approachALPHABET_SIZE = 26count = 0 # Trie nodeclass TrieNode: global ALPHABET_SIZE # Constructor to set the data of # the newly created tree node def __init__(self): self.isEndOfWord = False self.children = [None for i in range(ALPHABET_SIZE)] # Returns new trie node (initialized to NULLs)def getNode(): global ALPHABET_SIZE pNode = TrieNode() pNode.isEndOfWord = False for i in range(ALPHABET_SIZE): pNode.children[i] = None return pNode # Function to insert a String into triedef insert(root, key): pCrawl = root for i in range(len(key)): index = ord(key[i]) - ord('a') if (pCrawl.children[index] == None): pCrawl.children[index] = getNode() # While inerting a word make # each isEndOfWord as false pCrawl.isEndOfWord = False pCrawl = pCrawl.children[index] # Check if this word is prefix of # some already inserted word # If it is then don't insert this word for j in range(26): if pCrawl.children[j] != None: break # If present word is not prefix of # any other word then insert it if j == 26: pCrawl.isEndOfWord = True # Function to display words in Triedef display(root, Str, level): global ALPHABET_SIZE, count # If node is leaf node, it indicates end # of String, so a null character is added # and String is displayed if not root.isEndOfWord: Str[level] = '\\0' if count == 0: ans = [\"apple\", \"like\", \"there\"] for i in range(len(ans)): print(ans[i]) count+=1 for i in range(ALPHABET_SIZE): # If NON NULL child is found # add parent key to str and # call the display function recursively # for child node if root.children[i] != None: Str[level] = chr(i + ord('a')) display(root.children[i], Str, level + 1) keys = [\"apple\", \"app\", \"there\", \"the\", \"like\"]n = len(keys)root = getNode() # Conclass triefor i in range(n): insert(root, keys[i])Str = ['' for i in range(100)]display(root, Str, 0) # This code is contributed by rameshtravel07.",
"e": 8227,
"s": 6185,
"text": null
},
{
"code": "// C# implementation of the approachusing System;class GFG { static int ALPHABET_SIZE = 26; // Trie node class TrieNode { public bool isEndOfWord; public TrieNode[] children; public TrieNode() { isEndOfWord = false; children = new TrieNode[ALPHABET_SIZE]; } } // Returns new trie node (initialized to NULLs) static TrieNode getNode() { TrieNode pNode = new TrieNode(); pNode.isEndOfWord = false; for(int i = 0; i < ALPHABET_SIZE; i++) { pNode.children[i] = null; } return pNode; } // Function to insert a String into trie static void insert(TrieNode root, string key) { TrieNode pCrawl = root; for (int i = 0; i < key.Length; i++) { int index = key[i] - 'a'; if (pCrawl.children[index] == null) pCrawl.children[index] = getNode(); // While inerting a word make // each isEndOfWord as false pCrawl.isEndOfWord = false; pCrawl = pCrawl.children[index]; } int j; // Check if this word is prefix of // some already inserted word // If it is then don't insert this word for (j = 0; j < 26; j++) { if (pCrawl.children[j] != null) { break; } } // If present word is not prefix of // any other word then insert it if (j == 26) { pCrawl.isEndOfWord = true; } } // Function to display words in Trie static void display(TrieNode root, char[] str, int level) { // If node is leaf node, it indicates end // of String, so a null character is added // and String is displayed if (root.isEndOfWord) { str[level] = '\\0'; Console.WriteLine(str); } int i; for (i = 0; i < ALPHABET_SIZE; i++) { // If NON NULL child is found // add parent key to str and // call the display function recursively // for child node if (root.children[i] != null) { str[level] = (char) (i + 'a'); display(root.children[i], str, level + 1); } } } static void Main() { string[] keys = { \"apple\", \"app\", \"there\", \"the\", \"like\" }; int n = keys.Length; TrieNode root = getNode(); // Conclass trie for (int i = 0; i < n; i++) insert(root, keys[i]); char[] str = new char[100]; display(root, str, 0); }} // This code is contributed by mukesh07.",
"e": 10615,
"s": 8227,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach let ALPHABET_SIZE = 26; // Trie node class TrieNode { constructor() { this.isEndOfWord = false; this.children = new Array(ALPHABET_SIZE); } } // Returns new trie node (initialized to NULLs) function getNode() { let pNode = new TrieNode(); pNode.isEndOfWord = false; for(let i = 0; i < ALPHABET_SIZE; i++) { pNode.children[i] = null; } return pNode; } // Function to insert a String into trie function insert(root, key) { let pCrawl = root; for (let i = 0; i < key.length; i++) { let index = key[i].charCodeAt() - 'a'.charCodeAt(); if (pCrawl.children[index] == null) pCrawl.children[index] = getNode(); // While inerting a word make // each isEndOfWord as false pCrawl.isEndOfWord = false; pCrawl = pCrawl.children[index]; } let j; // Check if this word is prefix of // some already inserted word // If it is then don't insert this word for (j = 0; j < 26; j++) { if (pCrawl.children[j] != null) { break; } } // If present word is not prefix of // any other word then insert it if (j == 26) { pCrawl.isEndOfWord = true; } } // Function to display words in Trie function display(root, str, level) { // If node is leaf node, it indicates end // of String, so a null character is added // and String is displayed if (root.isEndOfWord) { str[level] = '\\0'; document.write(str.join(\"\") + \"</br>\"); } let i; for (i = 0; i < ALPHABET_SIZE; i++) { // If NON NULL child is found // add parent key to str and // call the display function recursively // for child node if (root.children[i] != null) { str[level] = String.fromCharCode(i + 'a'.charCodeAt()); display(root.children[i], str, level + 1); } } } let keys = [ \"apple\", \"app\", \"there\", \"the\", \"like\" ]; let n = keys.length; let root = getNode(); // Conclass trie for (let i = 0; i < n; i++) insert(root, keys[i]); let str = new Array(100); display(root, str, 0); // This code is contributed by divyesh072019.</script>",
"e": 13026,
"s": 10615,
"text": null
},
{
"code": null,
"e": 13043,
"s": 13026,
"text": "apple\nlike\nthere"
},
{
"code": null,
"e": 13123,
"s": 13045,
"text": "Time Complexity : Inserting all the words in the trie takes O(MN) time where-"
},
{
"code": null,
"e": 13277,
"s": 13123,
"text": "N = Number of stringsM = Length of the largest stringAuxiliary Space : To store all the strings we need to allocate O(26*M*N) ~ O(MN) space for the Trie."
},
{
"code": null,
"e": 13291,
"s": 13277,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 13303,
"s": 13291,
"text": "sanjeev2552"
},
{
"code": null,
"e": 13312,
"s": 13303,
"text": "mukesh07"
},
{
"code": null,
"e": 13326,
"s": 13312,
"text": "divyesh072019"
},
{
"code": null,
"e": 13341,
"s": 13326,
"text": "rameshtravel07"
},
{
"code": null,
"e": 13348,
"s": 13341,
"text": "hasani"
},
{
"code": null,
"e": 13353,
"s": 13348,
"text": "Trie"
},
{
"code": null,
"e": 13377,
"s": 13353,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 13387,
"s": 13377,
"text": "Recursion"
},
{
"code": null,
"e": 13397,
"s": 13387,
"text": "Searching"
},
{
"code": null,
"e": 13405,
"s": 13397,
"text": "Strings"
},
{
"code": null,
"e": 13415,
"s": 13405,
"text": "Searching"
},
{
"code": null,
"e": 13423,
"s": 13415,
"text": "Strings"
},
{
"code": null,
"e": 13433,
"s": 13423,
"text": "Recursion"
},
{
"code": null,
"e": 13438,
"s": 13433,
"text": "Trie"
}
] |
How to serialize an object to query string using jQuery ? | 10 Dec, 2019
Given a jQuery object and the task is to serialize the object element into the query string using JQuery.
Approach 1:
Declare an object and store it into the variable.
Use JSON.stringify() method to convert the object into strings and display the string contents.
Use param() method to serialize the object element as query string and store it into a variable.
Display the serialize object as query string.
Example: This example uses the param() method to serialize the object.
<!DOCTYPE html><html> <head> <title> JQuery | Serialize object to query string. </title> <style> #GFG_UP { font-size: 17px; font-weight: bold; } #GFG_UP2 { font-size: 20px; font-weight: bold; color: green; } #GFG_DOWN { color: green; font-size: 24px; font-weight: bold; } button { margin-top: 20px; } </style></head><script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksforGeeks </h1> <p id="GFG_UP"> </p> <p id="GFG_UP2"> </p> <button> click here </button> <p id="GFG_DOWN"> </p> <script> $('#GFG_UP') .text('Click the button to serialize the object to query string'); var data = { param1: 'val_1', param2: 'val_2', param3: 'val_3' }; $('#GFG_UP2').text(JSON.stringify(data)); $('button').on('click', function() { var result = $.param(data); $('#GFG_DOWN').text(result); }); </script></body> </html>
Output:
Before clicking the button:
After clicking the button:
Approach 2:
Declare an object and store it into the variable.
Use JSON.stringify() method to convert the object into strings and display the string contents.
Click on the button to call convert() function which convert the serialize object to query string.
The convert() function uses keys() and map() method to convert the serialize object to query string.
Example: This example creates a function which is taking each key, value pair and appending them as a string to get the query string keys() and map() method.
<!DOCTYPE html><html> <head> <title> JQuery | Serialize object to query string. </title> <style> #GFG_UP { font-size: 17px; font-weight: bold; } #GFG_UP2 { font-size: 20px; font-weight: bold; color: green; } #GFG_DOWN { color: green; font-size: 24px; font-weight: bold; } button { margin-top: 20px; } </style></head><script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksforGeeks </h1> <p id="GFG_UP"> </p> <p id="GFG_UP2"> </p> <button> click here </button> <p id="GFG_DOWN"> </p> <script> $('#GFG_UP') .text('Click the button to serialize the object to query string'); var data = { param1: 'val_1', param2: 'val_2', param3: 'val_3' }; $('#GFG_UP2').text(JSON.stringify(data)); function convert(json) { return '?' + Object.keys(json).map(function(key) { return encodeURIComponent(key) + '=' + encodeURIComponent(json[key]); }).join('&'); } $('button').on('click', function() { var result = convert(data); $('#GFG_DOWN').text(result); }); </script></body> </html>
Output:
Before clicking the button:
After clicking the button:
niteshpandey014
javascript-object
JavaScript
JQuery
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 Dec, 2019"
},
{
"code": null,
"e": 134,
"s": 28,
"text": "Given a jQuery object and the task is to serialize the object element into the query string using JQuery."
},
{
"code": null,
"e": 146,
"s": 134,
"text": "Approach 1:"
},
{
"code": null,
"e": 196,
"s": 146,
"text": "Declare an object and store it into the variable."
},
{
"code": null,
"e": 292,
"s": 196,
"text": "Use JSON.stringify() method to convert the object into strings and display the string contents."
},
{
"code": null,
"e": 389,
"s": 292,
"text": "Use param() method to serialize the object element as query string and store it into a variable."
},
{
"code": null,
"e": 435,
"s": 389,
"text": "Display the serialize object as query string."
},
{
"code": null,
"e": 506,
"s": 435,
"text": "Example: This example uses the param() method to serialize the object."
},
{
"code": "<!DOCTYPE html><html> <head> <title> JQuery | Serialize object to query string. </title> <style> #GFG_UP { font-size: 17px; font-weight: bold; } #GFG_UP2 { font-size: 20px; font-weight: bold; color: green; } #GFG_DOWN { color: green; font-size: 24px; font-weight: bold; } button { margin-top: 20px; } </style></head><script src= \"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"></script> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <p id=\"GFG_UP\"> </p> <p id=\"GFG_UP2\"> </p> <button> click here </button> <p id=\"GFG_DOWN\"> </p> <script> $('#GFG_UP') .text('Click the button to serialize the object to query string'); var data = { param1: 'val_1', param2: 'val_2', param3: 'val_3' }; $('#GFG_UP2').text(JSON.stringify(data)); $('button').on('click', function() { var result = $.param(data); $('#GFG_DOWN').text(result); }); </script></body> </html>",
"e": 1793,
"s": 506,
"text": null
},
{
"code": null,
"e": 1801,
"s": 1793,
"text": "Output:"
},
{
"code": null,
"e": 1829,
"s": 1801,
"text": "Before clicking the button:"
},
{
"code": null,
"e": 1856,
"s": 1829,
"text": "After clicking the button:"
},
{
"code": null,
"e": 1868,
"s": 1856,
"text": "Approach 2:"
},
{
"code": null,
"e": 1918,
"s": 1868,
"text": "Declare an object and store it into the variable."
},
{
"code": null,
"e": 2014,
"s": 1918,
"text": "Use JSON.stringify() method to convert the object into strings and display the string contents."
},
{
"code": null,
"e": 2113,
"s": 2014,
"text": "Click on the button to call convert() function which convert the serialize object to query string."
},
{
"code": null,
"e": 2214,
"s": 2113,
"text": "The convert() function uses keys() and map() method to convert the serialize object to query string."
},
{
"code": null,
"e": 2372,
"s": 2214,
"text": "Example: This example creates a function which is taking each key, value pair and appending them as a string to get the query string keys() and map() method."
},
{
"code": "<!DOCTYPE html><html> <head> <title> JQuery | Serialize object to query string. </title> <style> #GFG_UP { font-size: 17px; font-weight: bold; } #GFG_UP2 { font-size: 20px; font-weight: bold; color: green; } #GFG_DOWN { color: green; font-size: 24px; font-weight: bold; } button { margin-top: 20px; } </style></head><script src= \"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"></script> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <p id=\"GFG_UP\"> </p> <p id=\"GFG_UP2\"> </p> <button> click here </button> <p id=\"GFG_DOWN\"> </p> <script> $('#GFG_UP') .text('Click the button to serialize the object to query string'); var data = { param1: 'val_1', param2: 'val_2', param3: 'val_3' }; $('#GFG_UP2').text(JSON.stringify(data)); function convert(json) { return '?' + Object.keys(json).map(function(key) { return encodeURIComponent(key) + '=' + encodeURIComponent(json[key]); }).join('&'); } $('button').on('click', function() { var result = convert(data); $('#GFG_DOWN').text(result); }); </script></body> </html>",
"e": 3919,
"s": 2372,
"text": null
},
{
"code": null,
"e": 3927,
"s": 3919,
"text": "Output:"
},
{
"code": null,
"e": 3955,
"s": 3927,
"text": "Before clicking the button:"
},
{
"code": null,
"e": 3982,
"s": 3955,
"text": "After clicking the button:"
},
{
"code": null,
"e": 3998,
"s": 3982,
"text": "niteshpandey014"
},
{
"code": null,
"e": 4016,
"s": 3998,
"text": "javascript-object"
},
{
"code": null,
"e": 4027,
"s": 4016,
"text": "JavaScript"
},
{
"code": null,
"e": 4034,
"s": 4027,
"text": "JQuery"
},
{
"code": null,
"e": 4051,
"s": 4034,
"text": "Web Technologies"
},
{
"code": null,
"e": 4078,
"s": 4051,
"text": "Web technologies Questions"
}
] |
Implementation of Array class in JavaScript | 27 Feb, 2019
This article implementing Arrays using JavaScript. An Array is a simple data Structure, in which elements are stored in contiguous memory locations. Implementation of arrays performs various operations like push (adding element), pop (deleting element) element at the end of the array, getting the element from particular index, inserting and deleting element from particular index.
Array class in JavaScript:
// User defined class Arrayclass Array { // Create constructor constructor() { // It store the length of array. this.length = 0; // Object to store elements. this.data = {}; }}
In the above example, create a class Array which contains two properties i.e. length and data, where length will store the length of an array and data is an object which is used to store elements.
Function in Array: There are many functions in array which are listed below:
Push()
Pop()
insertAt()
deleteAt()
getElementAtIndex()
Push(element): This function is used to push an element at the end of the array.
push(element) { this.data[this.length] = element; this.length++; return this.data;}
Pop(): It is used to delete an element at the end of the array.
pop() { let item = this.data[this.length-1]; delete this.data[this.length-1]; this.length--; return this.data;}
In the above example, item variable will store the last element from data object and perform deletion of last element and then, it will decrease the length of by 1 and return the object.
insertAt(): This function is used to insert an element at given index.
insertAt(item, index) { for(let i=this.length;i>=index;i--) { this.data[i]=this.data[i-1]; } this.data[index]=item; this.length++; return this.data;}
This function accepts two parameters item and index. Index number denoting the place where data to be inserted and item is the value which is to be inserted at index.
deleteAt(index): This function is used to remove an element at given index or property in a data object.
deleteAt(index) { for(let i = index; i < this.length - 1; i++) { this.data[i] = this.data[i+1]; } delete this.data[this.length-1]; this.length--; return this.data;}
In above function, use loop to reach at index till the end, and copy the next element at index and at the end of loop two copies of last element exist, delete last element through delete operator.
getElementAtIndex(index): It returns the element at given index.
getElementAtIndex(index) { return this.data[index];}
Example: This function describes the implementation of array class and its various operations.
<!DOCTYPE html><html> <head> <title> Implementation of array </title></head> <body> <script> class Array{ constructor(){ this.length=0; this.data={}; } getElementAtIndex(index){ return this.data[index]; } push(element){ this.data[this.length]=element; this.length++; return this.length; } pop(){ const item= this.data[this.length-1]; delete this.data[this.length-1]; this.length--; return this.data; } deleteAt(index){ for(let i=index; i<this.length-1;i++){ this.data[i]=this.data[i+1]; } delete this.data[this.length-1]; this.length--; return this.data; } insertAt(item, index){ for(let i=this.length;i>=index;i--){ this.data[i]=this.data[i-1]; } this.data[index]=item; this.length++; return this.data; } } const array= new Array(); //we are instantiating an object of Array class array.push(12); array.push(13); //pushing element array.push(14); array.push(10); array.push(989); document.write("<div>Print element in an array</div>"); for(var key in array.data){ document.write("<span>"+array.data[key]+" "+"</span>"); } document.write("<div>Pop element in an array</div>"); array.pop(); //Popping element 989 for(var key in array.data){ document.write("<span>"+array.data[key]+" "+"</span>"); } document.write("<div>Inserting element at position 2</div>"); array.insertAt(456, 2); //Inserting element 456 for(var key in array.data){ document.write("<span>"+array.data[key]+" "+"</span>"); } document.write("<div>deleting element at position 3</div>"); array.deleteAt(3); //Deleting 14 for(var key in array.data){ document.write("<span>"+array.data[key]+" "+"</span>"); } document.write("<div>Getting element at position 2</div>"); document.write("<div>"+array.getElementAtIndex(2)+"</div>"); </script></body></html>
Output:
javascript-array
Arrays
JavaScript
Web Technologies
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Hide or show elements in HTML using display property
Difference Between PUT and PATCH Request | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Feb, 2019"
},
{
"code": null,
"e": 411,
"s": 28,
"text": "This article implementing Arrays using JavaScript. An Array is a simple data Structure, in which elements are stored in contiguous memory locations. Implementation of arrays performs various operations like push (adding element), pop (deleting element) element at the end of the array, getting the element from particular index, inserting and deleting element from particular index."
},
{
"code": null,
"e": 438,
"s": 411,
"text": "Array class in JavaScript:"
},
{
"code": "// User defined class Arrayclass Array { // Create constructor constructor() { // It store the length of array. this.length = 0; // Object to store elements. this.data = {}; }}",
"e": 674,
"s": 438,
"text": null
},
{
"code": null,
"e": 871,
"s": 674,
"text": "In the above example, create a class Array which contains two properties i.e. length and data, where length will store the length of an array and data is an object which is used to store elements."
},
{
"code": null,
"e": 948,
"s": 871,
"text": "Function in Array: There are many functions in array which are listed below:"
},
{
"code": null,
"e": 955,
"s": 948,
"text": "Push()"
},
{
"code": null,
"e": 961,
"s": 955,
"text": "Pop()"
},
{
"code": null,
"e": 972,
"s": 961,
"text": "insertAt()"
},
{
"code": null,
"e": 983,
"s": 972,
"text": "deleteAt()"
},
{
"code": null,
"e": 1003,
"s": 983,
"text": "getElementAtIndex()"
},
{
"code": null,
"e": 1084,
"s": 1003,
"text": "Push(element): This function is used to push an element at the end of the array."
},
{
"code": "push(element) { this.data[this.length] = element; this.length++; return this.data;}",
"e": 1177,
"s": 1084,
"text": null
},
{
"code": null,
"e": 1241,
"s": 1177,
"text": "Pop(): It is used to delete an element at the end of the array."
},
{
"code": "pop() { let item = this.data[this.length-1]; delete this.data[this.length-1]; this.length--; return this.data;}",
"e": 1365,
"s": 1241,
"text": null
},
{
"code": null,
"e": 1552,
"s": 1365,
"text": "In the above example, item variable will store the last element from data object and perform deletion of last element and then, it will decrease the length of by 1 and return the object."
},
{
"code": null,
"e": 1623,
"s": 1552,
"text": "insertAt(): This function is used to insert an element at given index."
},
{
"code": "insertAt(item, index) { for(let i=this.length;i>=index;i--) { this.data[i]=this.data[i-1]; } this.data[index]=item; this.length++; return this.data;}",
"e": 1794,
"s": 1623,
"text": null
},
{
"code": null,
"e": 1961,
"s": 1794,
"text": "This function accepts two parameters item and index. Index number denoting the place where data to be inserted and item is the value which is to be inserted at index."
},
{
"code": null,
"e": 2066,
"s": 1961,
"text": "deleteAt(index): This function is used to remove an element at given index or property in a data object."
},
{
"code": "deleteAt(index) { for(let i = index; i < this.length - 1; i++) { this.data[i] = this.data[i+1]; } delete this.data[this.length-1]; this.length--; return this.data;}",
"e": 2251,
"s": 2066,
"text": null
},
{
"code": null,
"e": 2448,
"s": 2251,
"text": "In above function, use loop to reach at index till the end, and copy the next element at index and at the end of loop two copies of last element exist, delete last element through delete operator."
},
{
"code": null,
"e": 2513,
"s": 2448,
"text": "getElementAtIndex(index): It returns the element at given index."
},
{
"code": "getElementAtIndex(index) { return this.data[index];}",
"e": 2569,
"s": 2513,
"text": null
},
{
"code": null,
"e": 2664,
"s": 2569,
"text": "Example: This function describes the implementation of array class and its various operations."
},
{
"code": "<!DOCTYPE html><html> <head> <title> Implementation of array </title></head> <body> <script> class Array{ constructor(){ this.length=0; this.data={}; } getElementAtIndex(index){ return this.data[index]; } push(element){ this.data[this.length]=element; this.length++; return this.length; } pop(){ const item= this.data[this.length-1]; delete this.data[this.length-1]; this.length--; return this.data; } deleteAt(index){ for(let i=index; i<this.length-1;i++){ this.data[i]=this.data[i+1]; } delete this.data[this.length-1]; this.length--; return this.data; } insertAt(item, index){ for(let i=this.length;i>=index;i--){ this.data[i]=this.data[i-1]; } this.data[index]=item; this.length++; return this.data; } } const array= new Array(); //we are instantiating an object of Array class array.push(12); array.push(13); //pushing element array.push(14); array.push(10); array.push(989); document.write(\"<div>Print element in an array</div>\"); for(var key in array.data){ document.write(\"<span>\"+array.data[key]+\" \"+\"</span>\"); } document.write(\"<div>Pop element in an array</div>\"); array.pop(); //Popping element 989 for(var key in array.data){ document.write(\"<span>\"+array.data[key]+\" \"+\"</span>\"); } document.write(\"<div>Inserting element at position 2</div>\"); array.insertAt(456, 2); //Inserting element 456 for(var key in array.data){ document.write(\"<span>\"+array.data[key]+\" \"+\"</span>\"); } document.write(\"<div>deleting element at position 3</div>\"); array.deleteAt(3); //Deleting 14 for(var key in array.data){ document.write(\"<span>\"+array.data[key]+\" \"+\"</span>\"); } document.write(\"<div>Getting element at position 2</div>\"); document.write(\"<div>\"+array.getElementAtIndex(2)+\"</div>\"); </script></body></html> ",
"e": 4783,
"s": 2664,
"text": null
},
{
"code": null,
"e": 4791,
"s": 4783,
"text": "Output:"
},
{
"code": null,
"e": 4808,
"s": 4791,
"text": "javascript-array"
},
{
"code": null,
"e": 4815,
"s": 4808,
"text": "Arrays"
},
{
"code": null,
"e": 4826,
"s": 4815,
"text": "JavaScript"
},
{
"code": null,
"e": 4843,
"s": 4826,
"text": "Web Technologies"
},
{
"code": null,
"e": 4850,
"s": 4843,
"text": "Arrays"
},
{
"code": null,
"e": 4948,
"s": 4850,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5016,
"s": 4948,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 5060,
"s": 5016,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 5092,
"s": 5060,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 5140,
"s": 5092,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 5154,
"s": 5140,
"text": "Linear Search"
},
{
"code": null,
"e": 5215,
"s": 5154,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 5287,
"s": 5215,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 5327,
"s": 5287,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 5380,
"s": 5327,
"text": "Hide or show elements in HTML using display property"
}
] |
Create Address Book in Python – Using Tkinter | 28 Apr, 2021
Prerequisite: Tkinter
In this article, we will discuss how to create an address book in Tkinter using Python.
Step 1: Creating GUI.
In this, we will add all the GUI Components like labels, text area and buttons.
Python3
# Import Modulefrom tkinter import * # Create Objectroot = Tk() # Set geometryroot.geometry('400x500') # Add Buttons, Label, ListBoxName = StringVar()Number = StringVar() frame = Frame()frame.pack(pady=10) frame1 = Frame()frame1.pack() frame2 = Frame()frame2.pack(pady=10) Label(frame, text = 'Name', font='arial 12 bold').pack(side=LEFT)Entry(frame, textvariable = Name,width=50).pack() Label(frame1, text = 'Phone No.', font='arial 12 bold').pack(side=LEFT)Entry(frame1, textvariable = Number,width=50).pack() Label(frame2, text = 'Address', font='arial 12 bold').pack(side=LEFT)address = Text(frame2,width=37,height=10)address.pack() Button(root,text="Add",font="arial 12 bold").place(x= 100, y=270)Button(root,text="View",font="arial 12 bold").place(x= 100, y=310)Button(root,text="Delete",font="arial 12 bold").place(x= 100, y=350)Button(root,text="Reset",font="arial 12 bold").place(x= 100, y=390) scroll_bar = Scrollbar(root, orient=VERTICAL)select = Listbox(root, yscrollcommand=scroll_bar.set, height=12)scroll_bar.config (command=select.yview)scroll_bar.pack(side=RIGHT, fill=Y)select.place(x=200,y=260) # Execute Tkinterroot.mainloop()
Output:
Step 2: Creating User define function to retrieve the operation.
These are function are used in this program:
add: This will add a record in the address book data structure and update the GUI.
view: This will represent all the values of the selected record.
delete: This will delete the selected record from the address book data structure and update the GUI.
reset: This will reset all the input values of the input parameters.
update_book: This will update the whole address book data structure.
Python3
# Information Listdatas = [] # Add Informationdef add(): global datas datas.append([Name.get(),Number.get(),address.get(1.0, "end-1c")]) update_book() # View Informationdef view(): Name.set(datas[int(select.curselection()[0])][0]) Number.set(datas[int(select.curselection()[0])][1]) address.delete(1.0,"end") address.insert(1.0, datas[int(select.curselection()[0])][2]) # Delete Informationdef delete(): del datas[int(select.curselection()[0])] update_book() def reset(): Name.set('') Number.set('') address.delete(1.0,"end") # Update Informationdef update_book(): select.delete(0,END) for n,p,a in datas: select.insert(END, n)
Complete Code:
Python3
# Import Modulefrom tkinter import * # Create Objectroot = Tk() # Set geometryroot.geometry('400x500') # Information Listdatas = [] # Add Informationdef add(): global datas datas.append([Name.get(),Number.get(),address.get(1.0, "end-1c")]) update_book() # View Informationdef view(): Name.set(datas[int(select.curselection()[0])][0]) Number.set(datas[int(select.curselection()[0])][1]) address.delete(1.0,"end") address.insert(1.0, datas[int(select.curselection()[0])][2]) # Delete Informationdef delete(): del datas[int(select.curselection()[0])] update_book() def reset(): Name.set('') Number.set('') address.delete(1.0,"end") # Update Informationdef update_book(): select.delete(0,END) for n,p,a in datas: select.insert(END, n) # Add Buttons, Label, ListBoxName = StringVar()Number = StringVar() frame = Frame()frame.pack(pady=10) frame1 = Frame()frame1.pack() frame2 = Frame()frame2.pack(pady=10) Label(frame, text = 'Name', font='arial 12 bold').pack(side=LEFT)Entry(frame, textvariable = Name,width=50).pack() Label(frame1, text = 'Phone No.', font='arial 12 bold').pack(side=LEFT)Entry(frame1, textvariable = Number,width=50).pack() Label(frame2, text = 'Address', font='arial 12 bold').pack(side=LEFT)address = Text(frame2,width=37,height=10)address.pack() Button(root,text="Add",font="arial 12 bold",command=add).place(x= 100, y=270)Button(root,text="View",font="arial 12 bold",command=view).place(x= 100, y=310)Button(root,text="Delete",font="arial 12 bold",command=delete).place(x= 100, y=350)Button(root,text="Reset",font="arial 12 bold",command=reset).place(x= 100, y=390) scroll_bar = Scrollbar(root, orient=VERTICAL)select = Listbox(root, yscrollcommand=scroll_bar.set, height=12)scroll_bar.config (command=select.yview)scroll_bar.pack(side=RIGHT, fill=Y)select.place(x=200,y=260) # Execute Tkinterroot.mainloop()
Output:
Python Tkinter-exercises
Python Tkinter-projects
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Apr, 2021"
},
{
"code": null,
"e": 50,
"s": 28,
"text": "Prerequisite: Tkinter"
},
{
"code": null,
"e": 138,
"s": 50,
"text": "In this article, we will discuss how to create an address book in Tkinter using Python."
},
{
"code": null,
"e": 160,
"s": 138,
"text": "Step 1: Creating GUI."
},
{
"code": null,
"e": 240,
"s": 160,
"text": "In this, we will add all the GUI Components like labels, text area and buttons."
},
{
"code": null,
"e": 248,
"s": 240,
"text": "Python3"
},
{
"code": "# Import Modulefrom tkinter import * # Create Objectroot = Tk() # Set geometryroot.geometry('400x500') # Add Buttons, Label, ListBoxName = StringVar()Number = StringVar() frame = Frame()frame.pack(pady=10) frame1 = Frame()frame1.pack() frame2 = Frame()frame2.pack(pady=10) Label(frame, text = 'Name', font='arial 12 bold').pack(side=LEFT)Entry(frame, textvariable = Name,width=50).pack() Label(frame1, text = 'Phone No.', font='arial 12 bold').pack(side=LEFT)Entry(frame1, textvariable = Number,width=50).pack() Label(frame2, text = 'Address', font='arial 12 bold').pack(side=LEFT)address = Text(frame2,width=37,height=10)address.pack() Button(root,text=\"Add\",font=\"arial 12 bold\").place(x= 100, y=270)Button(root,text=\"View\",font=\"arial 12 bold\").place(x= 100, y=310)Button(root,text=\"Delete\",font=\"arial 12 bold\").place(x= 100, y=350)Button(root,text=\"Reset\",font=\"arial 12 bold\").place(x= 100, y=390) scroll_bar = Scrollbar(root, orient=VERTICAL)select = Listbox(root, yscrollcommand=scroll_bar.set, height=12)scroll_bar.config (command=select.yview)scroll_bar.pack(side=RIGHT, fill=Y)select.place(x=200,y=260) # Execute Tkinterroot.mainloop()",
"e": 1407,
"s": 248,
"text": null
},
{
"code": null,
"e": 1415,
"s": 1407,
"text": "Output:"
},
{
"code": null,
"e": 1481,
"s": 1415,
"text": "Step 2: Creating User define function to retrieve the operation. "
},
{
"code": null,
"e": 1526,
"s": 1481,
"text": "These are function are used in this program:"
},
{
"code": null,
"e": 1609,
"s": 1526,
"text": "add: This will add a record in the address book data structure and update the GUI."
},
{
"code": null,
"e": 1674,
"s": 1609,
"text": "view: This will represent all the values of the selected record."
},
{
"code": null,
"e": 1776,
"s": 1674,
"text": "delete: This will delete the selected record from the address book data structure and update the GUI."
},
{
"code": null,
"e": 1845,
"s": 1776,
"text": "reset: This will reset all the input values of the input parameters."
},
{
"code": null,
"e": 1914,
"s": 1845,
"text": "update_book: This will update the whole address book data structure."
},
{
"code": null,
"e": 1922,
"s": 1914,
"text": "Python3"
},
{
"code": "# Information Listdatas = [] # Add Informationdef add(): global datas datas.append([Name.get(),Number.get(),address.get(1.0, \"end-1c\")]) update_book() # View Informationdef view(): Name.set(datas[int(select.curselection()[0])][0]) Number.set(datas[int(select.curselection()[0])][1]) address.delete(1.0,\"end\") address.insert(1.0, datas[int(select.curselection()[0])][2]) # Delete Informationdef delete(): del datas[int(select.curselection()[0])] update_book() def reset(): Name.set('') Number.set('') address.delete(1.0,\"end\") # Update Informationdef update_book(): select.delete(0,END) for n,p,a in datas: select.insert(END, n)",
"e": 2610,
"s": 1922,
"text": null
},
{
"code": null,
"e": 2625,
"s": 2610,
"text": "Complete Code:"
},
{
"code": null,
"e": 2633,
"s": 2625,
"text": "Python3"
},
{
"code": "# Import Modulefrom tkinter import * # Create Objectroot = Tk() # Set geometryroot.geometry('400x500') # Information Listdatas = [] # Add Informationdef add(): global datas datas.append([Name.get(),Number.get(),address.get(1.0, \"end-1c\")]) update_book() # View Informationdef view(): Name.set(datas[int(select.curselection()[0])][0]) Number.set(datas[int(select.curselection()[0])][1]) address.delete(1.0,\"end\") address.insert(1.0, datas[int(select.curselection()[0])][2]) # Delete Informationdef delete(): del datas[int(select.curselection()[0])] update_book() def reset(): Name.set('') Number.set('') address.delete(1.0,\"end\") # Update Informationdef update_book(): select.delete(0,END) for n,p,a in datas: select.insert(END, n) # Add Buttons, Label, ListBoxName = StringVar()Number = StringVar() frame = Frame()frame.pack(pady=10) frame1 = Frame()frame1.pack() frame2 = Frame()frame2.pack(pady=10) Label(frame, text = 'Name', font='arial 12 bold').pack(side=LEFT)Entry(frame, textvariable = Name,width=50).pack() Label(frame1, text = 'Phone No.', font='arial 12 bold').pack(side=LEFT)Entry(frame1, textvariable = Number,width=50).pack() Label(frame2, text = 'Address', font='arial 12 bold').pack(side=LEFT)address = Text(frame2,width=37,height=10)address.pack() Button(root,text=\"Add\",font=\"arial 12 bold\",command=add).place(x= 100, y=270)Button(root,text=\"View\",font=\"arial 12 bold\",command=view).place(x= 100, y=310)Button(root,text=\"Delete\",font=\"arial 12 bold\",command=delete).place(x= 100, y=350)Button(root,text=\"Reset\",font=\"arial 12 bold\",command=reset).place(x= 100, y=390) scroll_bar = Scrollbar(root, orient=VERTICAL)select = Listbox(root, yscrollcommand=scroll_bar.set, height=12)scroll_bar.config (command=select.yview)scroll_bar.pack(side=RIGHT, fill=Y)select.place(x=200,y=260) # Execute Tkinterroot.mainloop()",
"e": 4529,
"s": 2633,
"text": null
},
{
"code": null,
"e": 4537,
"s": 4529,
"text": "Output:"
},
{
"code": null,
"e": 4562,
"s": 4537,
"text": "Python Tkinter-exercises"
},
{
"code": null,
"e": 4586,
"s": 4562,
"text": "Python Tkinter-projects"
},
{
"code": null,
"e": 4601,
"s": 4586,
"text": "Python-tkinter"
},
{
"code": null,
"e": 4608,
"s": 4601,
"text": "Python"
}
] |
fmt.Scanf() Function in Golang With Examples | 26 Feb, 2021
In Go language, fmt package implements formatted I/O with functions analogous to C’s printf() and scanf() function. The fmt.Scanf() function in Go language scans the input texts which is given in the standard input, reads from there and stores the successive space-separated values into successive arguments as determined by the format. Moreover, this function is defined under the fmt package. Here, you need to import the “fmt” package in order to use these functions.Syntax:
func Scanf(format string, a ...interface{}) (n int, err error)
Parameters: This function accepts two parameters which are illustrated below:
format string: This is the different formats which are used for each given elements.
a ...interface{}: These parameters receive each given elements.
Returns: It returns the number of items successfully scanned.Example 1:
C
// Golang program to illustrate the usage of// fmt.Scanf() function // Including the main packagepackage main // Importing fmtimport ( "fmt") // Calling mainfunc main() { // Declaring some variables var name string var alphabet_count int // Calling Scanf() function for // scanning and reading the input // texts given in standard input fmt.Scanf("%s", &name) fmt.Scanf("%d", &alphabet_count) // Printing the given texts fmt.Printf("The word %s containing %d number of alphabets.", name, alphabet_count) }
Input:
GFG 3
Output:
The word GFG containing 3 number of alphabets.
Example 2:
C
// Golang program to illustrate the usage of// fmt.Scanf() function // Including the main packagepackage main // Importing fmtimport ( "fmt") // Calling mainfunc main() { // Declaring some variables var name string var alphabet_count int var float_value float32 var bool_value bool // Calling Scanf() function for // scanning and reading the input // texts given in standard input fmt.Scanf("%s", &name) fmt.Scanf("%d", &alphabet_count) fmt.Scanf("%g", &float_value) fmt.Scanf("%t", &bool_value) // Printing the given texts fmt.Printf("%s %d %g %t", name, alphabet_count, float_value, bool_value) }
Input:
GeeksforGeeks 13 6.789 true
Output:
GeeksforGeeks 13 6.789 true
arorakashish0911
Golang-fmt
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Feb, 2021"
},
{
"code": null,
"e": 508,
"s": 28,
"text": "In Go language, fmt package implements formatted I/O with functions analogous to C’s printf() and scanf() function. The fmt.Scanf() function in Go language scans the input texts which is given in the standard input, reads from there and stores the successive space-separated values into successive arguments as determined by the format. Moreover, this function is defined under the fmt package. Here, you need to import the “fmt” package in order to use these functions.Syntax: "
},
{
"code": null,
"e": 571,
"s": 508,
"text": "func Scanf(format string, a ...interface{}) (n int, err error)"
},
{
"code": null,
"e": 651,
"s": 571,
"text": "Parameters: This function accepts two parameters which are illustrated below: "
},
{
"code": null,
"e": 736,
"s": 651,
"text": "format string: This is the different formats which are used for each given elements."
},
{
"code": null,
"e": 800,
"s": 736,
"text": "a ...interface{}: These parameters receive each given elements."
},
{
"code": null,
"e": 873,
"s": 800,
"text": "Returns: It returns the number of items successfully scanned.Example 1: "
},
{
"code": null,
"e": 875,
"s": 873,
"text": "C"
},
{
"code": "// Golang program to illustrate the usage of// fmt.Scanf() function // Including the main packagepackage main // Importing fmtimport ( \"fmt\") // Calling mainfunc main() { // Declaring some variables var name string var alphabet_count int // Calling Scanf() function for // scanning and reading the input // texts given in standard input fmt.Scanf(\"%s\", &name) fmt.Scanf(\"%d\", &alphabet_count) // Printing the given texts fmt.Printf(\"The word %s containing %d number of alphabets.\", name, alphabet_count) }",
"e": 1431,
"s": 875,
"text": null
},
{
"code": null,
"e": 1440,
"s": 1431,
"text": "Input: "
},
{
"code": null,
"e": 1446,
"s": 1440,
"text": "GFG 3"
},
{
"code": null,
"e": 1456,
"s": 1446,
"text": "Output: "
},
{
"code": null,
"e": 1503,
"s": 1456,
"text": "The word GFG containing 3 number of alphabets."
},
{
"code": null,
"e": 1515,
"s": 1503,
"text": "Example 2: "
},
{
"code": null,
"e": 1517,
"s": 1515,
"text": "C"
},
{
"code": "// Golang program to illustrate the usage of// fmt.Scanf() function // Including the main packagepackage main // Importing fmtimport ( \"fmt\") // Calling mainfunc main() { // Declaring some variables var name string var alphabet_count int var float_value float32 var bool_value bool // Calling Scanf() function for // scanning and reading the input // texts given in standard input fmt.Scanf(\"%s\", &name) fmt.Scanf(\"%d\", &alphabet_count) fmt.Scanf(\"%g\", &float_value) fmt.Scanf(\"%t\", &bool_value) // Printing the given texts fmt.Printf(\"%s %d %g %t\", name, alphabet_count, float_value, bool_value) }",
"e": 2168,
"s": 1517,
"text": null
},
{
"code": null,
"e": 2177,
"s": 2168,
"text": "Input: "
},
{
"code": null,
"e": 2205,
"s": 2177,
"text": "GeeksforGeeks 13 6.789 true"
},
{
"code": null,
"e": 2215,
"s": 2205,
"text": "Output: "
},
{
"code": null,
"e": 2243,
"s": 2215,
"text": "GeeksforGeeks 13 6.789 true"
},
{
"code": null,
"e": 2262,
"s": 2245,
"text": "arorakashish0911"
},
{
"code": null,
"e": 2273,
"s": 2262,
"text": "Golang-fmt"
},
{
"code": null,
"e": 2285,
"s": 2273,
"text": "Go Language"
}
] |
How to Install PHP on AWS EC2? | 30 Nov, 2021
AWS or Amazon web services is a cloud service platform that provides on-demand computational services, databases, storage space, and many more services. EC2 or Elastic Compute Cloud is a scalable computing service launched on the AWS cloud platform. In simpler words, EC2 is nothing but a virtual computer on which we can perform all our tasks and we have the authority to configure, launch or even dissipate this virtual computer To know more about EC2 visit this page.
In this article we will learn how to install PHP on AWS EC2.
AWS account.EC2 Instance.User with privileges to create Instance.
AWS account.
EC2 Instance.
User with privileges to create Instance.
Step 1 – Create an AWS Elastic Cloud Compute Instance, to do so visit How-To-Create-EC2-Instance.
Step 2 – Start the EC2 instance that you have created in Step 1
Step 3 – Connect to your EC2 Instance by clicking on Connect Button
Step 4 – A prompt will pop up after connecting.
Step 5 – At first check, if PHP is already installed or not.
php --version
Step 6 – If PHP is not installed on your virtual machine then install the PHP using the following command
sudo apt install php7.4
Step 7 – A prompt will appear asking you for confirmation , press ‘y’ to confirm.
Step 8 – Wait for the process to end.
Step 9 –We have successfully installed PHP on our EC2 instance, to check if PHP is installed or not, verify using the following command.
php --version
Step 10 – To know the current version of PHP, use the following command.
apt search php7.*
In this way, we can install PHP on our EC2 instance using EC2 Instance Connect. And if you also use a free tier account, make sure you delete all the resources you have used before logging out.
how-to-install
Picked
How To
Installation Guide
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Set Git Username and Password in GitBash?
How to Install Jupyter Notebook on MacOS?
How to Install and Use NVM on Windows?
How to Install Python Packages for AWS Lambda Layers?
How to Install Git in VS Code?
Installation of Node.js on Linux
Installation of Node.js on Windows
How to Install Jupyter Notebook on MacOS?
How to Install and Use NVM on Windows?
How to Install Pygame on Windows ? | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n30 Nov, 2021"
},
{
"code": null,
"e": 525,
"s": 54,
"text": "AWS or Amazon web services is a cloud service platform that provides on-demand computational services, databases, storage space, and many more services. EC2 or Elastic Compute Cloud is a scalable computing service launched on the AWS cloud platform. In simpler words, EC2 is nothing but a virtual computer on which we can perform all our tasks and we have the authority to configure, launch or even dissipate this virtual computer To know more about EC2 visit this page."
},
{
"code": null,
"e": 586,
"s": 525,
"text": "In this article we will learn how to install PHP on AWS EC2."
},
{
"code": null,
"e": 652,
"s": 586,
"text": "AWS account.EC2 Instance.User with privileges to create Instance."
},
{
"code": null,
"e": 665,
"s": 652,
"text": "AWS account."
},
{
"code": null,
"e": 679,
"s": 665,
"text": "EC2 Instance."
},
{
"code": null,
"e": 720,
"s": 679,
"text": "User with privileges to create Instance."
},
{
"code": null,
"e": 818,
"s": 720,
"text": "Step 1 – Create an AWS Elastic Cloud Compute Instance, to do so visit How-To-Create-EC2-Instance."
},
{
"code": null,
"e": 882,
"s": 818,
"text": "Step 2 – Start the EC2 instance that you have created in Step 1"
},
{
"code": null,
"e": 951,
"s": 882,
"text": "Step 3 – Connect to your EC2 Instance by clicking on Connect Button "
},
{
"code": null,
"e": 999,
"s": 951,
"text": "Step 4 – A prompt will pop up after connecting."
},
{
"code": null,
"e": 1060,
"s": 999,
"text": "Step 5 – At first check, if PHP is already installed or not."
},
{
"code": null,
"e": 1074,
"s": 1060,
"text": "php --version"
},
{
"code": null,
"e": 1181,
"s": 1074,
"text": "Step 6 – If PHP is not installed on your virtual machine then install the PHP using the following command "
},
{
"code": null,
"e": 1205,
"s": 1181,
"text": "sudo apt install php7.4"
},
{
"code": null,
"e": 1288,
"s": 1205,
"text": "Step 7 – A prompt will appear asking you for confirmation , press ‘y’ to confirm."
},
{
"code": null,
"e": 1326,
"s": 1288,
"text": "Step 8 – Wait for the process to end."
},
{
"code": null,
"e": 1464,
"s": 1326,
"text": "Step 9 –We have successfully installed PHP on our EC2 instance, to check if PHP is installed or not, verify using the following command."
},
{
"code": null,
"e": 1478,
"s": 1464,
"text": "php --version"
},
{
"code": null,
"e": 1551,
"s": 1478,
"text": "Step 10 – To know the current version of PHP, use the following command."
},
{
"code": null,
"e": 1569,
"s": 1551,
"text": "apt search php7.*"
},
{
"code": null,
"e": 1764,
"s": 1569,
"text": "In this way, we can install PHP on our EC2 instance using EC2 Instance Connect. And if you also use a free tier account, make sure you delete all the resources you have used before logging out. "
},
{
"code": null,
"e": 1779,
"s": 1764,
"text": "how-to-install"
},
{
"code": null,
"e": 1786,
"s": 1779,
"text": "Picked"
},
{
"code": null,
"e": 1793,
"s": 1786,
"text": "How To"
},
{
"code": null,
"e": 1812,
"s": 1793,
"text": "Installation Guide"
},
{
"code": null,
"e": 1910,
"s": 1812,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1959,
"s": 1910,
"text": "How to Set Git Username and Password in GitBash?"
},
{
"code": null,
"e": 2001,
"s": 1959,
"text": "How to Install Jupyter Notebook on MacOS?"
},
{
"code": null,
"e": 2040,
"s": 2001,
"text": "How to Install and Use NVM on Windows?"
},
{
"code": null,
"e": 2094,
"s": 2040,
"text": "How to Install Python Packages for AWS Lambda Layers?"
},
{
"code": null,
"e": 2125,
"s": 2094,
"text": "How to Install Git in VS Code?"
},
{
"code": null,
"e": 2158,
"s": 2125,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2193,
"s": 2158,
"text": "Installation of Node.js on Windows"
},
{
"code": null,
"e": 2235,
"s": 2193,
"text": "How to Install Jupyter Notebook on MacOS?"
},
{
"code": null,
"e": 2274,
"s": 2235,
"text": "How to Install and Use NVM on Windows?"
}
] |
How to Generate a Random Password using JavaScript ? | 25 Apr, 2022
The task is to generate a random password that may consist of alphabets, numbers, and special characters. This can be achieved in various ways in this article we will discuss the most popular two methods which are discussed below to solve the problem.
Approach 1: Make a string consist of Alphabets(lowercase and uppercase), Numbers and Special Characters. the we will use Math.random() and Math.floor() method to generate a number in between 0 and l-1(where l is length of string). To get the character of the string of a particular index we can use .charAt() method. This will keep concatenating the random character from the string until the password of the desired length is obtained.
Example: This example implements the above approach.<!DOCTYPE HTML><html> <head> <title> Generate a Random Password using JavaScript </title></head> <body style="text-align:center;"> <h1 style="color: green"> GeeksforGeeks </h1> <h3> Click on the button to generate random password. </h3> <button onclick="gfg_Run()"> Click Here </button> <br> <div> <p id="geeks"></p> </div> <script> var el_down = document.getElementById("geeks"); /* Function to generate combination of password */ function generateP() { var pass = ''; var str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz0123456789@#$'; for (let i = 1; i <= 8; i++) { var char = Math.floor(Math.random() * str.length + 1); pass += str.charAt(char) } return pass; } function gfg_Run() { el_down.innerHTML = generateP(); } </script></body> </html>
<!DOCTYPE HTML><html> <head> <title> Generate a Random Password using JavaScript </title></head> <body style="text-align:center;"> <h1 style="color: green"> GeeksforGeeks </h1> <h3> Click on the button to generate random password. </h3> <button onclick="gfg_Run()"> Click Here </button> <br> <div> <p id="geeks"></p> </div> <script> var el_down = document.getElementById("geeks"); /* Function to generate combination of password */ function generateP() { var pass = ''; var str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz0123456789@#$'; for (let i = 1; i <= 8; i++) { var char = Math.floor(Math.random() * str.length + 1); pass += str.charAt(char) } return pass; } function gfg_Run() { el_down.innerHTML = generateP(); } </script></body> </html>
Output:
Approach 2: In this approach we will use Math.random() method to generate a number in between 0 and 1 then convert it to base36(which will consist of 0-9 and a-z in lowercase letters) using .toString() method. To remove the leading zero and decimal point .slice() method will be used and Math.random().toString(36).slice(2) to generate the password. For uppercase letters use the same method with .uppercase() method in concatenation with the previous method.
Example: This example implements the above approach.<!DOCTYPE HTML> <html> <head> <title> Generate a Random Password using JavaScript </title></head> <body style = "text-align:center;"> <h1 style = "color: green"> GeeksforGeeks </h1> <h3> Click on the button to generate random password. </h3> <button onclick = "gfg_Run()"> Click Here </button> <p id = "geeks"></p> <script> var el_down = document.getElementById("geeks"); function gfg_Run() { el_down.innerHTML = Math.random().toString(36).slice(2) + Math.random().toString(36) .toUpperCase().slice(2); } </script> </body> </html>
<!DOCTYPE HTML> <html> <head> <title> Generate a Random Password using JavaScript </title></head> <body style = "text-align:center;"> <h1 style = "color: green"> GeeksforGeeks </h1> <h3> Click on the button to generate random password. </h3> <button onclick = "gfg_Run()"> Click Here </button> <p id = "geeks"></p> <script> var el_down = document.getElementById("geeks"); function gfg_Run() { el_down.innerHTML = Math.random().toString(36).slice(2) + Math.random().toString(36) .toUpperCase().slice(2); } </script> </body> </html>
Output:
ilamuhil
JavaScript-Misc
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
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": 54,
"s": 26,
"text": "\n25 Apr, 2022"
},
{
"code": null,
"e": 306,
"s": 54,
"text": "The task is to generate a random password that may consist of alphabets, numbers, and special characters. This can be achieved in various ways in this article we will discuss the most popular two methods which are discussed below to solve the problem."
},
{
"code": null,
"e": 743,
"s": 306,
"text": "Approach 1: Make a string consist of Alphabets(lowercase and uppercase), Numbers and Special Characters. the we will use Math.random() and Math.floor() method to generate a number in between 0 and l-1(where l is length of string). To get the character of the string of a particular index we can use .charAt() method. This will keep concatenating the random character from the string until the password of the desired length is obtained."
},
{
"code": null,
"e": 1916,
"s": 743,
"text": "Example: This example implements the above approach.<!DOCTYPE HTML><html> <head> <title> Generate a Random Password using JavaScript </title></head> <body style=\"text-align:center;\"> <h1 style=\"color: green\"> GeeksforGeeks </h1> <h3> Click on the button to generate random password. </h3> <button onclick=\"gfg_Run()\"> Click Here </button> <br> <div> <p id=\"geeks\"></p> </div> <script> var el_down = document.getElementById(\"geeks\"); /* Function to generate combination of password */ function generateP() { var pass = ''; var str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz0123456789@#$'; for (let i = 1; i <= 8; i++) { var char = Math.floor(Math.random() * str.length + 1); pass += str.charAt(char) } return pass; } function gfg_Run() { el_down.innerHTML = generateP(); } </script></body> </html>"
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> Generate a Random Password using JavaScript </title></head> <body style=\"text-align:center;\"> <h1 style=\"color: green\"> GeeksforGeeks </h1> <h3> Click on the button to generate random password. </h3> <button onclick=\"gfg_Run()\"> Click Here </button> <br> <div> <p id=\"geeks\"></p> </div> <script> var el_down = document.getElementById(\"geeks\"); /* Function to generate combination of password */ function generateP() { var pass = ''; var str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz0123456789@#$'; for (let i = 1; i <= 8; i++) { var char = Math.floor(Math.random() * str.length + 1); pass += str.charAt(char) } return pass; } function gfg_Run() { el_down.innerHTML = generateP(); } </script></body> </html>",
"e": 3037,
"s": 1916,
"text": null
},
{
"code": null,
"e": 3045,
"s": 3037,
"text": "Output:"
},
{
"code": null,
"e": 3505,
"s": 3045,
"text": "Approach 2: In this approach we will use Math.random() method to generate a number in between 0 and 1 then convert it to base36(which will consist of 0-9 and a-z in lowercase letters) using .toString() method. To remove the leading zero and decimal point .slice() method will be used and Math.random().toString(36).slice(2) to generate the password. For uppercase letters use the same method with .uppercase() method in concatenation with the previous method."
},
{
"code": null,
"e": 4309,
"s": 3505,
"text": "Example: This example implements the above approach.<!DOCTYPE HTML> <html> <head> <title> Generate a Random Password using JavaScript </title></head> <body style = \"text-align:center;\"> <h1 style = \"color: green\"> GeeksforGeeks </h1> <h3> Click on the button to generate random password. </h3> <button onclick = \"gfg_Run()\"> Click Here </button> <p id = \"geeks\"></p> <script> var el_down = document.getElementById(\"geeks\"); function gfg_Run() { el_down.innerHTML = Math.random().toString(36).slice(2) + Math.random().toString(36) .toUpperCase().slice(2); } </script> </body> </html> "
},
{
"code": "<!DOCTYPE HTML> <html> <head> <title> Generate a Random Password using JavaScript </title></head> <body style = \"text-align:center;\"> <h1 style = \"color: green\"> GeeksforGeeks </h1> <h3> Click on the button to generate random password. </h3> <button onclick = \"gfg_Run()\"> Click Here </button> <p id = \"geeks\"></p> <script> var el_down = document.getElementById(\"geeks\"); function gfg_Run() { el_down.innerHTML = Math.random().toString(36).slice(2) + Math.random().toString(36) .toUpperCase().slice(2); } </script> </body> </html> ",
"e": 5061,
"s": 4309,
"text": null
},
{
"code": null,
"e": 5069,
"s": 5061,
"text": "Output:"
},
{
"code": null,
"e": 5078,
"s": 5069,
"text": "ilamuhil"
},
{
"code": null,
"e": 5094,
"s": 5078,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 5105,
"s": 5094,
"text": "JavaScript"
},
{
"code": null,
"e": 5122,
"s": 5105,
"text": "Web Technologies"
},
{
"code": null,
"e": 5149,
"s": 5122,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 5247,
"s": 5149,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5308,
"s": 5247,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 5380,
"s": 5308,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 5420,
"s": 5380,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 5461,
"s": 5420,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 5513,
"s": 5461,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 5546,
"s": 5513,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 5608,
"s": 5546,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 5669,
"s": 5608,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 5719,
"s": 5669,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Protecting Excel Worksheets and Workbooks | 29 Jun, 2021
Sometimes while sharing your spreadsheets you may not want the receiver to change the content of your worksheet or perhaps change only specific content and leave the rest untouched. To protect your worksheet from being edited by other people, Excel offers a protection feature. By following a couple of steps you can set protection to your work.
Protect an entire workbook from editing: A workbook can be protected by encrypting the workbook with a password, making the workbook read-only, or protecting the structure of a workbook.
To prevent other people from accessing your Excel files, protect them with a password. Head on to the file menu and fo the following:
Step 1: Select File > Info.
Step 2: Select the Protect Workbook box and choose Encrypt with Password.
Step 3: Enter a password in the Password box, and then select OK.
Step 4: Confirm the password in the Re-enter Password box and then select OK.
TIP: Excel can’t retrieve your password once forgotten hence it’s advised to keep it easy to remember.
By making a workbook read only the user can read the content of the file and then enable editing if the user wishes to make changes, it gives the user a hint to be cautious about editing the file.
To make a workbook read-only open the Excel file you want to protect and then :
Step 1: Head on to File>info
Step 2: Select the Protect Workbook box and choose Always open Read-Only.
Step 3: Open the file and a warning will be displayed stating the author prefers the file to be opened in read-only mode. This makes the user aware of the author’s concerns.
To prevent other users from viewing hidden worksheets, adding, moving, deleting, or hiding worksheets, and renaming worksheets, you can protect the structure of your Excel workbook with a password.
Step 1: Click on Review tab>Protect workbook (under Changes ).
Step 2: Enter a password in the password box.
Step 3: Click ok and re-enter the password to confirm and hit OK again.
To remove the password from the workbook Head on to Review > Protect Workbook > type in the password and the workbook will be free from the password.
To protect the Workbook from editing follow the below steps:
Step 1: Open the worksheet you want to protect.
Step 2: Head on to Review tab > Protect sheet.
Step 3: This opens a project sheet dialog and prompts you to enter a password for the sheet. You can check the boxes you want the user to be able to edit after protection and uncheck the rest.
Step 4: Hit OK and confirm password (don’t lose this password).
Your sheet is now protected, try typing into the sheet and see what excel prompts!
As a developer if you want to make changes to your sheet you can hit the unprotect sheet under the review tab>enter the password> make the changes.
By default, every single cell in an Excel worksheet is locked. So if you head on to the Review tab and hit protected every single cell in the worksheet gets protected and no one can make any changes. But if you want the user to be able to edit certain cells and leave the rest unedited then follow these steps :
Step 1: Open the file you want to protect.
Step 2: Select the cells from the file that you want the users to be able to edit and make changes to(cells you want to unlock).
Step 3: Then under the font section click on the arrow pointing downwards icon on the bottom-right (called font settings)
Step 4: As the Format cells dialog box opens up, head on to Protection, turn off the locked property for the selected cells, and hit ok.
These cells are no longer locked and can be edited by the user. Deciding which cells should be locked and which shouldn’t is important while protecting the sheets.
Step 5: Head on to the Review tab > Protect sheet. This opens a protect sheet dialog and prompts you to enter a password for the sheet. You can check the boxes you want the user to be able to edit after protection and uncheck the rest.
Step 6: Hit OK and confirm password (don’t lose this password).
Step 7: Click ok and re-enter the password to confirm and hit OK again.
According to the situation at hand, you can protect your worksheet or workbook in one of the many ways.
Excel
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Jun, 2021"
},
{
"code": null,
"e": 374,
"s": 28,
"text": "Sometimes while sharing your spreadsheets you may not want the receiver to change the content of your worksheet or perhaps change only specific content and leave the rest untouched. To protect your worksheet from being edited by other people, Excel offers a protection feature. By following a couple of steps you can set protection to your work."
},
{
"code": null,
"e": 561,
"s": 374,
"text": "Protect an entire workbook from editing: A workbook can be protected by encrypting the workbook with a password, making the workbook read-only, or protecting the structure of a workbook."
},
{
"code": null,
"e": 696,
"s": 561,
"text": "To prevent other people from accessing your Excel files, protect them with a password. Head on to the file menu and fo the following: "
},
{
"code": null,
"e": 724,
"s": 696,
"text": "Step 1: Select File > Info."
},
{
"code": null,
"e": 798,
"s": 724,
"text": "Step 2: Select the Protect Workbook box and choose Encrypt with Password."
},
{
"code": null,
"e": 864,
"s": 798,
"text": "Step 3: Enter a password in the Password box, and then select OK."
},
{
"code": null,
"e": 942,
"s": 864,
"text": "Step 4: Confirm the password in the Re-enter Password box and then select OK."
},
{
"code": null,
"e": 1045,
"s": 942,
"text": "TIP: Excel can’t retrieve your password once forgotten hence it’s advised to keep it easy to remember."
},
{
"code": null,
"e": 1242,
"s": 1045,
"text": "By making a workbook read only the user can read the content of the file and then enable editing if the user wishes to make changes, it gives the user a hint to be cautious about editing the file."
},
{
"code": null,
"e": 1322,
"s": 1242,
"text": "To make a workbook read-only open the Excel file you want to protect and then :"
},
{
"code": null,
"e": 1352,
"s": 1322,
"text": "Step 1: Head on to File>info "
},
{
"code": null,
"e": 1426,
"s": 1352,
"text": "Step 2: Select the Protect Workbook box and choose Always open Read-Only."
},
{
"code": null,
"e": 1600,
"s": 1426,
"text": "Step 3: Open the file and a warning will be displayed stating the author prefers the file to be opened in read-only mode. This makes the user aware of the author’s concerns."
},
{
"code": null,
"e": 1799,
"s": 1600,
"text": "To prevent other users from viewing hidden worksheets, adding, moving, deleting, or hiding worksheets, and renaming worksheets, you can protect the structure of your Excel workbook with a password. "
},
{
"code": null,
"e": 1862,
"s": 1799,
"text": "Step 1: Click on Review tab>Protect workbook (under Changes )."
},
{
"code": null,
"e": 1908,
"s": 1862,
"text": "Step 2: Enter a password in the password box."
},
{
"code": null,
"e": 1980,
"s": 1908,
"text": "Step 3: Click ok and re-enter the password to confirm and hit OK again."
},
{
"code": null,
"e": 2130,
"s": 1980,
"text": "To remove the password from the workbook Head on to Review > Protect Workbook > type in the password and the workbook will be free from the password."
},
{
"code": null,
"e": 2191,
"s": 2130,
"text": "To protect the Workbook from editing follow the below steps:"
},
{
"code": null,
"e": 2239,
"s": 2191,
"text": "Step 1: Open the worksheet you want to protect."
},
{
"code": null,
"e": 2287,
"s": 2239,
"text": "Step 2: Head on to Review tab > Protect sheet. "
},
{
"code": null,
"e": 2480,
"s": 2287,
"text": "Step 3: This opens a project sheet dialog and prompts you to enter a password for the sheet. You can check the boxes you want the user to be able to edit after protection and uncheck the rest."
},
{
"code": null,
"e": 2546,
"s": 2480,
"text": "Step 4: Hit OK and confirm password (don’t lose this password). "
},
{
"code": null,
"e": 2629,
"s": 2546,
"text": "Your sheet is now protected, try typing into the sheet and see what excel prompts!"
},
{
"code": null,
"e": 2777,
"s": 2629,
"text": "As a developer if you want to make changes to your sheet you can hit the unprotect sheet under the review tab>enter the password> make the changes."
},
{
"code": null,
"e": 3091,
"s": 2777,
"text": "By default, every single cell in an Excel worksheet is locked. So if you head on to the Review tab and hit protected every single cell in the worksheet gets protected and no one can make any changes. But if you want the user to be able to edit certain cells and leave the rest unedited then follow these steps :"
},
{
"code": null,
"e": 3135,
"s": 3091,
"text": "Step 1: Open the file you want to protect. "
},
{
"code": null,
"e": 3264,
"s": 3135,
"text": "Step 2: Select the cells from the file that you want the users to be able to edit and make changes to(cells you want to unlock)."
},
{
"code": null,
"e": 3386,
"s": 3264,
"text": "Step 3: Then under the font section click on the arrow pointing downwards icon on the bottom-right (called font settings)"
},
{
"code": null,
"e": 3523,
"s": 3386,
"text": "Step 4: As the Format cells dialog box opens up, head on to Protection, turn off the locked property for the selected cells, and hit ok."
},
{
"code": null,
"e": 3687,
"s": 3523,
"text": "These cells are no longer locked and can be edited by the user. Deciding which cells should be locked and which shouldn’t is important while protecting the sheets."
},
{
"code": null,
"e": 3923,
"s": 3687,
"text": "Step 5: Head on to the Review tab > Protect sheet. This opens a protect sheet dialog and prompts you to enter a password for the sheet. You can check the boxes you want the user to be able to edit after protection and uncheck the rest."
},
{
"code": null,
"e": 3989,
"s": 3923,
"text": "Step 6: Hit OK and confirm password (don’t lose this password). "
},
{
"code": null,
"e": 4061,
"s": 3989,
"text": "Step 7: Click ok and re-enter the password to confirm and hit OK again."
},
{
"code": null,
"e": 4165,
"s": 4061,
"text": "According to the situation at hand, you can protect your worksheet or workbook in one of the many ways."
},
{
"code": null,
"e": 4171,
"s": 4165,
"text": "Excel"
}
] |
How do we use checkbox buttons in HTML forms? | Using HTML forms, you can easily take user input. The <form> tag is used to get user input, by adding the form elements. Different types of form elements include text input, radio button input, submit button, etc.
Let’s learn about how to use radio checkbox in HTML forms to get user input. Checkboxes are used when more than one option is required to be selected. They are also created using HTML <input> tag but type attribute is set to a checkbox.
Here are the attributes −
You can try to run the following code to learn how to work with checkbox buttons in HTML −
Live Demo
<!DOCTYPE html>
<html>
<body>
<head>
<title>HTML Checkbox Button</title>
</head>
<p>Which languages you work on:</p>
<form>
<input type="checkbox" name="language1" value="java">Java
<br>
<input type="checkbox" name="language2" value="php">PHP
<br>
<input type="checkbox" name="language3" value="cpp">C++
<br>
</form>
</body>
</html> | [
{
"code": null,
"e": 1401,
"s": 1187,
"text": "Using HTML forms, you can easily take user input. The <form> tag is used to get user input, by adding the form elements. Different types of form elements include text input, radio button input, submit button, etc."
},
{
"code": null,
"e": 1638,
"s": 1401,
"text": "Let’s learn about how to use radio checkbox in HTML forms to get user input. Checkboxes are used when more than one option is required to be selected. They are also created using HTML <input> tag but type attribute is set to a checkbox."
},
{
"code": null,
"e": 1664,
"s": 1638,
"text": "Here are the attributes −"
},
{
"code": null,
"e": 1756,
"s": 1664,
"text": "You can try to run the following code to learn how to work with checkbox buttons in HTML −"
},
{
"code": null,
"e": 1766,
"s": 1756,
"text": "Live Demo"
},
{
"code": null,
"e": 2198,
"s": 1766,
"text": "<!DOCTYPE html>\n<html>\n <body>\n <head>\n <title>HTML Checkbox Button</title>\n </head>\n <p>Which languages you work on:</p>\n <form>\n <input type=\"checkbox\" name=\"language1\" value=\"java\">Java\n <br>\n <input type=\"checkbox\" name=\"language2\" value=\"php\">PHP\n <br>\n <input type=\"checkbox\" name=\"language3\" value=\"cpp\">C++\n <br>\n </form>\n </body>\n</html>"
}
] |
Differences between SQL and SQLite | 13 Aug, 2020
1. Structured Query Language (SQL) :SQL stands for Structured Query Language. SQL can access, created and manage databases. SQL has became standard of American National Standards Institute.
2. SQLite :SQLite is software which provides relational database management system. SQLite lightweight in terms of setup, database administration, and required resources. SQLite has features like self-contained, server-less, zero-configuration, etc.
Differences between SQL and SQLite :
DBMS-SQL
DBMS
Difference Between
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
Introduction of DBMS (Database Management System) | Set 1
SQL Trigger | Student Database
Introduction of B-Tree
Class method vs Static method in Python
Difference between BFS and DFS
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Differences between JDK, JRE and JVM | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n13 Aug, 2020"
},
{
"code": null,
"e": 243,
"s": 53,
"text": "1. Structured Query Language (SQL) :SQL stands for Structured Query Language. SQL can access, created and manage databases. SQL has became standard of American National Standards Institute."
},
{
"code": null,
"e": 493,
"s": 243,
"text": "2. SQLite :SQLite is software which provides relational database management system. SQLite lightweight in terms of setup, database administration, and required resources. SQLite has features like self-contained, server-less, zero-configuration, etc."
},
{
"code": null,
"e": 530,
"s": 493,
"text": "Differences between SQL and SQLite :"
},
{
"code": null,
"e": 539,
"s": 530,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 544,
"s": 539,
"text": "DBMS"
},
{
"code": null,
"e": 563,
"s": 544,
"text": "Difference Between"
},
{
"code": null,
"e": 567,
"s": 563,
"text": "SQL"
},
{
"code": null,
"e": 572,
"s": 567,
"text": "DBMS"
},
{
"code": null,
"e": 576,
"s": 572,
"text": "SQL"
},
{
"code": null,
"e": 674,
"s": 576,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 685,
"s": 674,
"text": "CTE in SQL"
},
{
"code": null,
"e": 738,
"s": 685,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 796,
"s": 738,
"text": "Introduction of DBMS (Database Management System) | Set 1"
},
{
"code": null,
"e": 827,
"s": 796,
"text": "SQL Trigger | Student Database"
},
{
"code": null,
"e": 850,
"s": 827,
"text": "Introduction of B-Tree"
},
{
"code": null,
"e": 890,
"s": 850,
"text": "Class method vs Static method in Python"
},
{
"code": null,
"e": 921,
"s": 890,
"text": "Difference between BFS and DFS"
},
{
"code": null,
"e": 982,
"s": 921,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1050,
"s": 982,
"text": "Difference Between Method Overloading and Method Overriding in Java"
}
] |
Python – Filter list elements starting with given Prefix | 30 Jun, 2020
Sometimes, we need to filter the list with the first character of each string in the list. This type of task has many applications in day-day programming and even in the competitive programming domain. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using list comprehension + startswith()In this method, we use list comprehension for traversal logic and the startswith method to filter out all the strings that starts with a particular letter. The remaining strings can be used to make a different list.
# Python3 code to demonstrate# Prefix Separation# Using list comprehension + startswith() # initializing listtest_list = ['sapple', 'orange', 'smango', 'grape'] # initializing start Prefixstart_letter = 's' # printing original listprint("The original list : " + str(test_list)) # using list comprehension + startswith()# Prefix Separationwith_s = [x for x in test_list if x.startswith(start_letter)]without_s = [x for x in test_list if x not in with_s] # print resultprint("The list without prefix s : " + str(without_s))print("The list with prefix s : " + str(with_s))
The original list : ['sapple', 'orange', 'smango', 'grape']
The list without prefix s : ['orange', 'grape']
The list with prefix s : ['sapple', 'smango']
Method #2 : Using filter() + lambda + startswith()This task can be performed using the filter function with performs the similar task internally as the above function and lambda is helper function to build the logic.
# Python3 code to demonstrate# Prefix Separation# Using filter() + startswith() + lambda # initializing listtest_list = ['sapple', 'orange', 'smango', 'grape'] # initializing start Prefixstart_letter = 's' # printing original listprint("The original list : " + str(test_list)) # using filter() + startswith() + lambda# Prefix Separationwith_s = list(filter(lambda x: x.startswith(start_letter), test_list))without_s = list(filter(lambda x: not x.startswith(start_letter), test_list)) # print resultprint("The list without prefix s : " + str(without_s))print("The list with prefix s : " + str(with_s))
The original list : ['sapple', 'orange', 'smango', 'grape']
The list without prefix s : ['orange', 'grape']
The list with prefix s : ['sapple', 'smango']
nidhi_biet
Python list-programs
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate over a list in Python
How to iterate through Excel rows in Python?
Enumerate() in Python
Rotate axis tick labels in Seaborn and Matplotlib
Python Dictionary
Deque in Python
Stack in Python
Queue in Python
Read a file line by line in Python
Defaultdict in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Jun, 2020"
},
{
"code": null,
"e": 294,
"s": 28,
"text": "Sometimes, we need to filter the list with the first character of each string in the list. This type of task has many applications in day-day programming and even in the competitive programming domain. Let’s discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 561,
"s": 294,
"text": "Method #1 : Using list comprehension + startswith()In this method, we use list comprehension for traversal logic and the startswith method to filter out all the strings that starts with a particular letter. The remaining strings can be used to make a different list."
},
{
"code": "# Python3 code to demonstrate# Prefix Separation# Using list comprehension + startswith() # initializing listtest_list = ['sapple', 'orange', 'smango', 'grape'] # initializing start Prefixstart_letter = 's' # printing original listprint(\"The original list : \" + str(test_list)) # using list comprehension + startswith()# Prefix Separationwith_s = [x for x in test_list if x.startswith(start_letter)]without_s = [x for x in test_list if x not in with_s] # print resultprint(\"The list without prefix s : \" + str(without_s))print(\"The list with prefix s : \" + str(with_s))",
"e": 1136,
"s": 561,
"text": null
},
{
"code": null,
"e": 1291,
"s": 1136,
"text": "The original list : ['sapple', 'orange', 'smango', 'grape']\nThe list without prefix s : ['orange', 'grape']\nThe list with prefix s : ['sapple', 'smango']\n"
},
{
"code": null,
"e": 1510,
"s": 1293,
"text": "Method #2 : Using filter() + lambda + startswith()This task can be performed using the filter function with performs the similar task internally as the above function and lambda is helper function to build the logic."
},
{
"code": "# Python3 code to demonstrate# Prefix Separation# Using filter() + startswith() + lambda # initializing listtest_list = ['sapple', 'orange', 'smango', 'grape'] # initializing start Prefixstart_letter = 's' # printing original listprint(\"The original list : \" + str(test_list)) # using filter() + startswith() + lambda# Prefix Separationwith_s = list(filter(lambda x: x.startswith(start_letter), test_list))without_s = list(filter(lambda x: not x.startswith(start_letter), test_list)) # print resultprint(\"The list without prefix s : \" + str(without_s))print(\"The list with prefix s : \" + str(with_s))",
"e": 2116,
"s": 1510,
"text": null
},
{
"code": null,
"e": 2271,
"s": 2116,
"text": "The original list : ['sapple', 'orange', 'smango', 'grape']\nThe list without prefix s : ['orange', 'grape']\nThe list with prefix s : ['sapple', 'smango']\n"
},
{
"code": null,
"e": 2282,
"s": 2271,
"text": "nidhi_biet"
},
{
"code": null,
"e": 2303,
"s": 2282,
"text": "Python list-programs"
},
{
"code": null,
"e": 2310,
"s": 2303,
"text": "Python"
},
{
"code": null,
"e": 2408,
"s": 2310,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2438,
"s": 2408,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 2483,
"s": 2438,
"text": "How to iterate through Excel rows in Python?"
},
{
"code": null,
"e": 2505,
"s": 2483,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2555,
"s": 2505,
"text": "Rotate axis tick labels in Seaborn and Matplotlib"
},
{
"code": null,
"e": 2573,
"s": 2555,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2589,
"s": 2573,
"text": "Deque in Python"
},
{
"code": null,
"e": 2605,
"s": 2589,
"text": "Stack in Python"
},
{
"code": null,
"e": 2621,
"s": 2605,
"text": "Queue in Python"
},
{
"code": null,
"e": 2656,
"s": 2621,
"text": "Read a file line by line in Python"
}
] |
Fibonacci modulo p - GeeksforGeeks | 24 Mar, 2021
The Fibonacci sequence is defined as = + where = 1 and = 1 are the seeds. For a given prime number p, consider a new sequence which is (Fibonacci sequence) mod p. For example for p = 5, the new sequence would be 1, 1, 2, 3, 0, 3, 3, 1, 4, 0, 4, 4 ... The minimal zero of the new sequence is defined as the first Fibonacci number that is a multiple of p or mod p = 0. Given prime no p, find the minimal zero of the sequence Fibonacci modulo p.Examples:
Input : 5
Output : 5
The fifth Fibonacci no (1 1 2 3 5)
is divisible by 5 so 5 % 5 = 0.
Input : 7
Output : 8
The 8th Fibonacci no (1 1 2 3 5 8 13 21)
is divisible by 7 so 21 % 7 = 0.
A simple approach is to keep calculating Fibonacci numbers and for each of them calculate Fi mod p. However if we observe this new sequence, let denote the term of the sequence, then it follows : = (+ ) mod p. i.e. the remainder is actually the sum of remainders of previous two terms of this series. Therefore instead of generating the Fibonacci sequence and then taking modulo of each term we simply add previous two remainders and then take its modulo p. Below is the implementation to find the minimal 0.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find minimal 0 Fibonacci// for a prime number p#include<bits/stdc++.h>using namespace std; // Returns position of first Fibonacci number// whose modulo p is 0.int findMinZero(int p){ int first = 1, second = 1, number = 2, next = 1; while (next) { next = (first + second) % p; first = second; second = next; number++; } return number;} // Driver codeint main(){ int p = 7; cout << "Minimal zero is: " << findMinZero(p) << endl; return 0;}
// Java program to find minimal 0 Fibonacci// for a prime number pimport java.io.*; class FibZero{ // Function that returns position of first Fibonacci number // whose modulo p is 0 static int findMinZero(int p) { int first = 1, second = 1, number = 2, next = 1; while (next > 0) { // add previous two remainders and // then take its modulo p. next = (first + second) % p; first = second; second = next; number++; } return number; } // Driver program public static void main (String[] args) { int p = 7; System.out.println("Minimal zero is " + findMinZero(p)); }}
# Python 3 program to find minimal# 0 Fibonacci for a prime number p # Returns position of first Fibonacci# number whose modulo p is 0.def findMinZero(p): first = 1 second = 1 number = 2 next = 1 while (next): next = (first + second) % p first = second second = next number = number + 1 return number # Driver codeif __name__ == '__main__': p = 7 print("Minimal zero is:", findMinZero(p)) # This code is contributed by# Surendra_Gangwar
// C# program to find minimal 0// Fibonacci for a prime number pusing System; class GFG { // Function that returns position // of first Fibonacci number // whose modulo p is 0 static int findMinZero(int p) { int first = 1, second = 1; int number = 2, next = 1; while (next > 0) { // add previous two // remainders and then // take its modulo p. next = (first + second) % p; first = second; second = next; number++; } return number; } // Driver program public static void Main () { int p = 7; Console.WriteLine("Minimal zero " + "is :" + findMinZero(p)); }} // This code is contributed by anuj_67.
<?php// PHP program to find// minimal 0 Fibonacci// for a prime number p // Returns position of// first Fibonacci number// whose modulo p is 0.function findMinZero($p){ $first = 1; $second = 1; $number = 2; $next = 1; while ($next) { $next = ($first + $second) % $p; $first = $second; $second = $next; $number++; } return $number;} // Driver code$p = 7;echo "Minimal zero is: ", findMinZero($p), "\n"; // This code is contributed// by akt_mit?>
<script>// Javascript program to find// minimal 0 Fibonacci// for a prime number p // Returns position of// first Fibonacci number// whose modulo p is 0.function findMinZero(p){ let first = 1; let second = 1; let number = 2; let next = 1; while (next) { next = (first + second) % p; first = second; second = next; number++; } return number;} // Driver codelet p = 7;document.write("Minimal zero is: ", findMinZero(p) + "<br>"); // This code is contributed// by akt_mit</script>
Output:
Minimal zero is: 8
This article is contributed by Aditi Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
vt_m
jit_t
SURENDRA_GANGWAR
_saurabh_jaiswal
Fibonacci
Modular Arithmetic
Mathematical
Mathematical
Fibonacci
Modular Arithmetic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Prime Numbers
Print all possible combinations of r elements in a given array of size n
The Knight's tour problem | Backtracking-1
Operators in C / C++
Program for factorial of a number
Program to find sum of elements in a given array
Minimum number of jumps to reach end
Program to print prime numbers from 1 to N. | [
{
"code": null,
"e": 25886,
"s": 25858,
"text": "\n24 Mar, 2021"
},
{
"code": null,
"e": 26340,
"s": 25886,
"text": "The Fibonacci sequence is defined as = + where = 1 and = 1 are the seeds. For a given prime number p, consider a new sequence which is (Fibonacci sequence) mod p. For example for p = 5, the new sequence would be 1, 1, 2, 3, 0, 3, 3, 1, 4, 0, 4, 4 ... The minimal zero of the new sequence is defined as the first Fibonacci number that is a multiple of p or mod p = 0. Given prime no p, find the minimal zero of the sequence Fibonacci modulo p.Examples: "
},
{
"code": null,
"e": 26526,
"s": 26340,
"text": "Input : 5\nOutput : 5\nThe fifth Fibonacci no (1 1 2 3 5) \nis divisible by 5 so 5 % 5 = 0.\n\nInput : 7\nOutput : 8\nThe 8th Fibonacci no (1 1 2 3 5 8 13 21) \nis divisible by 7 so 21 % 7 = 0."
},
{
"code": null,
"e": 27039,
"s": 26528,
"text": "A simple approach is to keep calculating Fibonacci numbers and for each of them calculate Fi mod p. However if we observe this new sequence, let denote the term of the sequence, then it follows : = (+ ) mod p. i.e. the remainder is actually the sum of remainders of previous two terms of this series. Therefore instead of generating the Fibonacci sequence and then taking modulo of each term we simply add previous two remainders and then take its modulo p. Below is the implementation to find the minimal 0. "
},
{
"code": null,
"e": 27043,
"s": 27039,
"text": "C++"
},
{
"code": null,
"e": 27048,
"s": 27043,
"text": "Java"
},
{
"code": null,
"e": 27056,
"s": 27048,
"text": "Python3"
},
{
"code": null,
"e": 27059,
"s": 27056,
"text": "C#"
},
{
"code": null,
"e": 27063,
"s": 27059,
"text": "PHP"
},
{
"code": null,
"e": 27074,
"s": 27063,
"text": "Javascript"
},
{
"code": "// C++ program to find minimal 0 Fibonacci// for a prime number p#include<bits/stdc++.h>using namespace std; // Returns position of first Fibonacci number// whose modulo p is 0.int findMinZero(int p){ int first = 1, second = 1, number = 2, next = 1; while (next) { next = (first + second) % p; first = second; second = next; number++; } return number;} // Driver codeint main(){ int p = 7; cout << \"Minimal zero is: \" << findMinZero(p) << endl; return 0;}",
"e": 27589,
"s": 27074,
"text": null
},
{
"code": "// Java program to find minimal 0 Fibonacci// for a prime number pimport java.io.*; class FibZero{ // Function that returns position of first Fibonacci number // whose modulo p is 0 static int findMinZero(int p) { int first = 1, second = 1, number = 2, next = 1; while (next > 0) { // add previous two remainders and // then take its modulo p. next = (first + second) % p; first = second; second = next; number++; } return number; } // Driver program public static void main (String[] args) { int p = 7; System.out.println(\"Minimal zero is \" + findMinZero(p)); }}",
"e": 28300,
"s": 27589,
"text": null
},
{
"code": "# Python 3 program to find minimal# 0 Fibonacci for a prime number p # Returns position of first Fibonacci# number whose modulo p is 0.def findMinZero(p): first = 1 second = 1 number = 2 next = 1 while (next): next = (first + second) % p first = second second = next number = number + 1 return number # Driver codeif __name__ == '__main__': p = 7 print(\"Minimal zero is:\", findMinZero(p)) # This code is contributed by# Surendra_Gangwar",
"e": 28795,
"s": 28300,
"text": null
},
{
"code": "// C# program to find minimal 0// Fibonacci for a prime number pusing System; class GFG { // Function that returns position // of first Fibonacci number // whose modulo p is 0 static int findMinZero(int p) { int first = 1, second = 1; int number = 2, next = 1; while (next > 0) { // add previous two // remainders and then // take its modulo p. next = (first + second) % p; first = second; second = next; number++; } return number; } // Driver program public static void Main () { int p = 7; Console.WriteLine(\"Minimal zero \" + \"is :\" + findMinZero(p)); }} // This code is contributed by anuj_67.",
"e": 29591,
"s": 28795,
"text": null
},
{
"code": "<?php// PHP program to find// minimal 0 Fibonacci// for a prime number p // Returns position of// first Fibonacci number// whose modulo p is 0.function findMinZero($p){ $first = 1; $second = 1; $number = 2; $next = 1; while ($next) { $next = ($first + $second) % $p; $first = $second; $second = $next; $number++; } return $number;} // Driver code$p = 7;echo \"Minimal zero is: \", findMinZero($p), \"\\n\"; // This code is contributed// by akt_mit?>",
"e": 30108,
"s": 29591,
"text": null
},
{
"code": "<script>// Javascript program to find// minimal 0 Fibonacci// for a prime number p // Returns position of// first Fibonacci number// whose modulo p is 0.function findMinZero(p){ let first = 1; let second = 1; let number = 2; let next = 1; while (next) { next = (first + second) % p; first = second; second = next; number++; } return number;} // Driver codelet p = 7;document.write(\"Minimal zero is: \", findMinZero(p) + \"<br>\"); // This code is contributed// by akt_mit</script>",
"e": 30657,
"s": 30108,
"text": null
},
{
"code": null,
"e": 30667,
"s": 30657,
"text": "Output: "
},
{
"code": null,
"e": 30686,
"s": 30667,
"text": "Minimal zero is: 8"
},
{
"code": null,
"e": 31111,
"s": 30686,
"text": "This article is contributed by Aditi Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 31116,
"s": 31111,
"text": "vt_m"
},
{
"code": null,
"e": 31122,
"s": 31116,
"text": "jit_t"
},
{
"code": null,
"e": 31139,
"s": 31122,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 31156,
"s": 31139,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 31166,
"s": 31156,
"text": "Fibonacci"
},
{
"code": null,
"e": 31185,
"s": 31166,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 31198,
"s": 31185,
"text": "Mathematical"
},
{
"code": null,
"e": 31211,
"s": 31198,
"text": "Mathematical"
},
{
"code": null,
"e": 31221,
"s": 31211,
"text": "Fibonacci"
},
{
"code": null,
"e": 31240,
"s": 31221,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 31338,
"s": 31240,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31362,
"s": 31338,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 31405,
"s": 31362,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 31419,
"s": 31405,
"text": "Prime Numbers"
},
{
"code": null,
"e": 31492,
"s": 31419,
"text": "Print all possible combinations of r elements in a given array of size n"
},
{
"code": null,
"e": 31535,
"s": 31492,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 31556,
"s": 31535,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 31590,
"s": 31556,
"text": "Program for factorial of a number"
},
{
"code": null,
"e": 31639,
"s": 31590,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 31676,
"s": 31639,
"text": "Minimum number of jumps to reach end"
}
] |
Python - Facial and hand recognition using MediaPipe Holistic - GeeksforGeeks | 03 Nov, 2021
Object Detection is one of the leading and most popular use cases in the domain of computer vision. Several object detection models are used worldwide for their particular use case applications. Many of these models have been used as an independent solution to a single computer vision task with its own fixed application. Combining several of these tasks into a single end-to-end solution, in real-time, is exactly what MediaPipe does.
MediaPipe is an open-source, cross-platform Machine Learning framework used for building complex and multimodal applied machine learning pipelines. It can be used to make cutting-edge Machine Learning Models like face detection, multi-hand tracking, object detection, and tracking, and many more. MediaPipe basically acts as a mediator for handling the implementation of models for systems running on any platform which helps the developer focus more on experimenting with models, than on the system.
Human Pose Detection and Tracking High-fidelity human body pose tracking, inferring a minimum of 25 2D upper-body landmarks from RGB video framesFace Mesh 468 face landmarks in 3D with multi-face supportHand Tracking 21 landmarks in 3D with multi-hand support, based on high-performance palm detection and hand landmark modelHolistic Tracking Simultaneous and semantically consistent tracking of 33 pose, 21 per-hand, and 468 facial landmarksHair Segmentation Super realistic real-time hair recoloringObject Detection and Tracking Detection and tracking of objects in the video in a single pipelineFace Detection Ultra-lightweight face detector with 6 landmarks and multi-face supportIris Tracking and Depth Estimation Accurate human iris tracking and metric depth estimation without specialized hardware. Tracks iris, pupil, and eye contour landmarks.3D Object Detection Detection and 3D pose estimation of everyday objects like shoes and chairs
Human Pose Detection and Tracking High-fidelity human body pose tracking, inferring a minimum of 25 2D upper-body landmarks from RGB video frames
Face Mesh 468 face landmarks in 3D with multi-face support
Hand Tracking 21 landmarks in 3D with multi-hand support, based on high-performance palm detection and hand landmark model
Holistic Tracking Simultaneous and semantically consistent tracking of 33 pose, 21 per-hand, and 468 facial landmarks
Hair Segmentation Super realistic real-time hair recoloring
Object Detection and Tracking Detection and tracking of objects in the video in a single pipeline
Face Detection Ultra-lightweight face detector with 6 landmarks and multi-face support
Iris Tracking and Depth Estimation Accurate human iris tracking and metric depth estimation without specialized hardware. Tracks iris, pupil, and eye contour landmarks.
3D Object Detection Detection and 3D pose estimation of everyday objects like shoes and chairs
Mediapipe Holistic is one of the pipelines which contains optimized face, hands, and pose components which allows for holistic tracking, thus enabling the model to simultaneously detect hand and body poses along with face landmarks. one of the main usages of MediaPipe holistic is to detect face and hands and extract key points to pass on to a computer vision model.
The following code snippet is a function to access image input from system web camera using OpenCV framework, detect hand and facial landmarks and extract key points.
Python3
'''Install dependenciespip install opencv-pythonpip install mediapipe'''# Import packagesimport cv2import mediapipe as mp #Build Keypoints using MP Holisticmp_holistic = mp.solutions.holistic # Holistic modelmp_drawing = mp.solutions.drawing_utils # Drawing utilities def mediapipe_detection(image, model): image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # COLOR CONVERSION BGR 2 RGB image.flags.writable = False # Image is no longer writable results = model.process(image) # Make prediction image.flags.writable = True # Image is now writable image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) # COLOR CONVERSION RGB 2 BGR return image, results def draw_landmarks(image, results): mp_drawing.draw_landmarks( image, results.face_landmarks, mp_holistic.FACE_CONNECTIONS) # Draw face connections mp_drawing.draw_landmarks( image, results.pose_landmarks, mp_holistic.POSE_CONNECTIONS) # Draw pose connections mp_drawing.draw_landmarks( image, results.left_hand_landmarks, mp_holistic.HAND_CONNECTIONS) # Draw left hand connections mp_drawing.draw_landmarks( image, results.right_hand_landmarks, mp_holistic.HAND_CONNECTIONS) # Draw right hand connections def draw_styled_landmarks(image, results): # Draw face connections mp_drawing.draw_landmarks( image, results.face_landmarks, mp_holistic.FACE_CONNECTIONS, mp_drawing.DrawingSpec(color=(80,110,10), thickness=1, circle_radius=1), mp_drawing.DrawingSpec(color=(80,256,121), thickness=1, circle_radius=1)) # Draw pose connections mp_drawing.draw_landmarks(image, results.pose_landmarks, mp_holistic.POSE_CONNECTIONS, mp_drawing.DrawingSpec(color=(80,22,10), thickness=2, circle_radius=4), mp_drawing.DrawingSpec(color=(80,44,121), thickness=2, circle_radius=2) ) # Draw left hand connections mp_drawing.draw_landmarks(image, results.left_hand_landmarks, mp_holistic.HAND_CONNECTIONS, mp_drawing.DrawingSpec(color=(121,22,76), thickness=2, circle_radius=4), mp_drawing.DrawingSpec(color=(121,44,250), thickness=2, circle_radius=2) ) # Draw right hand connections mp_drawing.draw_landmarks(image, results.right_hand_landmarks, mp_holistic.HAND_CONNECTIONS, mp_drawing.DrawingSpec(color=(245,117,66), thickness=2, circle_radius=4), mp_drawing.DrawingSpec(color=(245,66,230), thickness=2, circle_radius=2) )#Main functioncap = cv2.VideoCapture(0)# Set mediapipe modelwith mp_holistic.Holistic(min_detection_confidence=0.5, min_tracking_confidence=0.5) as holistic: while cap.isOpened(): # Read feed ret, frame = cap.read() # Make detections image, results = mediapipe_detection(frame, holistic) print(results) # Draw landmarks draw_styled_landmarks(image, results) # Show to screen cv2.imshow('OpenCV Feed', image) # Break gracefully if cv2.waitKey(10) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows()
Credit: MediaPipe
Credit: MediaPipe
Image generated using the mediapipe function posted above and plotted on a graphical plane using matplotlib. Source: Author
sagartomar9927
sagar0719kumar
Blogathon-2021
OpenCV
Blogathon
Machine Learning
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Create a Table With Multiple Foreign Keys in SQL?
How to Import JSON Data into SQL Server?
Stratified Sampling in Pandas
How to Install Tkinter in Windows?
Python program to convert XML to Dictionary
Naive Bayes Classifiers
Linear Regression (Python Implementation)
ML | Linear Regression
Reinforcement learning
Removing stop words with NLTK in Python | [
{
"code": null,
"e": 26123,
"s": 26095,
"text": "\n03 Nov, 2021"
},
{
"code": null,
"e": 26560,
"s": 26123,
"text": "Object Detection is one of the leading and most popular use cases in the domain of computer vision. Several object detection models are used worldwide for their particular use case applications. Many of these models have been used as an independent solution to a single computer vision task with its own fixed application. Combining several of these tasks into a single end-to-end solution, in real-time, is exactly what MediaPipe does."
},
{
"code": null,
"e": 27061,
"s": 26560,
"text": "MediaPipe is an open-source, cross-platform Machine Learning framework used for building complex and multimodal applied machine learning pipelines. It can be used to make cutting-edge Machine Learning Models like face detection, multi-hand tracking, object detection, and tracking, and many more. MediaPipe basically acts as a mediator for handling the implementation of models for systems running on any platform which helps the developer focus more on experimenting with models, than on the system."
},
{
"code": null,
"e": 28008,
"s": 27061,
"text": "Human Pose Detection and Tracking High-fidelity human body pose tracking, inferring a minimum of 25 2D upper-body landmarks from RGB video framesFace Mesh 468 face landmarks in 3D with multi-face supportHand Tracking 21 landmarks in 3D with multi-hand support, based on high-performance palm detection and hand landmark modelHolistic Tracking Simultaneous and semantically consistent tracking of 33 pose, 21 per-hand, and 468 facial landmarksHair Segmentation Super realistic real-time hair recoloringObject Detection and Tracking Detection and tracking of objects in the video in a single pipelineFace Detection Ultra-lightweight face detector with 6 landmarks and multi-face supportIris Tracking and Depth Estimation Accurate human iris tracking and metric depth estimation without specialized hardware. Tracks iris, pupil, and eye contour landmarks.3D Object Detection Detection and 3D pose estimation of everyday objects like shoes and chairs"
},
{
"code": null,
"e": 28154,
"s": 28008,
"text": "Human Pose Detection and Tracking High-fidelity human body pose tracking, inferring a minimum of 25 2D upper-body landmarks from RGB video frames"
},
{
"code": null,
"e": 28213,
"s": 28154,
"text": "Face Mesh 468 face landmarks in 3D with multi-face support"
},
{
"code": null,
"e": 28336,
"s": 28213,
"text": "Hand Tracking 21 landmarks in 3D with multi-hand support, based on high-performance palm detection and hand landmark model"
},
{
"code": null,
"e": 28454,
"s": 28336,
"text": "Holistic Tracking Simultaneous and semantically consistent tracking of 33 pose, 21 per-hand, and 468 facial landmarks"
},
{
"code": null,
"e": 28514,
"s": 28454,
"text": "Hair Segmentation Super realistic real-time hair recoloring"
},
{
"code": null,
"e": 28612,
"s": 28514,
"text": "Object Detection and Tracking Detection and tracking of objects in the video in a single pipeline"
},
{
"code": null,
"e": 28699,
"s": 28612,
"text": "Face Detection Ultra-lightweight face detector with 6 landmarks and multi-face support"
},
{
"code": null,
"e": 28868,
"s": 28699,
"text": "Iris Tracking and Depth Estimation Accurate human iris tracking and metric depth estimation without specialized hardware. Tracks iris, pupil, and eye contour landmarks."
},
{
"code": null,
"e": 28963,
"s": 28868,
"text": "3D Object Detection Detection and 3D pose estimation of everyday objects like shoes and chairs"
},
{
"code": null,
"e": 29331,
"s": 28963,
"text": "Mediapipe Holistic is one of the pipelines which contains optimized face, hands, and pose components which allows for holistic tracking, thus enabling the model to simultaneously detect hand and body poses along with face landmarks. one of the main usages of MediaPipe holistic is to detect face and hands and extract key points to pass on to a computer vision model."
},
{
"code": null,
"e": 29498,
"s": 29331,
"text": "The following code snippet is a function to access image input from system web camera using OpenCV framework, detect hand and facial landmarks and extract key points."
},
{
"code": null,
"e": 29506,
"s": 29498,
"text": "Python3"
},
{
"code": "'''Install dependenciespip install opencv-pythonpip install mediapipe'''# Import packagesimport cv2import mediapipe as mp #Build Keypoints using MP Holisticmp_holistic = mp.solutions.holistic # Holistic modelmp_drawing = mp.solutions.drawing_utils # Drawing utilities def mediapipe_detection(image, model): image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # COLOR CONVERSION BGR 2 RGB image.flags.writable = False # Image is no longer writable results = model.process(image) # Make prediction image.flags.writable = True # Image is now writable image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) # COLOR CONVERSION RGB 2 BGR return image, results def draw_landmarks(image, results): mp_drawing.draw_landmarks( image, results.face_landmarks, mp_holistic.FACE_CONNECTIONS) # Draw face connections mp_drawing.draw_landmarks( image, results.pose_landmarks, mp_holistic.POSE_CONNECTIONS) # Draw pose connections mp_drawing.draw_landmarks( image, results.left_hand_landmarks, mp_holistic.HAND_CONNECTIONS) # Draw left hand connections mp_drawing.draw_landmarks( image, results.right_hand_landmarks, mp_holistic.HAND_CONNECTIONS) # Draw right hand connections def draw_styled_landmarks(image, results): # Draw face connections mp_drawing.draw_landmarks( image, results.face_landmarks, mp_holistic.FACE_CONNECTIONS, mp_drawing.DrawingSpec(color=(80,110,10), thickness=1, circle_radius=1), mp_drawing.DrawingSpec(color=(80,256,121), thickness=1, circle_radius=1)) # Draw pose connections mp_drawing.draw_landmarks(image, results.pose_landmarks, mp_holistic.POSE_CONNECTIONS, mp_drawing.DrawingSpec(color=(80,22,10), thickness=2, circle_radius=4), mp_drawing.DrawingSpec(color=(80,44,121), thickness=2, circle_radius=2) ) # Draw left hand connections mp_drawing.draw_landmarks(image, results.left_hand_landmarks, mp_holistic.HAND_CONNECTIONS, mp_drawing.DrawingSpec(color=(121,22,76), thickness=2, circle_radius=4), mp_drawing.DrawingSpec(color=(121,44,250), thickness=2, circle_radius=2) ) # Draw right hand connections mp_drawing.draw_landmarks(image, results.right_hand_landmarks, mp_holistic.HAND_CONNECTIONS, mp_drawing.DrawingSpec(color=(245,117,66), thickness=2, circle_radius=4), mp_drawing.DrawingSpec(color=(245,66,230), thickness=2, circle_radius=2) )#Main functioncap = cv2.VideoCapture(0)# Set mediapipe modelwith mp_holistic.Holistic(min_detection_confidence=0.5, min_tracking_confidence=0.5) as holistic: while cap.isOpened(): # Read feed ret, frame = cap.read() # Make detections image, results = mediapipe_detection(frame, holistic) print(results) # Draw landmarks draw_styled_landmarks(image, results) # Show to screen cv2.imshow('OpenCV Feed', image) # Break gracefully if cv2.waitKey(10) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows()",
"e": 32771,
"s": 29506,
"text": null
},
{
"code": null,
"e": 32789,
"s": 32771,
"text": "Credit: MediaPipe"
},
{
"code": null,
"e": 32807,
"s": 32789,
"text": "Credit: MediaPipe"
},
{
"code": null,
"e": 32943,
"s": 32807,
"text": "Image generated using the mediapipe function posted above and plotted on a graphical plane using matplotlib. Source: Author"
},
{
"code": null,
"e": 32960,
"s": 32945,
"text": "sagartomar9927"
},
{
"code": null,
"e": 32975,
"s": 32960,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 32990,
"s": 32975,
"text": "Blogathon-2021"
},
{
"code": null,
"e": 32997,
"s": 32990,
"text": "OpenCV"
},
{
"code": null,
"e": 33007,
"s": 32997,
"text": "Blogathon"
},
{
"code": null,
"e": 33024,
"s": 33007,
"text": "Machine Learning"
},
{
"code": null,
"e": 33041,
"s": 33024,
"text": "Machine Learning"
},
{
"code": null,
"e": 33139,
"s": 33041,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33196,
"s": 33139,
"text": "How to Create a Table With Multiple Foreign Keys in SQL?"
},
{
"code": null,
"e": 33237,
"s": 33196,
"text": "How to Import JSON Data into SQL Server?"
},
{
"code": null,
"e": 33267,
"s": 33237,
"text": "Stratified Sampling in Pandas"
},
{
"code": null,
"e": 33302,
"s": 33267,
"text": "How to Install Tkinter in Windows?"
},
{
"code": null,
"e": 33346,
"s": 33302,
"text": "Python program to convert XML to Dictionary"
},
{
"code": null,
"e": 33370,
"s": 33346,
"text": "Naive Bayes Classifiers"
},
{
"code": null,
"e": 33412,
"s": 33370,
"text": "Linear Regression (Python Implementation)"
},
{
"code": null,
"e": 33435,
"s": 33412,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 33458,
"s": 33435,
"text": "Reinforcement learning"
}
] |
Sum of Factors of a Number using Prime Factorization - GeeksforGeeks | 19 May, 2021
Given a number N. The task is to find the sum of all factors of the given number N.
Examples:
Input : N = 12
Output : 28
All factors of 12 are: 1,2,3,4,6,12
Input : 60
Output : 168
Approach: Suppose N = 1100, the idea is to first find the prime factorization of the given number N. Therefore, the prime factorization of 1100 = 22 * 52 * 11.So, the formula to calculate the sum of all factors can be given as,
(20 + 21 + 22) * (50 + 51 + 52) * (110 + 111) (upto the power of factor in factorization i.e. power of 2 and 5 is 2 and 11 is 1.) = (1 + 2 + 22) * (1 + 5 + 52) * (1 + 11) = 7 * 31 * 12 = 2604So, the sum of all factors of 1100 = 2604
Below is the implementation of the above approach:
C++
Java
Python 3
C#
PHP
Javascript
// C++ Program to find sum of all// factors of a given number #include <bits/stdc++.h> using namespace std; // Using SieveOfEratosthenes to find smallest prime// factor of all the numbers.// For example, if N is 10,// s[2] = s[4] = s[6] = s[10] = 2// s[3] = s[9] = 3// s[5] = 5// s[7] = 7void sieveOfEratosthenes(int N, int s[]){ // Create a boolean array "prime[0..n]" and // initialize all entries in it as false. vector<bool> prime(N + 1, false); // Initializing smallest factor equal to 2 // for all the even numbers for (int i = 2; i <= N; i += 2) s[i] = 2; // For odd numbers less then equal to n for (int i = 3; i <= N; i += 2) { if (prime[i] == false) { // s(i) for a prime is the number itself s[i] = i; // For all multiples of current prime number for (int j = i; j * i <= N; j += 2) { if (prime[i * j] == false) { prime[i * j] = true; // i is the smallest prime factor for // number "i*j". s[i * j] = i; } } } }} // Function to find sum of all prime factorsint findSum(int N){ // Declaring array to store smallest prime // factor of i at i-th index int s[N + 1]; int ans = 1; // Filling values in s[] using sieve sieveOfEratosthenes(N, s); int currFactor = s[N]; // Current prime factor of N int power = 1; // Power of current prime factor while (N > 1) { N /= s[N]; // N is now N/s[N]. If new N als has smallest // prime factor as currFactor, increment power if (currFactor == s[N]) { power++; continue; } int sum = 0; for(int i=0; i<=power; i++) sum += pow(currFactor,i); ans *= sum; // Update current prime factor as s[N] and // initializing power of factor as 1. currFactor = s[N]; power = 1; } return ans;} // Driver codeint main(){ int n = 12; cout << "Sum of the factors is : "; cout << findSum(n); return 0;}
//Java Program to find sum of all//factors of a given numberpublic class GFG { //Using SieveOfEratosthenes to find smallest prime //factor of all the numbers. //For example, if N is 10, //s[2] = s[4] = s[6] = s[10] = 2 //s[3] = s[9] = 3 //s[5] = 5 //s[7] = 7 static void sieveOfEratosthenes(int N, int s[]) { // Create a boolean array "prime[0..n]" and // initialize all entries in it as false. boolean[] prime = new boolean[N + 1]; for(int i = 0; i < N+1; i++) prime[i] = false; // Initializing smallest factor equal to 2 // for all the even numbers for (int i = 2; i <= N; i += 2) s[i] = 2; // For odd numbers less then equal to n for (int i = 3; i <= N; i += 2) { if (prime[i] == false) { // s(i) for a prime is the number itself s[i] = i; // For all multiples of current prime number for (int j = i; j * i <= N; j += 2) { if (prime[i * j] == false) { prime[i * j] = true; // i is the smallest prime factor for // number "i*j". s[i * j] = i; } } } } } //Function to find sum of all prime factors static int findSum(int N) { // Declaring array to store smallest prime // factor of i at i-th index int[] s = new int[N + 1]; int ans = 1; // Filling values in s[] using sieve sieveOfEratosthenes(N, s); int currFactor = s[N]; // Current prime factor of N int power = 1; // Power of current prime factor while (N > 1) { N /= s[N]; // N is now N/s[N]. If new N als has smallest // prime factor as currFactor, increment power if (currFactor == s[N]) { power++; continue; } int sum = 0; for(int i=0; i<=power; i++) sum += Math.pow(currFactor,i); ans *= sum; // Update current prime factor as s[N] and // initializing power of factor as 1. currFactor = s[N]; power = 1; } return ans; } //Driver code public static void main(String[] args) { int n = 12; System.out.print("Sum of the factors is : "); System.out.print(findSum(n)); }}
# Python 3 Program to find# sum of all factors of a# given number # Using SieveOfEratosthenes# to find smallest prime# factor of all the numbers.# For example, if N is 10,# s[2] = s[4] = s[6] = s[10] = 2# s[3] = s[9] = 3# s[5] = 5# s[7] = 7def sieveOfEratosthenes(N, s) : # Create a boolean list "prime[0..n]" # and initialize all entries in it # as false. prime = [False] * (N + 1) # Initializing smallest # factor equal to 2 for # all the even numbers for i in range(2, N + 1, 2) : s[i] = 2 # For odd numbers less # then equal to n for i in range(3, N + 1, 2) : if prime[i] == False : # s[i] for a prime is # the number itself s[i] = i # For all multiples of # current prime number for j in range(i, (N + 1) // i, 2) : if prime[i * j] == False : prime[i * j] = True # i is the smallest # prime factor for # number "i*j". s[i * j] = i #J += 2 # Function to find sum# of all prime factorsdef findSum(N) : # Declaring list to store # smallest prime factor of # i at i-th index s = [0] * (N + 1) ans = 1 # Filling values in s[] using # sieve function calling sieveOfEratosthenes(N, s) # Current prime factor of N currFactor = s[N] # Power of current prime factor power = 1 while N > 1 : N //= s[N] # N is now N//s[N]. If new N # also has smallest prime # factor as currFactor, # increment power if currFactor == s[N] : power += 1 continue sum = 0 for i in range(power + 1) : sum += pow(currFactor, i) ans *= sum # Update current prime factor # as s[N] and initializing # power of factor as 1. currFactor = s[N] power = 1 return ans # Driver Codeif __name__ == "__main__" : n = 12 print("Sum of the factors is :", end = " ") print(findSum(n)) # This code is contributed by ANKITRAI1
// C# Program to find sum of all// factors of a given numberusing System; class GFG{ // Using SieveOfEratosthenes to find smallest// prime factor of all the numbers.// For example, if N is 10,// s[2] = s[4] = s[6] = s[10] = 2// s[3] = s[9] = 3// s[5] = 5// s[7] = 7static void sieveOfEratosthenes(int N, int []s){ // Create a boolean array "prime[0..n]" and// initialize all entries in it as false.bool[] prime = new bool[N + 1]; for(int i = 0; i < N + 1; i++) prime[i] = false; // Initializing smallest factor equal// to 2 for all the even numbersfor (int i = 2; i <= N; i += 2) s[i] = 2; // For odd numbers less then equal to nfor (int i = 3; i <= N; i += 2){ if (prime[i] == false) { // s(i) for a prime is the // number itself s[i] = i; // For all multiples of current // prime number for (int j = i; j * i <= N; j += 2) { if (prime[i * j] == false) { prime[i * j] = true; // i is the smallest prime factor // for number "i*j". s[i * j] = i; } } }}} // Function to find sum of all// prime factorsstatic int findSum(int N){// Declaring array to store smallest// prime factor of i at i-th indexint[] s = new int[N + 1]; int ans = 1; // Filling values in s[] using sievesieveOfEratosthenes(N, s); int currFactor = s[N]; // Current prime factor of Nint power = 1; // Power of current prime factor while (N > 1){ N /= s[N]; // N is now N/s[N]. If new N als has smallest // prime factor as currFactor, increment power if (currFactor == s[N]) { power++; continue; } int sum = 0; for(int i = 0; i <= power; i++) sum += (int)Math.Pow(currFactor, i); ans *= sum; // Update current prime factor as s[N] // and initializing power of factor as 1. currFactor = s[N]; power = 1;} return ans;} // Driver codepublic static void Main(){ int n = 12; Console.Write("Sum of the factors is : "); Console.WriteLine(findSum(n));}} // This code is contributed by Shashank
<?php// PHP Program to find sum of all// factors of a given number // Using SieveOfEratosthenes to find smallest prime// factor of all the numbers.// For example, if N is 10,// s[2] = s[4] = s[6] = s[10] = 2// s[3] = s[9] = 3// s[5] = 5// s[7] = 7function sieveOfEratosthenes($N, &$s){ // Create a boolean array "prime[0..n]" and // initialize all entries in it as false. $prime=array_fill(0,$N + 1, false); // Initializing smallest factor equal to 2 // for all the even numbers for ($i = 2; $i <= $N; $i += 2) $s[$i] = 2; // For odd numbers less then equal to n for ($i = 3; $i <= $N; $i += 2) { if ($prime[$i] == false) { // s(i) for a prime is the number itself $s[$i] = $i; // For all multiples of current prime number for ($j = $i; $j * $i <= $N; $j += 2) { if ($prime[$i * $j] == false) { $prime[$i * $j] = true; // i is the smallest prime factor for // number "i*j". $s[$i * $j] = $i; } } } }} // Function to find sum of all prime factorsfunction findSum($N){ // Declaring array to store smallest prime // factor of i at i-th index $s=array_fill(0,$N + 1,0); $ans = 1; // Filling values in s[] using sieve sieveOfEratosthenes($N, $s); $currFactor = $s[$N]; // Current prime factor of N $power = 1; // Power of current prime factor while ($N > 1) { $N /= $s[$N]; // N is now N/s[N]. If new N als has smallest // prime factor as currFactor, increment power if ($currFactor == $s[$N]) { $power++; continue; } $sum = 0; for($i=0; $i<=$power; $i++) $sum += (int)pow($currFactor,$i); $ans *= $sum; // Update current prime factor as s[N] and // initializing power of factor as 1. $currFactor = $s[$N]; $power = 1; } return $ans;} // Driver code $n = 12; echo "Sum of the factors is : "; echo findSum($n); // This code is contributed by mits?>
<script>//Javascript Program to find sum of all//factors of a given number //Using SieveOfEratosthenes to find smallest prime //factor of all the numbers. //For example, if N is 10, //s[2] = s[4] = s[6] = s[10] = 2 //s[3] = s[9] = 3 //s[5] = 5 //s[7] = 7 function sieveOfEratosthenes(N,s) { // Create a boolean array "prime[0..n]" and // initialize all entries in it as false. let prime = new Array(N + 1); for(let i = 0; i < N+1; i++) prime[i] = false; // Initializing smallest factor equal to 2 // for all the even numbers for (let i = 2; i <= N; i += 2) s[i] = 2; // For odd numbers less then equal to n for (let i = 3; i <= N; i += 2) { if (prime[i] == false) { // s(i) for a prime is the number itself s[i] = i; // For all multiples of current prime number for (let j = i; j * i <= N; j += 2) { if (prime[i * j] == false) { prime[i * j] = true; // i is the smallest prime factor for // number "i*j". s[i * j] = i; } } } } } //Function to find sum of all prime factors function findSum(N) { // Declaring array to store smallest prime // factor of i at i-th index let s = new Array(N + 1); let ans = 1; // Filling values in s[] using sieve sieveOfEratosthenes(N, s); let currFactor = s[N]; // Current prime factor of N let power = 1; // Power of current prime factor while (N > 1) { N = Math.floor(N/s[N]); // N is now N/s[N]. If new N als has smallest // prime factor as currFactor, increment power if (currFactor == s[N]) { power++; continue; } let sum = 0; for(let i=0; i<=power; i++) sum += Math.pow(currFactor,i); ans *= sum; // Update current prime factor as s[N] and // initializing power of factor as 1. currFactor = s[N]; power = 1; } return ans; } //Driver code let n = 12; document.write("Sum of the factors is : "); document.write(findSum(n)); // This code is contributed by rag2127</script>
Sum of the factors is : 28
ankthon
ukasp
Shashank12
Mithun Kumar
rag2127
factor
prime-factor
sieve
Mathematical
Mathematical
sieve
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Prime Numbers
Program for factorial of a number
Print all possible combinations of r elements in a given array of size n
The Knight's tour problem | Backtracking-1
Operators in C / C++
Find minimum number of coins that make a given value
Program to find sum of elements in a given array
Minimum number of jumps to reach end | [
{
"code": null,
"e": 25911,
"s": 25883,
"text": "\n19 May, 2021"
},
{
"code": null,
"e": 25995,
"s": 25911,
"text": "Given a number N. The task is to find the sum of all factors of the given number N."
},
{
"code": null,
"e": 26007,
"s": 25995,
"text": "Examples: "
},
{
"code": null,
"e": 26096,
"s": 26007,
"text": "Input : N = 12\nOutput : 28\nAll factors of 12 are: 1,2,3,4,6,12\n\nInput : 60\nOutput : 168 "
},
{
"code": null,
"e": 26325,
"s": 26096,
"text": "Approach: Suppose N = 1100, the idea is to first find the prime factorization of the given number N. Therefore, the prime factorization of 1100 = 22 * 52 * 11.So, the formula to calculate the sum of all factors can be given as, "
},
{
"code": null,
"e": 26559,
"s": 26325,
"text": "(20 + 21 + 22) * (50 + 51 + 52) * (110 + 111) (upto the power of factor in factorization i.e. power of 2 and 5 is 2 and 11 is 1.) = (1 + 2 + 22) * (1 + 5 + 52) * (1 + 11) = 7 * 31 * 12 = 2604So, the sum of all factors of 1100 = 2604 "
},
{
"code": null,
"e": 26611,
"s": 26559,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26615,
"s": 26611,
"text": "C++"
},
{
"code": null,
"e": 26620,
"s": 26615,
"text": "Java"
},
{
"code": null,
"e": 26629,
"s": 26620,
"text": "Python 3"
},
{
"code": null,
"e": 26632,
"s": 26629,
"text": "C#"
},
{
"code": null,
"e": 26636,
"s": 26632,
"text": "PHP"
},
{
"code": null,
"e": 26647,
"s": 26636,
"text": "Javascript"
},
{
"code": "// C++ Program to find sum of all// factors of a given number #include <bits/stdc++.h> using namespace std; // Using SieveOfEratosthenes to find smallest prime// factor of all the numbers.// For example, if N is 10,// s[2] = s[4] = s[6] = s[10] = 2// s[3] = s[9] = 3// s[5] = 5// s[7] = 7void sieveOfEratosthenes(int N, int s[]){ // Create a boolean array \"prime[0..n]\" and // initialize all entries in it as false. vector<bool> prime(N + 1, false); // Initializing smallest factor equal to 2 // for all the even numbers for (int i = 2; i <= N; i += 2) s[i] = 2; // For odd numbers less then equal to n for (int i = 3; i <= N; i += 2) { if (prime[i] == false) { // s(i) for a prime is the number itself s[i] = i; // For all multiples of current prime number for (int j = i; j * i <= N; j += 2) { if (prime[i * j] == false) { prime[i * j] = true; // i is the smallest prime factor for // number \"i*j\". s[i * j] = i; } } } }} // Function to find sum of all prime factorsint findSum(int N){ // Declaring array to store smallest prime // factor of i at i-th index int s[N + 1]; int ans = 1; // Filling values in s[] using sieve sieveOfEratosthenes(N, s); int currFactor = s[N]; // Current prime factor of N int power = 1; // Power of current prime factor while (N > 1) { N /= s[N]; // N is now N/s[N]. If new N als has smallest // prime factor as currFactor, increment power if (currFactor == s[N]) { power++; continue; } int sum = 0; for(int i=0; i<=power; i++) sum += pow(currFactor,i); ans *= sum; // Update current prime factor as s[N] and // initializing power of factor as 1. currFactor = s[N]; power = 1; } return ans;} // Driver codeint main(){ int n = 12; cout << \"Sum of the factors is : \"; cout << findSum(n); return 0;}",
"e": 28805,
"s": 26647,
"text": null
},
{
"code": "//Java Program to find sum of all//factors of a given numberpublic class GFG { //Using SieveOfEratosthenes to find smallest prime //factor of all the numbers. //For example, if N is 10, //s[2] = s[4] = s[6] = s[10] = 2 //s[3] = s[9] = 3 //s[5] = 5 //s[7] = 7 static void sieveOfEratosthenes(int N, int s[]) { // Create a boolean array \"prime[0..n]\" and // initialize all entries in it as false. boolean[] prime = new boolean[N + 1]; for(int i = 0; i < N+1; i++) prime[i] = false; // Initializing smallest factor equal to 2 // for all the even numbers for (int i = 2; i <= N; i += 2) s[i] = 2; // For odd numbers less then equal to n for (int i = 3; i <= N; i += 2) { if (prime[i] == false) { // s(i) for a prime is the number itself s[i] = i; // For all multiples of current prime number for (int j = i; j * i <= N; j += 2) { if (prime[i * j] == false) { prime[i * j] = true; // i is the smallest prime factor for // number \"i*j\". s[i * j] = i; } } } } } //Function to find sum of all prime factors static int findSum(int N) { // Declaring array to store smallest prime // factor of i at i-th index int[] s = new int[N + 1]; int ans = 1; // Filling values in s[] using sieve sieveOfEratosthenes(N, s); int currFactor = s[N]; // Current prime factor of N int power = 1; // Power of current prime factor while (N > 1) { N /= s[N]; // N is now N/s[N]. If new N als has smallest // prime factor as currFactor, increment power if (currFactor == s[N]) { power++; continue; } int sum = 0; for(int i=0; i<=power; i++) sum += Math.pow(currFactor,i); ans *= sum; // Update current prime factor as s[N] and // initializing power of factor as 1. currFactor = s[N]; power = 1; } return ans; } //Driver code public static void main(String[] args) { int n = 12; System.out.print(\"Sum of the factors is : \"); System.out.print(findSum(n)); }}",
"e": 31207,
"s": 28805,
"text": null
},
{
"code": "# Python 3 Program to find# sum of all factors of a# given number # Using SieveOfEratosthenes# to find smallest prime# factor of all the numbers.# For example, if N is 10,# s[2] = s[4] = s[6] = s[10] = 2# s[3] = s[9] = 3# s[5] = 5# s[7] = 7def sieveOfEratosthenes(N, s) : # Create a boolean list \"prime[0..n]\" # and initialize all entries in it # as false. prime = [False] * (N + 1) # Initializing smallest # factor equal to 2 for # all the even numbers for i in range(2, N + 1, 2) : s[i] = 2 # For odd numbers less # then equal to n for i in range(3, N + 1, 2) : if prime[i] == False : # s[i] for a prime is # the number itself s[i] = i # For all multiples of # current prime number for j in range(i, (N + 1) // i, 2) : if prime[i * j] == False : prime[i * j] = True # i is the smallest # prime factor for # number \"i*j\". s[i * j] = i #J += 2 # Function to find sum# of all prime factorsdef findSum(N) : # Declaring list to store # smallest prime factor of # i at i-th index s = [0] * (N + 1) ans = 1 # Filling values in s[] using # sieve function calling sieveOfEratosthenes(N, s) # Current prime factor of N currFactor = s[N] # Power of current prime factor power = 1 while N > 1 : N //= s[N] # N is now N//s[N]. If new N # also has smallest prime # factor as currFactor, # increment power if currFactor == s[N] : power += 1 continue sum = 0 for i in range(power + 1) : sum += pow(currFactor, i) ans *= sum # Update current prime factor # as s[N] and initializing # power of factor as 1. currFactor = s[N] power = 1 return ans # Driver Codeif __name__ == \"__main__\" : n = 12 print(\"Sum of the factors is :\", end = \" \") print(findSum(n)) # This code is contributed by ANKITRAI1",
"e": 33376,
"s": 31207,
"text": null
},
{
"code": "// C# Program to find sum of all// factors of a given numberusing System; class GFG{ // Using SieveOfEratosthenes to find smallest// prime factor of all the numbers.// For example, if N is 10,// s[2] = s[4] = s[6] = s[10] = 2// s[3] = s[9] = 3// s[5] = 5// s[7] = 7static void sieveOfEratosthenes(int N, int []s){ // Create a boolean array \"prime[0..n]\" and// initialize all entries in it as false.bool[] prime = new bool[N + 1]; for(int i = 0; i < N + 1; i++) prime[i] = false; // Initializing smallest factor equal// to 2 for all the even numbersfor (int i = 2; i <= N; i += 2) s[i] = 2; // For odd numbers less then equal to nfor (int i = 3; i <= N; i += 2){ if (prime[i] == false) { // s(i) for a prime is the // number itself s[i] = i; // For all multiples of current // prime number for (int j = i; j * i <= N; j += 2) { if (prime[i * j] == false) { prime[i * j] = true; // i is the smallest prime factor // for number \"i*j\". s[i * j] = i; } } }}} // Function to find sum of all// prime factorsstatic int findSum(int N){// Declaring array to store smallest// prime factor of i at i-th indexint[] s = new int[N + 1]; int ans = 1; // Filling values in s[] using sievesieveOfEratosthenes(N, s); int currFactor = s[N]; // Current prime factor of Nint power = 1; // Power of current prime factor while (N > 1){ N /= s[N]; // N is now N/s[N]. If new N als has smallest // prime factor as currFactor, increment power if (currFactor == s[N]) { power++; continue; } int sum = 0; for(int i = 0; i <= power; i++) sum += (int)Math.Pow(currFactor, i); ans *= sum; // Update current prime factor as s[N] // and initializing power of factor as 1. currFactor = s[N]; power = 1;} return ans;} // Driver codepublic static void Main(){ int n = 12; Console.Write(\"Sum of the factors is : \"); Console.WriteLine(findSum(n));}} // This code is contributed by Shashank",
"e": 35486,
"s": 33376,
"text": null
},
{
"code": "<?php// PHP Program to find sum of all// factors of a given number // Using SieveOfEratosthenes to find smallest prime// factor of all the numbers.// For example, if N is 10,// s[2] = s[4] = s[6] = s[10] = 2// s[3] = s[9] = 3// s[5] = 5// s[7] = 7function sieveOfEratosthenes($N, &$s){ // Create a boolean array \"prime[0..n]\" and // initialize all entries in it as false. $prime=array_fill(0,$N + 1, false); // Initializing smallest factor equal to 2 // for all the even numbers for ($i = 2; $i <= $N; $i += 2) $s[$i] = 2; // For odd numbers less then equal to n for ($i = 3; $i <= $N; $i += 2) { if ($prime[$i] == false) { // s(i) for a prime is the number itself $s[$i] = $i; // For all multiples of current prime number for ($j = $i; $j * $i <= $N; $j += 2) { if ($prime[$i * $j] == false) { $prime[$i * $j] = true; // i is the smallest prime factor for // number \"i*j\". $s[$i * $j] = $i; } } } }} // Function to find sum of all prime factorsfunction findSum($N){ // Declaring array to store smallest prime // factor of i at i-th index $s=array_fill(0,$N + 1,0); $ans = 1; // Filling values in s[] using sieve sieveOfEratosthenes($N, $s); $currFactor = $s[$N]; // Current prime factor of N $power = 1; // Power of current prime factor while ($N > 1) { $N /= $s[$N]; // N is now N/s[N]. If new N als has smallest // prime factor as currFactor, increment power if ($currFactor == $s[$N]) { $power++; continue; } $sum = 0; for($i=0; $i<=$power; $i++) $sum += (int)pow($currFactor,$i); $ans *= $sum; // Update current prime factor as s[N] and // initializing power of factor as 1. $currFactor = $s[$N]; $power = 1; } return $ans;} // Driver code $n = 12; echo \"Sum of the factors is : \"; echo findSum($n); // This code is contributed by mits?>",
"e": 37655,
"s": 35486,
"text": null
},
{
"code": "<script>//Javascript Program to find sum of all//factors of a given number //Using SieveOfEratosthenes to find smallest prime //factor of all the numbers. //For example, if N is 10, //s[2] = s[4] = s[6] = s[10] = 2 //s[3] = s[9] = 3 //s[5] = 5 //s[7] = 7 function sieveOfEratosthenes(N,s) { // Create a boolean array \"prime[0..n]\" and // initialize all entries in it as false. let prime = new Array(N + 1); for(let i = 0; i < N+1; i++) prime[i] = false; // Initializing smallest factor equal to 2 // for all the even numbers for (let i = 2; i <= N; i += 2) s[i] = 2; // For odd numbers less then equal to n for (let i = 3; i <= N; i += 2) { if (prime[i] == false) { // s(i) for a prime is the number itself s[i] = i; // For all multiples of current prime number for (let j = i; j * i <= N; j += 2) { if (prime[i * j] == false) { prime[i * j] = true; // i is the smallest prime factor for // number \"i*j\". s[i * j] = i; } } } } } //Function to find sum of all prime factors function findSum(N) { // Declaring array to store smallest prime // factor of i at i-th index let s = new Array(N + 1); let ans = 1; // Filling values in s[] using sieve sieveOfEratosthenes(N, s); let currFactor = s[N]; // Current prime factor of N let power = 1; // Power of current prime factor while (N > 1) { N = Math.floor(N/s[N]); // N is now N/s[N]. If new N als has smallest // prime factor as currFactor, increment power if (currFactor == s[N]) { power++; continue; } let sum = 0; for(let i=0; i<=power; i++) sum += Math.pow(currFactor,i); ans *= sum; // Update current prime factor as s[N] and // initializing power of factor as 1. currFactor = s[N]; power = 1; } return ans; } //Driver code let n = 12; document.write(\"Sum of the factors is : \"); document.write(findSum(n)); // This code is contributed by rag2127</script>",
"e": 40256,
"s": 37655,
"text": null
},
{
"code": null,
"e": 40283,
"s": 40256,
"text": "Sum of the factors is : 28"
},
{
"code": null,
"e": 40293,
"s": 40285,
"text": "ankthon"
},
{
"code": null,
"e": 40299,
"s": 40293,
"text": "ukasp"
},
{
"code": null,
"e": 40310,
"s": 40299,
"text": "Shashank12"
},
{
"code": null,
"e": 40323,
"s": 40310,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 40331,
"s": 40323,
"text": "rag2127"
},
{
"code": null,
"e": 40338,
"s": 40331,
"text": "factor"
},
{
"code": null,
"e": 40351,
"s": 40338,
"text": "prime-factor"
},
{
"code": null,
"e": 40357,
"s": 40351,
"text": "sieve"
},
{
"code": null,
"e": 40370,
"s": 40357,
"text": "Mathematical"
},
{
"code": null,
"e": 40383,
"s": 40370,
"text": "Mathematical"
},
{
"code": null,
"e": 40389,
"s": 40383,
"text": "sieve"
},
{
"code": null,
"e": 40487,
"s": 40389,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40511,
"s": 40487,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 40554,
"s": 40511,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 40568,
"s": 40554,
"text": "Prime Numbers"
},
{
"code": null,
"e": 40602,
"s": 40568,
"text": "Program for factorial of a number"
},
{
"code": null,
"e": 40675,
"s": 40602,
"text": "Print all possible combinations of r elements in a given array of size n"
},
{
"code": null,
"e": 40718,
"s": 40675,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 40739,
"s": 40718,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 40792,
"s": 40739,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 40841,
"s": 40792,
"text": "Program to find sum of elements in a given array"
}
] |
map::at() in C++ STL - GeeksforGeeks | 28 Sep, 2021
Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have same key values.
at() function is used to reference the element mapped to the key value given as the parameter to the function. For example, if we have a string “hi” mapped to an integer 1, then passing the integer 1 as the parameter of at() function will return the string “hi”.
How is at() function different from operator[] at() function checks the range of the container, and throws an exception when we try to access an element not in the range, while operator[] does not checks the range of the container and shows an undefined behavior when an element not in the range is accessed.
Syntax :
mapname.at(key)
Parameters :
Key value mapped to the element to be fetched.
Returns :
Direct reference to the element at the given key value.
Examples:
Input : map mymap;
mymap['a'] = 1;
mymap.at('a');
Output : 1
Input : map mymap;
mymap["abcd"] = 7;
mymap.at("abcd");
Output : 7
Errors and Exceptions1. If the key is not present in the map, it throws out_of_range. 2. It has a strong no exception throw guarantee otherwise.
C++
// CPP program to illustrate// Implementation of at() function#include <iostream>#include <map>#include <string>using namespace std; int main(){ // map declaration map<string, int> mymap; // mapping strings to integers mymap["hi"] = 1; mymap["welcome"] = 2; mymap["thanks"] = 3; mymap["bye"] = 4; // printing the integer mapped // by string "thanks" cout << mymap.at("thanks"); return 0;}
Output:
3
Time Complexity: O(logn)
How is at() function different from operator[] at() function checks the range of the container, and throws an exception when we try to access an element not in the range, while operator[] does not checks the range of the container and shows an undefined behavior when an element not in the range is accessed.
chhabradhanvi
cpp-map
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Sorting a vector in C++
Friend class and function in C++
std::string class in C++
Pair in C++ Standard Template Library (STL)
Queue in C++ Standard Template Library (STL)
Inline Functions in C++
Array of Strings in C++ (5 Different Ways to Create)
Convert string to char array in C++ | [
{
"code": null,
"e": 25369,
"s": 25341,
"text": "\n28 Sep, 2021"
},
{
"code": null,
"e": 25538,
"s": 25369,
"text": "Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have same key values."
},
{
"code": null,
"e": 25801,
"s": 25538,
"text": "at() function is used to reference the element mapped to the key value given as the parameter to the function. For example, if we have a string “hi” mapped to an integer 1, then passing the integer 1 as the parameter of at() function will return the string “hi”."
},
{
"code": null,
"e": 26110,
"s": 25801,
"text": "How is at() function different from operator[] at() function checks the range of the container, and throws an exception when we try to access an element not in the range, while operator[] does not checks the range of the container and shows an undefined behavior when an element not in the range is accessed."
},
{
"code": null,
"e": 26120,
"s": 26110,
"text": "Syntax : "
},
{
"code": null,
"e": 26262,
"s": 26120,
"text": "mapname.at(key)\nParameters :\nKey value mapped to the element to be fetched.\nReturns :\nDirect reference to the element at the given key value."
},
{
"code": null,
"e": 26273,
"s": 26262,
"text": "Examples: "
},
{
"code": null,
"e": 26448,
"s": 26273,
"text": "Input : map mymap;\n mymap['a'] = 1;\n mymap.at('a');\nOutput : 1\n\nInput : map mymap;\n mymap[\"abcd\"] = 7;\n mymap.at(\"abcd\");\nOutput : 7"
},
{
"code": null,
"e": 26593,
"s": 26448,
"text": "Errors and Exceptions1. If the key is not present in the map, it throws out_of_range. 2. It has a strong no exception throw guarantee otherwise."
},
{
"code": null,
"e": 26597,
"s": 26593,
"text": "C++"
},
{
"code": "// CPP program to illustrate// Implementation of at() function#include <iostream>#include <map>#include <string>using namespace std; int main(){ // map declaration map<string, int> mymap; // mapping strings to integers mymap[\"hi\"] = 1; mymap[\"welcome\"] = 2; mymap[\"thanks\"] = 3; mymap[\"bye\"] = 4; // printing the integer mapped // by string \"thanks\" cout << mymap.at(\"thanks\"); return 0;}",
"e": 27021,
"s": 26597,
"text": null
},
{
"code": null,
"e": 27029,
"s": 27021,
"text": "Output:"
},
{
"code": null,
"e": 27031,
"s": 27029,
"text": "3"
},
{
"code": null,
"e": 27056,
"s": 27031,
"text": "Time Complexity: O(logn)"
},
{
"code": null,
"e": 27366,
"s": 27056,
"text": "How is at() function different from operator[] at() function checks the range of the container, and throws an exception when we try to access an element not in the range, while operator[] does not checks the range of the container and shows an undefined behavior when an element not in the range is accessed. "
},
{
"code": null,
"e": 27380,
"s": 27366,
"text": "chhabradhanvi"
},
{
"code": null,
"e": 27388,
"s": 27380,
"text": "cpp-map"
},
{
"code": null,
"e": 27392,
"s": 27388,
"text": "STL"
},
{
"code": null,
"e": 27396,
"s": 27392,
"text": "C++"
},
{
"code": null,
"e": 27400,
"s": 27396,
"text": "STL"
},
{
"code": null,
"e": 27404,
"s": 27400,
"text": "CPP"
},
{
"code": null,
"e": 27502,
"s": 27404,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27530,
"s": 27502,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 27550,
"s": 27530,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 27574,
"s": 27550,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 27607,
"s": 27574,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 27632,
"s": 27607,
"text": "std::string class in C++"
},
{
"code": null,
"e": 27676,
"s": 27632,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 27721,
"s": 27676,
"text": "Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 27745,
"s": 27721,
"text": "Inline Functions in C++"
},
{
"code": null,
"e": 27798,
"s": 27745,
"text": "Array of Strings in C++ (5 Different Ways to Create)"
}
] |
How to Create Animated Loader Ring using HTML and CSS? - GeeksforGeeks | 11 May, 2020
The Loader Ring can be easily generated using HTML and CSS. The Loader Ring displays when the browsers are loading web pages. To create a loader ring, we will make the use of CSS animations that allows animation of HTML elements.
HTML Code is used to create a basic structure of the animated loader ring and CSS code is used to set the style of Loader Ring. We will use the @keyframes rule that allows the animation to gradually change from current style to the new style at certain times then we will use the transform property to rotate the animation 360 degrees.
Example:
<!DOCTYPE html><html> <head> <meta charset="utf-8"> <title> How to Create Animated Loader Ring using HTML and CSS? </title> <style> body { margin: 0; padding: 0; background: #008000; } .circle { position: absolute; top: 40%; left: 50%; transform: translate(-40%, -50%); animation: effect 1s linear infinite; width: 100px; height: 100px; border-radius: 50%; border: 6px solid rgba(255, 255, 255, 0.3); border-top-color: #fff; } @keyframes effect { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } } </style></head> <body> <div class="circle"></div></body> </html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
CSS-Misc
HTML-Misc
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set space between the flexbox ?
Design a web page using HTML and CSS
Form validation using jQuery
Search Bar using HTML, CSS and JavaScript
How to style a checkbox using CSS?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
How to set input type date in dd-mm-yyyy format using HTML ?
REST API (Introduction)
How to Insert Form Data into Database using PHP ? | [
{
"code": null,
"e": 26621,
"s": 26593,
"text": "\n11 May, 2020"
},
{
"code": null,
"e": 26851,
"s": 26621,
"text": "The Loader Ring can be easily generated using HTML and CSS. The Loader Ring displays when the browsers are loading web pages. To create a loader ring, we will make the use of CSS animations that allows animation of HTML elements."
},
{
"code": null,
"e": 27187,
"s": 26851,
"text": "HTML Code is used to create a basic structure of the animated loader ring and CSS code is used to set the style of Loader Ring. We will use the @keyframes rule that allows the animation to gradually change from current style to the new style at certain times then we will use the transform property to rotate the animation 360 degrees."
},
{
"code": null,
"e": 27196,
"s": 27187,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <meta charset=\"utf-8\"> <title> How to Create Animated Loader Ring using HTML and CSS? </title> <style> body { margin: 0; padding: 0; background: #008000; } .circle { position: absolute; top: 40%; left: 50%; transform: translate(-40%, -50%); animation: effect 1s linear infinite; width: 100px; height: 100px; border-radius: 50%; border: 6px solid rgba(255, 255, 255, 0.3); border-top-color: #fff; } @keyframes effect { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } } </style></head> <body> <div class=\"circle\"></div></body> </html>",
"e": 28082,
"s": 27196,
"text": null
},
{
"code": null,
"e": 28090,
"s": 28082,
"text": "Output:"
},
{
"code": null,
"e": 28227,
"s": 28090,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 28236,
"s": 28227,
"text": "CSS-Misc"
},
{
"code": null,
"e": 28246,
"s": 28236,
"text": "HTML-Misc"
},
{
"code": null,
"e": 28250,
"s": 28246,
"text": "CSS"
},
{
"code": null,
"e": 28255,
"s": 28250,
"text": "HTML"
},
{
"code": null,
"e": 28272,
"s": 28255,
"text": "Web Technologies"
},
{
"code": null,
"e": 28299,
"s": 28272,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 28304,
"s": 28299,
"text": "HTML"
},
{
"code": null,
"e": 28402,
"s": 28304,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28441,
"s": 28402,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 28478,
"s": 28441,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 28507,
"s": 28478,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 28549,
"s": 28507,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 28584,
"s": 28549,
"text": "How to style a checkbox using CSS?"
},
{
"code": null,
"e": 28644,
"s": 28584,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 28697,
"s": 28644,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 28758,
"s": 28697,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 28782,
"s": 28758,
"text": "REST API (Introduction)"
}
] |
JavaScript ReferenceError - variable is not defined - GeeksforGeeks | 31 Jul, 2020
This JavaScript exception variable is not defined occurs if there is a non-existent variable that is referenced somewhere.
Message:
ReferenceError: "x" is not defined
Error Type:
ReferenceError
Cause of Error:
There is a non-existent variable that is referenced somewhere in the script. That variable has to be declared, or make sure the variable is available in the current script or scope.
Example 1: In this example, the variable(val1) is being accessed from the outside of the function, So the error has not occurred.
HTML
<script> function sum() { var val1 = 2; var val2 = 3; return val1 + val2; } document.write(val1);</script>
Output:
ReferenceError: 'val1' is not defined
Example 2: In this example, the variable(GFG) is not defined, So the error has occurred.
HTML
<script> GFG.substring(2); </script>
Output:
ReferenceError: 'GFG' is not defined
JavaScript-Errors
JavaScript
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?
How to filter object array based on attributes?
How to remove duplicate elements from JavaScript Array ?
How to get selected value in dropdown list using JavaScript ?
Lodash _.debounce() Method
Angular File Upload | [
{
"code": null,
"e": 26543,
"s": 26515,
"text": "\n31 Jul, 2020"
},
{
"code": null,
"e": 26666,
"s": 26543,
"text": "This JavaScript exception variable is not defined occurs if there is a non-existent variable that is referenced somewhere."
},
{
"code": null,
"e": 26675,
"s": 26666,
"text": "Message:"
},
{
"code": null,
"e": 26711,
"s": 26675,
"text": "ReferenceError: \"x\" is not defined\n"
},
{
"code": null,
"e": 26723,
"s": 26711,
"text": "Error Type:"
},
{
"code": null,
"e": 26739,
"s": 26723,
"text": "ReferenceError\n"
},
{
"code": null,
"e": 26755,
"s": 26739,
"text": "Cause of Error:"
},
{
"code": null,
"e": 26937,
"s": 26755,
"text": "There is a non-existent variable that is referenced somewhere in the script. That variable has to be declared, or make sure the variable is available in the current script or scope."
},
{
"code": null,
"e": 27067,
"s": 26937,
"text": "Example 1: In this example, the variable(val1) is being accessed from the outside of the function, So the error has not occurred."
},
{
"code": null,
"e": 27072,
"s": 27067,
"text": "HTML"
},
{
"code": "<script> function sum() { var val1 = 2; var val2 = 3; return val1 + val2; } document.write(val1);</script>",
"e": 27210,
"s": 27072,
"text": null
},
{
"code": null,
"e": 27218,
"s": 27210,
"text": "Output:"
},
{
"code": null,
"e": 27257,
"s": 27218,
"text": "ReferenceError: 'val1' is not defined\n"
},
{
"code": null,
"e": 27346,
"s": 27257,
"text": "Example 2: In this example, the variable(GFG) is not defined, So the error has occurred."
},
{
"code": null,
"e": 27351,
"s": 27346,
"text": "HTML"
},
{
"code": "<script> GFG.substring(2); </script>",
"e": 27407,
"s": 27351,
"text": null
},
{
"code": null,
"e": 27415,
"s": 27407,
"text": "Output:"
},
{
"code": null,
"e": 27453,
"s": 27415,
"text": "ReferenceError: 'GFG' is not defined\n"
},
{
"code": null,
"e": 27471,
"s": 27453,
"text": "JavaScript-Errors"
},
{
"code": null,
"e": 27482,
"s": 27471,
"text": "JavaScript"
},
{
"code": null,
"e": 27580,
"s": 27482,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27620,
"s": 27580,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 27681,
"s": 27620,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27722,
"s": 27681,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 27744,
"s": 27722,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 27798,
"s": 27744,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 27846,
"s": 27798,
"text": "How to filter object array based on attributes?"
},
{
"code": null,
"e": 27903,
"s": 27846,
"text": "How to remove duplicate elements from JavaScript Array ?"
},
{
"code": null,
"e": 27965,
"s": 27903,
"text": "How to get selected value in dropdown list using JavaScript ?"
},
{
"code": null,
"e": 27992,
"s": 27965,
"text": "Lodash _.debounce() Method"
}
] |
Express.js res.jsonp() Function - GeeksforGeeks | 19 Aug, 2021
The res.jsonp() function is used to send a JSON response with JSONP support and this function is similar to the res.json() function except that it opts-in to the support of JSONP callback.
Syntax:
res.jsonp( [body] )
Parameter: The body parameter describes the body type which can be sent in response.Return Value: It returns an Object.
Installation of express module:
1. You can visit the link to Install express module. You can install this package by using this command.
npm install express
2. After installing the express module, you can check your express version in command prompt using the command.
npm version express
3. After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.
node index.js
Example 1: Filename: index.js
Javascript
var express = require('express');var app = express();var PORT = 3000; // Without middlewareapp.get('/', function(req, res){ res.jsonp({ title: 'GeeksforGeeks' });}); app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT);});
Steps to run the program:
1. The project structure will look like this:
2. Make sure you have installed express module using the following command:
npm install express
3. Run index.js file using below command:
node index.js
Output:
Server listening on PORT 3000
4. Now open browser and go to http://localhost:3000/, now on your screen you will see the following output:
{"title":"GeeksforGeeks"}
Example 2: Filename: index.js
Javascript
var express = require('express');var app = express();var PORT = 3000; // With middlewareapp.use('/', function(req, res, next) { res.jsonp({ name: 'Legend' }); next();}) app.get('/', function(req, res) { res.send();}); app.listen(PORT, function(err) { if (err) console.log(err); console.log("Server listening on PORT", PORT);});
Run index.js file using below command:
node index.js
Now open the browser and go to http://localhost:3000/, now check your browser screen and you will see the following output:
{"name":"Legend"}
Reference: https://expressjs.com/en/5x/api.html#res.jsonp
kalrap615
Express.js
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between dependencies, devDependencies and peerDependencies
Node.js Export Module
How to connect Node.js with React.js ?
Mongoose find() Function
Mongoose Populate() Method
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 26267,
"s": 26239,
"text": "\n19 Aug, 2021"
},
{
"code": null,
"e": 26456,
"s": 26267,
"text": "The res.jsonp() function is used to send a JSON response with JSONP support and this function is similar to the res.json() function except that it opts-in to the support of JSONP callback."
},
{
"code": null,
"e": 26465,
"s": 26456,
"text": "Syntax: "
},
{
"code": null,
"e": 26485,
"s": 26465,
"text": "res.jsonp( [body] )"
},
{
"code": null,
"e": 26605,
"s": 26485,
"text": "Parameter: The body parameter describes the body type which can be sent in response.Return Value: It returns an Object."
},
{
"code": null,
"e": 26639,
"s": 26605,
"text": "Installation of express module: "
},
{
"code": null,
"e": 26745,
"s": 26639,
"text": "1. You can visit the link to Install express module. You can install this package by using this command. "
},
{
"code": null,
"e": 26765,
"s": 26745,
"text": "npm install express"
},
{
"code": null,
"e": 26878,
"s": 26765,
"text": "2. After installing the express module, you can check your express version in command prompt using the command. "
},
{
"code": null,
"e": 26898,
"s": 26878,
"text": "npm version express"
},
{
"code": null,
"e": 27037,
"s": 26898,
"text": "3. After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command. "
},
{
"code": null,
"e": 27051,
"s": 27037,
"text": "node index.js"
},
{
"code": null,
"e": 27082,
"s": 27051,
"text": "Example 1: Filename: index.js "
},
{
"code": null,
"e": 27093,
"s": 27082,
"text": "Javascript"
},
{
"code": "var express = require('express');var app = express();var PORT = 3000; // Without middlewareapp.get('/', function(req, res){ res.jsonp({ title: 'GeeksforGeeks' });}); app.listen(PORT, function(err){ if (err) console.log(err); console.log(\"Server listening on PORT\", PORT);});",
"e": 27377,
"s": 27093,
"text": null
},
{
"code": null,
"e": 27405,
"s": 27377,
"text": "Steps to run the program: "
},
{
"code": null,
"e": 27452,
"s": 27405,
"text": "1. The project structure will look like this: "
},
{
"code": null,
"e": 27529,
"s": 27452,
"text": "2. Make sure you have installed express module using the following command: "
},
{
"code": null,
"e": 27549,
"s": 27529,
"text": "npm install express"
},
{
"code": null,
"e": 27592,
"s": 27549,
"text": "3. Run index.js file using below command: "
},
{
"code": null,
"e": 27606,
"s": 27592,
"text": "node index.js"
},
{
"code": null,
"e": 27615,
"s": 27606,
"text": "Output: "
},
{
"code": null,
"e": 27645,
"s": 27615,
"text": "Server listening on PORT 3000"
},
{
"code": null,
"e": 27754,
"s": 27645,
"text": "4. Now open browser and go to http://localhost:3000/, now on your screen you will see the following output: "
},
{
"code": null,
"e": 27780,
"s": 27754,
"text": "{\"title\":\"GeeksforGeeks\"}"
},
{
"code": null,
"e": 27812,
"s": 27780,
"text": "Example 2: Filename: index.js "
},
{
"code": null,
"e": 27823,
"s": 27812,
"text": "Javascript"
},
{
"code": "var express = require('express');var app = express();var PORT = 3000; // With middlewareapp.use('/', function(req, res, next) { res.jsonp({ name: 'Legend' }); next();}) app.get('/', function(req, res) { res.send();}); app.listen(PORT, function(err) { if (err) console.log(err); console.log(\"Server listening on PORT\", PORT);});",
"e": 28166,
"s": 27823,
"text": null
},
{
"code": null,
"e": 28206,
"s": 28166,
"text": "Run index.js file using below command: "
},
{
"code": null,
"e": 28220,
"s": 28206,
"text": "node index.js"
},
{
"code": null,
"e": 28345,
"s": 28220,
"text": "Now open the browser and go to http://localhost:3000/, now check your browser screen and you will see the following output: "
},
{
"code": null,
"e": 28363,
"s": 28345,
"text": "{\"name\":\"Legend\"}"
},
{
"code": null,
"e": 28422,
"s": 28363,
"text": "Reference: https://expressjs.com/en/5x/api.html#res.jsonp "
},
{
"code": null,
"e": 28432,
"s": 28422,
"text": "kalrap615"
},
{
"code": null,
"e": 28443,
"s": 28432,
"text": "Express.js"
},
{
"code": null,
"e": 28451,
"s": 28443,
"text": "Node.js"
},
{
"code": null,
"e": 28468,
"s": 28451,
"text": "Web Technologies"
},
{
"code": null,
"e": 28566,
"s": 28468,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28636,
"s": 28566,
"text": "Difference between dependencies, devDependencies and peerDependencies"
},
{
"code": null,
"e": 28658,
"s": 28636,
"text": "Node.js Export Module"
},
{
"code": null,
"e": 28697,
"s": 28658,
"text": "How to connect Node.js with React.js ?"
},
{
"code": null,
"e": 28722,
"s": 28697,
"text": "Mongoose find() Function"
},
{
"code": null,
"e": 28749,
"s": 28722,
"text": "Mongoose Populate() Method"
},
{
"code": null,
"e": 28789,
"s": 28749,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28834,
"s": 28789,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28877,
"s": 28834,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28927,
"s": 28877,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Java.net.NetworkInterface class in Java - GeeksforGeeks | 12 Feb, 2022
This class represents network interface, both software as well as hardware, its name, list of IP addresses assigned to it, and all related information. It can be used in cases when we want to specifically use a particular interface for transmitting our packet on a system with multiple NICs. What is a Network Interface? A network interface can be thought of as a point at which your computer connects to the network. It is not necessarily a piece of hardware but can also be implemented in software. For example, a loopback interface which is used for testing purposes. Methods :
1.getName() : Returns the name of this network interface.
Syntax : public String getName()
2.getInetAddresses() : Returns an enumeration of all Inetaddresses bound to this network interface, if security manager allows it.
Syntax :public Enumeration getInetAddresses()
3.getInterfaceAddresses() : Returns a list of all interface addresses on this interface.
Syntax :public List getInterfaceAddresses()
4.getSubInterfaces() : Returns an enumeration of all the sub or virtual interfaces of this network interface. For example, eth0:2 is a sub interface of eth0.
Syntax :public Enumeration getSubInterfaces()
5.getParent() : In case of a sub interface, this method returns the parent interface. If this is not a subinterface, this method will return null.
Syntax :public NetworkInterface getParent()
6.getIndex() : Returns the index assigned to this network interface by the system. Indexes can be used in place of long names to refer to any interface on the device.
Syntax :public int getIndex()
7.getDisplayName() : This method returns the name of network interface in a readable string format.
Syntax :public String getDisplayName()
8.getByName() : Finds and returns the network interface with the specified name, or null if none exists.
Syntax :public static NetworkInterface getByName(String name)
throws SocketException
Parameters :
name : name of network interface to search for.
Throws :
SocketException : if I/O error occurs.
9.getByIndex() : Performs similar function as the previous function with index used as search parameter instead of name.
Syntax :public static NetworkInterface getByIndex(int index)
throws SocketException
Parameters :
index : index of network interface to search for.
Throws :
SocketException : if I/O error occurs.
10.getByInetAddress() : This method is widely used as it returns the network interface the specified inetaddress is bound to. If an InetAddress is bound to multiple interfaces, any one of the interfaces may be returned.
Syntax : public static NetworkInterface getByInetAddress(InetAddress addr)
throws SocketException
Parameters :
addr : address to search for
Throws :
SocketException : If IO error occurs
11.getNetworkInterfaces() : Returns all the network interfaces on the system.
Syntax :public static Enumeration getNetworkInterfaces()
throws SocketException
Throws :
SocketException : If IO error occurs
12.isUp() : Returns a boolean value indicating if this network interface is up and running.
Syntax : public boolean isUp()
13.isLoopback() : Returns a boolean value indicating if this interface is a loopback interface or not.
Syntax : public boolean isLoopback()
14.isPointToPoint() : Returns a boolean value indicating if this interface is a point to point interface or not.
Syntax : public boolean isPointToPoint()
15.supportsMulticast() : Returns a boolean value indicating if this interface supports multicasting or not.
Syntax : public boolean supportsMulticast()
16.getHardwareAddress() : Returns a byte array containing the hardware address(MAC) address of this interface. The caller must have appropriate permissions before calling this method.
public byte[] getHardwareAddress()
17.getMTU() : Returns the maximum transmission unit of this interface. An MTU is the largest size of the packet or frame that can be sent in packet based network.
Syntax :public int getMTU()
18.isVirtual() : Returns a boolean value indicating whether this interface is a virtual interface or not. Virtual interfaces are used in conjunction physical interfaces to provide additional values such as addresses and MTU.
Syntax : public boolean isVirtual()
19.equals() : This method is used to compare two network interfaces for equality. Two network interfaces are equal if they have same name and addresses bound to them.
Syntax :public boolean equals(Object obj)
Parameters :
obj : Object to compare this network interface for equality
20.hashCode() : Returns the hashcode value for this object.
Syntax :public int hashCode()
21.toString() : Returns a textual description of this object.
Syntax :public String toString()
Java Implementation :
Java
//Java program to illustrate various//networkInterface class methods.import java.net.InetAddress;import java.net.InterfaceAddress;import java.net.NetworkInterface;import java.net.SocketException;import java.net.UnknownHostException;import java.util.ArrayList;import java.util.Arrays;import java.util.Collections;import java.util.Enumeration; public class NetworkInterfaceEx{ public static void main(String[] args) throws SocketException, UnknownHostException { // getNetworkInterfaces() returns a list of all interfaces // present in the system. ArrayList<NetworkInterface> interfaces = Collections.list( NetworkInterface.getNetworkInterfaces()); System.out.println("Information about present Network Interfaces...\n"); for (NetworkInterface iface : interfaces) { // isUp() method used for checking whether the interface in process // is up and running or not. if (iface.isUp()) { // getName() method System.out.println("Interface Name: " + iface.getName()); // getDisplayName() method System.out.println("Interface display name: " + iface.getDisplayName()); // gethardwareaddress() method System.out.println("Hardware Address: " + Arrays.toString(iface.getHardwareAddress())); // getParent() method System.out.println("Parent: " + iface.getParent()); // getIndex() method System.out.println("Index: " + iface.getIndex()); // Interface addresses of the network interface System.out.println("\tInterface addresses: "); // getInterfaceAddresses() method for (InterfaceAddress addr : iface.getInterfaceAddresses()) { System.out.println("\t\t" + addr.getAddress().toString()); } // Interface addresses of the network interface System.out.println("\tInetAddresses associated with this interface: "); // getInetAddresses() method returns list of all // addresses currently bound to this interface Enumeration<InetAddress> en = iface.getInetAddresses(); while (en.hasMoreElements()) { System.out.println("\t\t" + en.nextElement().toString()); } // getMTU() method System.out.println("\tMTU: " + iface.getMTU()); // getSubInterfaces() method System.out.println("\tSubinterfaces: " + Collections.list(iface.getSubInterfaces())); // isLoopback() method System.out.println("\this loopback: " + iface.isLoopback()); // isVirtual() method System.out.println("\this virtual: " + iface.isVirtual()); // isPointToPoint() method System.out.println("\this point to point: " + iface.isPointToPoint()); // supportsMulticast() method System.out.println("Supports Multicast: " + iface.supportsMulticast()); } } // getByIndex() method returns network interface // with the specified index NetworkInterface nif = NetworkInterface.getByIndex(1); // toString() method is used to display textual // information about this network interface System.out.println("Network interface 1: " + nif.toString()); // getByName() method returns network interface // with the specified name NetworkInterface nif2 = NetworkInterface.getByName("eth0"); InetAddress ip = InetAddress.getByName("localhost"); // getbyInetAddress() method NetworkInterface nif3 = NetworkInterface.getByInetAddress(ip); System.out.println("\nlocalhost associated with: " + nif3); // equals() method boolean eq = nif.equals(nif2); System.out.println("nif==nif2: " + eq); // hashCode() method System.out.println("Hashcode : " + nif.hashCode()); }}
Output :
Information about present Network Interfaces...
Interface Name: lo
Interface display name: Software Loopback Interface 1
Hardware Address: null
Parent: null
Index: 1
Interface addresses:
/127.0.0.1
/0:0:0:0:0:0:0:1
InetAddresses associated with this interface:
/127.0.0.1
/0:0:0:0:0:0:0:1
MTU: -1
Subinterfaces: []
is loopback: true
is virtual: false
is point to point: false
Supports Multicast: true
Interface Name: wlan5
Interface display name: Dell Wireless 1705 802.11b|g|n (2.4GHZ)
Hardware Address: [100, 90, 4, -90, 2, 15]
Parent: null
Index: 16
Interface addresses:
/192.168.43.96
/2405:205:1486:9a1b:e567:b46f:198a:fe0c
/2405:205:1486:9a1b:8c93:9f82:6dd2:350c
/fe80:0:0:0:e567:b46f:198a:fe0c%wlan5
InetAddresses associated with this interface:
/192.168.43.96
/2405:205:1486:9a1b:e567:b46f:198a:fe0c
/2405:205:1486:9a1b:8c93:9f82:6dd2:350c
/fe80:0:0:0:e567:b46f:198a:fe0c%wlan5
MTU: 1500
Subinterfaces: []
is loopback: false
is virtual: false
is point to point: false
Supports Multicast: true
Network interface 1: name:lo (Software Loopback Interface 1)
loclhost associated with: name:lo (Software Loopback Interface 1)
nif==nif2: false
HashCode : 2544
The output of the above program will differ if you run it on your system as than it will display information about your network interfaces.References : Official Java Documentation This article is contributed by Rishabh Mahrsee. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
ManasChhabra2
rajeev0719singh
sumitgumber28
gulshankumarar231
Java-Networking
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Stream In Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
Set in Java | [
{
"code": null,
"e": 25597,
"s": 25569,
"text": "\n12 Feb, 2022"
},
{
"code": null,
"e": 26180,
"s": 25597,
"text": "This class represents network interface, both software as well as hardware, its name, list of IP addresses assigned to it, and all related information. It can be used in cases when we want to specifically use a particular interface for transmitting our packet on a system with multiple NICs. What is a Network Interface? A network interface can be thought of as a point at which your computer connects to the network. It is not necessarily a piece of hardware but can also be implemented in software. For example, a loopback interface which is used for testing purposes. Methods : "
},
{
"code": null,
"e": 26239,
"s": 26180,
"text": "1.getName() : Returns the name of this network interface. "
},
{
"code": null,
"e": 26272,
"s": 26239,
"text": "Syntax : public String getName()"
},
{
"code": null,
"e": 26404,
"s": 26272,
"text": "2.getInetAddresses() : Returns an enumeration of all Inetaddresses bound to this network interface, if security manager allows it. "
},
{
"code": null,
"e": 26450,
"s": 26404,
"text": "Syntax :public Enumeration getInetAddresses()"
},
{
"code": null,
"e": 26541,
"s": 26450,
"text": "3.getInterfaceAddresses() : Returns a list of all interface addresses on this interface. "
},
{
"code": null,
"e": 26585,
"s": 26541,
"text": "Syntax :public List getInterfaceAddresses()"
},
{
"code": null,
"e": 26745,
"s": 26585,
"text": "4.getSubInterfaces() : Returns an enumeration of all the sub or virtual interfaces of this network interface. For example, eth0:2 is a sub interface of eth0. "
},
{
"code": null,
"e": 26791,
"s": 26745,
"text": "Syntax :public Enumeration getSubInterfaces()"
},
{
"code": null,
"e": 26940,
"s": 26791,
"text": "5.getParent() : In case of a sub interface, this method returns the parent interface. If this is not a subinterface, this method will return null. "
},
{
"code": null,
"e": 26984,
"s": 26940,
"text": "Syntax :public NetworkInterface getParent()"
},
{
"code": null,
"e": 27153,
"s": 26984,
"text": "6.getIndex() : Returns the index assigned to this network interface by the system. Indexes can be used in place of long names to refer to any interface on the device. "
},
{
"code": null,
"e": 27183,
"s": 27153,
"text": "Syntax :public int getIndex()"
},
{
"code": null,
"e": 27285,
"s": 27183,
"text": "7.getDisplayName() : This method returns the name of network interface in a readable string format. "
},
{
"code": null,
"e": 27324,
"s": 27285,
"text": "Syntax :public String getDisplayName()"
},
{
"code": null,
"e": 27431,
"s": 27324,
"text": "8.getByName() : Finds and returns the network interface with the specified name, or null if none exists. "
},
{
"code": null,
"e": 27659,
"s": 27431,
"text": "Syntax :public static NetworkInterface getByName(String name)\n throws SocketException\nParameters :\nname : name of network interface to search for.\nThrows :\nSocketException : if I/O error occurs."
},
{
"code": null,
"e": 27782,
"s": 27659,
"text": "9.getByIndex() : Performs similar function as the previous function with index used as search parameter instead of name. "
},
{
"code": null,
"e": 28011,
"s": 27782,
"text": "Syntax :public static NetworkInterface getByIndex(int index)\n throws SocketException\nParameters :\nindex : index of network interface to search for.\nThrows :\nSocketException : if I/O error occurs."
},
{
"code": null,
"e": 28233,
"s": 28011,
"text": "10.getByInetAddress() : This method is widely used as it returns the network interface the specified inetaddress is bound to. If an InetAddress is bound to multiple interfaces, any one of the interfaces may be returned. "
},
{
"code": null,
"e": 28462,
"s": 28233,
"text": "Syntax : public static NetworkInterface getByInetAddress(InetAddress addr)\n throws SocketException\nParameters : \naddr : address to search for\nThrows : \nSocketException : If IO error occurs"
},
{
"code": null,
"e": 28542,
"s": 28462,
"text": "11.getNetworkInterfaces() : Returns all the network interfaces on the system. "
},
{
"code": null,
"e": 28726,
"s": 28542,
"text": "Syntax :public static Enumeration getNetworkInterfaces()\n throws SocketException\nThrows :\nSocketException : If IO error occurs"
},
{
"code": null,
"e": 28820,
"s": 28726,
"text": "12.isUp() : Returns a boolean value indicating if this network interface is up and running. "
},
{
"code": null,
"e": 28851,
"s": 28820,
"text": "Syntax : public boolean isUp()"
},
{
"code": null,
"e": 28956,
"s": 28851,
"text": "13.isLoopback() : Returns a boolean value indicating if this interface is a loopback interface or not. "
},
{
"code": null,
"e": 28994,
"s": 28956,
"text": " Syntax : public boolean isLoopback()"
},
{
"code": null,
"e": 29109,
"s": 28994,
"text": "14.isPointToPoint() : Returns a boolean value indicating if this interface is a point to point interface or not. "
},
{
"code": null,
"e": 29150,
"s": 29109,
"text": "Syntax : public boolean isPointToPoint()"
},
{
"code": null,
"e": 29260,
"s": 29150,
"text": "15.supportsMulticast() : Returns a boolean value indicating if this interface supports multicasting or not. "
},
{
"code": null,
"e": 29304,
"s": 29260,
"text": "Syntax : public boolean supportsMulticast()"
},
{
"code": null,
"e": 29490,
"s": 29304,
"text": "16.getHardwareAddress() : Returns a byte array containing the hardware address(MAC) address of this interface. The caller must have appropriate permissions before calling this method. "
},
{
"code": null,
"e": 29525,
"s": 29490,
"text": "public byte[] getHardwareAddress()"
},
{
"code": null,
"e": 29690,
"s": 29525,
"text": "17.getMTU() : Returns the maximum transmission unit of this interface. An MTU is the largest size of the packet or frame that can be sent in packet based network. "
},
{
"code": null,
"e": 29718,
"s": 29690,
"text": "Syntax :public int getMTU()"
},
{
"code": null,
"e": 29945,
"s": 29718,
"text": "18.isVirtual() : Returns a boolean value indicating whether this interface is a virtual interface or not. Virtual interfaces are used in conjunction physical interfaces to provide additional values such as addresses and MTU. "
},
{
"code": null,
"e": 29981,
"s": 29945,
"text": "Syntax : public boolean isVirtual()"
},
{
"code": null,
"e": 30150,
"s": 29981,
"text": "19.equals() : This method is used to compare two network interfaces for equality. Two network interfaces are equal if they have same name and addresses bound to them. "
},
{
"code": null,
"e": 30266,
"s": 30150,
"text": "Syntax :public boolean equals(Object obj)\nParameters : \nobj : Object to compare this network interface for equality"
},
{
"code": null,
"e": 30328,
"s": 30266,
"text": "20.hashCode() : Returns the hashcode value for this object. "
},
{
"code": null,
"e": 30358,
"s": 30328,
"text": "Syntax :public int hashCode()"
},
{
"code": null,
"e": 30422,
"s": 30358,
"text": "21.toString() : Returns a textual description of this object. "
},
{
"code": null,
"e": 30455,
"s": 30422,
"text": "Syntax :public String toString()"
},
{
"code": null,
"e": 30479,
"s": 30455,
"text": "Java Implementation : "
},
{
"code": null,
"e": 30484,
"s": 30479,
"text": "Java"
},
{
"code": "//Java program to illustrate various//networkInterface class methods.import java.net.InetAddress;import java.net.InterfaceAddress;import java.net.NetworkInterface;import java.net.SocketException;import java.net.UnknownHostException;import java.util.ArrayList;import java.util.Arrays;import java.util.Collections;import java.util.Enumeration; public class NetworkInterfaceEx{ public static void main(String[] args) throws SocketException, UnknownHostException { // getNetworkInterfaces() returns a list of all interfaces // present in the system. ArrayList<NetworkInterface> interfaces = Collections.list( NetworkInterface.getNetworkInterfaces()); System.out.println(\"Information about present Network Interfaces...\\n\"); for (NetworkInterface iface : interfaces) { // isUp() method used for checking whether the interface in process // is up and running or not. if (iface.isUp()) { // getName() method System.out.println(\"Interface Name: \" + iface.getName()); // getDisplayName() method System.out.println(\"Interface display name: \" + iface.getDisplayName()); // gethardwareaddress() method System.out.println(\"Hardware Address: \" + Arrays.toString(iface.getHardwareAddress())); // getParent() method System.out.println(\"Parent: \" + iface.getParent()); // getIndex() method System.out.println(\"Index: \" + iface.getIndex()); // Interface addresses of the network interface System.out.println(\"\\tInterface addresses: \"); // getInterfaceAddresses() method for (InterfaceAddress addr : iface.getInterfaceAddresses()) { System.out.println(\"\\t\\t\" + addr.getAddress().toString()); } // Interface addresses of the network interface System.out.println(\"\\tInetAddresses associated with this interface: \"); // getInetAddresses() method returns list of all // addresses currently bound to this interface Enumeration<InetAddress> en = iface.getInetAddresses(); while (en.hasMoreElements()) { System.out.println(\"\\t\\t\" + en.nextElement().toString()); } // getMTU() method System.out.println(\"\\tMTU: \" + iface.getMTU()); // getSubInterfaces() method System.out.println(\"\\tSubinterfaces: \" + Collections.list(iface.getSubInterfaces())); // isLoopback() method System.out.println(\"\\this loopback: \" + iface.isLoopback()); // isVirtual() method System.out.println(\"\\this virtual: \" + iface.isVirtual()); // isPointToPoint() method System.out.println(\"\\this point to point: \" + iface.isPointToPoint()); // supportsMulticast() method System.out.println(\"Supports Multicast: \" + iface.supportsMulticast()); } } // getByIndex() method returns network interface // with the specified index NetworkInterface nif = NetworkInterface.getByIndex(1); // toString() method is used to display textual // information about this network interface System.out.println(\"Network interface 1: \" + nif.toString()); // getByName() method returns network interface // with the specified name NetworkInterface nif2 = NetworkInterface.getByName(\"eth0\"); InetAddress ip = InetAddress.getByName(\"localhost\"); // getbyInetAddress() method NetworkInterface nif3 = NetworkInterface.getByInetAddress(ip); System.out.println(\"\\nlocalhost associated with: \" + nif3); // equals() method boolean eq = nif.equals(nif2); System.out.println(\"nif==nif2: \" + eq); // hashCode() method System.out.println(\"Hashcode : \" + nif.hashCode()); }}",
"e": 34764,
"s": 30484,
"text": null
},
{
"code": null,
"e": 34775,
"s": 34764,
"text": "Output : "
},
{
"code": null,
"e": 36094,
"s": 34775,
"text": "Information about present Network Interfaces...\n\nInterface Name: lo\nInterface display name: Software Loopback Interface 1\nHardware Address: null\nParent: null\nIndex: 1\n Interface addresses: \n /127.0.0.1\n /0:0:0:0:0:0:0:1\n InetAddresses associated with this interface: \n /127.0.0.1\n /0:0:0:0:0:0:0:1\n MTU: -1\n Subinterfaces: []\n is loopback: true\n is virtual: false\n is point to point: false\nSupports Multicast: true\nInterface Name: wlan5\nInterface display name: Dell Wireless 1705 802.11b|g|n (2.4GHZ)\nHardware Address: [100, 90, 4, -90, 2, 15]\nParent: null\nIndex: 16\n Interface addresses: \n /192.168.43.96\n /2405:205:1486:9a1b:e567:b46f:198a:fe0c\n /2405:205:1486:9a1b:8c93:9f82:6dd2:350c\n /fe80:0:0:0:e567:b46f:198a:fe0c%wlan5\n InetAddresses associated with this interface: \n /192.168.43.96\n /2405:205:1486:9a1b:e567:b46f:198a:fe0c\n /2405:205:1486:9a1b:8c93:9f82:6dd2:350c\n /fe80:0:0:0:e567:b46f:198a:fe0c%wlan5\n MTU: 1500\n Subinterfaces: []\n is loopback: false\n is virtual: false\n is point to point: false\nSupports Multicast: true\nNetwork interface 1: name:lo (Software Loopback Interface 1)\n\nloclhost associated with: name:lo (Software Loopback Interface 1)\nnif==nif2: false\nHashCode : 2544"
},
{
"code": null,
"e": 36698,
"s": 36094,
"text": "The output of the above program will differ if you run it on your system as than it will display information about your network interfaces.References : Official Java Documentation This article is contributed by Rishabh Mahrsee. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 36712,
"s": 36698,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 36728,
"s": 36712,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 36742,
"s": 36728,
"text": "sumitgumber28"
},
{
"code": null,
"e": 36760,
"s": 36742,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 36776,
"s": 36760,
"text": "Java-Networking"
},
{
"code": null,
"e": 36781,
"s": 36776,
"text": "Java"
},
{
"code": null,
"e": 36786,
"s": 36781,
"text": "Java"
},
{
"code": null,
"e": 36884,
"s": 36786,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36935,
"s": 36884,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 36965,
"s": 36935,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 36980,
"s": 36965,
"text": "Stream In Java"
},
{
"code": null,
"e": 37011,
"s": 36980,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 37029,
"s": 37011,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 37061,
"s": 37029,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 37081,
"s": 37061,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 37113,
"s": 37081,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 37137,
"s": 37113,
"text": "Singleton Class in Java"
}
] |
Turn a Matrix into a Row Vector in MATLAB - GeeksforGeeks | 04 Jul, 2021
Conversion of a Matrix into a Row Vector. This conversion can be done using reshape() function along with the Transpose operation. This reshape() function is used to reshape the specified matrix using the given size vector.
reshape(A, sz)
Parameters: This function accepts two parameters, which are illustrated below:
A: This is the specified matrix of elements.
sz: This is the specified size vector.
Return Value: It returns the row vector of a given matrix.
Example 1
Matlab
% Conversion of a 2D matrix into its% row vector.A = [1 2; 3 4]; %Initializing a matrix % Calling the reshape() function% over the above matrix as its transpose% and size vector as 1,[]B = reshape(A.',1,[])
Output:
Example 2
Matlab
% MATLAB code for Conversion of a 3*3% matrix into its row vector.A = [1 2 3; 4 5 6; 7 8 9]; % Initializing a 3*3 matrix % Calling the reshape() function% over the above matrix as its transpose% and size vector as 1,[]B = reshape(A.',1,[])
Output:
MATLAB
MATLAB-programs
MATLAB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Forward and Inverse Fourier Transform of an Image in MATLAB
Boundary Extraction of image using MATLAB
How to Remove Noise from Digital Image in Frequency Domain Using MATLAB?
How to Solve Histogram Equalization Numerical Problem in MATLAB?
How to Normalize a Histogram in MATLAB?
How to Remove Salt and Pepper Noise from Image Using MATLAB?
Double Integral in MATLAB
Classes and Object in MATLAB
How to Convert Three Channels of Colored Image into Grayscale Image in MATLAB?
What are different types of denoising filters in MATLAB? | [
{
"code": null,
"e": 25777,
"s": 25749,
"text": "\n04 Jul, 2021"
},
{
"code": null,
"e": 26001,
"s": 25777,
"text": "Conversion of a Matrix into a Row Vector. This conversion can be done using reshape() function along with the Transpose operation. This reshape() function is used to reshape the specified matrix using the given size vector."
},
{
"code": null,
"e": 26016,
"s": 26001,
"text": "reshape(A, sz)"
},
{
"code": null,
"e": 26095,
"s": 26016,
"text": "Parameters: This function accepts two parameters, which are illustrated below:"
},
{
"code": null,
"e": 26140,
"s": 26095,
"text": "A: This is the specified matrix of elements."
},
{
"code": null,
"e": 26179,
"s": 26140,
"text": "sz: This is the specified size vector."
},
{
"code": null,
"e": 26238,
"s": 26179,
"text": "Return Value: It returns the row vector of a given matrix."
},
{
"code": null,
"e": 26249,
"s": 26238,
"text": "Example 1 "
},
{
"code": null,
"e": 26256,
"s": 26249,
"text": "Matlab"
},
{
"code": "% Conversion of a 2D matrix into its% row vector.A = [1 2; 3 4]; %Initializing a matrix % Calling the reshape() function% over the above matrix as its transpose% and size vector as 1,[]B = reshape(A.',1,[])",
"e": 26464,
"s": 26256,
"text": null
},
{
"code": null,
"e": 26472,
"s": 26464,
"text": "Output:"
},
{
"code": null,
"e": 26482,
"s": 26472,
"text": "Example 2"
},
{
"code": null,
"e": 26489,
"s": 26482,
"text": "Matlab"
},
{
"code": "% MATLAB code for Conversion of a 3*3% matrix into its row vector.A = [1 2 3; 4 5 6; 7 8 9]; % Initializing a 3*3 matrix % Calling the reshape() function% over the above matrix as its transpose% and size vector as 1,[]B = reshape(A.',1,[])",
"e": 26731,
"s": 26489,
"text": null
},
{
"code": null,
"e": 26739,
"s": 26731,
"text": "Output:"
},
{
"code": null,
"e": 26746,
"s": 26739,
"text": "MATLAB"
},
{
"code": null,
"e": 26762,
"s": 26746,
"text": "MATLAB-programs"
},
{
"code": null,
"e": 26769,
"s": 26762,
"text": "MATLAB"
},
{
"code": null,
"e": 26867,
"s": 26769,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26927,
"s": 26867,
"text": "Forward and Inverse Fourier Transform of an Image in MATLAB"
},
{
"code": null,
"e": 26969,
"s": 26927,
"text": "Boundary Extraction of image using MATLAB"
},
{
"code": null,
"e": 27042,
"s": 26969,
"text": "How to Remove Noise from Digital Image in Frequency Domain Using MATLAB?"
},
{
"code": null,
"e": 27107,
"s": 27042,
"text": "How to Solve Histogram Equalization Numerical Problem in MATLAB?"
},
{
"code": null,
"e": 27147,
"s": 27107,
"text": "How to Normalize a Histogram in MATLAB?"
},
{
"code": null,
"e": 27208,
"s": 27147,
"text": "How to Remove Salt and Pepper Noise from Image Using MATLAB?"
},
{
"code": null,
"e": 27234,
"s": 27208,
"text": "Double Integral in MATLAB"
},
{
"code": null,
"e": 27263,
"s": 27234,
"text": "Classes and Object in MATLAB"
},
{
"code": null,
"e": 27342,
"s": 27263,
"text": "How to Convert Three Channels of Colored Image into Grayscale Image in MATLAB?"
}
] |
Launching an EC2 instance using AWS CLI - GeeksforGeeks | 26 Aug, 2020
In this article, we will look into the process of launching instances that is through AWS CLI(Command Line Interface).
AWS CLI is a unified tool for running and managing your various AWS services. Just download and install the tool and you will be able to control multiple AWS services from the command line. For Developers, it is a great tool for managing AWS services.
So, let’s begin with AWS CLI by launching an EC2 Instance using it. Creating an instance with AWS CLI is the same as launching one with AWS console. Open your command prompt as administrator by right-clicking on it.
The first thing to do is to create a VPC(virtual private cloud) under which an EC2 instance will be launched. For creating a VPC in CLI type the given command on the cmd.
aws ec2 create-vpc --cidr-block 10.0.0.0/16
Here the CIDR block I have taken is 10.0.0.0/16, you can change it as per your need. After running this command following output will be given in a JSON format. Note the vpcId .
Next, create two subnets and make one as public to make it accessible from the internet. To do so use the below command:
aws ec2 create-subnet --vpc-id <vpcId> --cidr-block 10.0.1.0/24
Note the SubnetId generated here, so that this subnet can be made as public later on. The CIDR block we have used here is 10.0.1.0/24.
Now create a second subnet with CIDR block 10.0.0.0/24. (CIDR block values can be changed as per user needs):
aws ec2 create-subnet --vpc-id <vpcId> --cidr-block 10.0.0.0/24
Internet gateway is used by the private subnet to access the internet for its updates and other packages installations. Create an internet gateway by using the following command:
aws ec2 create-internet-gateway
After the internet gateway is created, note the InternetGatewayId and to attach this internet gateway to the already created VPC. To do so use the below command:
aws ec2 attach-internet-gateway --vpc-id <vpcId> --internet-gateway-id <InternetGatewayId>
Here type the noted vpcId (in place of <vpcId>) and InternetGatewayId (in place of <InternetGatewayId>)
The next step is to create a route table and assigning it to the already created VPC. After creating the route table assign the route to this route table. Commands for the same are as given.
aws ec2 create-route-table --vpc-id <vpcId>
Now, use the RouteTableId and use it in the next step:
aws ec2 create-route --route-table-id <RouteTableId>
--destination-cidr-block 0.0.0.0/0 --gateway-id <nternetGatewayI>
Here we have used the 0.0.0.0/0 as destination CIDR block.
To check whether route table and subnets are created and assigned successfully use the below commands:
aws ec2 describe-route-tables --route-table-id <RouteTableId>
aws ec2 describe-subnets --filters "Name=vpc-id,Values=<vpcId>"
--query "Subnets[*].{ID:SubnetId,CIDR:CidrBlock}"
Here replace your vpcId in place of <vpcId>.
The next step is to associate the route table with the subnet and making the same subnet as public by mapping the public IP address to it. Enter the SubnetId and RouteTableId that you noted earlier. To associate route table type...
Type:
aws ec2 associate-route-table --subnet-id <SubnetId> --route-table-id <RouteTableId>
To map the public IP to the subnet, use the below command:
aws ec2 modify-subnet-attribute --subnet-id <SubnetId> --map-public-ip-on-launch
The most important step is to create a key pair. This key pair must be kept safe and secure with the user so that the person can access the EC2 instance created using this key pair.
Now, create the key-pair using the below command:
aws ec2 create-key-pair --key-name AWS-Keypair --query "KeyMaterial"
--output text > "C:\AWS\AWS_Keypair.pem"
Here we have named the key pair file(.pem file) as AWS-Keypair and the path where our file will be downloaded is C:\AWS\AWS_Keypair.pem. Both these things can be changed by the user.
For security group use the below commands:
aws ec2 create-security-group --group-name <security-group-name> --description "<description>"
--vpc-id <vpcId>
Here provide name and description to the security group and add it in place of <security-group-name> and <description> respectively. Note the GroupId and use it in the next step.
aws ec2 authorize-security-group-ingress --group-id <GroupId>
--protocol tcp --port 22 --cidr 0.0.0.0/0
The protocol/port we use here is TCP/22.
Finally, after all the setup completed successfully now the time is to run the instance. For running the EC2 Instance use the command as given below.
aws ec2 run-instances --image-id <ami-id> --count 1 --instance-type t2.micro
--key-name <Keypair-name> --security-group-ids <SecurityGroupId>
--subnet-id <SubnetId>
At this step, you will need an AMI(Amazon Machine Image) image ID. For this login to your AWS Console and choose any AMI of your type. Copy the image id and replace it here in place of <ami-id>. Also use your key pair name, security group id, and subnet id at the correct place in the above command. Also, make a note of the InstanceId.
Now after the instance status is “running” type the command to view the complete details of the EC2 instance that you just created:
aws ec2 describe-instances --instance-id <InstanceId>
Enter the InstanceId you noted at the above step.
To verify whether the EC2 instance created using the AWS CLI is created as per need, log in to your AWS Console and open the EC2 service and check for the instance.
AWS
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
Reinforcement learning
Decision Tree
Decision Tree Introduction with example
System Design Tutorial
Python | Decision tree implementation
Copying Files to and from Docker Containers
ML | Underfitting and Overfitting
Clustering in Machine Learning
Docker - COPY Instruction | [
{
"code": null,
"e": 25653,
"s": 25625,
"text": "\n26 Aug, 2020"
},
{
"code": null,
"e": 25773,
"s": 25653,
"text": "In this article, we will look into the process of launching instances that is through AWS CLI(Command Line Interface). "
},
{
"code": null,
"e": 26025,
"s": 25773,
"text": "AWS CLI is a unified tool for running and managing your various AWS services. Just download and install the tool and you will be able to control multiple AWS services from the command line. For Developers, it is a great tool for managing AWS services."
},
{
"code": null,
"e": 26241,
"s": 26025,
"text": "So, let’s begin with AWS CLI by launching an EC2 Instance using it. Creating an instance with AWS CLI is the same as launching one with AWS console. Open your command prompt as administrator by right-clicking on it."
},
{
"code": null,
"e": 26412,
"s": 26241,
"text": "The first thing to do is to create a VPC(virtual private cloud) under which an EC2 instance will be launched. For creating a VPC in CLI type the given command on the cmd."
},
{
"code": null,
"e": 26457,
"s": 26412,
"text": "aws ec2 create-vpc --cidr-block 10.0.0.0/16\n"
},
{
"code": null,
"e": 26636,
"s": 26457,
"text": "Here the CIDR block I have taken is 10.0.0.0/16, you can change it as per your need. After running this command following output will be given in a JSON format. Note the vpcId . "
},
{
"code": null,
"e": 26757,
"s": 26636,
"text": "Next, create two subnets and make one as public to make it accessible from the internet. To do so use the below command:"
},
{
"code": null,
"e": 26822,
"s": 26757,
"text": "aws ec2 create-subnet --vpc-id <vpcId> --cidr-block 10.0.1.0/24\n"
},
{
"code": null,
"e": 26959,
"s": 26822,
"text": "Note the SubnetId generated here, so that this subnet can be made as public later on. The CIDR block we have used here is 10.0.1.0/24. "
},
{
"code": null,
"e": 27070,
"s": 26959,
"text": " Now create a second subnet with CIDR block 10.0.0.0/24. (CIDR block values can be changed as per user needs):"
},
{
"code": null,
"e": 27135,
"s": 27070,
"text": "aws ec2 create-subnet --vpc-id <vpcId> --cidr-block 10.0.0.0/24\n"
},
{
"code": null,
"e": 27314,
"s": 27135,
"text": "Internet gateway is used by the private subnet to access the internet for its updates and other packages installations. Create an internet gateway by using the following command:"
},
{
"code": null,
"e": 27347,
"s": 27314,
"text": "aws ec2 create-internet-gateway\n"
},
{
"code": null,
"e": 27509,
"s": 27347,
"text": "After the internet gateway is created, note the InternetGatewayId and to attach this internet gateway to the already created VPC. To do so use the below command:"
},
{
"code": null,
"e": 27601,
"s": 27509,
"text": "aws ec2 attach-internet-gateway --vpc-id <vpcId> --internet-gateway-id <InternetGatewayId>\n"
},
{
"code": null,
"e": 27705,
"s": 27601,
"text": "Here type the noted vpcId (in place of <vpcId>) and InternetGatewayId (in place of <InternetGatewayId>)"
},
{
"code": null,
"e": 27896,
"s": 27705,
"text": "The next step is to create a route table and assigning it to the already created VPC. After creating the route table assign the route to this route table. Commands for the same are as given."
},
{
"code": null,
"e": 27941,
"s": 27896,
"text": "aws ec2 create-route-table --vpc-id <vpcId>\n"
},
{
"code": null,
"e": 27996,
"s": 27941,
"text": "Now, use the RouteTableId and use it in the next step:"
},
{
"code": null,
"e": 28131,
"s": 27996,
"text": "aws ec2 create-route --route-table-id <RouteTableId> \n --destination-cidr-block 0.0.0.0/0 --gateway-id <nternetGatewayI>\n"
},
{
"code": null,
"e": 28190,
"s": 28131,
"text": "Here we have used the 0.0.0.0/0 as destination CIDR block."
},
{
"code": null,
"e": 28293,
"s": 28190,
"text": "To check whether route table and subnets are created and assigned successfully use the below commands:"
},
{
"code": null,
"e": 28356,
"s": 28293,
"text": "aws ec2 describe-route-tables --route-table-id <RouteTableId>\n"
},
{
"code": null,
"e": 28496,
"s": 28356,
"text": "aws ec2 describe-subnets --filters \"Name=vpc-id,Values=<vpcId>\"\n --query \"Subnets[*].{ID:SubnetId,CIDR:CidrBlock}\"\n"
},
{
"code": null,
"e": 28541,
"s": 28496,
"text": "Here replace your vpcId in place of <vpcId>."
},
{
"code": null,
"e": 28774,
"s": 28541,
"text": "The next step is to associate the route table with the subnet and making the same subnet as public by mapping the public IP address to it. Enter the SubnetId and RouteTableId that you noted earlier. To associate route table type..."
},
{
"code": null,
"e": 28780,
"s": 28774,
"text": "Type:"
},
{
"code": null,
"e": 28869,
"s": 28780,
"text": "aws ec2 associate-route-table --subnet-id <SubnetId> --route-table-id <RouteTableId>\n\n\n\n"
},
{
"code": null,
"e": 28928,
"s": 28869,
"text": "To map the public IP to the subnet, use the below command:"
},
{
"code": null,
"e": 29013,
"s": 28928,
"text": "aws ec2 modify-subnet-attribute --subnet-id <SubnetId> --map-public-ip-on-launch\n\n\n\n"
},
{
"code": null,
"e": 29195,
"s": 29013,
"text": "The most important step is to create a key pair. This key pair must be kept safe and secure with the user so that the person can access the EC2 instance created using this key pair."
},
{
"code": null,
"e": 29245,
"s": 29195,
"text": "Now, create the key-pair using the below command:"
},
{
"code": null,
"e": 29381,
"s": 29245,
"text": "aws ec2 create-key-pair --key-name AWS-Keypair --query \"KeyMaterial\" \n --output text > \"C:\\AWS\\AWS_Keypair.pem\"\n"
},
{
"code": null,
"e": 29564,
"s": 29381,
"text": "Here we have named the key pair file(.pem file) as AWS-Keypair and the path where our file will be downloaded is C:\\AWS\\AWS_Keypair.pem. Both these things can be changed by the user."
},
{
"code": null,
"e": 29607,
"s": 29564,
"text": "For security group use the below commands:"
},
{
"code": null,
"e": 29753,
"s": 29607,
"text": "aws ec2 create-security-group --group-name <security-group-name> --description \"<description>\"\n --vpc-id <vpcId>\n\n\n\n"
},
{
"code": null,
"e": 29932,
"s": 29753,
"text": "Here provide name and description to the security group and add it in place of <security-group-name> and <description> respectively. Note the GroupId and use it in the next step."
},
{
"code": null,
"e": 30079,
"s": 29932,
"text": "aws ec2 authorize-security-group-ingress --group-id <GroupId> \n --protocol tcp --port 22 --cidr 0.0.0.0/0\n"
},
{
"code": null,
"e": 30120,
"s": 30079,
"text": "The protocol/port we use here is TCP/22."
},
{
"code": null,
"e": 30270,
"s": 30120,
"text": "Finally, after all the setup completed successfully now the time is to run the instance. For running the EC2 Instance use the command as given below."
},
{
"code": null,
"e": 30482,
"s": 30270,
"text": "aws ec2 run-instances --image-id <ami-id> --count 1 --instance-type t2.micro \n --key-name <Keypair-name> --security-group-ids <SecurityGroupId> \n --subnet-id <SubnetId>\n"
},
{
"code": null,
"e": 30820,
"s": 30482,
"text": "At this step, you will need an AMI(Amazon Machine Image) image ID. For this login to your AWS Console and choose any AMI of your type. Copy the image id and replace it here in place of <ami-id>. Also use your key pair name, security group id, and subnet id at the correct place in the above command. Also, make a note of the InstanceId."
},
{
"code": null,
"e": 30952,
"s": 30820,
"text": "Now after the instance status is “running” type the command to view the complete details of the EC2 instance that you just created:"
},
{
"code": null,
"e": 31007,
"s": 30952,
"text": "aws ec2 describe-instances --instance-id <InstanceId>\n"
},
{
"code": null,
"e": 31057,
"s": 31007,
"text": "Enter the InstanceId you noted at the above step."
},
{
"code": null,
"e": 31222,
"s": 31057,
"text": "To verify whether the EC2 instance created using the AWS CLI is created as per need, log in to your AWS Console and open the EC2 service and check for the instance."
},
{
"code": null,
"e": 31226,
"s": 31222,
"text": "AWS"
},
{
"code": null,
"e": 31252,
"s": 31226,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 31350,
"s": 31252,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31373,
"s": 31350,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 31396,
"s": 31373,
"text": "Reinforcement learning"
},
{
"code": null,
"e": 31410,
"s": 31396,
"text": "Decision Tree"
},
{
"code": null,
"e": 31450,
"s": 31410,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 31473,
"s": 31450,
"text": "System Design Tutorial"
},
{
"code": null,
"e": 31511,
"s": 31473,
"text": "Python | Decision tree implementation"
},
{
"code": null,
"e": 31555,
"s": 31511,
"text": "Copying Files to and from Docker Containers"
},
{
"code": null,
"e": 31589,
"s": 31555,
"text": "ML | Underfitting and Overfitting"
},
{
"code": null,
"e": 31620,
"s": 31589,
"text": "Clustering in Machine Learning"
}
] |
Keep your Notebooks Consistent with JupyterLab Templates | by Luke Gloege, Ph.D. | Towards Data Science | I spend most of my day working in JupyterLab and each notebook I create tends to have a similar structure. Instead of copy and pasting notebooks, the JupyterLab Templates extension is a solution that allows you to create notebooks you can reuse.
This short post will outline how to install and set up this extension.
Install the jupyterlab_templates packages via pip:
pip install jupyterlab_templates
then install
jupyter labextension install jupyterlab_templates
and enable the extension
jupyter serverextension enable --py jupyterlab_templates
Now we just need to set up the template directory
Create a directory where you will store your notebooks. For instance, my templates are stored here:
~/.jupyter/templates
Create the following file (if it does not yet exist)
~/.jupyter/jupyter_notebook_config.py
Add the following line to this file. This tells jupyterLab the full path to your template directory. This must be the full path, do not use the ~ shorthand
template_dirs → List of directories where you will store templates. Each .ipynb file in any subdirectory of these paths will be a template. Files in the parent directory will be ignored
**important** Templates need to be in a subdirectory of template_dirs directory. Files in the parent directory will be ignored
You can have more than one notebook in each subdirectory. As an example, here is my directory tree.
├──.jupyter └── templates └── analysis ├── analysis-template.ipynb └── test-template.ipynb
Now that everything is set up, you can start making your reusable notebooks. Here is my analysis-template.ipynb notebook
short description
Change log
date created and any changes go here
import numpy as np
import pandas as pd
import xarray as xr
import matplotlib.pyplot as plt
from dask.distributed import Client
from dask_jobqueue import SLURMCluster
# define worker
cluster = SLURMCluster()
# connect cluster to client
client = Client(cluster)
# add workers to the cluster
cluster.scale(4)
Now when you start jupyterLab you can access your templates like this:
You may have noticed that the package comes with a Sample.ipynb. For those that are curious, the following command will display the location of that file on macOS:
locate Sample.ipynb
On my machine, it is located here:
/Users/luke/miniforge3/lib/python3.9/site-packages/jupyterlab_templates/templates/jupyterlab_templates/Sample.ipynb
I have tried other notebook template solutions in the past, but they were all difficult and confusing to set up. This is the easiest solution I have found.
The only feature missing, in my opinion, is prompting the user to immediately rename the newly created notebook.
I hope this post helps keep your personal notebooks, or those across your team, consistent.
towardsdatascience.com
betterprogramming.pub
betterprogramming.pub
Thank you for reading and supporting Medium writers | [
{
"code": null,
"e": 418,
"s": 172,
"text": "I spend most of my day working in JupyterLab and each notebook I create tends to have a similar structure. Instead of copy and pasting notebooks, the JupyterLab Templates extension is a solution that allows you to create notebooks you can reuse."
},
{
"code": null,
"e": 489,
"s": 418,
"text": "This short post will outline how to install and set up this extension."
},
{
"code": null,
"e": 540,
"s": 489,
"text": "Install the jupyterlab_templates packages via pip:"
},
{
"code": null,
"e": 573,
"s": 540,
"text": "pip install jupyterlab_templates"
},
{
"code": null,
"e": 586,
"s": 573,
"text": "then install"
},
{
"code": null,
"e": 636,
"s": 586,
"text": "jupyter labextension install jupyterlab_templates"
},
{
"code": null,
"e": 661,
"s": 636,
"text": "and enable the extension"
},
{
"code": null,
"e": 718,
"s": 661,
"text": "jupyter serverextension enable --py jupyterlab_templates"
},
{
"code": null,
"e": 768,
"s": 718,
"text": "Now we just need to set up the template directory"
},
{
"code": null,
"e": 868,
"s": 768,
"text": "Create a directory where you will store your notebooks. For instance, my templates are stored here:"
},
{
"code": null,
"e": 889,
"s": 868,
"text": "~/.jupyter/templates"
},
{
"code": null,
"e": 942,
"s": 889,
"text": "Create the following file (if it does not yet exist)"
},
{
"code": null,
"e": 980,
"s": 942,
"text": "~/.jupyter/jupyter_notebook_config.py"
},
{
"code": null,
"e": 1136,
"s": 980,
"text": "Add the following line to this file. This tells jupyterLab the full path to your template directory. This must be the full path, do not use the ~ shorthand"
},
{
"code": null,
"e": 1322,
"s": 1136,
"text": "template_dirs → List of directories where you will store templates. Each .ipynb file in any subdirectory of these paths will be a template. Files in the parent directory will be ignored"
},
{
"code": null,
"e": 1449,
"s": 1322,
"text": "**important** Templates need to be in a subdirectory of template_dirs directory. Files in the parent directory will be ignored"
},
{
"code": null,
"e": 1549,
"s": 1449,
"text": "You can have more than one notebook in each subdirectory. As an example, here is my directory tree."
},
{
"code": null,
"e": 1668,
"s": 1549,
"text": "├──.jupyter └── templates └── analysis ├── analysis-template.ipynb └── test-template.ipynb"
},
{
"code": null,
"e": 1789,
"s": 1668,
"text": "Now that everything is set up, you can start making your reusable notebooks. Here is my analysis-template.ipynb notebook"
},
{
"code": null,
"e": 1808,
"s": 1789,
"text": "short description "
},
{
"code": null,
"e": 1819,
"s": 1808,
"text": "Change log"
},
{
"code": null,
"e": 1856,
"s": 1819,
"text": "date created and any changes go here"
},
{
"code": null,
"e": 1948,
"s": 1856,
"text": "import numpy as np\nimport pandas as pd\nimport xarray as xr\nimport matplotlib.pyplot as plt\n"
},
{
"code": null,
"e": 2167,
"s": 1948,
"text": "from dask.distributed import Client\nfrom dask_jobqueue import SLURMCluster\n\n# define worker\ncluster = SLURMCluster()\n\n# connect cluster to client\nclient = Client(cluster)\n\n# add workers to the cluster\ncluster.scale(4)\n"
},
{
"code": null,
"e": 2247,
"s": 2176,
"text": "Now when you start jupyterLab you can access your templates like this:"
},
{
"code": null,
"e": 2411,
"s": 2247,
"text": "You may have noticed that the package comes with a Sample.ipynb. For those that are curious, the following command will display the location of that file on macOS:"
},
{
"code": null,
"e": 2431,
"s": 2411,
"text": "locate Sample.ipynb"
},
{
"code": null,
"e": 2466,
"s": 2431,
"text": "On my machine, it is located here:"
},
{
"code": null,
"e": 2582,
"s": 2466,
"text": "/Users/luke/miniforge3/lib/python3.9/site-packages/jupyterlab_templates/templates/jupyterlab_templates/Sample.ipynb"
},
{
"code": null,
"e": 2738,
"s": 2582,
"text": "I have tried other notebook template solutions in the past, but they were all difficult and confusing to set up. This is the easiest solution I have found."
},
{
"code": null,
"e": 2851,
"s": 2738,
"text": "The only feature missing, in my opinion, is prompting the user to immediately rename the newly created notebook."
},
{
"code": null,
"e": 2943,
"s": 2851,
"text": "I hope this post helps keep your personal notebooks, or those across your team, consistent."
},
{
"code": null,
"e": 2966,
"s": 2943,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 2988,
"s": 2966,
"text": "betterprogramming.pub"
},
{
"code": null,
"e": 3010,
"s": 2988,
"text": "betterprogramming.pub"
}
] |
Java else Keyword | ❮ Java Keywords
Use the else statement to specify a block of code to be executed if the condition is false.
int time = 20;
if (time < 18) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
// Outputs "Good evening."
Try it Yourself »
The else statement specifies a block of Java code to be executed if a condition is false in an if statement.
Java has the following conditional statements:
Use if to specify a block of code to be executed, if a specified condition is true
Use else to specify a block of code to be executed, if the same condition is false
Use else if to specify a new condition to test, if the first condition is false
Use switch to specify many alternative blocks of code to be executed
Use the else if statement to specify a new condition if the first condition is false.
int time = 22;
if (time < 10) {
System.out.println("Good morning.");
} else if (time < 20) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
// Outputs "Good evening."
Try it Yourself »
Read more about conditions in our Java If...Else Tutorial.
❮ Java Keywords
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools. | [
{
"code": null,
"e": 18,
"s": 0,
"text": "\n❮ Java Keywords\n"
},
{
"code": null,
"e": 110,
"s": 18,
"text": "Use the else statement to specify a block of code to be executed if the condition is false."
},
{
"code": null,
"e": 255,
"s": 110,
"text": "int time = 20;\nif (time < 18) {\n System.out.println(\"Good day.\");\n} else {\n System.out.println(\"Good evening.\");\n}\n// Outputs \"Good evening.\"\n"
},
{
"code": null,
"e": 275,
"s": 255,
"text": "\nTry it Yourself »\n"
},
{
"code": null,
"e": 384,
"s": 275,
"text": "The else statement specifies a block of Java code to be executed if a condition is false in an if statement."
},
{
"code": null,
"e": 431,
"s": 384,
"text": "Java has the following conditional statements:"
},
{
"code": null,
"e": 514,
"s": 431,
"text": "Use if to specify a block of code to be executed, if a specified condition is true"
},
{
"code": null,
"e": 597,
"s": 514,
"text": "Use else to specify a block of code to be executed, if the same condition is false"
},
{
"code": null,
"e": 677,
"s": 597,
"text": "Use else if to specify a new condition to test, if the first condition is false"
},
{
"code": null,
"e": 746,
"s": 677,
"text": "Use switch to specify many alternative blocks of code to be executed"
},
{
"code": null,
"e": 832,
"s": 746,
"text": "Use the else if statement to specify a new condition if the first condition is false."
},
{
"code": null,
"e": 1040,
"s": 832,
"text": "int time = 22;\nif (time < 10) {\n System.out.println(\"Good morning.\");\n} else if (time < 20) {\n System.out.println(\"Good day.\");\n} else {\n System.out.println(\"Good evening.\");\n}\n// Outputs \"Good evening.\"\n"
},
{
"code": null,
"e": 1060,
"s": 1040,
"text": "\nTry it Yourself »\n"
},
{
"code": null,
"e": 1119,
"s": 1060,
"text": "Read more about conditions in our Java If...Else Tutorial."
},
{
"code": null,
"e": 1137,
"s": 1119,
"text": "\n❮ Java Keywords\n"
},
{
"code": null,
"e": 1170,
"s": 1137,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 1212,
"s": 1170,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 1319,
"s": 1212,
"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": 1338,
"s": 1319,
"text": "help@w3schools.com"
}
] |
Better, Faster, Stronger Python Exploratory Data Analysis (EDA) | by Philippe Bouaziz,Data Scientist at Africa4Data,PhD | Towards Data Science | Exploratory data analysis (EDA) is a fundamental step in the understanding of most data science projects whether your developing machine learning models or business analytics. This process consists of handling missing data, coding data types (continuous, categorical), calculate associations-correlations between features, shaping data structures, building design charts (histogram, boxplot, time series, etc..). Due to the high quantity of data, finding tricks for faster analysis using automatizations library is a key advantage for becoming a unicorn data scientist. In this article, we will review the 4 most successful open source short python code lines which can be combined for making a first-class EDA. For this article, we will be analysing the sample chocolate bar rating dataset you can find here: chocolate-bar.
Pandas UI
Pandas UI
Pandas_ui is an efficient open-source alternative to bamboolib. This package reduces data pre-processing time creating useful visualizations combining python libraries such as plotly, pandas, qgrid, ipywidgets, and pandas profiling. With this package, you can delete columns, encode categorical features, merged features, filter-sort rows, groupby features, data types, unique and missing values count, replace values, quantiles statistics(Q1 median, Q3, maximum, range, interquartile range), descriptive statistics(mean, mode, standard deviation, sum, median absolute deviation), outliers, visualizations (histograms), correlations (Pearson matrices). Ultimately focusing on your machine learning goals saving time on the data explorations step. For using this package a jupyter notebook( or jupyter lab) on your computer with python 3.7 is required. Refer to this github for more details.
pip install pandas_uijupyter nbextension enable — py qgrid — sys-prefixjupyter nbextension enable — py widgetsnbextension — sys-prefixfrom pandas_ui import *pdf =pandas_ui(“../input/chocolate-bar-2020/chocolate.csv”)pdf.to_file(output_file=”pandas_ui1.html”)get_df() # to get the data frame#get_meltdf() or get_pivotdf() # to get melt or pivot dataframes if you have created any.
2. Pandas profiling
Pandas_profiling is an open-source one-line code that creates a complete HTML analytic report from a csv dataset for fast and accurate data analysis. With this package, you can obtain easily data types, unique and missing values(count, heatmap, and dendrogram), quantiles(Q1 median, Q3, maximum, range, interquartile range), descriptive statistics(mean, mode, standard deviation, sum, median absolute deviation, coefficient of variation, kurtosis, skewness), outliers, visualizations such as histograms, correlations (Spearman, Pearson and Kendall matrices), text analysis (Uppercase, Space, scripts and ASCII blocks), file and image analysis (dimensions, truncated images scan). For using this package a jupyter notebook(or jupyter lab) on your computer with python 3.7 is required.
Generates profile reports from a pandas DataFrame. The pandas df.describe() function is great but a little basic for serious exploratory data analysis. pandas_profiling extends the pandas DataFrame with df.profile_report() for quick data analysis.
pip install pandas-profilingorconda install -c anaconda pandas-profilingfrom pandas_profiling import ProfileReportdf = pd.read_csv(‘../input/chocolate-bar-2020/chocolate.csv’)pr = ProfileReport(df)pr.to_file(output_file=”pandas_profiling1.html”)pr
Refer to this GitHub for more details.
3. Sweetviz
Sweetviz is a great two-line code that creates high-density visualizations HTML report. With this package you can select features easily by the target value visualization against other features (A vs B for target feature y), comparing two datasets (train vas test). Also, you can obtain missing values, quantile and descriptive statistics, histograms, uncertainty correlations (categorical- categorical), correlation ratio (for categorical-numerical). For using this package a jupyter notebook( or jupyter lab) on your computer with python 3.7 is required.
After installation of Sweetviz (using pip install sweetviz), simply load the panda’s data frames as you normally would, then call either analyze(), compare(), or compare_intra() depending on your need (more on that below). The full documentation can be found on GitHub. For now, let’s start with the case at hand, loading it as so:
df = pd.read_csv(‘../input/chocolate-bar-2020/chocolate.csv’)from sklearn.model_selection import train_test_splittrain, test = train_test_split(df, test_size=0.3)!pip install sweetvizimport sweetviz as svsweetviz_report = sv.analyze([df,”data”],target_feat=’rating’)sweetviz_report.show_html(‘viz.html’)df1 = sv.compare(train, test)df1.show_html(‘Compare.html’)
We now have 2 data-frames (train and test), and we would like to analyse the target value “Rating”. Here the interactive report more in details : here
Squares represent categorical-featured-related variables correlations. Note that the trivial diagonal is left empty, for clarity.
4. Autoviz
Autoviz is an open-source one-line code that creates a complete HTML analytic report from a csv dataset for small and big datasets. With this package, you can obtain visualizations including bar charts, histograms, correlations heatmaps, quantile, and descriptive statistics. Autoviz offers a one-click engine Auto Viz.io in which you can upload your data online getting a completely free report directly send to your email.
AutoViz can be implemented in 4 simple steps:
!pip install autovizfrom autoviz.AutoViz_Class import AutoViz_ClassAV = AutoViz_Class()dft = AV.AutoViz(filename = “”, sep= ‘,’ , depVar=’rating’, dfte= df, header=0, verbose=2, lowess=False, chart_format=”svg”, max_rows_analyzed=2500, max_cols_analyzed= 21)dft.to_file(output_file=”autoviz_profiling.html”)
If you have some spare time I’d recommend, you’ll read this:
https://medium.com/swlh/eda-exploratory-data-analysis-e0f453d97894
Sum Up
Refer to this link Chocolate bar rating EDA for a complete EDA analysis of chocolate bar rating using these tools and other well-known visualizations.
This brief overview is a reminder of the importance of Exploratory Data Analysis using python in data science. This post has for the scope to covered 4 essential Python EDA tools for making a complete exploration workflow, as well as useful documentation.
I hope you enjoy it, keep exploring!!! | [
{
"code": null,
"e": 997,
"s": 172,
"text": "Exploratory data analysis (EDA) is a fundamental step in the understanding of most data science projects whether your developing machine learning models or business analytics. This process consists of handling missing data, coding data types (continuous, categorical), calculate associations-correlations between features, shaping data structures, building design charts (histogram, boxplot, time series, etc..). Due to the high quantity of data, finding tricks for faster analysis using automatizations library is a key advantage for becoming a unicorn data scientist. In this article, we will review the 4 most successful open source short python code lines which can be combined for making a first-class EDA. For this article, we will be analysing the sample chocolate bar rating dataset you can find here: chocolate-bar."
},
{
"code": null,
"e": 1007,
"s": 997,
"text": "Pandas UI"
},
{
"code": null,
"e": 1017,
"s": 1007,
"text": "Pandas UI"
},
{
"code": null,
"e": 1908,
"s": 1017,
"text": "Pandas_ui is an efficient open-source alternative to bamboolib. This package reduces data pre-processing time creating useful visualizations combining python libraries such as plotly, pandas, qgrid, ipywidgets, and pandas profiling. With this package, you can delete columns, encode categorical features, merged features, filter-sort rows, groupby features, data types, unique and missing values count, replace values, quantiles statistics(Q1 median, Q3, maximum, range, interquartile range), descriptive statistics(mean, mode, standard deviation, sum, median absolute deviation), outliers, visualizations (histograms), correlations (Pearson matrices). Ultimately focusing on your machine learning goals saving time on the data explorations step. For using this package a jupyter notebook( or jupyter lab) on your computer with python 3.7 is required. Refer to this github for more details."
},
{
"code": null,
"e": 2288,
"s": 1908,
"text": "pip install pandas_uijupyter nbextension enable — py qgrid — sys-prefixjupyter nbextension enable — py widgetsnbextension — sys-prefixfrom pandas_ui import *pdf =pandas_ui(“../input/chocolate-bar-2020/chocolate.csv”)pdf.to_file(output_file=”pandas_ui1.html”)get_df() # to get the data frame#get_meltdf() or get_pivotdf() # to get melt or pivot dataframes if you have created any."
},
{
"code": null,
"e": 2308,
"s": 2288,
"text": "2. Pandas profiling"
},
{
"code": null,
"e": 3092,
"s": 2308,
"text": "Pandas_profiling is an open-source one-line code that creates a complete HTML analytic report from a csv dataset for fast and accurate data analysis. With this package, you can obtain easily data types, unique and missing values(count, heatmap, and dendrogram), quantiles(Q1 median, Q3, maximum, range, interquartile range), descriptive statistics(mean, mode, standard deviation, sum, median absolute deviation, coefficient of variation, kurtosis, skewness), outliers, visualizations such as histograms, correlations (Spearman, Pearson and Kendall matrices), text analysis (Uppercase, Space, scripts and ASCII blocks), file and image analysis (dimensions, truncated images scan). For using this package a jupyter notebook(or jupyter lab) on your computer with python 3.7 is required."
},
{
"code": null,
"e": 3340,
"s": 3092,
"text": "Generates profile reports from a pandas DataFrame. The pandas df.describe() function is great but a little basic for serious exploratory data analysis. pandas_profiling extends the pandas DataFrame with df.profile_report() for quick data analysis."
},
{
"code": null,
"e": 3588,
"s": 3340,
"text": "pip install pandas-profilingorconda install -c anaconda pandas-profilingfrom pandas_profiling import ProfileReportdf = pd.read_csv(‘../input/chocolate-bar-2020/chocolate.csv’)pr = ProfileReport(df)pr.to_file(output_file=”pandas_profiling1.html”)pr"
},
{
"code": null,
"e": 3627,
"s": 3588,
"text": "Refer to this GitHub for more details."
},
{
"code": null,
"e": 3639,
"s": 3627,
"text": "3. Sweetviz"
},
{
"code": null,
"e": 4196,
"s": 3639,
"text": "Sweetviz is a great two-line code that creates high-density visualizations HTML report. With this package you can select features easily by the target value visualization against other features (A vs B for target feature y), comparing two datasets (train vas test). Also, you can obtain missing values, quantile and descriptive statistics, histograms, uncertainty correlations (categorical- categorical), correlation ratio (for categorical-numerical). For using this package a jupyter notebook( or jupyter lab) on your computer with python 3.7 is required."
},
{
"code": null,
"e": 4528,
"s": 4196,
"text": "After installation of Sweetviz (using pip install sweetviz), simply load the panda’s data frames as you normally would, then call either analyze(), compare(), or compare_intra() depending on your need (more on that below). The full documentation can be found on GitHub. For now, let’s start with the case at hand, loading it as so:"
},
{
"code": null,
"e": 4890,
"s": 4528,
"text": "df = pd.read_csv(‘../input/chocolate-bar-2020/chocolate.csv’)from sklearn.model_selection import train_test_splittrain, test = train_test_split(df, test_size=0.3)!pip install sweetvizimport sweetviz as svsweetviz_report = sv.analyze([df,”data”],target_feat=’rating’)sweetviz_report.show_html(‘viz.html’)df1 = sv.compare(train, test)df1.show_html(‘Compare.html’)"
},
{
"code": null,
"e": 5041,
"s": 4890,
"text": "We now have 2 data-frames (train and test), and we would like to analyse the target value “Rating”. Here the interactive report more in details : here"
},
{
"code": null,
"e": 5171,
"s": 5041,
"text": "Squares represent categorical-featured-related variables correlations. Note that the trivial diagonal is left empty, for clarity."
},
{
"code": null,
"e": 5182,
"s": 5171,
"text": "4. Autoviz"
},
{
"code": null,
"e": 5607,
"s": 5182,
"text": "Autoviz is an open-source one-line code that creates a complete HTML analytic report from a csv dataset for small and big datasets. With this package, you can obtain visualizations including bar charts, histograms, correlations heatmaps, quantile, and descriptive statistics. Autoviz offers a one-click engine Auto Viz.io in which you can upload your data online getting a completely free report directly send to your email."
},
{
"code": null,
"e": 5653,
"s": 5607,
"text": "AutoViz can be implemented in 4 simple steps:"
},
{
"code": null,
"e": 5961,
"s": 5653,
"text": "!pip install autovizfrom autoviz.AutoViz_Class import AutoViz_ClassAV = AutoViz_Class()dft = AV.AutoViz(filename = “”, sep= ‘,’ , depVar=’rating’, dfte= df, header=0, verbose=2, lowess=False, chart_format=”svg”, max_rows_analyzed=2500, max_cols_analyzed= 21)dft.to_file(output_file=”autoviz_profiling.html”)"
},
{
"code": null,
"e": 6022,
"s": 5961,
"text": "If you have some spare time I’d recommend, you’ll read this:"
},
{
"code": null,
"e": 6089,
"s": 6022,
"text": "https://medium.com/swlh/eda-exploratory-data-analysis-e0f453d97894"
},
{
"code": null,
"e": 6096,
"s": 6089,
"text": "Sum Up"
},
{
"code": null,
"e": 6247,
"s": 6096,
"text": "Refer to this link Chocolate bar rating EDA for a complete EDA analysis of chocolate bar rating using these tools and other well-known visualizations."
},
{
"code": null,
"e": 6503,
"s": 6247,
"text": "This brief overview is a reminder of the importance of Exploratory Data Analysis using python in data science. This post has for the scope to covered 4 essential Python EDA tools for making a complete exploration workflow, as well as useful documentation."
}
] |
How to Insert Hyperlink in HTML Page? | With HTML, easily add hyperlinks to any HTML page. Link team page, about page, or even a test by creating it a hyperlink. You can also create a hyperlink for an external website. To make a hyperlink in an HTML page, use the <a> and </a> tags, which are the tags used to define the links.
The <a> tag indicates where the hyperlink starts and the </a> tag indicates where it ends. Whatever text gets added inside these tags, will work as a hyperlink. Add the URL for the link in the <a href=” ”>. Just keep in mind that you should use the <a>...</a> tags inside <body>...</body> tags.
You can try to run the following code to insert a hyperlink in an HTML page
<!DOCTYPE html>
<html>
<head>
<title>HTML Hyperlinks</title>
</head>
<body>
<h1>Company</h1>
<p>
We are a <a href="/about/about_team.htm">team</a> of professionals working
hard to provide free learning content.
</p>
</body>
</html> | [
{
"code": null,
"e": 1350,
"s": 1062,
"text": "With HTML, easily add hyperlinks to any HTML page. Link team page, about page, or even a test by creating it a hyperlink. You can also create a hyperlink for an external website. To make a hyperlink in an HTML page, use the <a> and </a> tags, which are the tags used to define the links."
},
{
"code": null,
"e": 1645,
"s": 1350,
"text": "The <a> tag indicates where the hyperlink starts and the </a> tag indicates where it ends. Whatever text gets added inside these tags, will work as a hyperlink. Add the URL for the link in the <a href=” ”>. Just keep in mind that you should use the <a>...</a> tags inside <body>...</body> tags."
},
{
"code": null,
"e": 1721,
"s": 1645,
"text": "You can try to run the following code to insert a hyperlink in an HTML page"
},
{
"code": null,
"e": 2008,
"s": 1721,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML Hyperlinks</title>\n </head>\n\n <body>\n <h1>Company</h1>\n <p>\n We are a <a href=\"/about/about_team.htm\">team</a> of professionals working\n hard to provide free learning content.\n </p>\n </body>\n</html>"
}
] |
Why training set should always be smaller than test set | by Gianluca Malato | Towards Data Science | In the machine learning world, data scientists are often told to train a supervised model on a large training dataset and test it on a smaller amount of data. The reason why training dataset is always chosen larger than the test one is that somebody says that the larger the data used for training, the better the model learns.
I’ve always thought that this kind of perspective is actually not completely true and, in this article, I’ll show you why you should keep your training set as small as possible and, instead, reserve the larger part of your data to test purposes.
The real task of a supervised model is not learning on the largest dataset possible, but learning in a way that the model performance on unknown data is satisfactory. That’s why we perform the model cross-validation on an unseen dataset.
Data scientists usually provide some model performance metrics calculated on such test datasets, like AuROC, accuracy, precision, root mean squared error and so on. The idea is that if our model performs quite well on unseen data, it will likely perform well in a production environment.
But how accurate is our measure of model’s performance? If I say that my model has an AuROC of 86% on a 100 records test dataset and another person says that another model has still an 86% AuROC but on a 10.000 test dataset, are the two values comparable? Which one would you prefer if you were a manager of a large company and you had been asked to invest some money according to the model prediction?
I’ll give you a spoiler. The larger the test set, the higher the precision of any performance metrics calculated on it.
I am a physicist, so I’ve always been told that every measure must be followed by an error estimate. I could tell you I am 1.93 meters tall, but I’m not giving you any information about the precision of this estimate. Is it 1 centimeter, is it 12 centimeters? You can’t tell. The right information could be: I am 1.93 +/- 0.01 m tall, which is 1.93 m with an error estimate of 1 centimeter. If somebody else tries to measure my height, he may obtain 1.93 +/- 0.12 m, which is 1.93 m with an error estimate of 12 centimeters. Which measure is more accurate? Of course the former. Its error is an order of magnitude lower than the latter.
The same approach can be applied to machine learning models. Every time you calculate model performance (e.g. AuROC, accuracy, RMSE), you are performing a measure and this measure must be followed by an error estimate.
So how do you calculate the error estimate on such a measure? There are many techniques, but I prefer using bootstrap, which is a resampling technique that allows you to calculate the standard error and the confidence intervals for an estimate. The standard deviation of the observable among the bootstrap samples is the standard error we can use in our report. It can be easily proofed that the error estimate decreases as the square root of the sample size.
That’s why you must use a large test set. It provides a better estimate of model performance on unseen data.
In the following Python example, I’ll simulate a 1 million records dataset of 4 independent and normally distributed features, then I’ll artificially create a target variable according to the following linear model:
The error between the linear model prediction and the sample y values is normally distributed.
Then I’ll fit the linear model and calculate the RMSE with its standard error and show you that a larger test set gives a smaller standard error, therefore a higher precision for the RMSE value.
You can find the whole code on my GitHub repository: https://github.com/gianlucamalato/machinelearning/blob/master/Small_training_large_test.ipynb
First, let’s import some libraries.
import numpy as npfrom sklearn.model_selection import train_test_splitfrom sklearn.linear_model import LinearRegressionfrom sklearn.metrics import mean_squared_error
Let’s simulate 1 million records with 4 normally and independently distributed features.
np.random.seed(0)X = np.random.normal(size=4000000).reshape(1000000,4)
Now we can create the output variable applying a normally distributed noise.
y = []for record in X: y.append(np.sum(record) + np.random.normal()) y = np.array(y)
Let’s now split our X,y dataset in training and test sets with a test set size that is 20% of the total.
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
Now we can fit the linear regression model.
model = LinearRegression()model.fit(X_train,y_train)
Before calculating model performance, let’s define a function that calculates RMSE and its error estimate with a bootstrapping of 100 samples.
def estimate_error(X_test,y_test): n_iter = 100 np.random.seed(0) errors = [] indices = list(range(X_test.shape[0])) for i in range(n_iter): new_indices = np.random.choice(indices, len(indices),replace=True) new_X_test = X_test[new_indices] new_y_test = y_test[new_indices] new_y_pred = model.predict(new_X_test) new_error = np.sqrt(mean_squared_error(new_y_test,new_y_pred)) errors.append(new_error) return np.mean(errors),np.std(errors)
These are the results:
So we have a RMSE equal to 1.0028 +/- 0.0015.
What happens if we use a test set that covers 80% of the total population size?
The random split and the model training become:
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.8, random_state=42)model = LinearRegression()model.fit(X_train,y_train)
The new RMSE estimates are:
So we have 1.00072 +/- 0.00075. Our error has decreased by an order of magnitude, so this last measure is more accurate.
There’s no magic inside these numbers. Simply, it’s an effect of the law of large numbers and of the bootstrapping technique. With larger datasets, any observable estimate in a sample becomes very close to its value on the population it has been drawn from.
Larger test datasets ensure a more accurate calculation of model performance. Training on smaller datasets can be done by sampling techniques such as stratified sampling. It will speed up your training (because you use less data) and make your results more reliable.
[1] Gianluca Malato. The bootstrap. The Swiss army knife of any data scientist. Data Science Reporter. https://medium.com/data-science-reporter/the-bootstrap-the-swiss-army-knife-of-any-data-scientist-acd6e592be13
[2] Gianluca Malato. Stratified sampling and how to perform it in R. Towards Data Science. https://towardsdatascience.com/stratified-sampling-and-how-to-perform-it-in-r-8b753efde1ef
[3] Gianluca Malato. How to correctly select a sample from a huge dataset in machine learning. Data Science Reporter. https://medium.com/data-science-reporter/how-to-correctly-select-a-sample-from-a-huge-dataset-in-machine-learning-24327650372c | [
{
"code": null,
"e": 499,
"s": 171,
"text": "In the machine learning world, data scientists are often told to train a supervised model on a large training dataset and test it on a smaller amount of data. The reason why training dataset is always chosen larger than the test one is that somebody says that the larger the data used for training, the better the model learns."
},
{
"code": null,
"e": 745,
"s": 499,
"text": "I’ve always thought that this kind of perspective is actually not completely true and, in this article, I’ll show you why you should keep your training set as small as possible and, instead, reserve the larger part of your data to test purposes."
},
{
"code": null,
"e": 983,
"s": 745,
"text": "The real task of a supervised model is not learning on the largest dataset possible, but learning in a way that the model performance on unknown data is satisfactory. That’s why we perform the model cross-validation on an unseen dataset."
},
{
"code": null,
"e": 1271,
"s": 983,
"text": "Data scientists usually provide some model performance metrics calculated on such test datasets, like AuROC, accuracy, precision, root mean squared error and so on. The idea is that if our model performs quite well on unseen data, it will likely perform well in a production environment."
},
{
"code": null,
"e": 1674,
"s": 1271,
"text": "But how accurate is our measure of model’s performance? If I say that my model has an AuROC of 86% on a 100 records test dataset and another person says that another model has still an 86% AuROC but on a 10.000 test dataset, are the two values comparable? Which one would you prefer if you were a manager of a large company and you had been asked to invest some money according to the model prediction?"
},
{
"code": null,
"e": 1794,
"s": 1674,
"text": "I’ll give you a spoiler. The larger the test set, the higher the precision of any performance metrics calculated on it."
},
{
"code": null,
"e": 2431,
"s": 1794,
"text": "I am a physicist, so I’ve always been told that every measure must be followed by an error estimate. I could tell you I am 1.93 meters tall, but I’m not giving you any information about the precision of this estimate. Is it 1 centimeter, is it 12 centimeters? You can’t tell. The right information could be: I am 1.93 +/- 0.01 m tall, which is 1.93 m with an error estimate of 1 centimeter. If somebody else tries to measure my height, he may obtain 1.93 +/- 0.12 m, which is 1.93 m with an error estimate of 12 centimeters. Which measure is more accurate? Of course the former. Its error is an order of magnitude lower than the latter."
},
{
"code": null,
"e": 2650,
"s": 2431,
"text": "The same approach can be applied to machine learning models. Every time you calculate model performance (e.g. AuROC, accuracy, RMSE), you are performing a measure and this measure must be followed by an error estimate."
},
{
"code": null,
"e": 3110,
"s": 2650,
"text": "So how do you calculate the error estimate on such a measure? There are many techniques, but I prefer using bootstrap, which is a resampling technique that allows you to calculate the standard error and the confidence intervals for an estimate. The standard deviation of the observable among the bootstrap samples is the standard error we can use in our report. It can be easily proofed that the error estimate decreases as the square root of the sample size."
},
{
"code": null,
"e": 3219,
"s": 3110,
"text": "That’s why you must use a large test set. It provides a better estimate of model performance on unseen data."
},
{
"code": null,
"e": 3435,
"s": 3219,
"text": "In the following Python example, I’ll simulate a 1 million records dataset of 4 independent and normally distributed features, then I’ll artificially create a target variable according to the following linear model:"
},
{
"code": null,
"e": 3530,
"s": 3435,
"text": "The error between the linear model prediction and the sample y values is normally distributed."
},
{
"code": null,
"e": 3725,
"s": 3530,
"text": "Then I’ll fit the linear model and calculate the RMSE with its standard error and show you that a larger test set gives a smaller standard error, therefore a higher precision for the RMSE value."
},
{
"code": null,
"e": 3872,
"s": 3725,
"text": "You can find the whole code on my GitHub repository: https://github.com/gianlucamalato/machinelearning/blob/master/Small_training_large_test.ipynb"
},
{
"code": null,
"e": 3908,
"s": 3872,
"text": "First, let’s import some libraries."
},
{
"code": null,
"e": 4074,
"s": 3908,
"text": "import numpy as npfrom sklearn.model_selection import train_test_splitfrom sklearn.linear_model import LinearRegressionfrom sklearn.metrics import mean_squared_error"
},
{
"code": null,
"e": 4163,
"s": 4074,
"text": "Let’s simulate 1 million records with 4 normally and independently distributed features."
},
{
"code": null,
"e": 4234,
"s": 4163,
"text": "np.random.seed(0)X = np.random.normal(size=4000000).reshape(1000000,4)"
},
{
"code": null,
"e": 4311,
"s": 4234,
"text": "Now we can create the output variable applying a normally distributed noise."
},
{
"code": null,
"e": 4400,
"s": 4311,
"text": "y = []for record in X: y.append(np.sum(record) + np.random.normal()) y = np.array(y)"
},
{
"code": null,
"e": 4505,
"s": 4400,
"text": "Let’s now split our X,y dataset in training and test sets with a test set size that is 20% of the total."
},
{
"code": null,
"e": 4595,
"s": 4505,
"text": "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)"
},
{
"code": null,
"e": 4639,
"s": 4595,
"text": "Now we can fit the linear regression model."
},
{
"code": null,
"e": 4692,
"s": 4639,
"text": "model = LinearRegression()model.fit(X_train,y_train)"
},
{
"code": null,
"e": 4835,
"s": 4692,
"text": "Before calculating model performance, let’s define a function that calculates RMSE and its error estimate with a bootstrapping of 100 samples."
},
{
"code": null,
"e": 5305,
"s": 4835,
"text": "def estimate_error(X_test,y_test): n_iter = 100 np.random.seed(0) errors = [] indices = list(range(X_test.shape[0])) for i in range(n_iter): new_indices = np.random.choice(indices, len(indices),replace=True) new_X_test = X_test[new_indices] new_y_test = y_test[new_indices] new_y_pred = model.predict(new_X_test) new_error = np.sqrt(mean_squared_error(new_y_test,new_y_pred)) errors.append(new_error) return np.mean(errors),np.std(errors)"
},
{
"code": null,
"e": 5328,
"s": 5305,
"text": "These are the results:"
},
{
"code": null,
"e": 5374,
"s": 5328,
"text": "So we have a RMSE equal to 1.0028 +/- 0.0015."
},
{
"code": null,
"e": 5454,
"s": 5374,
"text": "What happens if we use a test set that covers 80% of the total population size?"
},
{
"code": null,
"e": 5502,
"s": 5454,
"text": "The random split and the model training become:"
},
{
"code": null,
"e": 5644,
"s": 5502,
"text": "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.8, random_state=42)model = LinearRegression()model.fit(X_train,y_train)"
},
{
"code": null,
"e": 5672,
"s": 5644,
"text": "The new RMSE estimates are:"
},
{
"code": null,
"e": 5793,
"s": 5672,
"text": "So we have 1.00072 +/- 0.00075. Our error has decreased by an order of magnitude, so this last measure is more accurate."
},
{
"code": null,
"e": 6051,
"s": 5793,
"text": "There’s no magic inside these numbers. Simply, it’s an effect of the law of large numbers and of the bootstrapping technique. With larger datasets, any observable estimate in a sample becomes very close to its value on the population it has been drawn from."
},
{
"code": null,
"e": 6318,
"s": 6051,
"text": "Larger test datasets ensure a more accurate calculation of model performance. Training on smaller datasets can be done by sampling techniques such as stratified sampling. It will speed up your training (because you use less data) and make your results more reliable."
},
{
"code": null,
"e": 6532,
"s": 6318,
"text": "[1] Gianluca Malato. The bootstrap. The Swiss army knife of any data scientist. Data Science Reporter. https://medium.com/data-science-reporter/the-bootstrap-the-swiss-army-knife-of-any-data-scientist-acd6e592be13"
},
{
"code": null,
"e": 6714,
"s": 6532,
"text": "[2] Gianluca Malato. Stratified sampling and how to perform it in R. Towards Data Science. https://towardsdatascience.com/stratified-sampling-and-how-to-perform-it-in-r-8b753efde1ef"
}
] |
Get the sum only from specific cells in MySQL? | For only specific cells, set a condition with WHERE and use aggregate function SUM() to add. Let us first create a table −
mysql> create table DemoTable1370
-> (
-> StudentName varchar(20),
-> Marks int
-> );
Query OK, 0 rows affected (0.87 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1370 values('Adam Smith',56);
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable1370 values('Chris Brown',67);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable1370 values('Adam Smith',69);
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable1370 values('David Miller',98);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1370 values('John Smith',59);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable1370 values('Adam Smith',79);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable1370 values('Chris Brown',77);
Query OK, 1 row affected (0.17 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1370;
This will produce the following output −
+--------------+-------+
| StudentName | Marks |
+--------------+-------+
| Adam Smith | 56 |
| Chris Brown | 67 |
| Adam Smith | 69 |
| David Miller | 98 |
| John Smith | 59 |
| Adam Smith | 79 |
| Chris Brown | 77 |
+--------------+-------+
7 rows in set (0.00 sec)
Here is the query that gets the sum from specific cells −
mysql> select sum(Marks) AS Total from DemoTable1370 where StudentName='Adam Smith';
This will produce the following output −
+-------+
| Total |
+-------+
| 204 |
+-------+
1 row in set (0.00 sec) | [
{
"code": null,
"e": 1185,
"s": 1062,
"text": "For only specific cells, set a condition with WHERE and use aggregate function SUM() to add. Let us first create a table −"
},
{
"code": null,
"e": 1320,
"s": 1185,
"text": "mysql> create table DemoTable1370\n -> (\n -> StudentName varchar(20),\n -> Marks int\n -> );\nQuery OK, 0 rows affected (0.87 sec)"
},
{
"code": null,
"e": 1376,
"s": 1320,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 2038,
"s": 1376,
"text": "mysql> insert into DemoTable1370 values('Adam Smith',56);\nQuery OK, 1 row affected (0.20 sec)\nmysql> insert into DemoTable1370 values('Chris Brown',67);\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into DemoTable1370 values('Adam Smith',69);\nQuery OK, 1 row affected (0.20 sec)\nmysql> insert into DemoTable1370 values('David Miller',98);\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into DemoTable1370 values('John Smith',59);\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable1370 values('Adam Smith',79);\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into DemoTable1370 values('Chris Brown',77);\nQuery OK, 1 row affected (0.17 sec)"
},
{
"code": null,
"e": 2098,
"s": 2038,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 2134,
"s": 2098,
"text": "mysql> select * from DemoTable1370;"
},
{
"code": null,
"e": 2175,
"s": 2134,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2475,
"s": 2175,
"text": "+--------------+-------+\n| StudentName | Marks |\n+--------------+-------+\n| Adam Smith | 56 |\n| Chris Brown | 67 |\n| Adam Smith | 69 |\n| David Miller | 98 |\n| John Smith | 59 |\n| Adam Smith | 79 |\n| Chris Brown | 77 |\n+--------------+-------+\n7 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2533,
"s": 2475,
"text": "Here is the query that gets the sum from specific cells −"
},
{
"code": null,
"e": 2618,
"s": 2533,
"text": "mysql> select sum(Marks) AS Total from DemoTable1370 where StudentName='Adam Smith';"
},
{
"code": null,
"e": 2659,
"s": 2618,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2733,
"s": 2659,
"text": "+-------+\n| Total |\n+-------+\n| 204 |\n+-------+\n1 row in set (0.00 sec)"
}
] |
What is the difference between DB2 JOIN and UNION? Explain with the help of an example | Both JOIN and UNION are used to combine the data from one or more tables. In case of JOIN, the additional data appears in column while in case of UNION additional data appears in rows.
For example,
Suppose we have two DB2 tables, ORDERS and TRANSACTIONS. We have to extract TRANSACTION_ID for each ORDER_ID, then we will use INNER JOIN as below:
SELECT ORDER_ID, TRANSACTION_ID
FROM ORDERS INNER JOIN TRANSACTIONS ON
ORDERS.TRANSACTION_ID = TRANSACTIONS.TRANSACTION_ID
This query will result in 2 columns. One column will be from ORDERS table i.e., ORDER_ID and other column will be from TRANSACTIONS table i.e. TRANSACTION_ID.
We have 2 tables ORDERS and ORDER_HIST. The ORDERS table has all the current orders while ORDER_HIST table has all the archived orders. If we want to list down all the orders having total value more than 10000, then we have to use the below query.
SELECT ORDER_ID, ORDER_TOTAL FROM ORDERS WHERE ORDER_TOTAL > 10000
UNION
SELECT ORDER_ID, ORDER_TOTAL FROM ORDERS_HIST WHERE ORDER_TOTAL > 10000 | [
{
"code": null,
"e": 1247,
"s": 1062,
"text": "Both JOIN and UNION are used to combine the data from one or more tables. In case of JOIN, the additional data appears in column while in case of UNION additional data appears in rows."
},
{
"code": null,
"e": 1260,
"s": 1247,
"text": "For example,"
},
{
"code": null,
"e": 1408,
"s": 1260,
"text": "Suppose we have two DB2 tables, ORDERS and TRANSACTIONS. We have to extract TRANSACTION_ID for each ORDER_ID, then we will use INNER JOIN as below:"
},
{
"code": null,
"e": 1537,
"s": 1408,
"text": "SELECT ORDER_ID, TRANSACTION_ID\n FROM ORDERS INNER JOIN TRANSACTIONS ON\n ORDERS.TRANSACTION_ID = TRANSACTIONS.TRANSACTION_ID"
},
{
"code": null,
"e": 1696,
"s": 1537,
"text": "This query will result in 2 columns. One column will be from ORDERS table i.e., ORDER_ID and other column will be from TRANSACTIONS table i.e. TRANSACTION_ID."
},
{
"code": null,
"e": 1944,
"s": 1696,
"text": "We have 2 tables ORDERS and ORDER_HIST. The ORDERS table has all the current orders while ORDER_HIST table has all the archived orders. If we want to list down all the orders having total value more than 10000, then we have to use the below query."
},
{
"code": null,
"e": 2089,
"s": 1944,
"text": "SELECT ORDER_ID, ORDER_TOTAL FROM ORDERS WHERE ORDER_TOTAL > 10000\nUNION\nSELECT ORDER_ID, ORDER_TOTAL FROM ORDERS_HIST WHERE ORDER_TOTAL > 10000"
}
] |
How to iterate over a callback n times in JavaScript ? | 17 Feb, 2022
Given a callback function we have to iterate over a callback n times. The callback is a function that is passed as an argument. for iterate over callback function, we have to run callback function n time.
Approach 1: We use recursion to iterate n times callback function.
First create callback function factor which takes n as argument.
Factor function generate pattern of n length.
Create test function that takes callback function and n.
Test function checks value of n is equal to 0 and not.
If n is 0 it return terminate test function, else it call callback function which print the pattern.
Example:
Javascript
<script> // callback function that print pattern function factor(n) { // base case for recursion if (n <= 1) { console.log("0" + n); return; } // string to store patterns let str = ""; // loop for generate pattern for (let i = 1; i <= n; i++) { str += `0${i} `; } // printing patterns console.log(str); // recursion call with decrement by 1 return factor(n - 1); } // function to run callback function function test(n, callback) { if (n == 0) { console.log("please provide value n greater than 0"); return; } let k = n; //calling callback function callback(k); } // initialising test number let t_number = 4; // calling main function to call callback function test(t_number, factor);</script>
Output:
01 02 03 04
01 02 03
01 02
01
Approach 2: We use loop statement to iterate over callback.
First we create callback function factor which generate factorial of number.
Create test function with argument n and callback function.
Check value of n if it in invalid terminate if not continue.
Create for loop with range n.
On each loop call callback function which print factorial of each number.
Example:
Javascript
<script> // call back function that return factorial function factor(number) { let j = 1; // loop that generate factorial of number for (let i = 1; i <= number; i++) { j *= i; } // printing value of factorial console.log(`factorial of ${number} is `); console.log(j); } // function that iterate over callback function function test(n, callback) { if (n <= 0) { console.log("invalid number"); return; } let k = n; // iterating over callback function with for loop for (let i = k; i >= 1; i--) callback(i); } // initialising test variable let t_umber = 5; // main function calling test(t_umber, factor);</script>
Output:
factorial of 5 is 120
factorial of 4 is 24
factorial of 3 is 6
factorial of 2 is 2
factorial of 1 is 1
ruhelaa48
sagartomar9927
surindertarika1234
sumitgumber28
adnanirshad158
simmytarika5
javascript-functions
JavaScript-Questions
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Hide or show elements in HTML using display property
How to append HTML code to a div using JavaScript ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Feb, 2022"
},
{
"code": null,
"e": 233,
"s": 28,
"text": "Given a callback function we have to iterate over a callback n times. The callback is a function that is passed as an argument. for iterate over callback function, we have to run callback function n time."
},
{
"code": null,
"e": 300,
"s": 233,
"text": "Approach 1: We use recursion to iterate n times callback function."
},
{
"code": null,
"e": 365,
"s": 300,
"text": "First create callback function factor which takes n as argument."
},
{
"code": null,
"e": 411,
"s": 365,
"text": "Factor function generate pattern of n length."
},
{
"code": null,
"e": 468,
"s": 411,
"text": "Create test function that takes callback function and n."
},
{
"code": null,
"e": 524,
"s": 468,
"text": "Test function checks value of n is equal to 0 and not."
},
{
"code": null,
"e": 625,
"s": 524,
"text": "If n is 0 it return terminate test function, else it call callback function which print the pattern."
},
{
"code": null,
"e": 635,
"s": 625,
"text": "Example: "
},
{
"code": null,
"e": 646,
"s": 635,
"text": "Javascript"
},
{
"code": "<script> // callback function that print pattern function factor(n) { // base case for recursion if (n <= 1) { console.log(\"0\" + n); return; } // string to store patterns let str = \"\"; // loop for generate pattern for (let i = 1; i <= n; i++) { str += `0${i} `; } // printing patterns console.log(str); // recursion call with decrement by 1 return factor(n - 1); } // function to run callback function function test(n, callback) { if (n == 0) { console.log(\"please provide value n greater than 0\"); return; } let k = n; //calling callback function callback(k); } // initialising test number let t_number = 4; // calling main function to call callback function test(t_number, factor);</script>",
"e": 1429,
"s": 646,
"text": null
},
{
"code": null,
"e": 1437,
"s": 1429,
"text": "Output:"
},
{
"code": null,
"e": 1467,
"s": 1437,
"text": "01 02 03 04\n01 02 03\n01 02\n01"
},
{
"code": null,
"e": 1528,
"s": 1467,
"text": "Approach 2: We use loop statement to iterate over callback. "
},
{
"code": null,
"e": 1605,
"s": 1528,
"text": "First we create callback function factor which generate factorial of number."
},
{
"code": null,
"e": 1665,
"s": 1605,
"text": "Create test function with argument n and callback function."
},
{
"code": null,
"e": 1726,
"s": 1665,
"text": "Check value of n if it in invalid terminate if not continue."
},
{
"code": null,
"e": 1756,
"s": 1726,
"text": "Create for loop with range n."
},
{
"code": null,
"e": 1830,
"s": 1756,
"text": "On each loop call callback function which print factorial of each number."
},
{
"code": null,
"e": 1841,
"s": 1830,
"text": "Example: "
},
{
"code": null,
"e": 1852,
"s": 1841,
"text": "Javascript"
},
{
"code": "<script> // call back function that return factorial function factor(number) { let j = 1; // loop that generate factorial of number for (let i = 1; i <= number; i++) { j *= i; } // printing value of factorial console.log(`factorial of ${number} is `); console.log(j); } // function that iterate over callback function function test(n, callback) { if (n <= 0) { console.log(\"invalid number\"); return; } let k = n; // iterating over callback function with for loop for (let i = k; i >= 1; i--) callback(i); } // initialising test variable let t_umber = 5; // main function calling test(t_umber, factor);</script>",
"e": 2526,
"s": 1852,
"text": null
},
{
"code": null,
"e": 2534,
"s": 2526,
"text": "Output:"
},
{
"code": null,
"e": 2638,
"s": 2534,
"text": "factorial of 5 is 120\nfactorial of 4 is 24\nfactorial of 3 is 6\nfactorial of 2 is 2 \nfactorial of 1 is 1"
},
{
"code": null,
"e": 2648,
"s": 2638,
"text": "ruhelaa48"
},
{
"code": null,
"e": 2663,
"s": 2648,
"text": "sagartomar9927"
},
{
"code": null,
"e": 2682,
"s": 2663,
"text": "surindertarika1234"
},
{
"code": null,
"e": 2696,
"s": 2682,
"text": "sumitgumber28"
},
{
"code": null,
"e": 2711,
"s": 2696,
"text": "adnanirshad158"
},
{
"code": null,
"e": 2724,
"s": 2711,
"text": "simmytarika5"
},
{
"code": null,
"e": 2745,
"s": 2724,
"text": "javascript-functions"
},
{
"code": null,
"e": 2766,
"s": 2745,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 2773,
"s": 2766,
"text": "Picked"
},
{
"code": null,
"e": 2784,
"s": 2773,
"text": "JavaScript"
},
{
"code": null,
"e": 2801,
"s": 2784,
"text": "Web Technologies"
},
{
"code": null,
"e": 2899,
"s": 2801,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2960,
"s": 2899,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3032,
"s": 2960,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 3072,
"s": 3032,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 3125,
"s": 3072,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 3177,
"s": 3125,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 3239,
"s": 3177,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3272,
"s": 3239,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3333,
"s": 3272,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3383,
"s": 3333,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Python | Check if all elements in a list are identical | 18 Jan, 2019
Given a list, write a Python program to check if all the elements in that list are identical.
Examples:
Input : ['a', 'b', 'c']
Output : False
Input : [1, 1, 1, 1]
Output : True
Approach #1 : Using loopStart a for loop and check if first element is identical to all other elements in the list. This approach takes O(n) time complexity.
# Python3 program to check if # all elements in a list are identicaldef check(list): return all(i == list[0] for i in list) # Driver codeprint(check(['a', 'b', 'c']))print(check([1, 1, 1]))
False
True
Approach #2 : Using SetConverting given list into set removes all duplicate elements, If the resultant set size is less than or equal to 1 then the list contains all identical elements.
# Python3 program to check if # all elements in a list are identicaldef check(list): return len(set(list)) <= 1 # Driver codeprint(check(['a', 'b', 'c']))print(check([1, 1, 1]))
False
True
Approach #3 : Using count()By counting the number of times the first element occurs in the list, we can check if the count is equal to the size of list or not. In simple words, check if the first element is repeated throughout the list or not.
# Python3 program to check if # all elements in a list are identicaldef check(list): return list.count(list[0]) == len(list) # Driver codeprint(check(['a', 'b', 'c']))print(check([1, 1, 1]))
False
True
Approach #4 : Alternative methodAnother method is to take the first element and multiply it with the length of given list to form a new list, So that the new list contains identical elements to first elements of given list size, and then compare it with the given list.
# Python3 program to check if # all elements in a list are identicaldef check(x): return x and [x[0]]*len(x) == x # Driver codeprint(check(['a', 'b', 'c']))print(check([1, 1, 1]))
False
True
Approach #5 : Using extended slicesPython slice notation is used to retrieve a subset of values. Thus, we compare the start to end of the list to end to start of the list.
# Python3 program to check if # all elements in a list are identicaldef check(list): return list[1:] == list[:-1] # Driver codeprint(check(['a', 'b', 'c']))print(check([1, 1, 1]))
False
True
Python list-programs
python-list
Python
Python Programs
python-list
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()
Python program to convert a list to string
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Jan, 2019"
},
{
"code": null,
"e": 122,
"s": 28,
"text": "Given a list, write a Python program to check if all the elements in that list are identical."
},
{
"code": null,
"e": 132,
"s": 122,
"text": "Examples:"
},
{
"code": null,
"e": 208,
"s": 132,
"text": "Input : ['a', 'b', 'c']\nOutput : False\n\nInput : [1, 1, 1, 1]\nOutput : True\n"
},
{
"code": null,
"e": 366,
"s": 208,
"text": "Approach #1 : Using loopStart a for loop and check if first element is identical to all other elements in the list. This approach takes O(n) time complexity."
},
{
"code": "# Python3 program to check if # all elements in a list are identicaldef check(list): return all(i == list[0] for i in list) # Driver codeprint(check(['a', 'b', 'c']))print(check([1, 1, 1]))",
"e": 564,
"s": 366,
"text": null
},
{
"code": null,
"e": 576,
"s": 564,
"text": "False\nTrue\n"
},
{
"code": null,
"e": 763,
"s": 576,
"text": " Approach #2 : Using SetConverting given list into set removes all duplicate elements, If the resultant set size is less than or equal to 1 then the list contains all identical elements."
},
{
"code": "# Python3 program to check if # all elements in a list are identicaldef check(list): return len(set(list)) <= 1 # Driver codeprint(check(['a', 'b', 'c']))print(check([1, 1, 1]))",
"e": 947,
"s": 763,
"text": null
},
{
"code": null,
"e": 959,
"s": 947,
"text": "False\nTrue\n"
},
{
"code": null,
"e": 1204,
"s": 959,
"text": " Approach #3 : Using count()By counting the number of times the first element occurs in the list, we can check if the count is equal to the size of list or not. In simple words, check if the first element is repeated throughout the list or not."
},
{
"code": "# Python3 program to check if # all elements in a list are identicaldef check(list): return list.count(list[0]) == len(list) # Driver codeprint(check(['a', 'b', 'c']))print(check([1, 1, 1]))",
"e": 1401,
"s": 1204,
"text": null
},
{
"code": null,
"e": 1413,
"s": 1401,
"text": "False\nTrue\n"
},
{
"code": null,
"e": 1684,
"s": 1413,
"text": " Approach #4 : Alternative methodAnother method is to take the first element and multiply it with the length of given list to form a new list, So that the new list contains identical elements to first elements of given list size, and then compare it with the given list."
},
{
"code": "# Python3 program to check if # all elements in a list are identicaldef check(x): return x and [x[0]]*len(x) == x # Driver codeprint(check(['a', 'b', 'c']))print(check([1, 1, 1]))",
"e": 1871,
"s": 1684,
"text": null
},
{
"code": null,
"e": 1883,
"s": 1871,
"text": "False\nTrue\n"
},
{
"code": null,
"e": 2056,
"s": 1883,
"text": " Approach #5 : Using extended slicesPython slice notation is used to retrieve a subset of values. Thus, we compare the start to end of the list to end to start of the list."
},
{
"code": "# Python3 program to check if # all elements in a list are identicaldef check(list): return list[1:] == list[:-1] # Driver codeprint(check(['a', 'b', 'c']))print(check([1, 1, 1]))",
"e": 2242,
"s": 2056,
"text": null
},
{
"code": null,
"e": 2254,
"s": 2242,
"text": "False\nTrue\n"
},
{
"code": null,
"e": 2275,
"s": 2254,
"text": "Python list-programs"
},
{
"code": null,
"e": 2287,
"s": 2275,
"text": "python-list"
},
{
"code": null,
"e": 2294,
"s": 2287,
"text": "Python"
},
{
"code": null,
"e": 2310,
"s": 2294,
"text": "Python Programs"
},
{
"code": null,
"e": 2322,
"s": 2310,
"text": "python-list"
},
{
"code": null,
"e": 2420,
"s": 2322,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2438,
"s": 2420,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2480,
"s": 2438,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2502,
"s": 2480,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2537,
"s": 2502,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2563,
"s": 2537,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2606,
"s": 2563,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 2645,
"s": 2606,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2683,
"s": 2645,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 2732,
"s": 2683,
"text": "Python | Convert string dictionary to dictionary"
}
] |
numpy.ix_() function | Python | 22 Apr, 2020
numpy.ix_() function construct an open mesh from multiple sequences. This function takes N 1-D sequences and returns N outputs with N dimensions each, such that the shape is 1 in all but one dimension and the dimension with the non-unit shape value cycles through all N dimensions.
Syntax : numpy.ix_(args)Parameters :args : [1-D sequences] Each sequence should be of integer or boolean type.Return : [tuple of ndarrays] N arrays with N dimensions each, with N the number of input sequences. Together these arrays form an open mesh.
Code #1 :
# Python program explaining# numpy.ix_() function # importing numpy as geek import numpy as geek gfg = geek.ix_([0, 1], [2, 4]) print (gfg)
Output :
(array([[0],
[1]]), array([[2, 4]]))
Code #2 :
# Python program explaining# numpy.ix_() function # importing numpy as geek import numpy as geek arr = geek.arange(10).reshape(2, 5)print("Initial array : \n", arr) ixgrid = geek.ix_([0, 1], [2, 4]) print("New array : \n", arr[ixgrid])
Output :
Initial array :
[[0 1 2 3 4]
[5 6 7 8 9]]
New array :
[[2 4]
[7 9]]
Python numpy-arrayManipulation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Apr, 2020"
},
{
"code": null,
"e": 310,
"s": 28,
"text": "numpy.ix_() function construct an open mesh from multiple sequences. This function takes N 1-D sequences and returns N outputs with N dimensions each, such that the shape is 1 in all but one dimension and the dimension with the non-unit shape value cycles through all N dimensions."
},
{
"code": null,
"e": 561,
"s": 310,
"text": "Syntax : numpy.ix_(args)Parameters :args : [1-D sequences] Each sequence should be of integer or boolean type.Return : [tuple of ndarrays] N arrays with N dimensions each, with N the number of input sequences. Together these arrays form an open mesh."
},
{
"code": null,
"e": 571,
"s": 561,
"text": "Code #1 :"
},
{
"code": "# Python program explaining# numpy.ix_() function # importing numpy as geek import numpy as geek gfg = geek.ix_([0, 1], [2, 4]) print (gfg)",
"e": 714,
"s": 571,
"text": null
},
{
"code": null,
"e": 723,
"s": 714,
"text": "Output :"
},
{
"code": null,
"e": 768,
"s": 723,
"text": "(array([[0],\n [1]]), array([[2, 4]]))\n"
},
{
"code": null,
"e": 779,
"s": 768,
"text": " Code #2 :"
},
{
"code": "# Python program explaining# numpy.ix_() function # importing numpy as geek import numpy as geek arr = geek.arange(10).reshape(2, 5)print(\"Initial array : \\n\", arr) ixgrid = geek.ix_([0, 1], [2, 4]) print(\"New array : \\n\", arr[ixgrid]) ",
"e": 1021,
"s": 779,
"text": null
},
{
"code": null,
"e": 1030,
"s": 1021,
"text": "Output :"
},
{
"code": null,
"e": 1105,
"s": 1030,
"text": "Initial array : \n [[0 1 2 3 4]\n [5 6 7 8 9]]\nNew array : \n [[2 4]\n [7 9]]\n"
},
{
"code": null,
"e": 1136,
"s": 1105,
"text": "Python numpy-arrayManipulation"
},
{
"code": null,
"e": 1149,
"s": 1136,
"text": "Python-numpy"
},
{
"code": null,
"e": 1156,
"s": 1149,
"text": "Python"
},
{
"code": null,
"e": 1254,
"s": 1156,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1286,
"s": 1254,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1313,
"s": 1286,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1334,
"s": 1313,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1357,
"s": 1334,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1413,
"s": 1357,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1444,
"s": 1413,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1486,
"s": 1444,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 1528,
"s": 1486,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 1567,
"s": 1528,
"text": "Python | Get unique values from a list"
}
] |
D3.js | d3.map.values() Function | 28 Jun, 2019
The map.values() function in D3.js used to return an array of values for every entry in the created map. The order of the returned values are arbitrary.
Syntax:
d3.map.values()
Parameters: This function does not accept any parameters.
Return Value: This function returns an array of values for every entry in the created map. Order of those returned values are arbitrary.
Below programs illustrate the d3.map.values() function in D3.js:
Example 1:
<!DOCTYPE html><html> <head> <title> d3.map.values() Function</title> <script src='https://d3js.org/d3.v4.min.js'></script></head> <body> <script> // Creating a map var map = d3.map({"Ram": 5, "Geeks": 10, "gfg": 15}); // Calling the map.values() function A = map.values(); // Getting an array of values for // every entry in the map. console.log(A); </script></body> </html>
Output:
[5, 10, 15]
Example 2:
<!DOCTYPE html><html> <head> <title> d3.map.values() Function</title> <script src='https://d3js.org/d3.v4.min.js'></script></head> <body> <script> // Creating some maps var map1 = d3.map({"Ram": 5}); var map2 = d3.map({"Geeks": 10}); var map3 = d3.map({"Ram": 5, "Geeks": 10}); var map4 = d3.map(); // Calling the map.values() function A = map1.values(); B = map2.values(); C = map3.values(); D = map4.values(); // Getting an array of values for // every entry in the map. console.log(A); console.log(B); console.log(C); console.log(D); </script></body> </html>
Output:
[5]
[10]
[5, 10]
[]
Ref: https://devdocs.io/d3~5/d3-collection#map_values
D3.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
How to Open URL in New Tab 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": "\n28 Jun, 2019"
},
{
"code": null,
"e": 181,
"s": 28,
"text": "The map.values() function in D3.js used to return an array of values for every entry in the created map. The order of the returned values are arbitrary."
},
{
"code": null,
"e": 189,
"s": 181,
"text": "Syntax:"
},
{
"code": null,
"e": 205,
"s": 189,
"text": "d3.map.values()"
},
{
"code": null,
"e": 263,
"s": 205,
"text": "Parameters: This function does not accept any parameters."
},
{
"code": null,
"e": 400,
"s": 263,
"text": "Return Value: This function returns an array of values for every entry in the created map. Order of those returned values are arbitrary."
},
{
"code": null,
"e": 465,
"s": 400,
"text": "Below programs illustrate the d3.map.values() function in D3.js:"
},
{
"code": null,
"e": 476,
"s": 465,
"text": "Example 1:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> d3.map.values() Function</title> <script src='https://d3js.org/d3.v4.min.js'></script></head> <body> <script> // Creating a map var map = d3.map({\"Ram\": 5, \"Geeks\": 10, \"gfg\": 15}); // Calling the map.values() function A = map.values(); // Getting an array of values for // every entry in the map. console.log(A); </script></body> </html>",
"e": 923,
"s": 476,
"text": null
},
{
"code": null,
"e": 931,
"s": 923,
"text": "Output:"
},
{
"code": null,
"e": 944,
"s": 931,
"text": "[5, 10, 15]\n"
},
{
"code": null,
"e": 955,
"s": 944,
"text": "Example 2:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> d3.map.values() Function</title> <script src='https://d3js.org/d3.v4.min.js'></script></head> <body> <script> // Creating some maps var map1 = d3.map({\"Ram\": 5}); var map2 = d3.map({\"Geeks\": 10}); var map3 = d3.map({\"Ram\": 5, \"Geeks\": 10}); var map4 = d3.map(); // Calling the map.values() function A = map1.values(); B = map2.values(); C = map3.values(); D = map4.values(); // Getting an array of values for // every entry in the map. console.log(A); console.log(B); console.log(C); console.log(D); </script></body> </html>",
"e": 1621,
"s": 955,
"text": null
},
{
"code": null,
"e": 1629,
"s": 1621,
"text": "Output:"
},
{
"code": null,
"e": 1650,
"s": 1629,
"text": "[5]\n[10]\n[5, 10]\n[]\n"
},
{
"code": null,
"e": 1704,
"s": 1650,
"text": "Ref: https://devdocs.io/d3~5/d3-collection#map_values"
},
{
"code": null,
"e": 1710,
"s": 1704,
"text": "D3.js"
},
{
"code": null,
"e": 1721,
"s": 1710,
"text": "JavaScript"
},
{
"code": null,
"e": 1738,
"s": 1721,
"text": "Web Technologies"
},
{
"code": null,
"e": 1836,
"s": 1738,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1897,
"s": 1836,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1969,
"s": 1897,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 2009,
"s": 1969,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 2050,
"s": 2009,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 2096,
"s": 2050,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 2129,
"s": 2096,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2191,
"s": 2129,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2252,
"s": 2191,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2302,
"s": 2252,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Chain of Pointers in C with Examples | 18 Jan, 2022
Prerequisite: Pointers in C, Double Pointer (Pointer to Pointer) in CA pointer is used to point to a memory location of a variable. A pointer stores the address of a variable.Similarly, a chain of pointers is when there are multiple levels of pointers. Simplifying, a pointer points to address of a variable, double-pointer points to a variable and so on. This is called multiple indirections.Syntax:
// level-1 pointer declaration
datatype *pointer;
// level-2 pointer declaration
datatype **pointer;
// level-3 pointer declaration
datatype ***pointer;
.
.
and so on
The level of the pointer depends on how many asterisks the pointer variable is preceded with at the time of declaration.Declaration:
int *pointer_1;
int **pointer_2;
int ***pointer_3;
.
.
and so on
Level of pointers or say chain can go up to N level depending upon the memory size. If you want to create a pointer of level-5, you need to precede the pointer variable name by 5 asterisks(*) at the time of declaration. Initialization:
// initializing level-1 pointer
// with address of variable 'var'
pointer_1 = &var;
// initializing level-2 pointer
// with address of level-1 pointer
pointer_2 = &pointer_1;
// initializing level-3 pointer
// with address of level-2 pointer
pointer_3 = &pointer_2;
.
.
and so on
Example 1:
As shown in the diagram, variable ‘a’ is a normal integer variable which stores integer value 10 and is at location 2006. ‘ptr1’ is a pointer variable which points to integer variable ‘a’ and stores its location i.e. 2006, as its value. Similarly ptr2 points to pointer variable ptr1 and ptr3 points at pointer variable ptr2. As every pointer is directly or indirectly pointing to the variable ‘a’, they all have the same integer value as variable ‘a’, i.e. 10Let’s understand better with below given code:
C
#include <stdio.h>// C program for chain of pointer int main(){ int var = 10; // Pointer level-1 // Declaring pointer to variable var int* ptr1; // Pointer level-2 // Declaring pointer to pointer variable *ptr1 int** ptr2; // Pointer level-3 // Declaring pointer to double pointer **ptr2 int*** ptr3; // Storing address of variable var // to pointer variable ptr1 ptr1 = &var; // Storing address of pointer variable // ptr1 to level -2 pointer ptr2 ptr2 = &ptr1; // Storing address of level-2 pointer // ptr2 to level-3 pointer ptr3 ptr3 = &ptr2; // Displaying values printf("Value of variable " "var = %d\n", var); printf("Value of variable var using" " pointer ptr1 = %d\n", *ptr1); printf("Value of variable var using" " pointer ptr2 = %d\n", **ptr2); printf("Value of variable var using" " pointer ptr3 = %d\n", ***ptr3); return 0;}
Value of variable var = 10
Value of variable var using pointer ptr1 = 10
Value of variable var using pointer ptr2 = 10
Value of variable var using pointer ptr3 = 10
Example 2: Consider below-given code where we have taken float data type of the variable, so now we have to take same data type for the chain of pointers too. As the pointer and the variable, it is pointing to should have the same data type.
C
#include <stdio.h>int main(){ float var = 23.564327; // Declaring pointer variables upto level_4 float *ptr1, **ptr2, ***ptr3, ****ptr4; // Initializing pointer variables ptr1 = &var; ptr2 = &ptr1; ptr3 = &ptr2; ptr4 = &ptr3; // Printing values printf("Value of var = %f\n", var); printf("Value of var using level-1" " pointer = %f\n", *ptr1); printf("Value of var using level-2" " pointer = %f\n", **ptr2); printf("Value of var using level-3" " pointer = %f\n", ***ptr3); printf("Value of var using level-4" " pointer = %f\n", ****ptr4); return 0;}
Value of var = 23.564327
Value of var using level-1 pointer = 23.564327
Value of var using level-2 pointer = 23.564327
Value of var using level-3 pointer = 23.564327
Value of var using level-4 pointer = 23.564327
Example 3: Updating variable using chained pointer As we already know that a pointer points to address location of a variable so when we access the value of pointer it’ll point to the variable’s value. Now to update the value of variable, we can use any level of pointer as ultimately every pointer is directly or indirectly pointing to that variable only. It’ll directly change the value present at the address location of variable.
C
#include <stdio.h> int main(){ // Initializing integer variable int var = 10; // Declaring pointer variables upto level-3 int *ptr1, **ptr2, ***ptr3; // Initializing pointer variables ptr1 = &var; ptr2 = &ptr1; ptr3 = &ptr2; // Printing values BEFORE updation printf("Before:\n"); printf("Value of var = %d\n", var); printf("Value of var using level-1" " pointer = %d\n", *ptr1); printf("Value of var using level-2" " pointer = %d\n", **ptr2); printf("Value of var using level-3" " pointer = %d\n", ***ptr3); // Updating var's value using level-3 pointer ***ptr3 = 35; // Printing values AFTER updation printf("After:\n"); printf("Value of var = %d\n", var); printf("Value of var using level-1" " pointer = %d\n", *ptr1); printf("Value of var using level-2" " pointer = %d\n", **ptr2); printf("Value of var using level-3" " pointer = %d\n", ***ptr3); return 0;}
Before:
Value of var = 10
Value of var using level-1 pointer = 10
Value of var using level-2 pointer = 10
Value of var using level-3 pointer = 10
After:
Value of var = 35
Value of var using level-1 pointer = 35
Value of var using level-2 pointer = 35
Value of var using level-3 pointer = 35
Note: Level-N pointer can only be used to point level-(N-1) pointer. Except for Level-1 pointer. The level-1 pointer will always point to the variable.
surinderdawra388
C-Pointers
Pointers
C Language
Pointers
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n18 Jan, 2022"
},
{
"code": null,
"e": 455,
"s": 52,
"text": "Prerequisite: Pointers in C, Double Pointer (Pointer to Pointer) in CA pointer is used to point to a memory location of a variable. A pointer stores the address of a variable.Similarly, a chain of pointers is when there are multiple levels of pointers. Simplifying, a pointer points to address of a variable, double-pointer points to a variable and so on. This is called multiple indirections.Syntax: "
},
{
"code": null,
"e": 627,
"s": 455,
"text": "// level-1 pointer declaration\ndatatype *pointer; \n\n// level-2 pointer declaration\ndatatype **pointer; \n\n// level-3 pointer declaration\ndatatype ***pointer; \n.\n.\nand so on"
},
{
"code": null,
"e": 762,
"s": 627,
"text": "The level of the pointer depends on how many asterisks the pointer variable is preceded with at the time of declaration.Declaration: "
},
{
"code": null,
"e": 827,
"s": 762,
"text": "int *pointer_1;\nint **pointer_2;\nint ***pointer_3;\n.\n.\nand so on"
},
{
"code": null,
"e": 1065,
"s": 827,
"text": "Level of pointers or say chain can go up to N level depending upon the memory size. If you want to create a pointer of level-5, you need to precede the pointer variable name by 5 asterisks(*) at the time of declaration. Initialization: "
},
{
"code": null,
"e": 1347,
"s": 1065,
"text": "// initializing level-1 pointer\n// with address of variable 'var'\npointer_1 = &var;\n\n// initializing level-2 pointer\n// with address of level-1 pointer\npointer_2 = &pointer_1;\n\n// initializing level-3 pointer\n// with address of level-2 pointer\npointer_3 = &pointer_2;\n.\n.\nand so on"
},
{
"code": null,
"e": 1360,
"s": 1347,
"text": "Example 1: "
},
{
"code": null,
"e": 1868,
"s": 1360,
"text": "As shown in the diagram, variable ‘a’ is a normal integer variable which stores integer value 10 and is at location 2006. ‘ptr1’ is a pointer variable which points to integer variable ‘a’ and stores its location i.e. 2006, as its value. Similarly ptr2 points to pointer variable ptr1 and ptr3 points at pointer variable ptr2. As every pointer is directly or indirectly pointing to the variable ‘a’, they all have the same integer value as variable ‘a’, i.e. 10Let’s understand better with below given code: "
},
{
"code": null,
"e": 1870,
"s": 1868,
"text": "C"
},
{
"code": "#include <stdio.h>// C program for chain of pointer int main(){ int var = 10; // Pointer level-1 // Declaring pointer to variable var int* ptr1; // Pointer level-2 // Declaring pointer to pointer variable *ptr1 int** ptr2; // Pointer level-3 // Declaring pointer to double pointer **ptr2 int*** ptr3; // Storing address of variable var // to pointer variable ptr1 ptr1 = &var; // Storing address of pointer variable // ptr1 to level -2 pointer ptr2 ptr2 = &ptr1; // Storing address of level-2 pointer // ptr2 to level-3 pointer ptr3 ptr3 = &ptr2; // Displaying values printf(\"Value of variable \" \"var = %d\\n\", var); printf(\"Value of variable var using\" \" pointer ptr1 = %d\\n\", *ptr1); printf(\"Value of variable var using\" \" pointer ptr2 = %d\\n\", **ptr2); printf(\"Value of variable var using\" \" pointer ptr3 = %d\\n\", ***ptr3); return 0;}",
"e": 2870,
"s": 1870,
"text": null
},
{
"code": null,
"e": 3035,
"s": 2870,
"text": "Value of variable var = 10\nValue of variable var using pointer ptr1 = 10\nValue of variable var using pointer ptr2 = 10\nValue of variable var using pointer ptr3 = 10"
},
{
"code": null,
"e": 3280,
"s": 3037,
"text": "Example 2: Consider below-given code where we have taken float data type of the variable, so now we have to take same data type for the chain of pointers too. As the pointer and the variable, it is pointing to should have the same data type. "
},
{
"code": null,
"e": 3282,
"s": 3280,
"text": "C"
},
{
"code": "#include <stdio.h>int main(){ float var = 23.564327; // Declaring pointer variables upto level_4 float *ptr1, **ptr2, ***ptr3, ****ptr4; // Initializing pointer variables ptr1 = &var; ptr2 = &ptr1; ptr3 = &ptr2; ptr4 = &ptr3; // Printing values printf(\"Value of var = %f\\n\", var); printf(\"Value of var using level-1\" \" pointer = %f\\n\", *ptr1); printf(\"Value of var using level-2\" \" pointer = %f\\n\", **ptr2); printf(\"Value of var using level-3\" \" pointer = %f\\n\", ***ptr3); printf(\"Value of var using level-4\" \" pointer = %f\\n\", ****ptr4); return 0;}",
"e": 3961,
"s": 3282,
"text": null
},
{
"code": null,
"e": 4174,
"s": 3961,
"text": "Value of var = 23.564327\nValue of var using level-1 pointer = 23.564327\nValue of var using level-2 pointer = 23.564327\nValue of var using level-3 pointer = 23.564327\nValue of var using level-4 pointer = 23.564327"
},
{
"code": null,
"e": 4611,
"s": 4176,
"text": "Example 3: Updating variable using chained pointer As we already know that a pointer points to address location of a variable so when we access the value of pointer it’ll point to the variable’s value. Now to update the value of variable, we can use any level of pointer as ultimately every pointer is directly or indirectly pointing to that variable only. It’ll directly change the value present at the address location of variable. "
},
{
"code": null,
"e": 4613,
"s": 4611,
"text": "C"
},
{
"code": "#include <stdio.h> int main(){ // Initializing integer variable int var = 10; // Declaring pointer variables upto level-3 int *ptr1, **ptr2, ***ptr3; // Initializing pointer variables ptr1 = &var; ptr2 = &ptr1; ptr3 = &ptr2; // Printing values BEFORE updation printf(\"Before:\\n\"); printf(\"Value of var = %d\\n\", var); printf(\"Value of var using level-1\" \" pointer = %d\\n\", *ptr1); printf(\"Value of var using level-2\" \" pointer = %d\\n\", **ptr2); printf(\"Value of var using level-3\" \" pointer = %d\\n\", ***ptr3); // Updating var's value using level-3 pointer ***ptr3 = 35; // Printing values AFTER updation printf(\"After:\\n\"); printf(\"Value of var = %d\\n\", var); printf(\"Value of var using level-1\" \" pointer = %d\\n\", *ptr1); printf(\"Value of var using level-2\" \" pointer = %d\\n\", **ptr2); printf(\"Value of var using level-3\" \" pointer = %d\\n\", ***ptr3); return 0;}",
"e": 5670,
"s": 4613,
"text": null
},
{
"code": null,
"e": 5961,
"s": 5670,
"text": "Before:\nValue of var = 10\nValue of var using level-1 pointer = 10\nValue of var using level-2 pointer = 10\nValue of var using level-3 pointer = 10\nAfter:\nValue of var = 35\nValue of var using level-1 pointer = 35\nValue of var using level-2 pointer = 35\nValue of var using level-3 pointer = 35"
},
{
"code": null,
"e": 6116,
"s": 5963,
"text": "Note: Level-N pointer can only be used to point level-(N-1) pointer. Except for Level-1 pointer. The level-1 pointer will always point to the variable. "
},
{
"code": null,
"e": 6133,
"s": 6116,
"text": "surinderdawra388"
},
{
"code": null,
"e": 6144,
"s": 6133,
"text": "C-Pointers"
},
{
"code": null,
"e": 6153,
"s": 6144,
"text": "Pointers"
},
{
"code": null,
"e": 6164,
"s": 6153,
"text": "C Language"
},
{
"code": null,
"e": 6173,
"s": 6164,
"text": "Pointers"
}
] |