title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
Hazelcast - Client
|
Hazelcast clients are the lightweight clients to Hazelcast members. Hazelcast members are responsible to store data and the partitions. They act like the server in the traditional client-server model.
Hazelcast clients are created only for accessing data stored with Hazelcast members of the cluster. They are not responsible to store data and do not take any ownership to store data.
The clients have their own life cycle and do not affect the Hazelcast member instances.
Let's first create Server.java and run it.
import java.util.Map;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
public class Server {
public static void main(String... args){
//initialize hazelcast server/instance
HazelcastInstance hazelcast = Hazelcast.newHazelcastInstance();
//create a simple map
Map<String, String> vehicleOwners = hazelcast.getMap("vehicleOwnerMap");
// add key-value to map
vehicleOwners.put("John", "Honda-9235");
// do not shutdown, let the server run
//hazelcast.shutdown();
}
}
Now, run the above class.
java -cp .\target\demo-0.0.1-SNAPSHOT.jar com.example.demo.Server
For setting up a client, we also need to add client jar.
<dependency>
<groupId>com.hazelcast</groupId>
<artifactId>hazelcast-client</artifactId>
<version>3.12.12</version>
</dependency>
Let's now create Client.java. Note that similar to Hazelcast members, clients can also be configured programmatically or via XML configuration (i.e., via -Dhazelcast.client.config or hazelcast-client.xml).
Letβs use the default configuration which means our client would be able to connect to local instances.
import java.util.Map;
import com.hazelcast.client.HazelcastClient;
import com.hazelcast.core.HazelcastInstance;
public class Client {
public static void main(String... args){
//initialize hazelcast client
HazelcastInstance hzClient = HazelcastClient.newHazelcastClient();
//read from map
Map<String, String> vehicleOwners = hzClient.getMap("vehicleOwnerMap");
System.out.println(vehicleOwners.get("John"));
System.out.println("Member of cluster: " +
hzClient.getCluster().getMembers());
// perform shutdown
hzClient.getLifecycleService().shutdown();
}
}
Now, run the above class.
java -cp .\target\demo-0.0.1-SNAPSHOT.jar com.example.demo.Client
It will produce the following output β
Honda-9235
Member of cluster: [Member [localhost]:5701 - a47ec375-3105-42cd-96c7-fc5eb382e1b0]
As seen from the output β
The cluster only contains 1 member which is from Server.java.
The cluster only contains 1 member which is from Server.java.
The client is able to access the map which is stored inside the server.
The client is able to access the map which is stored inside the server.
Hazelcast Client supports load balancing using various algorithms. Load balancing ensures that the load is shared across members and no single member of the cluster is overloaded. The default load balancing mechanism is set to round-robin. The same can be changed by using the loadBalancer tag in the config.
We can specify the type of load balancer using the load-balancer tag in the configuration. Here is a sample for choosing a strategy that randomly picks up a node.
<hazelcast-client xmlns="http://www.hazelcast.com/schema/client-config"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.hazelcast.com/schema/client-config
http://www.hazelcast.com/schema/client-config/hazelcastclient-config-4.2.xsd">
<load-balancer type="random"/>
</hazelcast-client>
In a distributed environment, members can fail arbitrarily. For supporting failover, it is recommended that address to multiple members is provided. If the client gets access to any one member, that is sufficient for it to get addressed to other members. The parameters addressList can be specified in the client configuration.
For example, if we use the following configuration β
<hazelcast-client xmlns="http://www.hazelcast.com/schema/client-config"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.hazelcast.com/schema/client-config
http://www.hazelcast.com/schema/client-config/hazelcastclient-config-4.2.xsd">
<address-list>machine1, machine2</address-list>
</hazelcast-client>
Even if, say, machine1 goes down, clients can use machine2 to get access to other members of the cluster.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2164,
"s": 1963,
"text": "Hazelcast clients are the lightweight clients to Hazelcast members. Hazelcast members are responsible to store data and the partitions. They act like the server in the traditional client-server model."
},
{
"code": null,
"e": 2348,
"s": 2164,
"text": "Hazelcast clients are created only for accessing data stored with Hazelcast members of the cluster. They are not responsible to store data and do not take any ownership to store data."
},
{
"code": null,
"e": 2436,
"s": 2348,
"text": "The clients have their own life cycle and do not affect the Hazelcast member instances."
},
{
"code": null,
"e": 2479,
"s": 2436,
"text": "Let's first create Server.java and run it."
},
{
"code": null,
"e": 3030,
"s": 2479,
"text": "import java.util.Map;\nimport com.hazelcast.core.Hazelcast;\nimport com.hazelcast.core.HazelcastInstance;\npublic class Server {\n public static void main(String... args){\n //initialize hazelcast server/instance\n HazelcastInstance hazelcast = Hazelcast.newHazelcastInstance();\n //create a simple map\n Map<String, String> vehicleOwners = hazelcast.getMap(\"vehicleOwnerMap\");\n // add key-value to map\n vehicleOwners.put(\"John\", \"Honda-9235\");\n // do not shutdown, let the server run\n //hazelcast.shutdown();\n }\n}"
},
{
"code": null,
"e": 3056,
"s": 3030,
"text": "Now, run the above class."
},
{
"code": null,
"e": 3123,
"s": 3056,
"text": "java -cp .\\target\\demo-0.0.1-SNAPSHOT.jar com.example.demo.Server\n"
},
{
"code": null,
"e": 3180,
"s": 3123,
"text": "For setting up a client, we also need to add client jar."
},
{
"code": null,
"e": 3319,
"s": 3180,
"text": "<dependency>\n <groupId>com.hazelcast</groupId>\n <artifactId>hazelcast-client</artifactId>\n <version>3.12.12</version>\n</dependency>\n"
},
{
"code": null,
"e": 3525,
"s": 3319,
"text": "Let's now create Client.java. Note that similar to Hazelcast members, clients can also be configured programmatically or via XML configuration (i.e., via -Dhazelcast.client.config or hazelcast-client.xml)."
},
{
"code": null,
"e": 3629,
"s": 3525,
"text": "Letβs use the default configuration which means our client would be able to connect to local instances."
},
{
"code": null,
"e": 4243,
"s": 3629,
"text": "import java.util.Map;\nimport com.hazelcast.client.HazelcastClient;\nimport com.hazelcast.core.HazelcastInstance;\npublic class Client {\n public static void main(String... args){\n //initialize hazelcast client\n HazelcastInstance hzClient = HazelcastClient.newHazelcastClient();\n //read from map\n Map<String, String> vehicleOwners = hzClient.getMap(\"vehicleOwnerMap\");\n System.out.println(vehicleOwners.get(\"John\"));\n System.out.println(\"Member of cluster: \" +\n hzClient.getCluster().getMembers());\n // perform shutdown\n hzClient.getLifecycleService().shutdown();\n }\n}"
},
{
"code": null,
"e": 4269,
"s": 4243,
"text": "Now, run the above class."
},
{
"code": null,
"e": 4336,
"s": 4269,
"text": "java -cp .\\target\\demo-0.0.1-SNAPSHOT.jar com.example.demo.Client\n"
},
{
"code": null,
"e": 4375,
"s": 4336,
"text": "It will produce the following output β"
},
{
"code": null,
"e": 4471,
"s": 4375,
"text": "Honda-9235\nMember of cluster: [Member [localhost]:5701 - a47ec375-3105-42cd-96c7-fc5eb382e1b0]\n"
},
{
"code": null,
"e": 4497,
"s": 4471,
"text": "As seen from the output β"
},
{
"code": null,
"e": 4559,
"s": 4497,
"text": "The cluster only contains 1 member which is from Server.java."
},
{
"code": null,
"e": 4621,
"s": 4559,
"text": "The cluster only contains 1 member which is from Server.java."
},
{
"code": null,
"e": 4693,
"s": 4621,
"text": "The client is able to access the map which is stored inside the server."
},
{
"code": null,
"e": 4765,
"s": 4693,
"text": "The client is able to access the map which is stored inside the server."
},
{
"code": null,
"e": 5074,
"s": 4765,
"text": "Hazelcast Client supports load balancing using various algorithms. Load balancing ensures that the load is shared across members and no single member of the cluster is overloaded. The default load balancing mechanism is set to round-robin. The same can be changed by using the loadBalancer tag in the config."
},
{
"code": null,
"e": 5237,
"s": 5074,
"text": "We can specify the type of load balancer using the load-balancer tag in the configuration. Here is a sample for choosing a strategy that randomly picks up a node."
},
{
"code": null,
"e": 5574,
"s": 5237,
"text": "<hazelcast-client xmlns=\"http://www.hazelcast.com/schema/client-config\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://www.hazelcast.com/schema/client-config\n http://www.hazelcast.com/schema/client-config/hazelcastclient-config-4.2.xsd\">\n <load-balancer type=\"random\"/>\n</hazelcast-client>"
},
{
"code": null,
"e": 5902,
"s": 5574,
"text": "In a distributed environment, members can fail arbitrarily. For supporting failover, it is recommended that address to multiple members is provided. If the client gets access to any one member, that is sufficient for it to get addressed to other members. The parameters addressList can be specified in the client configuration."
},
{
"code": null,
"e": 5955,
"s": 5902,
"text": "For example, if we use the following configuration β"
},
{
"code": null,
"e": 6307,
"s": 5955,
"text": "<hazelcast-client xmlns=\"http://www.hazelcast.com/schema/client-config\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://www.hazelcast.com/schema/client-config\n http://www.hazelcast.com/schema/client-config/hazelcastclient-config-4.2.xsd\">\n <address-list>machine1, machine2</address-list>\n</hazelcast-client>\n"
},
{
"code": null,
"e": 6413,
"s": 6307,
"text": "Even if, say, machine1 goes down, clients can use machine2 to get access to other members of the cluster."
},
{
"code": null,
"e": 6420,
"s": 6413,
"text": " Print"
},
{
"code": null,
"e": 6431,
"s": 6420,
"text": " Add Notes"
}
] |
Neo4j - Remove Clause
|
The REMOVE clause is used to remove properties and labels from graph elements (Nodes or Relationships).
The main difference between Neo4j CQL DELETE and REMOVE commands is β
DELETE operation is used to delete nodes and associated relationships.
REMOVE operation is used to remove labels and properties.
You can remove a property of a node using MATCH along with the REMOVE clause.
Following is the syntax to remove a property of a node using the REMOVE clause.
MATCH (node:label{properties . . . . . . . })
REMOVE node.property
RETURN node
Before proceeding with the example, create a node named Dhoni as shown below.
CREATE (Dhoni:player {name: "MahendraSingh Dhoni", YOB: 1981, POB: "Ranchi"})
Following is a sample Cypher Query to remove the above created node using the REMOVE clause.
MATCH (Dhoni:player {name: "MahendraSingh Dhoni", YOB: 1981, POB: "Ranchi"})
REMOVE Dhoni.POB
RETURN Dhoni
To execute the above query, carry out the following steps β
Step 1 β Open the Neo4j desktop App and start the Neo4j Server. Open the built-in browser app of Neo4j using the URL http://localhost:7474/ as shown in the following screenshot.
Step 2 β Copy and paste the desired query in the dollar prompt and press the play button (to execute the query) highlighted in the following screenshot.
On executing, you will get the following result. Here, you can observe that the node named POB was deleted.
Similar to property, you can also remove a label from an existing node using the remove clause.
Following is the syntax to remove a label from a node.
MATCH (node:label {properties . . . . . . . . . . . })
REMOVE node:label
RETURN node
Following is a sample Cypher Query to remove a label from an existing node using the remove clause.
MATCH (Dhoni:player {name: "MahendraSingh Dhoni", YOB: 1981, POB: "Ranchi"})
REMOVE Dhoni:player
RETURN Dhoni
To execute the above query, carry out the following steps β
Step 1 β Open the Neo4j desktop App and start the Neo4j Server. Open the built-in browser app of Neo4j using the URL http://localhost:7474/ as shown in the following screenshot.
Step 2 β Copy and paste the desired query in the dollar prompt and press the play button (to execute the query) highlighted in the following screenshot.
On executing, you will get the following result. Here, you can observe that the label was deleted from the node.
You can also remove multiple labels from an existing node.
Following is the syntax to remove multiple labels from a node.
MATCH (node:label1:label2 {properties . . . . . . . . })
REMOVE node:label1:label2
RETURN node
Before proceeding with the example, create a node Ishant as shown below.
CREATE (Ishant:player:person {name: "Ishant Sharma", YOB: 1988, POB: "Delhi"})
Following is a sample Cypher Query to remove multiple labels from a node.
MATCH (Ishant:player:person {name: "Ishant Sharma", YOB: 1988, POB: "Delhi"})
REMOVE Ishant:player:person
RETURN Ishant
To execute the above query, carry out the following steps β
Step 1 β Open the Neo4j desktop App and start the Neo4j Server. Open the built-in browser app of Neo4j using the URL http://localhost:7474/ as shown in the following screenshot.
Step 2 β Copy and paste the desired query in the dollar prompt and press the play button (to execute the query) highlighted in the following screenshot.
On executing, you will get the following result. Here, you can observe that the specified labels were deleted from the node.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2443,
"s": 2339,
"text": "The REMOVE clause is used to remove properties and labels from graph elements (Nodes or Relationships)."
},
{
"code": null,
"e": 2513,
"s": 2443,
"text": "The main difference between Neo4j CQL DELETE and REMOVE commands is β"
},
{
"code": null,
"e": 2584,
"s": 2513,
"text": "DELETE operation is used to delete nodes and associated relationships."
},
{
"code": null,
"e": 2642,
"s": 2584,
"text": "REMOVE operation is used to remove labels and properties."
},
{
"code": null,
"e": 2720,
"s": 2642,
"text": "You can remove a property of a node using MATCH along with the REMOVE clause."
},
{
"code": null,
"e": 2800,
"s": 2720,
"text": "Following is the syntax to remove a property of a node using the REMOVE clause."
},
{
"code": null,
"e": 2883,
"s": 2800,
"text": "MATCH (node:label{properties . . . . . . . }) \nREMOVE node.property \nRETURN node \n"
},
{
"code": null,
"e": 2961,
"s": 2883,
"text": "Before proceeding with the example, create a node named Dhoni as shown below."
},
{
"code": null,
"e": 3039,
"s": 2961,
"text": "CREATE (Dhoni:player {name: \"MahendraSingh Dhoni\", YOB: 1981, POB: \"Ranchi\"})"
},
{
"code": null,
"e": 3132,
"s": 3039,
"text": "Following is a sample Cypher Query to remove the above created node using the REMOVE clause."
},
{
"code": null,
"e": 3242,
"s": 3132,
"text": "MATCH (Dhoni:player {name: \"MahendraSingh Dhoni\", YOB: 1981, POB: \"Ranchi\"}) \nREMOVE Dhoni.POB \nRETURN Dhoni "
},
{
"code": null,
"e": 3302,
"s": 3242,
"text": "To execute the above query, carry out the following steps β"
},
{
"code": null,
"e": 3480,
"s": 3302,
"text": "Step 1 β Open the Neo4j desktop App and start the Neo4j Server. Open the built-in browser app of Neo4j using the URL http://localhost:7474/ as shown in the following screenshot."
},
{
"code": null,
"e": 3633,
"s": 3480,
"text": "Step 2 β Copy and paste the desired query in the dollar prompt and press the play button (to execute the query) highlighted in the following screenshot."
},
{
"code": null,
"e": 3741,
"s": 3633,
"text": "On executing, you will get the following result. Here, you can observe that the node named POB was deleted."
},
{
"code": null,
"e": 3837,
"s": 3741,
"text": "Similar to property, you can also remove a label from an existing node using the remove clause."
},
{
"code": null,
"e": 3892,
"s": 3837,
"text": "Following is the syntax to remove a label from a node."
},
{
"code": null,
"e": 3981,
"s": 3892,
"text": "MATCH (node:label {properties . . . . . . . . . . . }) \nREMOVE node:label \nRETURN node \n"
},
{
"code": null,
"e": 4081,
"s": 3981,
"text": "Following is a sample Cypher Query to remove a label from an existing node using the remove clause."
},
{
"code": null,
"e": 4194,
"s": 4081,
"text": "MATCH (Dhoni:player {name: \"MahendraSingh Dhoni\", YOB: 1981, POB: \"Ranchi\"}) \nREMOVE Dhoni:player \nRETURN Dhoni "
},
{
"code": null,
"e": 4254,
"s": 4194,
"text": "To execute the above query, carry out the following steps β"
},
{
"code": null,
"e": 4432,
"s": 4254,
"text": "Step 1 β Open the Neo4j desktop App and start the Neo4j Server. Open the built-in browser app of Neo4j using the URL http://localhost:7474/ as shown in the following screenshot."
},
{
"code": null,
"e": 4585,
"s": 4432,
"text": "Step 2 β Copy and paste the desired query in the dollar prompt and press the play button (to execute the query) highlighted in the following screenshot."
},
{
"code": null,
"e": 4698,
"s": 4585,
"text": "On executing, you will get the following result. Here, you can observe that the label was deleted from the node."
},
{
"code": null,
"e": 4757,
"s": 4698,
"text": "You can also remove multiple labels from an existing node."
},
{
"code": null,
"e": 4820,
"s": 4757,
"text": "Following is the syntax to remove multiple labels from a node."
},
{
"code": null,
"e": 4918,
"s": 4820,
"text": "MATCH (node:label1:label2 {properties . . . . . . . . }) \nREMOVE node:label1:label2 \nRETURN node\n"
},
{
"code": null,
"e": 4991,
"s": 4918,
"text": "Before proceeding with the example, create a node Ishant as shown below."
},
{
"code": null,
"e": 5071,
"s": 4991,
"text": "CREATE (Ishant:player:person {name: \"Ishant Sharma\", YOB: 1988, POB: \"Delhi\"}) "
},
{
"code": null,
"e": 5145,
"s": 5071,
"text": "Following is a sample Cypher Query to remove multiple labels from a node."
},
{
"code": null,
"e": 5268,
"s": 5145,
"text": "MATCH (Ishant:player:person {name: \"Ishant Sharma\", YOB: 1988, POB: \"Delhi\"}) \nREMOVE Ishant:player:person \nRETURN Ishant "
},
{
"code": null,
"e": 5328,
"s": 5268,
"text": "To execute the above query, carry out the following steps β"
},
{
"code": null,
"e": 5506,
"s": 5328,
"text": "Step 1 β Open the Neo4j desktop App and start the Neo4j Server. Open the built-in browser app of Neo4j using the URL http://localhost:7474/ as shown in the following screenshot."
},
{
"code": null,
"e": 5659,
"s": 5506,
"text": "Step 2 β Copy and paste the desired query in the dollar prompt and press the play button (to execute the query) highlighted in the following screenshot."
},
{
"code": null,
"e": 5784,
"s": 5659,
"text": "On executing, you will get the following result. Here, you can observe that the specified labels were deleted from the node."
},
{
"code": null,
"e": 5791,
"s": 5784,
"text": " Print"
},
{
"code": null,
"e": 5802,
"s": 5791,
"text": " Add Notes"
}
] |
C program to display the prime numbers in between two intervals
|
Enter two numbers at console during runtime. Then, declare the flag variable which is used to check whether the number is prime or not with the help of for loop condition.
Whenever, the flag is zero, it prints the prime number and if flag is one, it exists from the loop.
Following is the C program to display the prime numbers in between two intervals β
Live Demo
#include <stdio.h>
int main(){
int number1,number2,i,j,flag;
printf("enter the two intervals:");
scanf("%d %d",&number1,&number2);
printf("prime noβs present in between %d and %d:",number1,number2);
for(i=number1+1;i<number2;i++){// interval between two numbers
flag=0;
for(j=2;j<=i/2;++j){ //checking number is prime or not
if(i%j==0){
flag=1;
break;
}
}
if(flag==0)
printf("%d\n",i);
}
return 0;
}
You will see the following output β
enter the two intervals:10 50
the number of prime numbers present in between 10 and 50:11
13
17
19
23
29
31
37
41
43
47
Consider another example, wherein, we are trying to remove the prime numbers in between two numbers.
Following is the C program to display the numbers in between two intervals excluding prime numbers β
Live Demo
#include <stdio.h>
int main(){
int number1,number2,i,j,flag;
printf("enter the two intervals:");
scanf("%d %d",&number1,&number2);
printf("the numbers that are present after removing prime numbers in between %d and %d:\n",number1,number2);
for(i=number1+1;i<number2;i++){// interval between two numbers
flag=1;
for(j=2;j<=i/2;++j){ //checking number is prime or not
if(i%j==0){
flag=0;
break;
}
}
if(flag==0)
printf("%d\n",i);
}
return 0;
}
You will see the following output β
enter the two intervals:10 20
the numbers that are present after removing prime numbers in between 10 and 20:
12
14
15
16
18
|
[
{
"code": null,
"e": 1234,
"s": 1062,
"text": "Enter two numbers at console during runtime. Then, declare the flag variable which is used to check whether the number is prime or not with the help of for loop condition."
},
{
"code": null,
"e": 1334,
"s": 1234,
"text": "Whenever, the flag is zero, it prints the prime number and if flag is one, it exists from the loop."
},
{
"code": null,
"e": 1417,
"s": 1334,
"text": "Following is the C program to display the prime numbers in between two intervals β"
},
{
"code": null,
"e": 1428,
"s": 1417,
"text": " Live Demo"
},
{
"code": null,
"e": 1924,
"s": 1428,
"text": "#include <stdio.h>\nint main(){\n int number1,number2,i,j,flag;\n printf(\"enter the two intervals:\");\n scanf(\"%d %d\",&number1,&number2);\n printf(\"prime noβs present in between %d and %d:\",number1,number2);\n for(i=number1+1;i<number2;i++){// interval between two numbers\n flag=0;\n for(j=2;j<=i/2;++j){ //checking number is prime or not\n if(i%j==0){\n flag=1;\n break;\n }\n }\n if(flag==0)\n printf(\"%d\\n\",i);\n }\n return 0;\n}"
},
{
"code": null,
"e": 1960,
"s": 1924,
"text": "You will see the following output β"
},
{
"code": null,
"e": 2080,
"s": 1960,
"text": "enter the two intervals:10 50\nthe number of prime numbers present in between 10 and 50:11\n13\n17\n19\n23\n29\n31\n37\n41\n43\n47"
},
{
"code": null,
"e": 2181,
"s": 2080,
"text": "Consider another example, wherein, we are trying to remove the prime numbers in between two numbers."
},
{
"code": null,
"e": 2282,
"s": 2181,
"text": "Following is the C program to display the numbers in between two intervals excluding prime numbers β"
},
{
"code": null,
"e": 2293,
"s": 2282,
"text": " Live Demo"
},
{
"code": null,
"e": 2830,
"s": 2293,
"text": "#include <stdio.h>\nint main(){\n int number1,number2,i,j,flag;\n printf(\"enter the two intervals:\");\n scanf(\"%d %d\",&number1,&number2);\n printf(\"the numbers that are present after removing prime numbers in between %d and %d:\\n\",number1,number2);\n for(i=number1+1;i<number2;i++){// interval between two numbers\n flag=1;\n for(j=2;j<=i/2;++j){ //checking number is prime or not\n if(i%j==0){\n flag=0;\n break;\n }\n }\n if(flag==0)\n printf(\"%d\\n\",i);\n }\n return 0;\n}"
},
{
"code": null,
"e": 2866,
"s": 2830,
"text": "You will see the following output β"
},
{
"code": null,
"e": 2991,
"s": 2866,
"text": "enter the two intervals:10 20\nthe numbers that are present after removing prime numbers in between 10 and 20:\n12\n14\n15\n16\n18"
}
] |
Top 5 SQL Analytic Functions Every Data Analyst Needs to Know | by Dario RadecΜicΜ | Towards Data Science
|
Analytical functions are one of the most popular tools among BI/Data analysts for performing complex data analysis. These functions perform computations over multiple rows and return the multiple rows as well. Today weβll cover 5 functions I find most useful, with a lot of practical examples.
For the uninitiated, the relative size of a query with an analytical function might seem a bit intimidating. Donβt worry, we have you covered. Most of these functions follow a basic syntax:
analytic_function_name([argument_list])OVER ([PARTITION BY partition_expression,...][ORDER BY sort_expression, ... [ASC|DESC]])
There are three parts to this syntax, namely function, partition by and order by. Letβs briefly cover what each one does:
analytic_function_name: name of the function β like RANK(), SUM(), FIRST(), etc
partition_expression: column/expression on the basis of which the partition or window frames have to be created
sort_expression: column/expression on the basis of which the rows in the partition will be sorted
Okay, weβve covered the basics thus far. For the practical part weβre gonna use the Orders table stored inside the PostgreSQL database:
Letβs begin with the practical part now, shall we?
Weβve all been using aggregate functions such as SUM, AVG, MIN, MAX, and COUNT in our GROUP BY clauses. But when these functions are used over an ORDER BY clause they can give us running sum, mean, total, etc.
The following example will make it a lot more clear β we want to calculate the running average revenue and total revenue for each agent in the third quarter:
SELECT ord_date, agent_code, AVG(ord_amount) OVER ( PARTITION BY agent_code ORDER BY ord_date) running_agent_avg_revenue, SUM (ord_amount) OVER ( PARTITION BY agent_code ORDER BY ord_date ) running_agent_total_revenueFROM ordersWHERE ord_date BETWEEN β2008β07β01β AND β2008β09β30β;
And here are the results:
Awesome! These functions are simple and require no additional explanations. Letβs proceed.
FIRST_VALUE() is an analytical function that returns the value of the specified column from the first row of the window frame. If youβve understood the previous sentence, LAST_VALUE() is self-explanatory. It fetches the value from the last row.
PostgreSQL provides us with one more additional function called NTH_VALUE(column_name, n) that fetches the value from the n-th row. Isnβt it great? No more complex self joins.
Letβs answer the following question β How many days after the first purchase of a customer was the next purchase made?
SELECT cust_code, ord_date, ord_date β FIRST_VALUE(ord_date) OVER ( PARTITION BY cust_code ORDER BY ord_date) next_order_gapFROM ordersORDER BY cust_code, next_order_gap;
And here are the results:
There are just so many occasions where this function might be useful. Also, itβs nice to know the results can be obtained from the database directly, so we donβt have to do this calculation manually with Python/R.
Letβs proceed with the next one.
LEAD() function, as the name suggests, fetches the value of a specific column from the next row and returns the fetched value in the current row. In PostgreSQL, LEAD() takes two arguments:
column_name from which the next value has to be fetched
index of the next row relative to the current row.
LAG() is just the opposite of. It fetches values from the previous rows.
Letβs answer the following question to make this concept a bit more clear β what is the last highest amount for which an order was sold by an agent?
SELECT agent_code, ord_amount, LAG(ord_amount, 1) OVER ( PARTITION BY agent_code ORDER BY ord_amount DESC) last_highest_amountFROM ordersORDER BY agent_code, ord_amount DESC;
And here are the results:
Above you can see how last_highest_amount clearly shows data per agent β thatβs why thereβs no result for agent A001, and first values for other agents are NULL.
RANK() and DENSE_RANK() are numbering functions. They assign an integer value to a row depending upon the partition and the ordering. I cannot stress enough on the importance of these functions when it comes to finding the nth highest/lowest record from the table.
DENSE_RANK() and RANK() differ on the point that in the former we get consecutive ranks while in the later the rank after a tie is skipped. For example, ranking using DENSE_RANK() would be something like (1,2,2,3) whereas ranking using RANK() would be (1,2,2,4). Hope you get the difference.
Anyhow, letβs answer the following question with the help of these functions β what are the second highest order values for each month?
SELECT * FROM ( SELECT ord_num, ord_date, ord_amount, DENSE_RANK() OVER( PARTITION BY DATE_PART(βmonthβ, ord_date) ORDER BY ord_amount DESC) order_rank FROM orders) tWHERE order_rank = 2ORDER BY ord_date;
And here are the results:
Cool! Letβs proceed with the next one.
CUME_DIST() function is used to calculate the cumulative distribution of values within a given partition. It computes the fraction of rows in the partition that is less than or equal to the current row. Itβs very helpful when we have to fetch only the top n% of the results.
Letβs use it to calculate the revenue percentile for each order in August and September:
SELECT DATE_PART(βMonthβ,ord_date), agent_code, ord_amount, CUME_DIST() OVER( PARTITION BY DATE_PART(βMonthβ,ord_date) ORDER BY ord_amount)FROM ordersWHERE ord_date BETWEEN β2008β08β01β AND β2008β09β30β;
And here are the results:
Itβs not the function I use on a daily basis, but itβs nice to know it exists.
And there you have it β 5 most common analytical functions I use when performing analysis in the database. Itβs not as common for me as doing analysis with Python and Pandas, but I still find this useful from time to time β especially for analysts limited only to SQL.
I hope this 5 will suit you well, and feel free to research and study more on your own. Thanks for reading.
Loved the article? Become a Medium member to continue learning without limits. Iβll receive a portion of your membership fee if you use the following link, with no extra cost to you.
medium.com
Join my private email list for more helpful insights.
|
[
{
"code": null,
"e": 466,
"s": 172,
"text": "Analytical functions are one of the most popular tools among BI/Data analysts for performing complex data analysis. These functions perform computations over multiple rows and return the multiple rows as well. Today weβll cover 5 functions I find most useful, with a lot of practical examples."
},
{
"code": null,
"e": 656,
"s": 466,
"text": "For the uninitiated, the relative size of a query with an analytical function might seem a bit intimidating. Donβt worry, we have you covered. Most of these functions follow a basic syntax:"
},
{
"code": null,
"e": 784,
"s": 656,
"text": "analytic_function_name([argument_list])OVER ([PARTITION BY partition_expression,...][ORDER BY sort_expression, ... [ASC|DESC]])"
},
{
"code": null,
"e": 906,
"s": 784,
"text": "There are three parts to this syntax, namely function, partition by and order by. Letβs briefly cover what each one does:"
},
{
"code": null,
"e": 986,
"s": 906,
"text": "analytic_function_name: name of the function β like RANK(), SUM(), FIRST(), etc"
},
{
"code": null,
"e": 1098,
"s": 986,
"text": "partition_expression: column/expression on the basis of which the partition or window frames have to be created"
},
{
"code": null,
"e": 1196,
"s": 1098,
"text": "sort_expression: column/expression on the basis of which the rows in the partition will be sorted"
},
{
"code": null,
"e": 1332,
"s": 1196,
"text": "Okay, weβve covered the basics thus far. For the practical part weβre gonna use the Orders table stored inside the PostgreSQL database:"
},
{
"code": null,
"e": 1383,
"s": 1332,
"text": "Letβs begin with the practical part now, shall we?"
},
{
"code": null,
"e": 1593,
"s": 1383,
"text": "Weβve all been using aggregate functions such as SUM, AVG, MIN, MAX, and COUNT in our GROUP BY clauses. But when these functions are used over an ORDER BY clause they can give us running sum, mean, total, etc."
},
{
"code": null,
"e": 1751,
"s": 1593,
"text": "The following example will make it a lot more clear β we want to calculate the running average revenue and total revenue for each agent in the third quarter:"
},
{
"code": null,
"e": 2060,
"s": 1751,
"text": "SELECT ord_date, agent_code, AVG(ord_amount) OVER ( PARTITION BY agent_code ORDER BY ord_date) running_agent_avg_revenue, SUM (ord_amount) OVER ( PARTITION BY agent_code ORDER BY ord_date ) running_agent_total_revenueFROM ordersWHERE ord_date BETWEEN β2008β07β01β AND β2008β09β30β;"
},
{
"code": null,
"e": 2086,
"s": 2060,
"text": "And here are the results:"
},
{
"code": null,
"e": 2177,
"s": 2086,
"text": "Awesome! These functions are simple and require no additional explanations. Letβs proceed."
},
{
"code": null,
"e": 2422,
"s": 2177,
"text": "FIRST_VALUE() is an analytical function that returns the value of the specified column from the first row of the window frame. If youβve understood the previous sentence, LAST_VALUE() is self-explanatory. It fetches the value from the last row."
},
{
"code": null,
"e": 2598,
"s": 2422,
"text": "PostgreSQL provides us with one more additional function called NTH_VALUE(column_name, n) that fetches the value from the n-th row. Isnβt it great? No more complex self joins."
},
{
"code": null,
"e": 2717,
"s": 2598,
"text": "Letβs answer the following question β How many days after the first purchase of a customer was the next purchase made?"
},
{
"code": null,
"e": 2895,
"s": 2717,
"text": "SELECT cust_code, ord_date, ord_date β FIRST_VALUE(ord_date) OVER ( PARTITION BY cust_code ORDER BY ord_date) next_order_gapFROM ordersORDER BY cust_code, next_order_gap;"
},
{
"code": null,
"e": 2921,
"s": 2895,
"text": "And here are the results:"
},
{
"code": null,
"e": 3135,
"s": 2921,
"text": "There are just so many occasions where this function might be useful. Also, itβs nice to know the results can be obtained from the database directly, so we donβt have to do this calculation manually with Python/R."
},
{
"code": null,
"e": 3168,
"s": 3135,
"text": "Letβs proceed with the next one."
},
{
"code": null,
"e": 3357,
"s": 3168,
"text": "LEAD() function, as the name suggests, fetches the value of a specific column from the next row and returns the fetched value in the current row. In PostgreSQL, LEAD() takes two arguments:"
},
{
"code": null,
"e": 3413,
"s": 3357,
"text": "column_name from which the next value has to be fetched"
},
{
"code": null,
"e": 3464,
"s": 3413,
"text": "index of the next row relative to the current row."
},
{
"code": null,
"e": 3537,
"s": 3464,
"text": "LAG() is just the opposite of. It fetches values from the previous rows."
},
{
"code": null,
"e": 3686,
"s": 3537,
"text": "Letβs answer the following question to make this concept a bit more clear β what is the last highest amount for which an order was sold by an agent?"
},
{
"code": null,
"e": 3867,
"s": 3686,
"text": "SELECT agent_code, ord_amount, LAG(ord_amount, 1) OVER ( PARTITION BY agent_code ORDER BY ord_amount DESC) last_highest_amountFROM ordersORDER BY agent_code, ord_amount DESC;"
},
{
"code": null,
"e": 3893,
"s": 3867,
"text": "And here are the results:"
},
{
"code": null,
"e": 4055,
"s": 3893,
"text": "Above you can see how last_highest_amount clearly shows data per agent β thatβs why thereβs no result for agent A001, and first values for other agents are NULL."
},
{
"code": null,
"e": 4320,
"s": 4055,
"text": "RANK() and DENSE_RANK() are numbering functions. They assign an integer value to a row depending upon the partition and the ordering. I cannot stress enough on the importance of these functions when it comes to finding the nth highest/lowest record from the table."
},
{
"code": null,
"e": 4612,
"s": 4320,
"text": "DENSE_RANK() and RANK() differ on the point that in the former we get consecutive ranks while in the later the rank after a tie is skipped. For example, ranking using DENSE_RANK() would be something like (1,2,2,3) whereas ranking using RANK() would be (1,2,2,4). Hope you get the difference."
},
{
"code": null,
"e": 4748,
"s": 4612,
"text": "Anyhow, letβs answer the following question with the help of these functions β what are the second highest order values for each month?"
},
{
"code": null,
"e": 4975,
"s": 4748,
"text": "SELECT * FROM ( SELECT ord_num, ord_date, ord_amount, DENSE_RANK() OVER( PARTITION BY DATE_PART(βmonthβ, ord_date) ORDER BY ord_amount DESC) order_rank FROM orders) tWHERE order_rank = 2ORDER BY ord_date;"
},
{
"code": null,
"e": 5001,
"s": 4975,
"text": "And here are the results:"
},
{
"code": null,
"e": 5040,
"s": 5001,
"text": "Cool! Letβs proceed with the next one."
},
{
"code": null,
"e": 5315,
"s": 5040,
"text": "CUME_DIST() function is used to calculate the cumulative distribution of values within a given partition. It computes the fraction of rows in the partition that is less than or equal to the current row. Itβs very helpful when we have to fetch only the top n% of the results."
},
{
"code": null,
"e": 5404,
"s": 5315,
"text": "Letβs use it to calculate the revenue percentile for each order in August and September:"
},
{
"code": null,
"e": 5613,
"s": 5404,
"text": "SELECT DATE_PART(βMonthβ,ord_date), agent_code, ord_amount, CUME_DIST() OVER( PARTITION BY DATE_PART(βMonthβ,ord_date) ORDER BY ord_amount)FROM ordersWHERE ord_date BETWEEN β2008β08β01β AND β2008β09β30β;"
},
{
"code": null,
"e": 5639,
"s": 5613,
"text": "And here are the results:"
},
{
"code": null,
"e": 5718,
"s": 5639,
"text": "Itβs not the function I use on a daily basis, but itβs nice to know it exists."
},
{
"code": null,
"e": 5987,
"s": 5718,
"text": "And there you have it β 5 most common analytical functions I use when performing analysis in the database. Itβs not as common for me as doing analysis with Python and Pandas, but I still find this useful from time to time β especially for analysts limited only to SQL."
},
{
"code": null,
"e": 6095,
"s": 5987,
"text": "I hope this 5 will suit you well, and feel free to research and study more on your own. Thanks for reading."
},
{
"code": null,
"e": 6278,
"s": 6095,
"text": "Loved the article? Become a Medium member to continue learning without limits. Iβll receive a portion of your membership fee if you use the following link, with no extra cost to you."
},
{
"code": null,
"e": 6289,
"s": 6278,
"text": "medium.com"
}
] |
Food and Beverage Services - Quick Guide
|
Food and beverage services sector contributes a great deal to the profits in hospitality industry. With the increase in importance of business meetings, a range of personal and social events, a large number of customers visit catering establishments frequently. The food and beverage professionals tirelessly work to intensify customersβ experience through their service.
The F&B Services providing businesses deliver food and beverages to their customers at a particular location (on-premise) such as hotel, restaurant, or at the customerβs intended premises (off-premise).
Food and Beverage Services can be broadly defined as the process of preparing, presenting and serving of food and beverages to the customers.
F&B Services can be of the following two types β
On Premise β Food is delivered where it is prepared. The customer visits the premise to avail the food service. The premises are kept well-equipped and well-finished to attract customers to avail F&B service.
For example, restaurants, pubs, etc.
On Premise β Food is delivered where it is prepared. The customer visits the premise to avail the food service. The premises are kept well-equipped and well-finished to attract customers to avail F&B service.
For example, restaurants, pubs, etc.
Off Premise or Outdoor Catering β This kind of service includes partial cooking, preparation, and service at customerβs premises. It is provided away from the F&B Services providerβs base on the occasion of major events which call for a large number of customers.
Off Premise or Outdoor Catering β This kind of service includes partial cooking, preparation, and service at customerβs premises. It is provided away from the F&B Services providerβs base on the occasion of major events which call for a large number of customers.
There are two broad types of F&B Services operations β
Commercial β In this case, F&B Services is the primary business. The most known commercial catering establishments are β hotels, all kinds of restaurants, lounges, cafeterias, pubs, clubs, and bars.
Commercial β In this case, F&B Services is the primary business. The most known commercial catering establishments are β hotels, all kinds of restaurants, lounges, cafeterias, pubs, clubs, and bars.
Non-Commercial β Non-commercial operations are secondary businesses in alliance with the main business. These F&B services mainly cater to their consumers with limited choice of food and beverages. These establishments often run under contracts. For example, food and beverage services provided at hospitals, hostels, and prisons.
Non-Commercial β Non-commercial operations are secondary businesses in alliance with the main business. These F&B services mainly cater to their consumers with limited choice of food and beverages. These establishments often run under contracts. For example, food and beverage services provided at hospitals, hostels, and prisons.
In this tutorial, we mainly consider commercial food and beverage service sector. Let us first understand some common forms of F&B service.
Catering is the business of providing foods and beverage service to the people at a remote location. It is a part of food and beverage service sector. For example, arranging food services at a wedding location.
These are the fast food outlets called Quick Service Restaurants where the food is prepared, purchased, and generally consumed quickly. They are run with convenience as a main factor. Branded outlets such as McDonalds and Nandoβs are QSRs.
They are fine dining, family, specialty, ethnic, or theme restaurants called Full Service Restaurants where the food and beverage menu is wide and the customerβs expectations are high. They are operated with customer satisfaction and experience as the key factors.
Food and Beverage Services come only after preparing what is to be served. Most food and beverage service businesses operate in the following cycle β
The upper half depicts food preparation related functions, whereas the lower half depicts food and beverage service to customers.
The food and beverage service is looked as a means of achieving satisfaction and making yourself feel comfortable in todayβs world. The main objectives of this service are β
To satisfy the following needs β
Physiological β The need to taste different varieties of food.
Economical β The need to get F&B Services at the invested cost.
Social β The need to find friendly atmosphere.
Psychological β The need to elevate self-esteem.
To satisfy the following needs β
Physiological β The need to taste different varieties of food.
Physiological β The need to taste different varieties of food.
Economical β The need to get F&B Services at the invested cost.
Economical β The need to get F&B Services at the invested cost.
Social β The need to find friendly atmosphere.
Social β The need to find friendly atmosphere.
Psychological β The need to elevate self-esteem.
Psychological β The need to elevate self-esteem.
To provide high quality food and beverages.
To provide high quality food and beverages.
To provide friendly and welcoming atmosphere.
To provide friendly and welcoming atmosphere.
To provide professional, hygienic, and attentive service.
To provide professional, hygienic, and attentive service.
To impart value for money.
To impart value for money.
To retain the existing customers and to bring in new ones.
To retain the existing customers and to bring in new ones.
The following terms are frequently used in F&B services β
Back bar
A range of shelves displaying glassware and bottles.
Banquet
A sit-down meal served on the occasion of a formal or informal event such as a wedding party or a conference.
Binge Drinking
Drinking too much in a single session.
Buffet
A dining system where the guests serve themselves. Popular with a large number of guests and a small number of workforce.
Cocktail
Any mixed drink prepared using alcohol.
Condiments
Spices, sauce or other food preparations used to enhance the flavor or to complement the dish.
Crockery
Plates, dishes, cups, and other similar items, especially ones made of glass, earthenware, or china clay.
Cross-Contamination
It is a process of unintentional transfer microorganisms from one substance or object to another, with harmful effect.
Croutons
Crispy cubes of bread
Cutlery
Knives, forks, and spoons used for eating or serving food.
Deli
A store that sells pre-cooked fine food.
Dram Shop
American term for βAlcohol Barβ.
Gueridon Trolley
A trolley used in F&B Services business on which the food can be cooked, finished, or presented to the guest at the table.
High Ball (Long Drink)
Alcoholic beverage mixed with a large volume of soft drink and served in a tall glass with straw.
Mocktail
A non-alcoholic drink prepared using fruit juices or other soft drinks.
Pathogen
It is a biological agent that causes disease to its host.
Platter
A large flat dish or plate for serving food.
Pub
British name for βPublic Houseβ, an establishment licensed to serve alcoholic drinks.
Shot Ball (Short Drink)
Alcoholic drink consumed in a gulp. It is served in shot glass.
Situ
On site, locally.
Spot Checking
Regular surprise checking conducted to review standardized recipes and food products to maintain quality.
Station
A set of tables allocated to waiters in the F&B Services establishment.
Table Cover
It is the area on the table for plates, glasses, and cutlery for single person.
Tines
Parallel or branching spikes of a fork.
Toque
Cooks cap with multiple folds represents the many different ways a chef knows to prepare a dish.
The food and beverage service is part of the service-oriented hospitality sector. It can be a part of a large hotel or tourism business and it can also be run as an independent business. The members of the F&B Services team are required to perform a wide range of tasks which include preparation for service, greeting the guests, taking their orders, settling the bills, and performing various other tasks after the guests leave.
Let us see the F&B services in hotels, structure of F&B department and ancillary services in a hotel.
Most of the star-ranked hotels offer multiple F&B services in their hotels. They can be β
Restaurant
Lounge
Coffee Shop
Room Service
Poolside Barbecue/Grill Service
Banquet Service
Bar
Outside Catering Service
The F&B Services personnel are responsible to create the exact experience the guests wish for. The department consists of the following positions β
The Food & Beverage Service Manager is responsible for β
Ensuring profit margins are achieved in each financial period from each department of F&B service.
Planning menus for various service areas in liaison with kitchen.
Purchasing material and equipment for F&B Services department.
The Assistant Food & Beverage Service Manager is aware of and is tuned to all the work the F&B Services Manager performs and carries out the same in the absence of his superior.
The Restaurant Manager looks after the overall functioning of a restaurant. The responsibility of this staff member include β
Managing the functions in the dining room
Ordering material
Stock-taking or inventory checking.
Supervising, training, grooming, and evaluating the subordinates
Preparing reports of staff and sales
Managing budgets
Handling daily sales and coordinating with cashiers
The Room Service Manager is responsible for β
Selecting, training, encouraging, and evaluating all junior employees
Ensuring that cultural values and core standards of F&B department/establishment are met
Controlling labor expenses through staffing, budgeting, and scheduling
Handling guest complaints
Providing special requests
The Banquet Manager is responsible for β
Setting service standard for banquets
Forecasting and allocating budgets for various types of events such as conferences, meetings, etc.
Achieving food and beverage sales
Controlling chinaware, cutlery, glassware, linen, and equipment
Handling decorations and guest complaints
Providing special requests
Purchasing required stock by following appropriate requisition procedures
Following up each function by receiving guest feedback and submitting it to F&B Manager
Participating in departmental meetings
Planning and pricing menu
Training, grooming, and development of staff underneath
The Bar Manager is responsible for β
Forecasting the daily flow of customers
Allocating right number of staff according to customer influx
Managing and monitoring bar inventory from store to bar
Tracking all types of drink sales
Allocating cleaning and tendering tasks
A Food Safety Supervisor is a person who is trained to recognize and prevent risks associated with food handling in an F&B Services business. He holds an FSS certificate that needs to be no more than five years old. He is required in an F&B Services business so that he can train and supervise other staff about safe practices of handling food.
Food and Beverage department relies upon the support of the following departments β
The Kitchen Stewarding department strives to ensure cleanliness, preparedness, and orderliness in the commercial kitchen so that the kitchen staff can work efficiently. It also ensures that all the tools and utensils required for a specific meal or cooking task are cleaned properly and are ready to go. The kitchen steward is a working link between the F&B Services and the commercial kitchen.
The Dishwashing department is responsible for providing clean and dry supply of glassware, chinaware, and cutlery for bar, banquet, lounge, and restaurant service.
The F&B department is highly reliable on laundry department or outsourced laundry services for timely supply of dry-cleaned and wrinkleless linen.
Each member of the F&B department hierarchy needs to have the following traits and skills β
Awareness of oneβs responsibilities and roles, appropriate knowledge of food items, food and beverage pairing, etiquettes, and service styles is a great way to build confidence while serving the guests.
It creates the first impression on the guests. The F&B staff members must maintain personal hygiene, cleanliness, and professional appearance while being on duty.
Attentiveness is paying sincere attention to details, memorizing the guestsβ needs and fulfilling them timely with as much perfection as one can put in.
The F&B Services staff needs to conduct themselves with very positive, energetic, and friendly gestures.
It is very vital when it comes to talking with co-workers and guests. Clear and correct manner of communication using right language and tone can make the service workflow smooth. It can bring truly enhanced experience to the guests.
The F&B Services staff needs to know the value of time while serving the guests. Sincere time-keeping and sense of urgency helps to keep the service workflow smooth.
These two core values in any well-brought-up person are important for serving the guests in hospitality sector.
There are a number of service styles to be followed when it comes to how food and beverage should be served to the customers. The following are the most prominent styles β
In this type of service, the guests enter the dining area and take seats. The waiter offers them water and menu card. The guests then place their order to the waiter. The table is covered in this service. It is grouped into the following types.
Here, the host contributes actively in the service. The waiter brings food on platters, shows to the host for approval, and then places the platters on the tables. The host either makes food portions and serves the guests or allows the waiter to serve. To replenish the guestsβ plates, the waiter takes the platters around to serve or to let the guests help themselves. This is a common family service in specialty restaurants where customers spend more time on premise.
The food is served on guest's plate in the kitchen itself in predetermined portion. The accompaniments served with the food, the color, and the presentation are determined in the kitchen. The food plates are then brought to the guest. This service is commonly used in a coffee shop where service is required to be fast.
It is very personalized and private service. The food is taken in platters and casseroles and kept on the table of guests near their plates. The guests then help themselves. It is expensive and elaborate service commonly used in fine dining restaurants. This service has two variants β
Cart French Service β The food is prepared and assembled at tableside. The guests select food from the cart while sitting at their tables and are later served from the right. It is offered for small groups of VIPs.
Cart French Service β The food is prepared and assembled at tableside. The guests select food from the cart while sitting at their tables and are later served from the right. It is offered for small groups of VIPs.
Banquet French Service β The food is prepared in the kitchen. The servers serve food on each individualβs plate from guestβs left side. For replenishment, the servers keep the food platters in front of the guests.
Banquet French Service β The food is prepared in the kitchen. The servers serve food on each individualβs plate from guestβs left side. For replenishment, the servers keep the food platters in front of the guests.
In this service, partially cooked food from the kitchen is taken to the Gueridon Trolly for cooking it completely. This partial cooking is done beside the guest table for achieving a particular appearance and aroma of food, and for exhibiting showmanship. It also offers a complete view of food. The waiter needs to perform the role of cook partially and needs to be dexterous.
In this service, the food is presented on silver platters and casseroles. The table is set with sterling silverware. The food is portioned into silver platters in the kitchen itself. The platters are placed on the sideboard with burners or hot plates. At the time of serving, the waiter picks the platter from hot plate and presents it to the host for approval and serves each guest using a service spoon and fork.
It is identical to the Cart French service barring the servers place the food on the platters and serve it from the left side.
Here, the guests enter the dining area, collect their plates, and go to buffet counters and help themselves. The guests may partially get service at the table or replenish their own plates themselves.
It this type of service, the guests get plates from the stack and goes to buffet counter where food is kept in large casseroles and platters with burners. The guests can serve themselves or can request the server behind the buffet table to serve. In sit-down buffet restaurants, the tables are arranged with crockery and cutlery where guests can sit and eat, and then replenish their plates.
In this type of service, the guests enter the dining area and select food items. They pay for coupons of respective food items. They go to food counter and give the coupons to avail the chosen food. The guests are required to take their own plates to the table and eat.
This service exists in industrial canteens, hostels, and cafeterias. The menu and the space is limited; the cutlery is handed over to the guests. The tables are not covered. Sometimes high chairs are provided to eat food at narrow tables. It is a quick service.
In this type of service, the guest orders, pays for his order and gets served all at a single point. There may be may not be any dining area or seats. The following are the different methods of Single Point Service.
This is an array of autonomous counters at which the customers can order, eat, or buy from a number of different counters and eat in adjacent eating area.
The customer enters the choice and amount of money physically and the machine dispenses what customer demanded accurately.
Customer orders and avails food and beverage from a single counter and consumes it off the premises.
The customer can get food or beverage service by means of automatic machines. The vending machines are installed in industrial canteens, shopping centers, and airports.
It is called special service because it provides food and beverage at the places which are not meant for food & beverage service. The following are the different methods of special service.
In this type of service, various vegetables and meats are displayed for better view and choice. The counter is decorated with great aesthetics, and the guest can select meat or vegetable of choice. The guest then takes a seat and is served cooked food with accompaniments.
Method of service of whole or part of meal on tray to customer in situ, such as hospitals, aircraft, or railway catering.
Food is cooked, finished or presented to the guest at a table, from a moveable trolley. For example, food served on trollies for office workers or in aircrafts and trains.
Food delivered to a customerβs home or place of work. For example, home delivery of pizza or Meals on Wheels.
Service of variety of foods and beverages in lounge area of a hotel or independent place.
Here food is served to guests in their allotted rooms in hotels. Small orders are served in trays. Major meals are taken to the room on trolleys. The guest places his order with the room service order taker.
The waiter receives the order and transmits the same to the kitchen. Meanwhile, he prepares his tray or trolley. He then goes to the cashier to prepare and take the bill. He then takes the bill along with the food order for the guestsβ signature or payment. Usually clearance of soiled dishes from the room is done after half an hour or an hour. However, the guest can telephone Room Service for the clearance as and when he has finished with the meal.
Today, numerous types of food and beverage service outlets have come up in the market. They offer a wide range of food and beverage services that the customers can avail. The extent of service depends upon the type of service outlet. They include drive-through service of fast food where the customers can purchase their favorite food without having to leave their cars and pick-up points where food is delivered in minutes. There are also some elite class fine dining outlets which exhibit classy articles in the house and provide elaborate food services.
Here are some famous types of food and beverage outlets β
Appropriate architecture of F&B outlet makes it prepare, present, and serve in optimum way and increase productivity. These are few basic considerations for various sections of F&B outlets β
It is farthest from the customers.
It has large fridges, cupboards with multiple shelves, and lockers. It is attached to the kitchen.
It is being the area where food or beverage is prepared ready to serve, it is located between the dining area and the kitchen.
There are two different schools of thought for location of restrooms β some experts consider that the restrooms must be near the entrance and some think that it should be isolated from entrance or dining area.
While designing an F&B outlet, one needs to consider every factor that contributes to the smooth running of operations right from food preparation, cooking, dish presentation, serving, and all allied tasks.
While designing commercial F&B outlets, the following points are important β
Target customer segment (Youth/Men/Women/All).
Type of food (Light Food/Fast Food/Fine Dining).
Manner of food production (Cooking/Grilling/Boiling/Baking/Steaming).
Type of food distribution (On/Off Premise).
Availability of carpet area.
Number of staff required.
The kitchen is designed not to be directly visible. The chef cannot directly communicate to the guests. The guest tables and chairs are placed away from kitchen.
Food and Beverage Service operations involve a multitude of activities which engage the staff right from purchasing raw material, preparing food and beverage, keeping the inventory of material, maintaining service quality continuously, managing various catered events, and most importantly, analyzing the business outcomes to decide future policies.
Let us look into the operations involved in F&B service β
The purchasing department in F&B Services is responsible for purchasing, storing, and issuing the supply of raw food items, canned/bottled beverages, and equipment. The following is a typical product purchasing cycle β
The purchasing department works with accounts department to keep the information on allocated budget and balance budget.
The following factors influence purchasing β
Size of F&B Organization
Location of F&B Organization
Availability and Size of Storage Space
Organization Budget and Policies
Availability of the commodity due to season
The purchaser is responsible for purchasing a product. He studies the market, and analyzes and selects suppliers, wholesalers, and the contemporary market prices. He then liaisons with suppliers and wholesalers to get good material at fair price and purchases the required commodities by following appropriate purchase procedures.
The receiver receives the products from the suppliers. He checks the product for right quality and quantity. He deals with the delivery personnel from the supplierβs end and signs on the related receipts.
The store men carry out the task of storing received supply and issuing it to respective departments. They update the stock database, and manage old and new material in the stock. They also keep record of stock to the latest date.
This includes preparation of various food items and fresh beverages. The cooks prepare various foods and the bar tenders prepare cold beverages such as mocktails and cocktails. They also make the dish most presentable by arranging food on platter and decorating it in an attractive manner. The beverages are also decorated by using fruit slices, decorating the glasses, sippers, and stirrers.
This part is played by the guests. At the service end, the respective staff takes inventory of the consumed and balanced stock of food and beverages and keeps it updated to latest figures.
It is very vital for an F&B Services organization or an F&B department in a large hotel to keep their standards of food and beverage high. If the quality of food and beverage along with the best service is what the guests liked, then the chances of the guests coming repeatedly and singing praises of what they received are high.
Any food and beverage service business has a great responsibility of serving hygienic, safe, clean, and fresh food. The customers also rightfully question if the food or beverage they consume at the F&B Services outlet is healthy, safe, and fresh.
For ensuring food safety, a system named Hazard Analysis and Critical Control Points (HACCP) in Europe works to identify Critical Control Points (CCP) for the presence of physical, chemical, and bacterial hazards to food. HACCP has set guidelines and principles on producing healthy and safe food. It also enables food and beverage businesses to adhere to consistent safety and quality of food production.
In India, Food Safety and Standards Authority (FSSA) works towards setting standards for safe and hygienic food. In USA, Food Safety and Inspection Service (FSIS) is responsible for the safety of meat, poultry, and processed egg products. Also, the Food and Drug Administration (FDA) is responsible for virtually all other foods.
Before planning and executing buffets, banquets, or catered events, the respective managers and supervisors need to consider the following factors β
It can be formal such as seminars, meetings, or conference, or informal such as a wedding reception, birthday party, employee outing, and alike.
The participants such as decorating staff, planning staff such as managers, serving staff, supervising staff, whole sellers, and the guests.
It is important to know the date and time of event, the number of expected guests, dance floor, audio or projector systems, or any special requirement demanded by the guests before planning the event.
It includes flowers, table arrangement, center-pieces, candles, artificial fountains/waterfalls, decorative art pieces, plants and pots; for both formal and informal occasions with the involvement of deΜcor artists. The display pieces may be carved, baked, or assembled; made of edible or non-edible substances according to the laid standards. The decoration needs to go in pair with the theme of the banquet, buffet, or some event.
According to the time of event, it can include starters, salads, breads, main courses (meats, poultry, or sea food), desserts (fruits, pastries, or frozen desserts), beverages, accompaniments, and garnishes according to the establishment standards. It must be hygienic, in-line with the occasion, and meeting the F&B Services establishment standards.
Depending upon the requirement of guests and serving style, it can include silverware, platters, table linens, and other required serving equipment. It also includes size and shape of tables and chairs.
According to establishment norms, serving right food at right temperature, replenishing food platters timely, keeping the overall display neat and attractive, storing food and managing beverage consumption after service, cleaning buffet or banquet area, restoring plates, cutlery, Guerion trollies, and glassware after completion of service.
The decision making responsibility in an F&B establishment rests with the managers. They have full access to the numbers, data, reports, and trends of the market as well as knowledge of F&B establishments.
The F&B services managers need to conduct financial analysis and quality analysis.
Financial Analysis is carried out in three steps β
The managers study current and future market trends and forecast expenses. Budgets are prepared based on managersβ inputs.
The managers also keep a keen eye on present situation in which F&B Services is functioning. They need to consider fixed costs such as rents and property taxes, and variable costs such as material, advertisement, and music and entertainment costs.
They come up with the difference and find out the reasons and apply the required policies.
The Quality Analysis needs to consider the following factors while providing the food product or service. Some of these factors are β
Evaluating ongoing product analysis checklist that includes doneness, aroma and taste of the ready dish, garnish, color, appearance, presentation, serving portion, and alike.
Evaluating ongoing product analysis checklist that includes doneness, aroma and taste of the ready dish, garnish, color, appearance, presentation, serving portion, and alike.
Evaluating the food or beverage product for safety against consumption.
Evaluating the food or beverage product for safety against consumption.
Evaluating weekly review of product deviation that includes date, product name, problem, solutions, and recommendation.
Evaluating weekly review of product deviation that includes date, product name, problem, solutions, and recommendation.
It includes coming up with corrective actions in case of certain unpleasant results. The managers make decisions after going through the following steps β
Identifying problems
Identifying reason
Determining a number of solutions
Selecting a best solution
Applying the solution
Evaluating the solution
For example, the response for chilled cucumber soup is declining for the past four months.
Identify problems β Menu problem? Taste issue? Price issue? Serving quantity or quality issue?
Identify problems β Menu problem? Taste issue? Price issue? Serving quantity or quality issue?
Identify reason β Soup is outstanding on quality, portion of service, and taste marks. But it is Winter and guests are preferring hot soups than the chilled ones though it is on the lunch menu.
Identify reason β Soup is outstanding on quality, portion of service, and taste marks. But it is Winter and guests are preferring hot soups than the chilled ones though it is on the lunch menu.
Solutions β Can a hot variant of the same soup be developed? Can the soup be replaced by a preferred alternative?
Solutions β Can a hot variant of the same soup be developed? Can the soup be replaced by a preferred alternative?
Best solution β Shift chilled cucumber soup to summer-time menus and bring in a new hot soup or a variant of one of the present soups that will potentially rule the guestsβ taste buds.
Best solution β Shift chilled cucumber soup to summer-time menus and bring in a new hot soup or a variant of one of the present soups that will potentially rule the guestsβ taste buds.
Food and beverages form an integral part of the human culture. Ever since human culture started evolving, food and beverages preparation also went on finding new ways. Today, every country flaunts a different line of food and beverages prepared in authentic culinary ways.
Over the past several years, various food and beverages have been developed using local crops, meats, fruits, and vegetables, and trying different recipes with them. This manner of development contributed in the authenticity of the food and beverages to a great extent.
It is a detailed list of food and beverage offerings with their respective prices. It is prepared by a food and beverage service businesses to keep the customers informed about the availability of various F&B items.
A good menu must β
Present clear, unambiguous information.
Adhere to food safety and nutrition policies of the business.
Meet or outstrip guestsβ expectations.
Meet the quality standards of the business.
Be truthful in describing the taste and preparations.
Be strictly going with the production and service facilities of the business.
The restaurant menu should be planned well by considering various aspects of the food outlet. There are myriad menus available right from breakfast, lunch, small bites, up to dinner. The following information is gathered before planning food and beverage menu for a commercial kitchen.
What kind of food outlet is it? (Vintage, Contemporary, Modern, Theme, Bar, and more)
What is the name of the outlet?
What is the expanse of food items, their accompaniments, and beverages the owner wishes to keep?
Which information needs elaboration for food and beverages?
What tone of language is required? (formal/informal)
What types of names and category headings would best suit for the food and beverage items?
What design, images, colors, and typeface would look best for the menu?
Are the graphic details relevant to the food outlet theme?
How large should the menu be on paper?
These days, numerous apps such as MenuPro, FineDine, MenuExpress, InnMenu, and more are readily available to create catchy and engaging menus. A good menu design is a treat for eyes that drive the guests to place orders.
Depending upon the expanse of physical outlet and service, and the variety of food and beverages it offers, the menu design and details change.
This is the selection of menu in advance for an upcoming event. Menu planning plays an important role in customer satisfaction.
Menu planning is beneficial in the following areas β
Purchasing of essential material in advance.
Pricing of the food.
Guiding the food preparation.
Evaluating the dietary needs.
Evaluating the food in terms of necessary improvements.
The menu must be planned such that it goes well with the theme of the F&B outlet and it must be a good bargain for food price and dietary value.
There are various cuisines around the world. Each cuisine involves a lot of preparation. The following most famous ethnic menus are prepared in various cuisines around the world
Indian food is perhaps as diverse as its culture and offers a lot more than curries and gravies. It balances all tastes β savory, sweet, salty, and sour. Indian food broadly goes according to the regions where it originates such as Northern, Southern, Western, and Eastern. Within regions it is varied according to states such as Kashmiri, Punjabi, Gujarati, Marathi, Keralite, Bengali, and so on. It is an authentic combination of the base food paired with aromatic herbs nuts, and spices.
It includes various appetizers, snacks and their accompaniments, veg and non-veg stews, various types of flat breads, plain or spicy lentils, rice preparations, sea-food, street food, and sweets made of milk products and nuts.
Indian food is eaten using oneβs clean fingers because that way, the flatbreads are easy to portion. The spoons and forks are used for having snacks, curries, stews, rice, curds, or sweets when the need arises. Authentic Indian food is generally served in copper or brass bowls and plates or you can have it on fresh banana leaves or Patravali (Plates made of dried leaves), which help to save efforts of cleaning and disposing.
A few popular Indian foods are β
Poha (beaten rice soaked and cooked by adding chopped vegetables and cilantro)
Poha (beaten rice soaked and cooked by adding chopped vegetables and cilantro)
Aloo Bonda (Boiled, mashed, and flavored potatoes enwrapped with lentil flour and deep fried)
Aloo Bonda (Boiled, mashed, and flavored potatoes enwrapped with lentil flour and deep fried)
Kadhai Panner (Savory cubes of cottage cheese in thick tangy curry or gravy)
Kadhai Panner (Savory cubes of cottage cheese in thick tangy curry or gravy)
Veg Kolhapuri (Wholesome vegetables cooked in spicy red gravy)
Veg Kolhapuri (Wholesome vegetables cooked in spicy red gravy)
Rajma (Black beans cooked in spicy gravy)
Rajma (Black beans cooked in spicy gravy)
Biryani (Aromatic and flavored rice dish cooked with vegetables or meat)
Biryani (Aromatic and flavored rice dish cooked with vegetables or meat)
Sarson-da-saag (Mustard leaves cooked with chili, garlic, and mustard oil)
Sarson-da-saag (Mustard leaves cooked with chili, garlic, and mustard oil)
Jalebi (Coils of flour batter deep fried and dipped in sugar syrup)
Jalebi (Coils of flour batter deep fried and dipped in sugar syrup)
Gulab Jamun (Deep fried balls of milk powder and flour soaked into sugar syrup)
Gulab Jamun (Deep fried balls of milk powder and flour soaked into sugar syrup)
France boasts of a wide range of cuisines. The cuisines follow authentic traditional cooking practices. French food caters to the preparation of appetizers, salads, soups, stews, side and main dishes, and desserts. A large variety of classic food is prepared using red and white meats. Recipes have evolved with seafood, fruits, cheeses, vegetables, pastries, and chocolates using authentic sauces and dressings.
The following are some traditional French dishes are β
Soupe a l'oignon (Onion soup in meat stock)
Soupe a l'oignon (Onion soup in meat stock)
Petits Pates a la Sage (Little pies of sage)
Petits Pates a la Sage (Little pies of sage)
Ratatouille (Traditional vegetable stew)
Ratatouille (Traditional vegetable stew)
Coq au vin (Rooster in wine)
Coq au vin (Rooster in wine)
Italian food boasts of classically prepared pizza bases baked with savoury toppings of vegetables, meat, and cheese. It also includes a wide range of pastas of various shapes and sizes cooked and served with authentic Italian accompaniments and sauces.
The local customs of baking and cooking provide a large array of soups, salads, snacks, meals, and desserts from Italian cuisine. The food is often accompanied with beverages such as wine, champagnes, or other similar drinks.
The following are some popular dishes in Italian cuisine β
Bellini (a cocktail made with white peach puree and sparkling wine.)
Bellini (a cocktail made with white peach puree and sparkling wine.)
Caprese Salad
Caprese Salad
Cacciuco (Seafood stew)
Cacciuco (Seafood stew)
Risotto Alla Milanese (Saffron Rice)
Risotto Alla Milanese (Saffron Rice)
Arancini Veneziani (Venetian Rice Fritters)
Arancini Veneziani (Venetian Rice Fritters)
Braciola (Italian Beef Rolls in Tomato Sauce)
Braciola (Italian Beef Rolls in Tomato Sauce)
Spinach and Mushroom Lasagna (Baked sheets of flour separated by stew and cheese)
Spinach and Mushroom Lasagna (Baked sheets of flour separated by stew and cheese)
They say, Chinese food is the tastiest in the world. It includes soups, snacks, and meals prepared with rice, noodles, vegetables, meats, seafood, sauces, and seasonings. The stir frying manner of cooking brings crunchiness, texture, and adds a great flavor to various Chinese dishes.
Chinese food is prepared with crunchy or leafy vegetables, bean sprouts, a variety of mushrooms, bamboo shoots, tofu (soybean curds), and spices such as chilies, ginger, Chinese celery, and garlic. The food is consumed using traditional chopsticks and spoons. The table setting displays porcelain bowls and spoons for soup, a large bowl for food kept on the flat plate underneath, Rice bowl, and a pair of chopsticks with resting stand.
The following are some traditional Chinese dishes β
Gong Bao Chicken (Diced chicken cooked with dried chili and fried peanuts).
Gong Bao Chicken (Diced chicken cooked with dried chili and fried peanuts).
Ma Po Tofu (Tofu cubes cooked with pepper powder, ground beef, and green onions).
Ma Po Tofu (Tofu cubes cooked with pepper powder, ground beef, and green onions).
Wontons (Triangles of flour added in soup).
Wontons (Triangles of flour added in soup).
Dumplings (Small dough disks filled with minced meat or spicy chopped vegetables, closed, and steamed).
Dumplings (Small dough disks filled with minced meat or spicy chopped vegetables, closed, and steamed).
Spring Rolls (fried cylindrical rolls that enwrap minced meat or vegetables).
Spring Rolls (fried cylindrical rolls that enwrap minced meat or vegetables).
Chow Mein (Cooked and stir fried vegetables in savory sauce).
Chow Mein (Cooked and stir fried vegetables in savory sauce).
Chinese food includes a cup of tea as beverage. No aerated drinks are served as part of authentic Chinese meal. Desserts are not commonly consumed in Chinese cuisine except on special occasions. The meal is generally completed with fruits.
Thai food is popular for the aroma it brings with the addition of lemongrass, lemon leaves, galangal, chili, and aromatic herbs. The base food is vegetables, meats, eggs, sauces, noodles, and rice. A complete Thai meal comprises of snacks, salads, soups, one-dish meals, and desserts. It makes a blend of great taste and treat for eyes too.
As per the traditional customs, the soups are enjoyed along with rice and noodles; not before. The rice or noodles are topped with the toppings of choice and consumed with spoon. Some popular Thai dishes are β
Tom Yam Goong (Jumbo prawns in savory hot and spicy sauce)
Tom Yam Goong (Jumbo prawns in savory hot and spicy sauce)
Pad Thai (Noodles with tofu, sprouts, fried onion, chili sauce, and finely powdered peanuts)
Pad Thai (Noodles with tofu, sprouts, fried onion, chili sauce, and finely powdered peanuts)
Kuay Tiew (Noodles served in vegetables and meat broth)
Kuay Tiew (Noodles served in vegetables and meat broth)
Gai Med Ma Moung (Chicken in soy sauce, garlic, honey, and cashew nuts)
Gai Med Ma Moung (Chicken in soy sauce, garlic, honey, and cashew nuts)
Kao Phad (Fried rice)
Kao Phad (Fried rice)
Massaman Curry (Meat and potato cooked in cinnamon flavored curry)
Massaman Curry (Meat and potato cooked in cinnamon flavored curry)
Mexican line of food is famous for spicy and tangy taste. It includes salads, snacks, one-dish meals, elaborate meals, and desserts.
The basic food items in Mexican cuisine are β
Tortillas (Corn flour or wheat flour disks)
Tortillas (Corn flour or wheat flour disks)
Fajitas (Grilled meat on tortilla)
Fajitas (Grilled meat on tortilla)
Tacos (Small tortilla partially enwrapping the filling)
Tacos (Small tortilla partially enwrapping the filling)
Quesadillas (Wheat or corn tortilla filled with cheese and meat or vegetables)
Quesadillas (Wheat or corn tortilla filled with cheese and meat or vegetables)
Nachos (A Texan-Mexican or Tex-Mex snack with savory flavored tortilla chips)
Nachos (A Texan-Mexican or Tex-Mex snack with savory flavored tortilla chips)
Enchiladas (Corn tortillas rolled around a filling of cooked meat, seafood, beans, or vegetables and covered with a chili pepper sauce and cheese)
Enchiladas (Corn tortillas rolled around a filling of cooked meat, seafood, beans, or vegetables and covered with a chili pepper sauce and cheese)
Empanadas (Baked or fried stuffed bread or pastry)
Empanadas (Baked or fried stuffed bread or pastry)
Corn, black beans, native fruits and vegetables, herbs, and meats are integral ingredients of Mexican food. A few popular Mexican dishes are β
Chicken-mango-jalapeno salad
Mango-pineapple salsa
Prawn fajita with avocado cream
Mexican chicken stew
Grilled chicken nacho
The courses of meal around the world vary in number from as small as just one to as wide as 17, in case of a traditional French meal. The courses are divided according to what food one eats. There are different food profiles according to the countryβs culture and customs. Generally, there are at least three courses of a meal β
In this course, a welcoming appetizer that induces hunger is given to the guests. Also, the guests can prefer soups accompanied with the bite-size savory snacks as side orders in this course.
During this course, main dishes with vegetables or meats accompanied with rice and breads are served. In some cultures, such as Indian, the main dish is accompanied with salads.
This course signals the end of meal and is usually had with a cup of coffee.
Salads form an important part of diet in France. A typical French meal has an addition of Salad Course. It is often accompanied by other courses such as Fish Course and Cheese Course. There are cultures where people prefer to take one dish meal with no elaborate and distinguished courses of food.
Depending upon what and how the food is made available to the guests, there are following broad menu types β
Table Dβhote is a menu where the meal is combined with a number of food options from each course. The guests can make their choice and order for a fixed price. Irrespective of what the guest chooses or declines, the price remains the same. Hence, it may also be called prix fixe or fixed price menu. Banquet menus, childrenβs menus, and occasion menus cater to special occasions and are offered at a set price.
A la carte is a multi-course or multi-category menu that comes with appetizers, starters, sea-food, meats, side dishes, beverages, and alike. Each dish is offered at a separate price. The guest can choose individual dishes to make own meal package.
In this menu, the typical types of meals are served yearlong with an occasional change on some special days.
Cycle menu includes different meals offered on different days of a week. The cafeterias at educational institutes and otherwise use this menu which they can repeat after a week or a month. Serving a feast on Sunday, offering special variants of chicken on Fridays can add to the cyclic menu.
Let us now look at a few other menus which boost your platter and the F & B Services.
This menu displays puddings, cakes, tarts, ice creams, smoothies, fondues, sundaes, sweet pies, and ice creams and frozen yogurts along with their respective prices.
Frozen Desserts β They are usually popular with people from all ages and walks of life. They are always served chilled. The following are some mouthwatering frozen desserts are β
Ice Cream/Gelato (Italian for ice-cream) β They are primarily same with just a little difference in composition of milk, custard, water, and eggs. In India, frozen desserts are prepared with thick full cream milk and fruit pulp or crushed nuts and saffron. It is popularly known as βKulfiβ. Kulfi is served on stick or in terracotta pot called βMatkaβ.
Sorbet β It is a frozen dessert made of fruit juices, dessert wines, and ice shaves. It is flavored by a variety of edible food colors and essences. In contrast to ice cream, frozen dessert appears icier than milky.
Frozen Yogurt β It is made by freezing flavored yogurt. It also contains less fat, sugar, and thus less calories as compared to ice creams.
This menu includes variants of tea and coffee, hot chocolate, juices, milkshakes, mocktails, and so on. The wine menu includes wines, beers, liquors, types of water, cocktails, and spirits with their respective serving quantities and prices.
Beverage is any liquid consumed by humans for quenching thirst, or merely for pleasure. Beverages come in various types β
There are two types of non-alcoholic beverages.
These are served hot. Hot beverages typically include tea, masala tea (spiced tea), milk, hot chocolate, and variants of coffee such as expresso, latte, and cappuccino.
These are served and consumed while chilled. Cold beverages include juices, mocktails, coolers, cold versions of tea and coffee, milkshakes, carbonated drinks, mocktails, and sherbets. The following beverages are famous in countries like India β
Buttermilk with a dash of powdered cumin seeds and salt.
Buttermilk with a dash of powdered cumin seeds and salt.
Aam Panna, a sweet and sour raw mango juice with a dash of cardamom in it.
Aam Panna, a sweet and sour raw mango juice with a dash of cardamom in it.
Tender coconut water locally called Nariyal-Pani.
Tender coconut water locally called Nariyal-Pani.
Sol Kadhi, thin coconut milk flavored with Kokum and ginger-garlic-chili paste.
Sol Kadhi, thin coconut milk flavored with Kokum and ginger-garlic-chili paste.
There are a few cold beverages which come as cocktails and are prepared using alcohol.
These are served cold. Alcoholic beverages are intoxicating and contain ethanol, commonly known as alcohol. Such beverages need to undergo fermentation and distillation to generate alcohol contents. The percentage of alcohol varies in the range of 0.5% to 95% depending upon the methods of fermentation and distillation.
Wine, Cider, Perry, and Champaign are fermented alcohols.
Wine, Cider, Perry, and Champaign are fermented alcohols.
Beer, ale, and lager are fermented and brewed alcohols.
Beer, ale, and lager are fermented and brewed alcohols.
Gin, Vodka, Whisky, Rum, Brandy, and Tequila are distilled alcohols.
Gin, Vodka, Whisky, Rum, Brandy, and Tequila are distilled alcohols.
If a beverage contains at least 20% Alcohol by Volume (ABV), it is called spirit. Liquors are similar to spirits. The only difference is that liquors come with added sweetness and flavoring. Liquors and spirits, both are strong alcoholic beverages. The following are a few most popular alcoholic beverages β
Due to the unwanted side effects of alcohol on consumer and the society, it is the responsibility of food and beverage service staff to verify the young customerβs age before serving alcoholic beverages.
The equipment forms an inevitable part of food and beverage service. It plays an important role to build the mood of the guests, to complement the outlet theme, and to elevate guest experience. Right from the largest commodities used for food preparation and interior decoration such as chandeliers or ovens to the smallest piece of cutlery, furniture, or linen participate in creating overall ambience of the outlet.
Let us discuss in detail the equipment used in food and beverage services β
Furniture is an important part of any F&B Services outlet. It needs to be strong, easy to use and clean. The furniture plays an important role in bringing the look and creating an ambience of the outlet. The furniture, fixtures, and fittings are fixed commodities.
It mainly consists of tables, chairs, push-down chairs, racks, and lockers.
It needs to be sturdy as well as attractive. It includes coffee tables and chairs, bar chairs, dining sets, day beds, loungers, hammocks, and swings.
A fixture is any item bolted to the floor or walls. For example, air conditioners, electric plugs, sinks and toilets, art pieces, and television screens mounted on wall are fixtures.
A fitting is any free standing item or an item that can be hung by a nail or hook. For example, paintings, mirrors, curtain rails, and lamps are fittings.
Tableware consists of crockery, cutlery, glassware and linen used while serving and eating meals at a table. These are circulating equipment which can be grouped into the following types β
This is a collection of fine dishes, bowls, food platters, section dishes, ramekins, cups and saucers, soup spoons, vases, and ash trays made using a translucent ceramic material.
This consists of containers such as serving bowls, pots, kettles, ice jugs, and water. These containers are either made from glass or metals such as copper, brass, or stainless steel.
This consists of articles made of fine glass. Glassware includes jugs, pitchers, drinkware, ash trays, vases, and similar articles.
The objects in silverware are made of Electro Plated Nickel Silver (EPNS). These are made from an alloy of brass, zinc, stainless steel or nickel with silver plating of 10 to 15 microns. Silverware includes spoons, forks, knives, hollowware, drinkware, tongs, ice bucket, and a salver.
These are food warming dishes. They keep the food warm for an adequate time and temperature. They come in two variants: electric or chafer fuel candle.
Chaffing dishes are available in multiple sizes, shapes, and lids. Modern-day chafing dishes are made of light metal or ceramic with handles, sometimes covered with a see-through lid. Here are some chaffing dishes β
Cutlery comprises of any hand-held implement for eating or serving food. It includes various spoons, forks, knives, and tongs. It is also called silverware or flatware. Cutlery is made of metals like stainless steel or silver.
In modern days, cutlery has come up in wonderful combinations β spife (spoon + knife), spork (spoon + fork), and knork (knife + fork).
There are different types of spoons for serving or eating different kinds of food. The forks often accompany spoons or help independently to pick food bites. The knives are used to portion the food.
Dinner Spoon (Table Spoon) β It has elongated round cup. It is used to eat main course food items. It can pick up just the right amount of rice, stew, or curry. It is always paired with a fork (with four tines) of the same length or a dessert knife.
Dinner Spoon (Table Spoon) β It has elongated round cup. It is used to eat main course food items. It can pick up just the right amount of rice, stew, or curry. It is always paired with a fork (with four tines) of the same length or a dessert knife.
Dessert Spoon, Dessert Knife, and Dessert Fork β These are smaller than their main course peers and are used to have desserts.
Dessert Spoon, Dessert Knife, and Dessert Fork β These are smaller than their main course peers and are used to have desserts.
Soup Spoon β It has a round cup bigger than that of the table spoon. It is as long as a dinner spoon.
Soup Spoon β It has a round cup bigger than that of the table spoon. It is as long as a dinner spoon.
Tea/Coffee Spoons β These are smaller than the dessert spoon in length and size of cup. We use these spoons to stir tea or coffee.
Tea/Coffee Spoons β These are smaller than the dessert spoon in length and size of cup. We use these spoons to stir tea or coffee.
Sugar Spoon β It has a flower shaped round cup. It is used to take sugar from sugar bowl of tea set.
Sugar Spoon β It has a flower shaped round cup. It is used to take sugar from sugar bowl of tea set.
Ice Cream Spoon β It is a small spoon with flat rim that can help to cut the right amount of ice cream. It can come in small, medium, and large sizes according to the quantity of the ice cream served and the size of the bowl.
Ice Cream Spoon β It is a small spoon with flat rim that can help to cut the right amount of ice cream. It can come in small, medium, and large sizes according to the quantity of the ice cream served and the size of the bowl.
Cocktail (Soda) Spoon β It is a drink spoon with a long handle that helps the spoon to reach the bottom of a tall glass.
Cocktail (Soda) Spoon β It is a drink spoon with a long handle that helps the spoon to reach the bottom of a tall glass.
Butter knife β It has short rectangular blade that is sharp on the lower side to form an edge. It is useful in cutting semi-firm pieces of butter and apply them on food items such as breads.
Butter knife β It has short rectangular blade that is sharp on the lower side to form an edge. It is useful in cutting semi-firm pieces of butter and apply them on food items such as breads.
Salad Spoon β It is always used in pair with salad fork. It helps mixing and serving salad efficiently.
Salad Spoon β It is always used in pair with salad fork. It helps mixing and serving salad efficiently.
Serving Spoon β It is a spoon with large round cup designed to serve stews and rice.
Serving Spoon β It is a spoon with large round cup designed to serve stews and rice.
Deli (Fruit) Fork β has two tines. It helps to pick thinly sliced food such as slices of fruits.
Deli (Fruit) Fork β has two tines. It helps to pick thinly sliced food such as slices of fruits.
Roast Fork β It is the largest fork. It has longer and stronger tines that help to hold and pick large meat or vegetable pieces.
Roast Fork β It is the largest fork. It has longer and stronger tines that help to hold and pick large meat or vegetable pieces.
Cake Knife β It is a flat, elongated triangle-shaped knife and is used to cut pieces of cake and handle it smoothly.
Cake Knife β It is a flat, elongated triangle-shaped knife and is used to cut pieces of cake and handle it smoothly.
The glasses and tumblers come in a wide variety of shapes and sizes. They are either footed with stem or non-footed. They can also be high-ball or low-ball. Some of the widely used shapes are β
Cooler β It is used to serve welcome drinks or appetizers.
Cooler β It is used to serve welcome drinks or appetizers.
Flute β It is a glass with a long cup and is mainly used to serve champagne.
Flute β It is a glass with a long cup and is mainly used to serve champagne.
Goblet β It is a round glass with or without stem. The goblets with stem are used to serve wines and brandy. A non-footed version is used to serve whisky.
Goblet β It is a round glass with or without stem. The goblets with stem are used to serve wines and brandy. A non-footed version is used to serve whisky.
Margarita β It is a variant of goblet with a wide round dish-like cup. Margarita is used as a cocktail, mocktail, or a sorbet glass.
Margarita β It is a variant of goblet with a wide round dish-like cup. Margarita is used as a cocktail, mocktail, or a sorbet glass.
Mug β It is used to serve beers.
Mug β It is used to serve beers.
Nonic Glass β It is a tall glass with a broad rim. It is used to serve beers.
Nonic Glass β It is a tall glass with a broad rim. It is used to serve beers.
Pilsner β It is a high-ball glass used to serve cold coffee, iced tea, juices, and beer. A pilsner can support beers or aerated drinks gracefully.
Pilsner β It is a high-ball glass used to serve cold coffee, iced tea, juices, and beer. A pilsner can support beers or aerated drinks gracefully.
Pint β It is a glass used to pour distilled alcohol into other glasses.
Pint β It is a glass used to pour distilled alcohol into other glasses.
Shot Glass β It is a small glass used to consume fermented or distilled alcohol directly. It can also be used to pour distilled alcohol into other glasses for mixing with water or sparkling water.
Shot Glass β It is a small glass used to consume fermented or distilled alcohol directly. It can also be used to pour distilled alcohol into other glasses for mixing with water or sparkling water.
Snifter β It is used to serve spirits.
Snifter β It is used to serve spirits.
Thistle Glass β Its silhouette is shaped like a thistle flower. These glasses have tapered broad rims with round cups attached to a stem and disk. It is used to serve ales and aerated drinks.
Thistle Glass β Its silhouette is shaped like a thistle flower. These glasses have tapered broad rims with round cups attached to a stem and disk. It is used to serve ales and aerated drinks.
Tulip Glass β It is used to serve beer, cocktail, or mocktail.
Tulip Glass β It is used to serve beer, cocktail, or mocktail.
The linen at any food and beverage service outlet is either disposable or non-disposable.
This includes items that can be used only once. These items are made of recycled paper with high absorbing capacity. For example, table napkins, restroom tissues, wrappers, and facial tissues. Facial tissues soaked in Cologne water are given to the guests. It is considered a good welcome gesture. Disposable table linen is usually offered to guests in trains or aircrafts before meals.
The items in this category are made from flax. This includes table cover, dinner napkins, tea napkins, and table runners. Non-disposable linen must be clean and pleasantly scented. It must be starched if required.
Non-Disposable linen must be placed on the table tidily. The staff can fold them and arrange them in decorative shapes or just put them through decorative linen rings to catch guestsβ eyes and start imparting warm experience to them at the table.
Pantry is the adjoining area or room to the kitchen from where the finished food or a drink is ready to be served. This area serves as an ancillary capacity of the kitchen. The food is given final touch-up for presentation, and then handed over to the serving staff. The pantry is often equipped with a sink attached with normal water and hot water taps. The pantry mainly keeps the following necessary items β
Refrigerator
Electric oven
Toaster
Coffee Brewing Machine
Blender
Electric food whisk
Knives and chopping boards
Hollowware like casserole, bowls, and dishes of various sizes
Crockery
Drinkware
Cutlery
Sideboards are mainly shelves with drawers. These can be used to store hollowware and glassware. The following are the different varieties of sideboards β
Buffet β It has high legs than the sideboard.
Buffet β It has high legs than the sideboard.
Credenza β They are the storage cabinets without legs. They mostly have sliding glass doors.
Credenza β They are the storage cabinets without legs. They mostly have sliding glass doors.
Server β A server is smaller, shorter, and more formal than a buffet or sideboard.
Server β A server is smaller, shorter, and more formal than a buffet or sideboard.
Sideboard β It has short legs.
Sideboard β It has short legs.
It is a serving cart used for serving as well as storing. It has wheels which enable it to move easily around the kitchen. It is also used in elite food and beverage outlets for serving the guests. It is available in various designs, sizes, and shapes. You can choose on number of shelves and sections, and burners. When not in use, it is preferably parked at the wall.
When the food is ready to arrive in the pantry, used utensils for food preparation are cleaned immediately and wiped off dry for later use. If any other ancillary serving item such as electric hand blender is damaged, it is reported to the concerned manager and replaced with a working one at the earliest.
When the guests complete their meals and leave the table, it is required to prepare the table immediately by clearing the used tableware. If any tableware is found broken or damaged, it is reported to the concerned store department and a request is made for its replacement. The table covers and runners are checked and replaced with fresh ones if need be.
The used tableware is handed over to the cleaning and washing staff. The linen is also handed over to the laundry department in the hotel. In case of other F&B Services businesses, the soiled linen can be stored separately and given away to contracted laundry service.
Today, many restaurants use Point-of-Sale (POS) equipment, a computer-based technology to take orders, record them, accept payments, and display or print their receipts. Restaurant servers, bartenders, and cashiers can use POS systems to enter and record food and beverage orders easily.
A POS system in the F&B Services can increase convenience and accuracy in order tracking, and can save time during rush hours. It can smoothly perform the following functions β
Calculating cash due for every order entered for a table.
Recording the method of payment.
Tracking balance cash.
Creating periodic sales reports.
Calculating labor and payroll data.
Recording daily check averages for each worker.
Tracking the number of balance and sold food items.
Recording information of repeat customers.
The guestsβ experience of food and beverage starts when the serving staff brings beautifully garnished food with the appropriate accompaniments on their table. The service staff turns a guiding hand to the guests in suggesting which accompaniment will go well with the main food the guest is interested in having.
There are numerous interesting pairs of foods with their garnishes or accompaniments. Let us see in detail about garnishing, food accompaniments, and some typical food-garnishing paired with accompaniments.
It is the way of decorating the food or beverage so that it is aesthetically appealing for the guests/customers. It works on the plate. Garnishing also harmonizes color, flavor, and taste of the main dish.
Chopped herbs or small twigs of herbs, leafy vegetables, twirls of carrots or tomatoes, swirls of fresh cream, fruit glaze, chopped nuts, seedless berries, and lemon zest or slices are used for garnishing.
Desserts are garnished with dried fruits, fresh fruit zests, glazes, roasted or candied nuts, frostings, chocolate curls, chocolate coated buts, or small pieces of sugar arts.
Drinks like cocktails and mocktails are garnished using fruit pieces and zests, mint leaves, and castor sugar. Milk based drinks are garnished mostly with fruit pieces, cherries, chocolates, or nuts.
The following are some important Dos and Donβts to be understood in food garnishing β
Place it where it seems just perfect.
Contrast color schemes work best for garnishing.
Do not overdo garnishing; this overshadows the main food.
Do not reuse the garnish.
Avoid being too elaborate.
There are dishes that come along with accompaniments. These accompaniments complement the main food and enrich its taste. It provides an aesthetic value to the main dish. The accompanying food or beverage itself can have a garnish of its own. An accompaniment can be inside the main dish or in a separate bowl.
The following are a few different types of accompaniments β
Sauces and Dips
Pickles
Dressings
Chips and Wedges
Salads
Gravies
Beverages such as soft drinks or wines
Breads
For example, grilled Hake fish served with potato chips and Pizza served with garlic bread, cheese dip, and a carbonated beverage.
The following are a few popular food items with their garnishing and accompaniments β
There are no stringent rules for which wine goes well with which cheese but one must observe the following guidelines while pairing wines with cheese β
Select wine and cheese originating from the same region.
Dessert wines accompanying the desserts must be sweeter than the dessert itself.
Cheeses go well with wines of contrast taste.
Lighter chocolates contain more milk based-products and less chocolate. Chocolates with light and elegant tastes are paired best with light-bodied wines. The ones with more bitter taste are paired with intense flavored full-bodied wines.
A critical standardized recipe is one that, βhas been tried, adapted, and retried several times for use by a given food service operation and has been found to yield the same good results under same procedures, equipment, and quantity and quality of ingredients.β
Generally, popular menu items are developed using standard recipes, ingredients, and presentation.
A standardized recipe can bring in the following benefits β
Consistency in food quality.
Consistency in nutrients per unit serving.
Increase in customer satisfaction.
Control on cost of food.
Prediction of accurate yield.
Reduction in food leftover and record keeping.
Increase in the confidence of employees.
A typical standardized recipe is composed of the following description β
Recipe name/title β It is the name that describes the recipe in brief.
Recipe name/title β It is the name that describes the recipe in brief.
Recipe section β It is the section that the recipe should be classified under (grains, starters, desserts, etc.)
Recipe section β It is the section that the recipe should be classified under (grains, starters, desserts, etc.)
Ingredients β Types (fresh/canned/cooked/uncooked/ground, etc.)
Ingredients β Types (fresh/canned/cooked/uncooked/ground, etc.)
Weight and measures of ingredients
Weight and measures of ingredients
Method β This is a set of instructions to prepare a particular recipe. A method includes guidelines for steps such as mixing, selecting pans, and setting the right cooking temperature.
Method β This is a set of instructions to prepare a particular recipe. A method includes guidelines for steps such as mixing, selecting pans, and setting the right cooking temperature.
Time β This includes preparation time, cooking time, and serving time.
Time β This includes preparation time, cooking time, and serving time.
Serving size β It is the portion of food to be served.
Serving size β It is the portion of food to be served.
Critical Control Points (CCP) β They are control measures taken to avoid food safety hazards. Every CCP includes control of time, preparation, and cooking temperature.
Critical Control Points (CCP) β They are control measures taken to avoid food safety hazards. Every CCP includes control of time, preparation, and cooking temperature.
Predicting the total yield for a particular number of customers and calculating weights of ingredients accordingly is important in standardized recipes.
For recipe to be prepared for new lot of customers, the total yield changes. The new yield can be calculated in the following two steps β
Step 1 β Calculate conversion factor as β
Conversion Factor = New Yield / Old Yield
Step 2 β Multiply the measure of each ingredient by the conversion factor to obtain the new yield β
New Yield = Old ingredient quantity x Conversion factor
Beverages play an important role in accompanying food. Beverages also enhance flavor of main dish and help to cleanse the taste buds in between bites, and complement the dish.
Hot beverages such as hot tea or coffee, and hot chocolate are prepared in the kitchen and generally served from the kitchen pantry. Cold beverages such as mocktails and alcoholic beverages such as spirits, liquors, and cocktails come to the guestsβ tables from bars.
A bar is a place where non-alcoholic and alcoholic beverages are served. It is equipped with a back bar with necessary equipment such as bar tools, and glassware to serve the beverages. The customers sit on tall push-down chairs around the counter. The barmen or barmaids commonly known as bartenders prepare drinks and serve them to the customers. There are some typical types of bars β
Public β It is a bar in a public house which is open for public and not exclusive.
Public β It is a bar in a public house which is open for public and not exclusive.
Service Bar β It is for the staff.
Service Bar β It is for the staff.
Portable β They are compact bars easy to set up for off-premise catering.
Portable β They are compact bars easy to set up for off-premise catering.
Mini β It is a private bar located in VIP rooms, suites, or penthouses of the hotel.
Mini β It is a private bar located in VIP rooms, suites, or penthouses of the hotel.
The following tools are necessary to serve beverages from bar β
Bar Linen and Cocktail Napkins β They are used to save work area from any mess while pouring the beverage.
Bar Linen and Cocktail Napkins β They are used to save work area from any mess while pouring the beverage.
Pouring Spouts β They make smooth serving of beverage apportioned equally into the glasses.
Pouring Spouts β They make smooth serving of beverage apportioned equally into the glasses.
Juice Containers β They are useful to save bartending time by keeping most demanded juices handy.
Juice Containers β They are useful to save bartending time by keeping most demanded juices handy.
Cocktail Shaker Tins β They are suitable for mixing the ingredients of cocktails and martinis well.
Cocktail Shaker Tins β They are suitable for mixing the ingredients of cocktails and martinis well.
Short Shaker Tins β They are used to shake small amount of drinks efficiently.
Short Shaker Tins β They are used to shake small amount of drinks efficiently.
Cocktail Strainer β It is used to sieve cocktails before serving.
Cocktail Strainer β It is used to sieve cocktails before serving.
Corkscrew or Wine Opener β They are used to open corks of wine bottles.
Corkscrew or Wine Opener β They are used to open corks of wine bottles.
Bottle Opener β They are used to open caps of bottled beverages.
Bottle Opener β They are used to open caps of bottled beverages.
Jigger β It is an alcohol measuring two-sided cup.
Jigger β It is an alcohol measuring two-sided cup.
Lemon Zester β It is used for cutting lemon zest.
Lemon Zester β It is used for cutting lemon zest.
Bar Spoon β Also called muddler, is used for mixing beverages briefly.
Bar Spoon β Also called muddler, is used for mixing beverages briefly.
Masher β It is used to mash ingredients to help release oils and flavors effectively.
Masher β It is used to mash ingredients to help release oils and flavors effectively.
The Dram Shop Liability in US is the body of law that governs the liability of alcohol stores and the commercial establishments where alcohol is served. This body endeavors to protect the society from the unpleasant outcomes of serving alcohol to minors and intoxicated people.
The legal age of drinking alcohol is different in different countries. The minimum age to purchase and consume alcohol ranges from 16 years to 25 years. In some countries, this age limit varies according to strength of the alcohol, premises of consumption, or whether the young customer is accompanied by an adult.
When the customer looks underage, the beverage serving staff is compelled to ask for the customerβs driving license or any reliable identity card from a well-recognized institution as a proof of age before serving the alcohol.
It is up to the serving staff who has had enough drink as the drunk persons themselves often fail to be composed and know their own state. To keep the account of how much the customers are drinking, the bartenders must use standard measures for pouring drinks.
The bartending staff needs to cut off alcohol service if the customer is on the way of binge drinking and seems not able to handle it. Refusal of alcohol service should be β
Executed professionally by speaking firmly and clearly with the drunk/under-aged customers.
Denied quietly without notifying other customers.
Imparting an out of the world meal experience requires a lot of preparation beforehand. Food and beverage businesses work to bring out the best possible experience for their guests and customers to achieve maximum customer satisfaction. All operations regarding food and beverage service need preparations by anticipating guest arrival at any time during working hours.
Let us see what all basic preparations are required to be done.
It is the activity of preparing the environment in the F&B Services establishment so that the guests and the service staff find it hygienic and pleasant.
To prepare the environment, the staff carries out the following activities β
Opening all windows and doors before working hours to let fresh air and sunlight enter the venue.
Opening all windows and doors before working hours to let fresh air and sunlight enter the venue.
Ensuring menu cards and promotional material are presentable.
Ensuring menu cards and promotional material are presentable.
Removing the furniture that needs servicing and handing it over to the maintenance department or any outsourced agency.
Removing the furniture that needs servicing and handing it over to the maintenance department or any outsourced agency.
Vacuuming carpets if any.
Vacuuming carpets if any.
Switching on all lamps to check the fused ones.
Switching on all lamps to check the fused ones.
It is the activity of putting things in place to make the subsequent F&B Services smooth. The serving staff carries out the following duties β
Removing all soiled linen and replacing them with the fresh ones.
Ensuring that the side board is well-equipped.
Replenishing condiment containers, shakers, and water jugs.
Polishing cutlery and glassware.
Replacing pale flowers with the fresh ones.
It is a piece of furniture with numerous compartments and shelves to keep condiments, water jug or bottles, cutlery, food platters, and linens. Side boards are allocated for every station.
To prepare the side boards, the serving staff must place β
The replenished containers of water, butter, and condiments.
The replenished containers of water, butter, and condiments.
The dinner plates, side plates, glasses, mugs, and fingerbowls in the lower shelves.
The dinner plates, side plates, glasses, mugs, and fingerbowls in the lower shelves.
The linen, napkins, and dolly papers neatly and stalked.
The linen, napkins, and dolly papers neatly and stalked.
The cutlery in the appropriate sections separately according to the type.
The cutlery in the appropriate sections separately according to the type.
The condiments containers and shakers, water jug, butter dish, toothpick holders, straw holders, on the upper shelf or board.
The condiments containers and shakers, water jug, butter dish, toothpick holders, straw holders, on the upper shelf or board.
Ice and water are the preliminary requirements of any food and beverage service establishment. Clean drinkable water is obtained from the water purifiers installed in the service establishment. The purifiers are selected such that they can cater to large number of people per hour.
Crystal clear ice in the shape of large cubes can be prepared in-house if the size of F&B establishment is large enough to install the required equipment. The ice can also be purchased from an outsourced ice-making business and stored in the freezers.
When the guests are seated, they are first served water at adequate temperature according to the season.
Table setup plays an important role in contributing to the appearance of the table.
Each table cover needs space of 24 to 30 inches wide.
Crockery and cutlery must be placed 2 inches away from the edge of the table.
Knives are placed on the right of the dinner plate whereas forks are placed on the left.
Butter knife is placed on the side plate.
The cutting edge of the knives must be towards the plate.
Table napkin must be neatly folded and placed on the side plate.
This type of table setup is required for formal events like corporate lunch or dinner, or a wedding party. The formal dining contains multiple courses and second helpings are not offered.
This table setup looks as follows β
This table setup is required for informal events like holiday parties and family gatherings. Casual dining can contain multiple courses and service staff offers or serves second rounds of helping when a guest requests for it. This table setup appears as follows β
This set up is required for catering to large groups of people. Buffet table setting can be done in numerous ways depending upon the size and shape of the place, the menu, and the number of guests.
The food items are placed in a sequence from lightest to heaviest, starters to desserts, or coolest to warmest.
Cutlery is placed on the guest tables.
Glasses, cups, and saucers are placed on a separate table to avoid congestion.
Table decoration pieces are placed such that they do not interfere with the food items.
Plates are stacked not more than 15 plates per stack.
Paper napkins are placed between the plates.
The condiments are kept according to the theme of the F&B service. For example, if the establishment is serving Italian food, the staff needs to prepare shakers of dried herbs, salt, and pepper flakes. In European restaurants, they typically keep salt, sugar, and pepper as basic condiments.
When the guests leave the tables, the serving staff needs to check the condiment containers and replenish them if required.
Today, there are large varieties of napkins available in different colors and materials. Paper napkins are used majorly for informal dining whereas for formal dining, linen napkins are preferred.
Napkin can be folded in a number of attractive ways. They can be shaped as a flower, a character, or some object. A well-folded and well-placed napkin on the plate grabs the attention of the guests.
Presentation of a food or beverage is equally important as its recipe as the other senses are stimulated through sight and aroma. A well-prepared dish is complete only when it is presented with beautiful garnish in an appropriate food container or platter. The serving staff must follow the basic guidelines for food presentation β
It must be presented at the required temperature.
It must be presented at the required temperature.
It must be presented according to the serving size.
It must be presented according to the serving size.
It must be presented in appropriate hollowware of suitable size.
It must be presented in appropriate hollowware of suitable size.
It is also recommended to serve food with the right garnish that adds to the catchiness of the dish. The garnish in contrast color is quite appealing.
It is also recommended to serve food with the right garnish that adds to the catchiness of the dish. The garnish in contrast color is quite appealing.
The garnish or accompaniment should not overshadow the main food.
The garnish or accompaniment should not overshadow the main food.
The cook needs to be creative at presenting the dish so well that the final result comes out as a treat for not only the taste buds but also for the eyes.
Beverage presentation gains a lot of importance in todayβs world. Beverages taste good if they are presented at the temperature at which they are meant to have. Right from selecting the appropriate service glassware, creating various pleasant color schemes of the ingredients, and serving the beverage with creative ideas pays.
For example, the coconut water from a tender coconut can be served in the neatly cut and clean tender coconut itself from which it is taken out. Also, mocktails or cocktails can be presented with straws and slices of fruits in different shapes and colors.
When few tasks in an organization are required to be conducted repetitively, it is a good idea to generate a set of Standard Operating Procedures (SOPs). These make the tasks in hand easy and effective, and save a great deal of time and effort. SOPs also help to train the staff and avoid silly errors.
Let us understand a few important SOPs set in F&B service establishments β
The procedure is as follows β
Check the table linen for cleanliness and spread it on the table neatly to remove wrinkles.
Check the table linen for cleanliness and spread it on the table neatly to remove wrinkles.
Replace the table soiled linen if required.
Replace the table soiled linen if required.
Ensure the dining type before the setting table layout: Formal or Informal.
Ensure the dining type before the setting table layout: Formal or Informal.
For a formal table setup, place the tableware as follows β
Place the dinner plate one inch from the table edge near the chair.
Place the dinner plate one inch from the table edge near the chair.
Place the salad plate above the dinner plate.
Place the salad plate above the dinner plate.
Place the forks on left of the dinner plate. Arrange the forks according to their size with the largest fork nearest to the dinner plate.
Place the forks on left of the dinner plate. Arrange the forks according to their size with the largest fork nearest to the dinner plate.
Place the spoons and knives on the right side of the dinner plate according to their size with the largest spoon and knife near the plate.
Place the spoons and knives on the right side of the dinner plate according to their size with the largest spoon and knife near the plate.
Place the dessert spoon and fork above the plate horizontally.
Place the dessert spoon and fork above the plate horizontally.
Place the quarter plate on the left side of the dinner plate.
Place the quarter plate on the left side of the dinner plate.
Place the water and the wine glasses on the top-right corner of the dinner plate.
Place the water and the wine glasses on the top-right corner of the dinner plate.
Shape the clean linen aesthetically and place it on the extreme left.
Shape the clean linen aesthetically and place it on the extreme left.
For an informal table setup, place the tableware as follows β
Place the dinner plate one inch inside the table edge near the chair.
Place the forks on the left side in descending order of their size with the largest fork to be closest to the dinner plate.
Place dinner spoon and knife on the dinner plateβs right side.
Place water and the wine glasses on the top-right side of the dinner plate.
Shape the clean linen aesthetically and place it on the extreme left on the top of the dinner plate.
The staff members who handle the telephone calls must be thoroughly aware of the work system. The procedure for handling calls is as follows β
Always answer the phone call promptly, within three rings. If it takes time to answer, apologize to the customer.
Always answer the phone call promptly, within three rings. If it takes time to answer, apologize to the customer.
Speak with the caller attentively by avoiding any distractions around.
Speak with the caller attentively by avoiding any distractions around.
Always inform the caller before transferring his call and putting him/her on hold.
Always inform the caller before transferring his call and putting him/her on hold.
Always talk politely and respectfully to the customers by addressing women as βMadamβ and men as βSirβ.
Always talk politely and respectfully to the customers by addressing women as βMadamβ and men as βSirβ.
Ensure that you solve all the customer queries before terminating the telephonic conversation.
Ensure that you solve all the customer queries before terminating the telephonic conversation.
Speak clearly with a cooperative tone; do not speak loudly.
Speak clearly with a cooperative tone; do not speak loudly.
Avoid domain jargons and informal words such as βYupβ, βhang-onβ or yeah.β Instead, use formal words such as βabsolutelyβ, βplease waitβ, βYesβ, etc.
Avoid domain jargons and informal words such as βYupβ, βhang-onβ or yeah.β Instead, use formal words such as βabsolutelyβ, βplease waitβ, βYesβ, etc.
Always end the phone call by saying, βThank you for calling (sir/madam)!β.
Always end the phone call by saying, βThank you for calling (sir/madam)!β.
The orders for table reservation or food delivery can be taken on phone. Direct service orders are placed and taken to the guest table.
While taking orders on phone, the visual channel of communication is absent. Hence the staff needs to listen to the caller attentively while taking order on the phone.
Answer the customerβs call immediately and take the communication further cordially by saying, βGood (morning/afternoon/evening), I am (own name); How can I help you?β
Answer the customerβs call immediately and take the communication further cordially by saying, βGood (morning/afternoon/evening), I am (own name); How can I help you?β
Pay a complete ear to the customerβs requirement of food, beverage, table reservation, or any specific requirement.
Pay a complete ear to the customerβs requirement of food, beverage, table reservation, or any specific requirement.
Note down the order details on a notepad.
Note down the order details on a notepad.
Inform the customer about time estimation of delivery if it is home delivery order. If it is table reservation, confirm the timing of customerβs arrival and the total number of persons to the customer.
Inform the customer about time estimation of delivery if it is home delivery order. If it is table reservation, confirm the timing of customerβs arrival and the total number of persons to the customer.
Repeat the order to the customer and take his confirmation.
Repeat the order to the customer and take his confirmation.
Ask for the address or confirm the address and contact number if it is already in the database.
Ask for the address or confirm the address and contact number if it is already in the database.
End the conversation by greeting the customer and assuring him the best service.
End the conversation by greeting the customer and assuring him the best service.
Hand over the order to the kitchen staff. Inform the delivery staff member in case of home delivery. Inform the service staff members to prepare a table for the given number of persons and the occasion in case of table reservation.
Hand over the order to the kitchen staff. Inform the delivery staff member in case of home delivery. Inform the service staff members to prepare a table for the given number of persons and the occasion in case of table reservation.
This takes place when the guests are already seated.
Ensure that the guests are seated comfortably.
Ensure that the guests are seated comfortably.
At the start, offer them welcome drink if any or chilled water.
At the start, offer them welcome drink if any or chilled water.
Offer them food and wine menus.
Offer them food and wine menus.
Greet the guests and ask them courteously, βWhat would you like to have, (Sir/Madam)?β
Greet the guests and ask them courteously, βWhat would you like to have, (Sir/Madam)?β
Note down the order carefully.
Note down the order carefully.
Confirm which variant of the food or beverage they wish to have; if there are multiple variants of the same food item. Help the guests by suggesting the beverage or side dish that goes well with the main dish if required.
Confirm which variant of the food or beverage they wish to have; if there are multiple variants of the same food item. Help the guests by suggesting the beverage or side dish that goes well with the main dish if required.
Repeat the items ordered with their respective quantities.
Repeat the items ordered with their respective quantities.
Inform the guest about expected time of the order arrival.
Inform the guest about expected time of the order arrival.
Leave the guest table and send the order to the kitchen.
Leave the guest table and send the order to the kitchen.
Conversation with the guests is the backbone of any service-providing business. The guidelines for conversing with the guests are β
Keep upright posture and smiling face.
Let them know that you are enthusiastic and eager to serve them.
Be respectful to elderly guests, friendly with the same-age guests, and jovial with the children.
Keep the voice of speech audible and clear.
Apologize if some food item or beverage has run out of the stock.
While the guests are having their meals, make a brief round at the table to observe if everything is fine.
The service staff actually must remain prepared to handle any unforeseen circumstances which include β
Handling spill-over of food or drink while serving.
Dealing with highly drunk gusts.
Dealing with guests who are physically challenged or the ones who show difficulty in communicating.
Dealing with hyper-active toddler guests.
Dealing with unwelcomed situations such as large fire hazards.
The service staff needs to be careful while carrying the trays in their hands and going around the dining area. They need to follow the given rules β
Do not overload the tray.
Place the items on the tray such that the load is evenly distributed.
Alter the position of drinks or food promptly every time something is removed from the tray.
Carry one tray at a time.
Carry the tray with a firm support of the palm with fingers wide open.
Hold the tray on the left palm slightly above the shoulder.
Hold it little away from neck and mouth for hygienic reasons.
Following are some meticulous ways while serving food or beverages.
Bring food to the guest table if it is not a buffet service.
Bring food to the guest table if it is not a buffet service.
Present the food from guestβs left side in case of formal dining.
Present the food from guestβs left side in case of formal dining.
Prepare the food plates from the kitchen and place them on the guest table in case of casual dining.
Prepare the food plates from the kitchen and place them on the guest table in case of casual dining.
Ask the guests if they need help to serve the food.
Ask the guests if they need help to serve the food.
Serve one food item at a time.
Serve one food item at a time.
Serve the eldest lady guest of the group first unless the lady herself is a host. After all ladies are served, serve the men guests starting from the oldest.
Serve the eldest lady guest of the group first unless the lady herself is a host. After all ladies are served, serve the men guests starting from the oldest.
Always present a dish with its respective serving spoon.
Always present a dish with its respective serving spoon.
Tilt the service bowl a little to bring east in serving and take it away after serving.
Tilt the service bowl a little to bring east in serving and take it away after serving.
Always present the ordered drink in an appropriate glass by informing its name to the guest.
Always present the ordered drink in an appropriate glass by informing its name to the guest.
When same wine is offered in consecutive courses, serve it in the same wine glass. If wine is changed then replace the glass with fresh one.
When same wine is offered in consecutive courses, serve it in the same wine glass. If wine is changed then replace the glass with fresh one.
Always tilt the glass while pouring drinks or fuzzy drinks so that its head and aroma is held.
Always tilt the glass while pouring drinks or fuzzy drinks so that its head and aroma is held.
Do not bend over served plates while serving other plates across the table. Move as near as possible to the plate in which you serve.
Do not bend over served plates while serving other plates across the table. Move as near as possible to the plate in which you serve.
It is important to clear the table between two dining sessions by following procedure β
Clear the table first when the guests finish their main course.
Clear the table first when the guests finish their main course.
Clear it for the second time just before the guests leave the table.
Clear it for the second time just before the guests leave the table.
While clearing, first remove all the pieces of flatware and chinaware except table linen and center piece. Let the dessert flatware remain in case of first clearing.
While clearing, first remove all the pieces of flatware and chinaware except table linen and center piece. Let the dessert flatware remain in case of first clearing.
Let wine glasses be on the table even after the main course.
Let wine glasses be on the table even after the main course.
While clearing, pickup one plate at a time and place on the tray carefully. In case of formal dining, replace the removed plate by a fresh one so that table cover of the guest is never empty.
While clearing, pickup one plate at a time and place on the tray carefully. In case of formal dining, replace the removed plate by a fresh one so that table cover of the guest is never empty.
Do not overload the tray with pile of used plates; make extra rounds to the table if required.
Do not overload the tray with pile of used plates; make extra rounds to the table if required.
Before presenting bill to the guest, make sure the guests donβt want to order anything more. There are many policies of setting guest bills in the F&B establishments. Some prefer the guests pay cash at the cash collection counter. In such case, the serving staff must accompany the guest to the payment counter to ensure only the right amount is charged to the guest.
Some F&B Services businesses prefer to bring bills (or checks) to the guestsβ tables and get them settled. While presenting and settling the bill, follow the given steps β
Ask politely, βShould I bring you the bill, Sir/Madam?β
Ask politely, βShould I bring you the bill, Sir/Madam?β
Once the guest confirms, ask how he/she would like to pay. It should be either credit card, debit card, or cash.
Once the guest confirms, ask how he/she would like to pay. It should be either credit card, debit card, or cash.
Go to the payment counter to prepare the bill.
Go to the payment counter to prepare the bill.
Cashier prepares the bill according to the table number told by waiter.
Cashier prepares the bill according to the table number told by waiter.
Present the bill in a small closed folder to the guest from his/her left side.
Present the bill in a small closed folder to the guest from his/her left side.
Stand beside the guest till the guest examines the bill.
Stand beside the guest till the guest examines the bill.
If the guest pays by cash, take it and deposit the amount at the payment counter. If the guest wishes to pay by card, take the guestβs signature on the bill, and take the card and bill to the payment counter. If the establishment has facility of mobile card-payment service, take the transaction device to the guest table.
If the guest pays by cash, take it and deposit the amount at the payment counter. If the guest wishes to pay by card, take the guestβs signature on the bill, and take the card and bill to the payment counter. If the establishment has facility of mobile card-payment service, take the transaction device to the guest table.
The cashier returns the balance amount if paid by cash. If the payment is by card, he ensures the cardβs expiry date and accepts the payment.
The cashier returns the balance amount if paid by cash. If the payment is by card, he ensures the cardβs expiry date and accepts the payment.
Bring back the copy of printed bill and any change or the card to the guest.
Bring back the copy of printed bill and any change or the card to the guest.
If the guest insists to take the tip, mention your thankfulness with smile.
If the guest insists to take the tip, mention your thankfulness with smile.
When the guest stands up to leave the table, pull the chair backwards by informing him/her to help to get out of the chair gracefully.
When the guest stands up to leave the table, pull the chair backwards by informing him/her to help to get out of the chair gracefully.
Thank the guest for his/her visit and invite him/her to visit again.
Thank the guest for his/her visit and invite him/her to visit again.
It is an extremely important responsibility of every F&B Services to serve their guests hygienic food and beverages. The guests keep faith in F&B Services businesses that they will provide them the best food and serve it the best careful manner. The F&B services are bound to provide safe-to-eat food that is prepared by following hygiene and sanitation practices.
F&B services have direct access to guestsβ health through food and beverages. The working staff handles every food and drink item closely that the guest is going to eat. Hence, if these services do not follow proper practices of hygiene and sanitation, the guests might get foodborne diseases such as food poisoning, nausea, diarrhea, or vomiting.
Food contamination can occur through unwashed vegetables, uncooked meat, soft cheeses, and unpasteurized milk. If the food preparation and serving equipment used in F&B Services are not clean, then they become primary source of food contamination.
There are three main sources of food contamination β
Physical β This is accidental in nature and is caused by employee carelessness. The major culprits are air, dust, smoke, and dirt. To prevent this, food must be properly covered and stored.
Physical β This is accidental in nature and is caused by employee carelessness. The major culprits are air, dust, smoke, and dirt. To prevent this, food must be properly covered and stored.
Biological β This contamination is caused by pathogens and microorganisms such as bacteria, molds, parasites, and fungi.
Biological β This contamination is caused by pathogens and microorganisms such as bacteria, molds, parasites, and fungi.
Chemical β It is accidental contamination of food caused by cleaning solvents, pest control sprays, or other chemicals used in entire food production chain. This food contamination occurs when utensils or other tableware are not wiped dry after washing them using cleaning liquids. It also takes place when the food is not stored properly when pest control chemicals are sprayed.
Chemical β It is accidental contamination of food caused by cleaning solvents, pest control sprays, or other chemicals used in entire food production chain. This food contamination occurs when utensils or other tableware are not wiped dry after washing them using cleaning liquids. It also takes place when the food is not stored properly when pest control chemicals are sprayed.
Personal hygiene is essential when one handles the food or beverage that the other is going to consume. The service staff must follow the given basic principles β
It is said that the hygiene starts from home. Perform your daily cleanliness regime without any excuses.
It is said that the hygiene starts from home. Perform your daily cleanliness regime without any excuses.
Wash hands and arms immediately β
When you come from toilet.
When you sneeze, blow nose, yawn, or cough covering your mouth with hands.
After eating food, tobacco, or touching animals.
After you touch hair, scalp, skin, or any body-opening.
Wash hands and arms immediately β
When you come from toilet.
When you come from toilet.
When you sneeze, blow nose, yawn, or cough covering your mouth with hands.
When you sneeze, blow nose, yawn, or cough covering your mouth with hands.
After eating food, tobacco, or touching animals.
After eating food, tobacco, or touching animals.
After you touch hair, scalp, skin, or any body-opening.
After you touch hair, scalp, skin, or any body-opening.
Wash hands with mild cleansing soap and warm water; not merely with running water.
Wash hands with mild cleansing soap and warm water; not merely with running water.
Wipe sweat often.
Wipe sweat often.
Do not smoke or eat tobacco while working.
Do not smoke or eat tobacco while working.
Cover cuts, burns, or wounds on the skin.
Cover cuts, burns, or wounds on the skin.
Keep hair and nails trimmed.
Keep hair and nails trimmed.
Try using hand gloves as much as possible. Kitchen staff must use toque.
Try using hand gloves as much as possible. Kitchen staff must use toque.
Do not work when facing cold, cough, or any other contagious diseases. Inform your superior staff if you are not well.
Do not work when facing cold, cough, or any other contagious diseases. Inform your superior staff if you are not well.
Do not touch ready-to-eat food directly. Always use gloves, serving tongs deli papers, or forks to handle such food.
Do not touch ready-to-eat food directly. Always use gloves, serving tongs deli papers, or forks to handle such food.
Do whatever required to let not your skin, body fluids, or any clothes you are wearing to come into contact with food or food containers.
Do whatever required to let not your skin, body fluids, or any clothes you are wearing to come into contact with food or food containers.
Ensure a clean uniform.
Ensure a clean uniform.
Do not wear loose jewelry. Avoid wrist jewelry.
Do not wear loose jewelry. Avoid wrist jewelry.
Any food business must be concerned about β
Training all food handling and service staff with a detailed knowledge of food and equipment hygiene and safety.
Training all food handling and service staff with a detailed knowledge of food and equipment hygiene and safety.
Ensuring food handlers and servers not to handle food in case of contamination possibility.
Ensuring food handlers and servers not to handle food in case of contamination possibility.
Supplying hand-washing facilities with soap, running hot water, and paper towels for its staff.
Supplying hand-washing facilities with soap, running hot water, and paper towels for its staff.
Every F&B Services business must also be concerned about food safety and adhere to safety of food and beverage it serves. It must ensure β
Marking Date on Food β The perishable ready-to-eat food refrigerated for more than 24 hours must be clearly marked at the time of preparation to indicate the date by which the food should be consumed.
Marking Date on Food β The perishable ready-to-eat food refrigerated for more than 24 hours must be clearly marked at the time of preparation to indicate the date by which the food should be consumed.
Storing of Food β Hot and cold foods and beverages need to be stored at the right temperature. The food temperature measuring devices must be accurate.
Storing of Food β Hot and cold foods and beverages need to be stored at the right temperature. The food temperature measuring devices must be accurate.
Cleaning Equipment β The area and facilities allocated for cleaning food preparation and service equipment must be large enough to immerse the utensils and sanitize them.
Cleaning Equipment β The area and facilities allocated for cleaning food preparation and service equipment must be large enough to immerse the utensils and sanitize them.
Limiting Cross-Contamination β Storing raw food such as raw meat or vegetables from cooked food is essential to avoid cross-contamination of the food.
Limiting Cross-Contamination β Storing raw food such as raw meat or vegetables from cooked food is essential to avoid cross-contamination of the food.
Employing FSS β The F&B Services businesses must employee at least one Food Safety Supervisor depending upon the business size.
Employing FSS β The F&B Services businesses must employee at least one Food Safety Supervisor depending upon the business size.
Hygiene and safety of food starts right from selecting raw material carefully, preparing food with health and safety cautiousness, and serving it in the clean environment.
The service staff must β
Attend duty in clean and tidy uniform.
Wear less jewelry while working. This avoids entangling articles and calling for trouble.
Be aware of the equipment and their appropriate application.
Be careful of handling hot food and beverages.
Clear spillages on the floor immediately.
Never run in the workspace.
18 Lectures
2 hours
Manish Gupta
185 Lectures
46.5 hours
Nikhil Agarwal
10 Lectures
34 mins
Faiq Ismayilov
7 Lectures
52 mins
Dr. Harris
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2676,
"s": 2304,
"text": "Food and beverage services sector contributes a great deal to the profits in hospitality industry. With the increase in importance of business meetings, a range of personal and social events, a large number of customers visit catering establishments frequently. The food and beverage professionals tirelessly work to intensify customersβ experience through their service."
},
{
"code": null,
"e": 2879,
"s": 2676,
"text": "The F&B Services providing businesses deliver food and beverages to their customers at a particular location (on-premise) such as hotel, restaurant, or at the customerβs intended premises (off-premise)."
},
{
"code": null,
"e": 3021,
"s": 2879,
"text": "Food and Beverage Services can be broadly defined as the process of preparing, presenting and serving of food and beverages to the customers."
},
{
"code": null,
"e": 3070,
"s": 3021,
"text": "F&B Services can be of the following two types β"
},
{
"code": null,
"e": 3317,
"s": 3070,
"text": "On Premise β Food is delivered where it is prepared. The customer visits the premise to avail the food service. The premises are kept well-equipped and well-finished to attract customers to avail F&B service.\nFor example, restaurants, pubs, etc.\n"
},
{
"code": null,
"e": 3526,
"s": 3317,
"text": "On Premise β Food is delivered where it is prepared. The customer visits the premise to avail the food service. The premises are kept well-equipped and well-finished to attract customers to avail F&B service."
},
{
"code": null,
"e": 3563,
"s": 3526,
"text": "For example, restaurants, pubs, etc."
},
{
"code": null,
"e": 3827,
"s": 3563,
"text": "Off Premise or Outdoor Catering β This kind of service includes partial cooking, preparation, and service at customerβs premises. It is provided away from the F&B Services providerβs base on the occasion of major events which call for a large number of customers."
},
{
"code": null,
"e": 4091,
"s": 3827,
"text": "Off Premise or Outdoor Catering β This kind of service includes partial cooking, preparation, and service at customerβs premises. It is provided away from the F&B Services providerβs base on the occasion of major events which call for a large number of customers."
},
{
"code": null,
"e": 4146,
"s": 4091,
"text": "There are two broad types of F&B Services operations β"
},
{
"code": null,
"e": 4345,
"s": 4146,
"text": "Commercial β In this case, F&B Services is the primary business. The most known commercial catering establishments are β hotels, all kinds of restaurants, lounges, cafeterias, pubs, clubs, and bars."
},
{
"code": null,
"e": 4544,
"s": 4345,
"text": "Commercial β In this case, F&B Services is the primary business. The most known commercial catering establishments are β hotels, all kinds of restaurants, lounges, cafeterias, pubs, clubs, and bars."
},
{
"code": null,
"e": 4875,
"s": 4544,
"text": "Non-Commercial β Non-commercial operations are secondary businesses in alliance with the main business. These F&B services mainly cater to their consumers with limited choice of food and beverages. These establishments often run under contracts. For example, food and beverage services provided at hospitals, hostels, and prisons."
},
{
"code": null,
"e": 5206,
"s": 4875,
"text": "Non-Commercial β Non-commercial operations are secondary businesses in alliance with the main business. These F&B services mainly cater to their consumers with limited choice of food and beverages. These establishments often run under contracts. For example, food and beverage services provided at hospitals, hostels, and prisons."
},
{
"code": null,
"e": 5346,
"s": 5206,
"text": "In this tutorial, we mainly consider commercial food and beverage service sector. Let us first understand some common forms of F&B service."
},
{
"code": null,
"e": 5557,
"s": 5346,
"text": "Catering is the business of providing foods and beverage service to the people at a remote location. It is a part of food and beverage service sector. For example, arranging food services at a wedding location."
},
{
"code": null,
"e": 5797,
"s": 5557,
"text": "These are the fast food outlets called Quick Service Restaurants where the food is prepared, purchased, and generally consumed quickly. They are run with convenience as a main factor. Branded outlets such as McDonalds and Nandoβs are QSRs."
},
{
"code": null,
"e": 6062,
"s": 5797,
"text": "They are fine dining, family, specialty, ethnic, or theme restaurants called Full Service Restaurants where the food and beverage menu is wide and the customerβs expectations are high. They are operated with customer satisfaction and experience as the key factors."
},
{
"code": null,
"e": 6212,
"s": 6062,
"text": "Food and Beverage Services come only after preparing what is to be served. Most food and beverage service businesses operate in the following cycle β"
},
{
"code": null,
"e": 6342,
"s": 6212,
"text": "The upper half depicts food preparation related functions, whereas the lower half depicts food and beverage service to customers."
},
{
"code": null,
"e": 6516,
"s": 6342,
"text": "The food and beverage service is looked as a means of achieving satisfaction and making yourself feel comfortable in todayβs world. The main objectives of this service are β"
},
{
"code": null,
"e": 6775,
"s": 6516,
"text": "To satisfy the following needs β\n\nPhysiological β The need to taste different varieties of food.\nEconomical β The need to get F&B Services at the invested cost.\nSocial β The need to find friendly atmosphere.\nPsychological β The need to elevate self-esteem.\n\n"
},
{
"code": null,
"e": 6808,
"s": 6775,
"text": "To satisfy the following needs β"
},
{
"code": null,
"e": 6871,
"s": 6808,
"text": "Physiological β The need to taste different varieties of food."
},
{
"code": null,
"e": 6934,
"s": 6871,
"text": "Physiological β The need to taste different varieties of food."
},
{
"code": null,
"e": 6998,
"s": 6934,
"text": "Economical β The need to get F&B Services at the invested cost."
},
{
"code": null,
"e": 7062,
"s": 6998,
"text": "Economical β The need to get F&B Services at the invested cost."
},
{
"code": null,
"e": 7109,
"s": 7062,
"text": "Social β The need to find friendly atmosphere."
},
{
"code": null,
"e": 7156,
"s": 7109,
"text": "Social β The need to find friendly atmosphere."
},
{
"code": null,
"e": 7205,
"s": 7156,
"text": "Psychological β The need to elevate self-esteem."
},
{
"code": null,
"e": 7254,
"s": 7205,
"text": "Psychological β The need to elevate self-esteem."
},
{
"code": null,
"e": 7298,
"s": 7254,
"text": "To provide high quality food and beverages."
},
{
"code": null,
"e": 7342,
"s": 7298,
"text": "To provide high quality food and beverages."
},
{
"code": null,
"e": 7388,
"s": 7342,
"text": "To provide friendly and welcoming atmosphere."
},
{
"code": null,
"e": 7434,
"s": 7388,
"text": "To provide friendly and welcoming atmosphere."
},
{
"code": null,
"e": 7492,
"s": 7434,
"text": "To provide professional, hygienic, and attentive service."
},
{
"code": null,
"e": 7550,
"s": 7492,
"text": "To provide professional, hygienic, and attentive service."
},
{
"code": null,
"e": 7577,
"s": 7550,
"text": "To impart value for money."
},
{
"code": null,
"e": 7604,
"s": 7577,
"text": "To impart value for money."
},
{
"code": null,
"e": 7663,
"s": 7604,
"text": "To retain the existing customers and to bring in new ones."
},
{
"code": null,
"e": 7722,
"s": 7663,
"text": "To retain the existing customers and to bring in new ones."
},
{
"code": null,
"e": 7780,
"s": 7722,
"text": "The following terms are frequently used in F&B services β"
},
{
"code": null,
"e": 7789,
"s": 7780,
"text": "Back bar"
},
{
"code": null,
"e": 7842,
"s": 7789,
"text": "A range of shelves displaying glassware and bottles."
},
{
"code": null,
"e": 7850,
"s": 7842,
"text": "Banquet"
},
{
"code": null,
"e": 7960,
"s": 7850,
"text": "A sit-down meal served on the occasion of a formal or informal event such as a wedding party or a conference."
},
{
"code": null,
"e": 7975,
"s": 7960,
"text": "Binge Drinking"
},
{
"code": null,
"e": 8014,
"s": 7975,
"text": "Drinking too much in a single session."
},
{
"code": null,
"e": 8021,
"s": 8014,
"text": "Buffet"
},
{
"code": null,
"e": 8143,
"s": 8021,
"text": "A dining system where the guests serve themselves. Popular with a large number of guests and a small number of workforce."
},
{
"code": null,
"e": 8152,
"s": 8143,
"text": "Cocktail"
},
{
"code": null,
"e": 8192,
"s": 8152,
"text": "Any mixed drink prepared using alcohol."
},
{
"code": null,
"e": 8203,
"s": 8192,
"text": "Condiments"
},
{
"code": null,
"e": 8298,
"s": 8203,
"text": "Spices, sauce or other food preparations used to enhance the flavor or to complement the dish."
},
{
"code": null,
"e": 8307,
"s": 8298,
"text": "Crockery"
},
{
"code": null,
"e": 8413,
"s": 8307,
"text": "Plates, dishes, cups, and other similar items, especially ones made of glass, earthenware, or china clay."
},
{
"code": null,
"e": 8433,
"s": 8413,
"text": "Cross-Contamination"
},
{
"code": null,
"e": 8552,
"s": 8433,
"text": "It is a process of unintentional transfer microorganisms from one substance or object to another, with harmful effect."
},
{
"code": null,
"e": 8561,
"s": 8552,
"text": "Croutons"
},
{
"code": null,
"e": 8583,
"s": 8561,
"text": "Crispy cubes of bread"
},
{
"code": null,
"e": 8591,
"s": 8583,
"text": "Cutlery"
},
{
"code": null,
"e": 8650,
"s": 8591,
"text": "Knives, forks, and spoons used for eating or serving food."
},
{
"code": null,
"e": 8655,
"s": 8650,
"text": "Deli"
},
{
"code": null,
"e": 8696,
"s": 8655,
"text": "A store that sells pre-cooked fine food."
},
{
"code": null,
"e": 8706,
"s": 8696,
"text": "Dram Shop"
},
{
"code": null,
"e": 8739,
"s": 8706,
"text": "American term for βAlcohol Barβ."
},
{
"code": null,
"e": 8756,
"s": 8739,
"text": "Gueridon Trolley"
},
{
"code": null,
"e": 8879,
"s": 8756,
"text": "A trolley used in F&B Services business on which the food can be cooked, finished, or presented to the guest at the table."
},
{
"code": null,
"e": 8902,
"s": 8879,
"text": "High Ball (Long Drink)"
},
{
"code": null,
"e": 9000,
"s": 8902,
"text": "Alcoholic beverage mixed with a large volume of soft drink and served in a tall glass with straw."
},
{
"code": null,
"e": 9009,
"s": 9000,
"text": "Mocktail"
},
{
"code": null,
"e": 9081,
"s": 9009,
"text": "A non-alcoholic drink prepared using fruit juices or other soft drinks."
},
{
"code": null,
"e": 9090,
"s": 9081,
"text": "Pathogen"
},
{
"code": null,
"e": 9148,
"s": 9090,
"text": "It is a biological agent that causes disease to its host."
},
{
"code": null,
"e": 9156,
"s": 9148,
"text": "Platter"
},
{
"code": null,
"e": 9201,
"s": 9156,
"text": "A large flat dish or plate for serving food."
},
{
"code": null,
"e": 9205,
"s": 9201,
"text": "Pub"
},
{
"code": null,
"e": 9291,
"s": 9205,
"text": "British name for βPublic Houseβ, an establishment licensed to serve alcoholic drinks."
},
{
"code": null,
"e": 9315,
"s": 9291,
"text": "Shot Ball (Short Drink)"
},
{
"code": null,
"e": 9379,
"s": 9315,
"text": "Alcoholic drink consumed in a gulp. It is served in shot glass."
},
{
"code": null,
"e": 9384,
"s": 9379,
"text": "Situ"
},
{
"code": null,
"e": 9402,
"s": 9384,
"text": "On site, locally."
},
{
"code": null,
"e": 9416,
"s": 9402,
"text": "Spot Checking"
},
{
"code": null,
"e": 9522,
"s": 9416,
"text": "Regular surprise checking conducted to review standardized recipes and food products to maintain quality."
},
{
"code": null,
"e": 9530,
"s": 9522,
"text": "Station"
},
{
"code": null,
"e": 9602,
"s": 9530,
"text": "A set of tables allocated to waiters in the F&B Services establishment."
},
{
"code": null,
"e": 9614,
"s": 9602,
"text": "Table Cover"
},
{
"code": null,
"e": 9694,
"s": 9614,
"text": "It is the area on the table for plates, glasses, and cutlery for single person."
},
{
"code": null,
"e": 9700,
"s": 9694,
"text": "Tines"
},
{
"code": null,
"e": 9740,
"s": 9700,
"text": "Parallel or branching spikes of a fork."
},
{
"code": null,
"e": 9746,
"s": 9740,
"text": "Toque"
},
{
"code": null,
"e": 9843,
"s": 9746,
"text": "Cooks cap with multiple folds represents the many different ways a chef knows to prepare a dish."
},
{
"code": null,
"e": 10273,
"s": 9843,
"text": "The food and beverage service is part of the service-oriented hospitality sector. It can be a part of a large hotel or tourism business and it can also be run as an independent business. The members of the F&B Services team are required to perform a wide range of tasks which include preparation for service, greeting the guests, taking their orders, settling the bills, and performing various other tasks after the guests leave."
},
{
"code": null,
"e": 10375,
"s": 10273,
"text": "Let us see the F&B services in hotels, structure of F&B department and ancillary services in a hotel."
},
{
"code": null,
"e": 10465,
"s": 10375,
"text": "Most of the star-ranked hotels offer multiple F&B services in their hotels. They can be β"
},
{
"code": null,
"e": 10476,
"s": 10465,
"text": "Restaurant"
},
{
"code": null,
"e": 10483,
"s": 10476,
"text": "Lounge"
},
{
"code": null,
"e": 10495,
"s": 10483,
"text": "Coffee Shop"
},
{
"code": null,
"e": 10508,
"s": 10495,
"text": "Room Service"
},
{
"code": null,
"e": 10540,
"s": 10508,
"text": "Poolside Barbecue/Grill Service"
},
{
"code": null,
"e": 10556,
"s": 10540,
"text": "Banquet Service"
},
{
"code": null,
"e": 10560,
"s": 10556,
"text": "Bar"
},
{
"code": null,
"e": 10585,
"s": 10560,
"text": "Outside Catering Service"
},
{
"code": null,
"e": 10733,
"s": 10585,
"text": "The F&B Services personnel are responsible to create the exact experience the guests wish for. The department consists of the following positions β"
},
{
"code": null,
"e": 10790,
"s": 10733,
"text": "The Food & Beverage Service Manager is responsible for β"
},
{
"code": null,
"e": 10889,
"s": 10790,
"text": "Ensuring profit margins are achieved in each financial period from each department of F&B service."
},
{
"code": null,
"e": 10955,
"s": 10889,
"text": "Planning menus for various service areas in liaison with kitchen."
},
{
"code": null,
"e": 11018,
"s": 10955,
"text": "Purchasing material and equipment for F&B Services department."
},
{
"code": null,
"e": 11196,
"s": 11018,
"text": "The Assistant Food & Beverage Service Manager is aware of and is tuned to all the work the F&B Services Manager performs and carries out the same in the absence of his superior."
},
{
"code": null,
"e": 11322,
"s": 11196,
"text": "The Restaurant Manager looks after the overall functioning of a restaurant. The responsibility of this staff member include β"
},
{
"code": null,
"e": 11364,
"s": 11322,
"text": "Managing the functions in the dining room"
},
{
"code": null,
"e": 11382,
"s": 11364,
"text": "Ordering material"
},
{
"code": null,
"e": 11418,
"s": 11382,
"text": "Stock-taking or inventory checking."
},
{
"code": null,
"e": 11483,
"s": 11418,
"text": "Supervising, training, grooming, and evaluating the subordinates"
},
{
"code": null,
"e": 11520,
"s": 11483,
"text": "Preparing reports of staff and sales"
},
{
"code": null,
"e": 11537,
"s": 11520,
"text": "Managing budgets"
},
{
"code": null,
"e": 11589,
"s": 11537,
"text": "Handling daily sales and coordinating with cashiers"
},
{
"code": null,
"e": 11635,
"s": 11589,
"text": "The Room Service Manager is responsible for β"
},
{
"code": null,
"e": 11705,
"s": 11635,
"text": "Selecting, training, encouraging, and evaluating all junior employees"
},
{
"code": null,
"e": 11794,
"s": 11705,
"text": "Ensuring that cultural values and core standards of F&B department/establishment are met"
},
{
"code": null,
"e": 11865,
"s": 11794,
"text": "Controlling labor expenses through staffing, budgeting, and scheduling"
},
{
"code": null,
"e": 11891,
"s": 11865,
"text": "Handling guest complaints"
},
{
"code": null,
"e": 11918,
"s": 11891,
"text": "Providing special requests"
},
{
"code": null,
"e": 11959,
"s": 11918,
"text": "The Banquet Manager is responsible for β"
},
{
"code": null,
"e": 11997,
"s": 11959,
"text": "Setting service standard for banquets"
},
{
"code": null,
"e": 12096,
"s": 11997,
"text": "Forecasting and allocating budgets for various types of events such as conferences, meetings, etc."
},
{
"code": null,
"e": 12130,
"s": 12096,
"text": "Achieving food and beverage sales"
},
{
"code": null,
"e": 12194,
"s": 12130,
"text": "Controlling chinaware, cutlery, glassware, linen, and equipment"
},
{
"code": null,
"e": 12236,
"s": 12194,
"text": "Handling decorations and guest complaints"
},
{
"code": null,
"e": 12263,
"s": 12236,
"text": "Providing special requests"
},
{
"code": null,
"e": 12337,
"s": 12263,
"text": "Purchasing required stock by following appropriate requisition procedures"
},
{
"code": null,
"e": 12425,
"s": 12337,
"text": "Following up each function by receiving guest feedback and submitting it to F&B Manager"
},
{
"code": null,
"e": 12464,
"s": 12425,
"text": "Participating in departmental meetings"
},
{
"code": null,
"e": 12490,
"s": 12464,
"text": "Planning and pricing menu"
},
{
"code": null,
"e": 12546,
"s": 12490,
"text": "Training, grooming, and development of staff underneath"
},
{
"code": null,
"e": 12583,
"s": 12546,
"text": "The Bar Manager is responsible for β"
},
{
"code": null,
"e": 12623,
"s": 12583,
"text": "Forecasting the daily flow of customers"
},
{
"code": null,
"e": 12685,
"s": 12623,
"text": "Allocating right number of staff according to customer influx"
},
{
"code": null,
"e": 12741,
"s": 12685,
"text": "Managing and monitoring bar inventory from store to bar"
},
{
"code": null,
"e": 12775,
"s": 12741,
"text": "Tracking all types of drink sales"
},
{
"code": null,
"e": 12815,
"s": 12775,
"text": "Allocating cleaning and tendering tasks"
},
{
"code": null,
"e": 13160,
"s": 12815,
"text": "A Food Safety Supervisor is a person who is trained to recognize and prevent risks associated with food handling in an F&B Services business. He holds an FSS certificate that needs to be no more than five years old. He is required in an F&B Services business so that he can train and supervise other staff about safe practices of handling food."
},
{
"code": null,
"e": 13244,
"s": 13160,
"text": "Food and Beverage department relies upon the support of the following departments β"
},
{
"code": null,
"e": 13639,
"s": 13244,
"text": "The Kitchen Stewarding department strives to ensure cleanliness, preparedness, and orderliness in the commercial kitchen so that the kitchen staff can work efficiently. It also ensures that all the tools and utensils required for a specific meal or cooking task are cleaned properly and are ready to go. The kitchen steward is a working link between the F&B Services and the commercial kitchen."
},
{
"code": null,
"e": 13803,
"s": 13639,
"text": "The Dishwashing department is responsible for providing clean and dry supply of glassware, chinaware, and cutlery for bar, banquet, lounge, and restaurant service."
},
{
"code": null,
"e": 13950,
"s": 13803,
"text": "The F&B department is highly reliable on laundry department or outsourced laundry services for timely supply of dry-cleaned and wrinkleless linen."
},
{
"code": null,
"e": 14042,
"s": 13950,
"text": "Each member of the F&B department hierarchy needs to have the following traits and skills β"
},
{
"code": null,
"e": 14245,
"s": 14042,
"text": "Awareness of oneβs responsibilities and roles, appropriate knowledge of food items, food and beverage pairing, etiquettes, and service styles is a great way to build confidence while serving the guests."
},
{
"code": null,
"e": 14408,
"s": 14245,
"text": "It creates the first impression on the guests. The F&B staff members must maintain personal hygiene, cleanliness, and professional appearance while being on duty."
},
{
"code": null,
"e": 14561,
"s": 14408,
"text": "Attentiveness is paying sincere attention to details, memorizing the guestsβ needs and fulfilling them timely with as much perfection as one can put in."
},
{
"code": null,
"e": 14666,
"s": 14561,
"text": "The F&B Services staff needs to conduct themselves with very positive, energetic, and friendly gestures."
},
{
"code": null,
"e": 14900,
"s": 14666,
"text": "It is very vital when it comes to talking with co-workers and guests. Clear and correct manner of communication using right language and tone can make the service workflow smooth. It can bring truly enhanced experience to the guests."
},
{
"code": null,
"e": 15066,
"s": 14900,
"text": "The F&B Services staff needs to know the value of time while serving the guests. Sincere time-keeping and sense of urgency helps to keep the service workflow smooth."
},
{
"code": null,
"e": 15178,
"s": 15066,
"text": "These two core values in any well-brought-up person are important for serving the guests in hospitality sector."
},
{
"code": null,
"e": 15350,
"s": 15178,
"text": "There are a number of service styles to be followed when it comes to how food and beverage should be served to the customers. The following are the most prominent styles β"
},
{
"code": null,
"e": 15595,
"s": 15350,
"text": "In this type of service, the guests enter the dining area and take seats. The waiter offers them water and menu card. The guests then place their order to the waiter. The table is covered in this service. It is grouped into the following types."
},
{
"code": null,
"e": 16066,
"s": 15595,
"text": "Here, the host contributes actively in the service. The waiter brings food on platters, shows to the host for approval, and then places the platters on the tables. The host either makes food portions and serves the guests or allows the waiter to serve. To replenish the guestsβ plates, the waiter takes the platters around to serve or to let the guests help themselves. This is a common family service in specialty restaurants where customers spend more time on premise."
},
{
"code": null,
"e": 16386,
"s": 16066,
"text": "The food is served on guest's plate in the kitchen itself in predetermined portion. The accompaniments served with the food, the color, and the presentation are determined in the kitchen. The food plates are then brought to the guest. This service is commonly used in a coffee shop where service is required to be fast."
},
{
"code": null,
"e": 16672,
"s": 16386,
"text": "It is very personalized and private service. The food is taken in platters and casseroles and kept on the table of guests near their plates. The guests then help themselves. It is expensive and elaborate service commonly used in fine dining restaurants. This service has two variants β"
},
{
"code": null,
"e": 16887,
"s": 16672,
"text": "Cart French Service β The food is prepared and assembled at tableside. The guests select food from the cart while sitting at their tables and are later served from the right. It is offered for small groups of VIPs."
},
{
"code": null,
"e": 17102,
"s": 16887,
"text": "Cart French Service β The food is prepared and assembled at tableside. The guests select food from the cart while sitting at their tables and are later served from the right. It is offered for small groups of VIPs."
},
{
"code": null,
"e": 17316,
"s": 17102,
"text": "Banquet French Service β The food is prepared in the kitchen. The servers serve food on each individualβs plate from guestβs left side. For replenishment, the servers keep the food platters in front of the guests."
},
{
"code": null,
"e": 17530,
"s": 17316,
"text": "Banquet French Service β The food is prepared in the kitchen. The servers serve food on each individualβs plate from guestβs left side. For replenishment, the servers keep the food platters in front of the guests."
},
{
"code": null,
"e": 17908,
"s": 17530,
"text": "In this service, partially cooked food from the kitchen is taken to the Gueridon Trolly for cooking it completely. This partial cooking is done beside the guest table for achieving a particular appearance and aroma of food, and for exhibiting showmanship. It also offers a complete view of food. The waiter needs to perform the role of cook partially and needs to be dexterous."
},
{
"code": null,
"e": 18323,
"s": 17908,
"text": "In this service, the food is presented on silver platters and casseroles. The table is set with sterling silverware. The food is portioned into silver platters in the kitchen itself. The platters are placed on the sideboard with burners or hot plates. At the time of serving, the waiter picks the platter from hot plate and presents it to the host for approval and serves each guest using a service spoon and fork."
},
{
"code": null,
"e": 18450,
"s": 18323,
"text": "It is identical to the Cart French service barring the servers place the food on the platters and serve it from the left side."
},
{
"code": null,
"e": 18651,
"s": 18450,
"text": "Here, the guests enter the dining area, collect their plates, and go to buffet counters and help themselves. The guests may partially get service at the table or replenish their own plates themselves."
},
{
"code": null,
"e": 19043,
"s": 18651,
"text": "It this type of service, the guests get plates from the stack and goes to buffet counter where food is kept in large casseroles and platters with burners. The guests can serve themselves or can request the server behind the buffet table to serve. In sit-down buffet restaurants, the tables are arranged with crockery and cutlery where guests can sit and eat, and then replenish their plates."
},
{
"code": null,
"e": 19313,
"s": 19043,
"text": "In this type of service, the guests enter the dining area and select food items. They pay for coupons of respective food items. They go to food counter and give the coupons to avail the chosen food. The guests are required to take their own plates to the table and eat."
},
{
"code": null,
"e": 19575,
"s": 19313,
"text": "This service exists in industrial canteens, hostels, and cafeterias. The menu and the space is limited; the cutlery is handed over to the guests. The tables are not covered. Sometimes high chairs are provided to eat food at narrow tables. It is a quick service."
},
{
"code": null,
"e": 19791,
"s": 19575,
"text": "In this type of service, the guest orders, pays for his order and gets served all at a single point. There may be may not be any dining area or seats. The following are the different methods of Single Point Service."
},
{
"code": null,
"e": 19946,
"s": 19791,
"text": "This is an array of autonomous counters at which the customers can order, eat, or buy from a number of different counters and eat in adjacent eating area."
},
{
"code": null,
"e": 20069,
"s": 19946,
"text": "The customer enters the choice and amount of money physically and the machine dispenses what customer demanded accurately."
},
{
"code": null,
"e": 20170,
"s": 20069,
"text": "Customer orders and avails food and beverage from a single counter and consumes it off the premises."
},
{
"code": null,
"e": 20339,
"s": 20170,
"text": "The customer can get food or beverage service by means of automatic machines. The vending machines are installed in industrial canteens, shopping centers, and airports."
},
{
"code": null,
"e": 20529,
"s": 20339,
"text": "It is called special service because it provides food and beverage at the places which are not meant for food & beverage service. The following are the different methods of special service."
},
{
"code": null,
"e": 20802,
"s": 20529,
"text": "In this type of service, various vegetables and meats are displayed for better view and choice. The counter is decorated with great aesthetics, and the guest can select meat or vegetable of choice. The guest then takes a seat and is served cooked food with accompaniments."
},
{
"code": null,
"e": 20924,
"s": 20802,
"text": "Method of service of whole or part of meal on tray to customer in situ, such as hospitals, aircraft, or railway catering."
},
{
"code": null,
"e": 21096,
"s": 20924,
"text": "Food is cooked, finished or presented to the guest at a table, from a moveable trolley. For example, food served on trollies for office workers or in aircrafts and trains."
},
{
"code": null,
"e": 21206,
"s": 21096,
"text": "Food delivered to a customerβs home or place of work. For example, home delivery of pizza or Meals on Wheels."
},
{
"code": null,
"e": 21296,
"s": 21206,
"text": "Service of variety of foods and beverages in lounge area of a hotel or independent place."
},
{
"code": null,
"e": 21504,
"s": 21296,
"text": "Here food is served to guests in their allotted rooms in hotels. Small orders are served in trays. Major meals are taken to the room on trolleys. The guest places his order with the room service order taker."
},
{
"code": null,
"e": 21957,
"s": 21504,
"text": "The waiter receives the order and transmits the same to the kitchen. Meanwhile, he prepares his tray or trolley. He then goes to the cashier to prepare and take the bill. He then takes the bill along with the food order for the guestsβ signature or payment. Usually clearance of soiled dishes from the room is done after half an hour or an hour. However, the guest can telephone Room Service for the clearance as and when he has finished with the meal."
},
{
"code": null,
"e": 22514,
"s": 21957,
"text": "Today, numerous types of food and beverage service outlets have come up in the market. They offer a wide range of food and beverage services that the customers can avail. The extent of service depends upon the type of service outlet. They include drive-through service of fast food where the customers can purchase their favorite food without having to leave their cars and pick-up points where food is delivered in minutes. There are also some elite class fine dining outlets which exhibit classy articles in the house and provide elaborate food services."
},
{
"code": null,
"e": 22572,
"s": 22514,
"text": "Here are some famous types of food and beverage outlets β"
},
{
"code": null,
"e": 22763,
"s": 22572,
"text": "Appropriate architecture of F&B outlet makes it prepare, present, and serve in optimum way and increase productivity. These are few basic considerations for various sections of F&B outlets β"
},
{
"code": null,
"e": 22798,
"s": 22763,
"text": "It is farthest from the customers."
},
{
"code": null,
"e": 22897,
"s": 22798,
"text": "It has large fridges, cupboards with multiple shelves, and lockers. It is attached to the kitchen."
},
{
"code": null,
"e": 23024,
"s": 22897,
"text": "It is being the area where food or beverage is prepared ready to serve, it is located between the dining area and the kitchen."
},
{
"code": null,
"e": 23234,
"s": 23024,
"text": "There are two different schools of thought for location of restrooms β some experts consider that the restrooms must be near the entrance and some think that it should be isolated from entrance or dining area."
},
{
"code": null,
"e": 23441,
"s": 23234,
"text": "While designing an F&B outlet, one needs to consider every factor that contributes to the smooth running of operations right from food preparation, cooking, dish presentation, serving, and all allied tasks."
},
{
"code": null,
"e": 23518,
"s": 23441,
"text": "While designing commercial F&B outlets, the following points are important β"
},
{
"code": null,
"e": 23565,
"s": 23518,
"text": "Target customer segment (Youth/Men/Women/All)."
},
{
"code": null,
"e": 23614,
"s": 23565,
"text": "Type of food (Light Food/Fast Food/Fine Dining)."
},
{
"code": null,
"e": 23684,
"s": 23614,
"text": "Manner of food production (Cooking/Grilling/Boiling/Baking/Steaming)."
},
{
"code": null,
"e": 23728,
"s": 23684,
"text": "Type of food distribution (On/Off Premise)."
},
{
"code": null,
"e": 23757,
"s": 23728,
"text": "Availability of carpet area."
},
{
"code": null,
"e": 23783,
"s": 23757,
"text": "Number of staff required."
},
{
"code": null,
"e": 23945,
"s": 23783,
"text": "The kitchen is designed not to be directly visible. The chef cannot directly communicate to the guests. The guest tables and chairs are placed away from kitchen."
},
{
"code": null,
"e": 24295,
"s": 23945,
"text": "Food and Beverage Service operations involve a multitude of activities which engage the staff right from purchasing raw material, preparing food and beverage, keeping the inventory of material, maintaining service quality continuously, managing various catered events, and most importantly, analyzing the business outcomes to decide future policies."
},
{
"code": null,
"e": 24353,
"s": 24295,
"text": "Let us look into the operations involved in F&B service β"
},
{
"code": null,
"e": 24572,
"s": 24353,
"text": "The purchasing department in F&B Services is responsible for purchasing, storing, and issuing the supply of raw food items, canned/bottled beverages, and equipment. The following is a typical product purchasing cycle β"
},
{
"code": null,
"e": 24693,
"s": 24572,
"text": "The purchasing department works with accounts department to keep the information on allocated budget and balance budget."
},
{
"code": null,
"e": 24738,
"s": 24693,
"text": "The following factors influence purchasing β"
},
{
"code": null,
"e": 24763,
"s": 24738,
"text": "Size of F&B Organization"
},
{
"code": null,
"e": 24792,
"s": 24763,
"text": "Location of F&B Organization"
},
{
"code": null,
"e": 24831,
"s": 24792,
"text": "Availability and Size of Storage Space"
},
{
"code": null,
"e": 24864,
"s": 24831,
"text": "Organization Budget and Policies"
},
{
"code": null,
"e": 24908,
"s": 24864,
"text": "Availability of the commodity due to season"
},
{
"code": null,
"e": 25239,
"s": 24908,
"text": "The purchaser is responsible for purchasing a product. He studies the market, and analyzes and selects suppliers, wholesalers, and the contemporary market prices. He then liaisons with suppliers and wholesalers to get good material at fair price and purchases the required commodities by following appropriate purchase procedures."
},
{
"code": null,
"e": 25444,
"s": 25239,
"text": "The receiver receives the products from the suppliers. He checks the product for right quality and quantity. He deals with the delivery personnel from the supplierβs end and signs on the related receipts."
},
{
"code": null,
"e": 25675,
"s": 25444,
"text": "The store men carry out the task of storing received supply and issuing it to respective departments. They update the stock database, and manage old and new material in the stock. They also keep record of stock to the latest date."
},
{
"code": null,
"e": 26068,
"s": 25675,
"text": "This includes preparation of various food items and fresh beverages. The cooks prepare various foods and the bar tenders prepare cold beverages such as mocktails and cocktails. They also make the dish most presentable by arranging food on platter and decorating it in an attractive manner. The beverages are also decorated by using fruit slices, decorating the glasses, sippers, and stirrers."
},
{
"code": null,
"e": 26257,
"s": 26068,
"text": "This part is played by the guests. At the service end, the respective staff takes inventory of the consumed and balanced stock of food and beverages and keeps it updated to latest figures."
},
{
"code": null,
"e": 26587,
"s": 26257,
"text": "It is very vital for an F&B Services organization or an F&B department in a large hotel to keep their standards of food and beverage high. If the quality of food and beverage along with the best service is what the guests liked, then the chances of the guests coming repeatedly and singing praises of what they received are high."
},
{
"code": null,
"e": 26835,
"s": 26587,
"text": "Any food and beverage service business has a great responsibility of serving hygienic, safe, clean, and fresh food. The customers also rightfully question if the food or beverage they consume at the F&B Services outlet is healthy, safe, and fresh."
},
{
"code": null,
"e": 27241,
"s": 26835,
"text": "For ensuring food safety, a system named Hazard Analysis and Critical Control Points (HACCP) in Europe works to identify Critical Control Points (CCP) for the presence of physical, chemical, and bacterial hazards to food. HACCP has set guidelines and principles on producing healthy and safe food. It also enables food and beverage businesses to adhere to consistent safety and quality of food production."
},
{
"code": null,
"e": 27571,
"s": 27241,
"text": "In India, Food Safety and Standards Authority (FSSA) works towards setting standards for safe and hygienic food. In USA, Food Safety and Inspection Service (FSIS) is responsible for the safety of meat, poultry, and processed egg products. Also, the Food and Drug Administration (FDA) is responsible for virtually all other foods."
},
{
"code": null,
"e": 27720,
"s": 27571,
"text": "Before planning and executing buffets, banquets, or catered events, the respective managers and supervisors need to consider the following factors β"
},
{
"code": null,
"e": 27865,
"s": 27720,
"text": "It can be formal such as seminars, meetings, or conference, or informal such as a wedding reception, birthday party, employee outing, and alike."
},
{
"code": null,
"e": 28006,
"s": 27865,
"text": "The participants such as decorating staff, planning staff such as managers, serving staff, supervising staff, whole sellers, and the guests."
},
{
"code": null,
"e": 28207,
"s": 28006,
"text": "It is important to know the date and time of event, the number of expected guests, dance floor, audio or projector systems, or any special requirement demanded by the guests before planning the event."
},
{
"code": null,
"e": 28640,
"s": 28207,
"text": "It includes flowers, table arrangement, center-pieces, candles, artificial fountains/waterfalls, decorative art pieces, plants and pots; for both formal and informal occasions with the involvement of deΜcor artists. The display pieces may be carved, baked, or assembled; made of edible or non-edible substances according to the laid standards. The decoration needs to go in pair with the theme of the banquet, buffet, or some event."
},
{
"code": null,
"e": 28991,
"s": 28640,
"text": "According to the time of event, it can include starters, salads, breads, main courses (meats, poultry, or sea food), desserts (fruits, pastries, or frozen desserts), beverages, accompaniments, and garnishes according to the establishment standards. It must be hygienic, in-line with the occasion, and meeting the F&B Services establishment standards."
},
{
"code": null,
"e": 29194,
"s": 28991,
"text": "Depending upon the requirement of guests and serving style, it can include silverware, platters, table linens, and other required serving equipment. It also includes size and shape of tables and chairs."
},
{
"code": null,
"e": 29536,
"s": 29194,
"text": "According to establishment norms, serving right food at right temperature, replenishing food platters timely, keeping the overall display neat and attractive, storing food and managing beverage consumption after service, cleaning buffet or banquet area, restoring plates, cutlery, Guerion trollies, and glassware after completion of service."
},
{
"code": null,
"e": 29742,
"s": 29536,
"text": "The decision making responsibility in an F&B establishment rests with the managers. They have full access to the numbers, data, reports, and trends of the market as well as knowledge of F&B establishments."
},
{
"code": null,
"e": 29825,
"s": 29742,
"text": "The F&B services managers need to conduct financial analysis and quality analysis."
},
{
"code": null,
"e": 29876,
"s": 29825,
"text": "Financial Analysis is carried out in three steps β"
},
{
"code": null,
"e": 29999,
"s": 29876,
"text": "The managers study current and future market trends and forecast expenses. Budgets are prepared based on managersβ inputs."
},
{
"code": null,
"e": 30247,
"s": 29999,
"text": "The managers also keep a keen eye on present situation in which F&B Services is functioning. They need to consider fixed costs such as rents and property taxes, and variable costs such as material, advertisement, and music and entertainment costs."
},
{
"code": null,
"e": 30338,
"s": 30247,
"text": "They come up with the difference and find out the reasons and apply the required policies."
},
{
"code": null,
"e": 30472,
"s": 30338,
"text": "The Quality Analysis needs to consider the following factors while providing the food product or service. Some of these factors are β"
},
{
"code": null,
"e": 30647,
"s": 30472,
"text": "Evaluating ongoing product analysis checklist that includes doneness, aroma and taste of the ready dish, garnish, color, appearance, presentation, serving portion, and alike."
},
{
"code": null,
"e": 30822,
"s": 30647,
"text": "Evaluating ongoing product analysis checklist that includes doneness, aroma and taste of the ready dish, garnish, color, appearance, presentation, serving portion, and alike."
},
{
"code": null,
"e": 30894,
"s": 30822,
"text": "Evaluating the food or beverage product for safety against consumption."
},
{
"code": null,
"e": 30966,
"s": 30894,
"text": "Evaluating the food or beverage product for safety against consumption."
},
{
"code": null,
"e": 31086,
"s": 30966,
"text": "Evaluating weekly review of product deviation that includes date, product name, problem, solutions, and recommendation."
},
{
"code": null,
"e": 31206,
"s": 31086,
"text": "Evaluating weekly review of product deviation that includes date, product name, problem, solutions, and recommendation."
},
{
"code": null,
"e": 31361,
"s": 31206,
"text": "It includes coming up with corrective actions in case of certain unpleasant results. The managers make decisions after going through the following steps β"
},
{
"code": null,
"e": 31382,
"s": 31361,
"text": "Identifying problems"
},
{
"code": null,
"e": 31401,
"s": 31382,
"text": "Identifying reason"
},
{
"code": null,
"e": 31435,
"s": 31401,
"text": "Determining a number of solutions"
},
{
"code": null,
"e": 31461,
"s": 31435,
"text": "Selecting a best solution"
},
{
"code": null,
"e": 31483,
"s": 31461,
"text": "Applying the solution"
},
{
"code": null,
"e": 31507,
"s": 31483,
"text": "Evaluating the solution"
},
{
"code": null,
"e": 31598,
"s": 31507,
"text": "For example, the response for chilled cucumber soup is declining for the past four months."
},
{
"code": null,
"e": 31693,
"s": 31598,
"text": "Identify problems β Menu problem? Taste issue? Price issue? Serving quantity or quality issue?"
},
{
"code": null,
"e": 31788,
"s": 31693,
"text": "Identify problems β Menu problem? Taste issue? Price issue? Serving quantity or quality issue?"
},
{
"code": null,
"e": 31982,
"s": 31788,
"text": "Identify reason β Soup is outstanding on quality, portion of service, and taste marks. But it is Winter and guests are preferring hot soups than the chilled ones though it is on the lunch menu."
},
{
"code": null,
"e": 32176,
"s": 31982,
"text": "Identify reason β Soup is outstanding on quality, portion of service, and taste marks. But it is Winter and guests are preferring hot soups than the chilled ones though it is on the lunch menu."
},
{
"code": null,
"e": 32290,
"s": 32176,
"text": "Solutions β Can a hot variant of the same soup be developed? Can the soup be replaced by a preferred alternative?"
},
{
"code": null,
"e": 32404,
"s": 32290,
"text": "Solutions β Can a hot variant of the same soup be developed? Can the soup be replaced by a preferred alternative?"
},
{
"code": null,
"e": 32589,
"s": 32404,
"text": "Best solution β Shift chilled cucumber soup to summer-time menus and bring in a new hot soup or a variant of one of the present soups that will potentially rule the guestsβ taste buds."
},
{
"code": null,
"e": 32774,
"s": 32589,
"text": "Best solution β Shift chilled cucumber soup to summer-time menus and bring in a new hot soup or a variant of one of the present soups that will potentially rule the guestsβ taste buds."
},
{
"code": null,
"e": 33047,
"s": 32774,
"text": "Food and beverages form an integral part of the human culture. Ever since human culture started evolving, food and beverages preparation also went on finding new ways. Today, every country flaunts a different line of food and beverages prepared in authentic culinary ways."
},
{
"code": null,
"e": 33317,
"s": 33047,
"text": "Over the past several years, various food and beverages have been developed using local crops, meats, fruits, and vegetables, and trying different recipes with them. This manner of development contributed in the authenticity of the food and beverages to a great extent."
},
{
"code": null,
"e": 33533,
"s": 33317,
"text": "It is a detailed list of food and beverage offerings with their respective prices. It is prepared by a food and beverage service businesses to keep the customers informed about the availability of various F&B items."
},
{
"code": null,
"e": 33552,
"s": 33533,
"text": "A good menu must β"
},
{
"code": null,
"e": 33592,
"s": 33552,
"text": "Present clear, unambiguous information."
},
{
"code": null,
"e": 33654,
"s": 33592,
"text": "Adhere to food safety and nutrition policies of the business."
},
{
"code": null,
"e": 33693,
"s": 33654,
"text": "Meet or outstrip guestsβ expectations."
},
{
"code": null,
"e": 33737,
"s": 33693,
"text": "Meet the quality standards of the business."
},
{
"code": null,
"e": 33791,
"s": 33737,
"text": "Be truthful in describing the taste and preparations."
},
{
"code": null,
"e": 33869,
"s": 33791,
"text": "Be strictly going with the production and service facilities of the business."
},
{
"code": null,
"e": 34155,
"s": 33869,
"text": "The restaurant menu should be planned well by considering various aspects of the food outlet. There are myriad menus available right from breakfast, lunch, small bites, up to dinner. The following information is gathered before planning food and beverage menu for a commercial kitchen."
},
{
"code": null,
"e": 34241,
"s": 34155,
"text": "What kind of food outlet is it? (Vintage, Contemporary, Modern, Theme, Bar, and more)"
},
{
"code": null,
"e": 34273,
"s": 34241,
"text": "What is the name of the outlet?"
},
{
"code": null,
"e": 34370,
"s": 34273,
"text": "What is the expanse of food items, their accompaniments, and beverages the owner wishes to keep?"
},
{
"code": null,
"e": 34430,
"s": 34370,
"text": "Which information needs elaboration for food and beverages?"
},
{
"code": null,
"e": 34483,
"s": 34430,
"text": "What tone of language is required? (formal/informal)"
},
{
"code": null,
"e": 34574,
"s": 34483,
"text": "What types of names and category headings would best suit for the food and beverage items?"
},
{
"code": null,
"e": 34646,
"s": 34574,
"text": "What design, images, colors, and typeface would look best for the menu?"
},
{
"code": null,
"e": 34705,
"s": 34646,
"text": "Are the graphic details relevant to the food outlet theme?"
},
{
"code": null,
"e": 34744,
"s": 34705,
"text": "How large should the menu be on paper?"
},
{
"code": null,
"e": 34965,
"s": 34744,
"text": "These days, numerous apps such as MenuPro, FineDine, MenuExpress, InnMenu, and more are readily available to create catchy and engaging menus. A good menu design is a treat for eyes that drive the guests to place orders."
},
{
"code": null,
"e": 35109,
"s": 34965,
"text": "Depending upon the expanse of physical outlet and service, and the variety of food and beverages it offers, the menu design and details change."
},
{
"code": null,
"e": 35237,
"s": 35109,
"text": "This is the selection of menu in advance for an upcoming event. Menu planning plays an important role in customer satisfaction."
},
{
"code": null,
"e": 35290,
"s": 35237,
"text": "Menu planning is beneficial in the following areas β"
},
{
"code": null,
"e": 35335,
"s": 35290,
"text": "Purchasing of essential material in advance."
},
{
"code": null,
"e": 35356,
"s": 35335,
"text": "Pricing of the food."
},
{
"code": null,
"e": 35386,
"s": 35356,
"text": "Guiding the food preparation."
},
{
"code": null,
"e": 35416,
"s": 35386,
"text": "Evaluating the dietary needs."
},
{
"code": null,
"e": 35472,
"s": 35416,
"text": "Evaluating the food in terms of necessary improvements."
},
{
"code": null,
"e": 35617,
"s": 35472,
"text": "The menu must be planned such that it goes well with the theme of the F&B outlet and it must be a good bargain for food price and dietary value."
},
{
"code": null,
"e": 35796,
"s": 35617,
"text": "There are various cuisines around the world. Each cuisine involves a lot of preparation. The following most famous ethnic menus are prepared in various cuisines around the world "
},
{
"code": null,
"e": 36287,
"s": 35796,
"text": "Indian food is perhaps as diverse as its culture and offers a lot more than curries and gravies. It balances all tastes β savory, sweet, salty, and sour. Indian food broadly goes according to the regions where it originates such as Northern, Southern, Western, and Eastern. Within regions it is varied according to states such as Kashmiri, Punjabi, Gujarati, Marathi, Keralite, Bengali, and so on. It is an authentic combination of the base food paired with aromatic herbs nuts, and spices."
},
{
"code": null,
"e": 36514,
"s": 36287,
"text": "It includes various appetizers, snacks and their accompaniments, veg and non-veg stews, various types of flat breads, plain or spicy lentils, rice preparations, sea-food, street food, and sweets made of milk products and nuts."
},
{
"code": null,
"e": 36943,
"s": 36514,
"text": "Indian food is eaten using oneβs clean fingers because that way, the flatbreads are easy to portion. The spoons and forks are used for having snacks, curries, stews, rice, curds, or sweets when the need arises. Authentic Indian food is generally served in copper or brass bowls and plates or you can have it on fresh banana leaves or Patravali (Plates made of dried leaves), which help to save efforts of cleaning and disposing."
},
{
"code": null,
"e": 36976,
"s": 36943,
"text": "A few popular Indian foods are β"
},
{
"code": null,
"e": 37055,
"s": 36976,
"text": "Poha (beaten rice soaked and cooked by adding chopped vegetables and cilantro)"
},
{
"code": null,
"e": 37134,
"s": 37055,
"text": "Poha (beaten rice soaked and cooked by adding chopped vegetables and cilantro)"
},
{
"code": null,
"e": 37228,
"s": 37134,
"text": "Aloo Bonda (Boiled, mashed, and flavored potatoes enwrapped with lentil flour and deep fried)"
},
{
"code": null,
"e": 37322,
"s": 37228,
"text": "Aloo Bonda (Boiled, mashed, and flavored potatoes enwrapped with lentil flour and deep fried)"
},
{
"code": null,
"e": 37399,
"s": 37322,
"text": "Kadhai Panner (Savory cubes of cottage cheese in thick tangy curry or gravy)"
},
{
"code": null,
"e": 37476,
"s": 37399,
"text": "Kadhai Panner (Savory cubes of cottage cheese in thick tangy curry or gravy)"
},
{
"code": null,
"e": 37539,
"s": 37476,
"text": "Veg Kolhapuri (Wholesome vegetables cooked in spicy red gravy)"
},
{
"code": null,
"e": 37602,
"s": 37539,
"text": "Veg Kolhapuri (Wholesome vegetables cooked in spicy red gravy)"
},
{
"code": null,
"e": 37644,
"s": 37602,
"text": "Rajma (Black beans cooked in spicy gravy)"
},
{
"code": null,
"e": 37686,
"s": 37644,
"text": "Rajma (Black beans cooked in spicy gravy)"
},
{
"code": null,
"e": 37759,
"s": 37686,
"text": "Biryani (Aromatic and flavored rice dish cooked with vegetables or meat)"
},
{
"code": null,
"e": 37832,
"s": 37759,
"text": "Biryani (Aromatic and flavored rice dish cooked with vegetables or meat)"
},
{
"code": null,
"e": 37907,
"s": 37832,
"text": "Sarson-da-saag (Mustard leaves cooked with chili, garlic, and mustard oil)"
},
{
"code": null,
"e": 37982,
"s": 37907,
"text": "Sarson-da-saag (Mustard leaves cooked with chili, garlic, and mustard oil)"
},
{
"code": null,
"e": 38050,
"s": 37982,
"text": "Jalebi (Coils of flour batter deep fried and dipped in sugar syrup)"
},
{
"code": null,
"e": 38118,
"s": 38050,
"text": "Jalebi (Coils of flour batter deep fried and dipped in sugar syrup)"
},
{
"code": null,
"e": 38198,
"s": 38118,
"text": "Gulab Jamun (Deep fried balls of milk powder and flour soaked into sugar syrup)"
},
{
"code": null,
"e": 38278,
"s": 38198,
"text": "Gulab Jamun (Deep fried balls of milk powder and flour soaked into sugar syrup)"
},
{
"code": null,
"e": 38691,
"s": 38278,
"text": "France boasts of a wide range of cuisines. The cuisines follow authentic traditional cooking practices. French food caters to the preparation of appetizers, salads, soups, stews, side and main dishes, and desserts. A large variety of classic food is prepared using red and white meats. Recipes have evolved with seafood, fruits, cheeses, vegetables, pastries, and chocolates using authentic sauces and dressings."
},
{
"code": null,
"e": 38746,
"s": 38691,
"text": "The following are some traditional French dishes are β"
},
{
"code": null,
"e": 38790,
"s": 38746,
"text": "Soupe a l'oignon (Onion soup in meat stock)"
},
{
"code": null,
"e": 38834,
"s": 38790,
"text": "Soupe a l'oignon (Onion soup in meat stock)"
},
{
"code": null,
"e": 38879,
"s": 38834,
"text": "Petits Pates a la Sage (Little pies of sage)"
},
{
"code": null,
"e": 38924,
"s": 38879,
"text": "Petits Pates a la Sage (Little pies of sage)"
},
{
"code": null,
"e": 38965,
"s": 38924,
"text": "Ratatouille (Traditional vegetable stew)"
},
{
"code": null,
"e": 39006,
"s": 38965,
"text": "Ratatouille (Traditional vegetable stew)"
},
{
"code": null,
"e": 39035,
"s": 39006,
"text": "Coq au vin (Rooster in wine)"
},
{
"code": null,
"e": 39064,
"s": 39035,
"text": "Coq au vin (Rooster in wine)"
},
{
"code": null,
"e": 39317,
"s": 39064,
"text": "Italian food boasts of classically prepared pizza bases baked with savoury toppings of vegetables, meat, and cheese. It also includes a wide range of pastas of various shapes and sizes cooked and served with authentic Italian accompaniments and sauces."
},
{
"code": null,
"e": 39543,
"s": 39317,
"text": "The local customs of baking and cooking provide a large array of soups, salads, snacks, meals, and desserts from Italian cuisine. The food is often accompanied with beverages such as wine, champagnes, or other similar drinks."
},
{
"code": null,
"e": 39602,
"s": 39543,
"text": "The following are some popular dishes in Italian cuisine β"
},
{
"code": null,
"e": 39671,
"s": 39602,
"text": "Bellini (a cocktail made with white peach puree and sparkling wine.)"
},
{
"code": null,
"e": 39740,
"s": 39671,
"text": "Bellini (a cocktail made with white peach puree and sparkling wine.)"
},
{
"code": null,
"e": 39754,
"s": 39740,
"text": "Caprese Salad"
},
{
"code": null,
"e": 39768,
"s": 39754,
"text": "Caprese Salad"
},
{
"code": null,
"e": 39792,
"s": 39768,
"text": "Cacciuco (Seafood stew)"
},
{
"code": null,
"e": 39816,
"s": 39792,
"text": "Cacciuco (Seafood stew)"
},
{
"code": null,
"e": 39853,
"s": 39816,
"text": "Risotto Alla Milanese (Saffron Rice)"
},
{
"code": null,
"e": 39890,
"s": 39853,
"text": "Risotto Alla Milanese (Saffron Rice)"
},
{
"code": null,
"e": 39934,
"s": 39890,
"text": "Arancini Veneziani (Venetian Rice Fritters)"
},
{
"code": null,
"e": 39978,
"s": 39934,
"text": "Arancini Veneziani (Venetian Rice Fritters)"
},
{
"code": null,
"e": 40024,
"s": 39978,
"text": "Braciola (Italian Beef Rolls in Tomato Sauce)"
},
{
"code": null,
"e": 40070,
"s": 40024,
"text": "Braciola (Italian Beef Rolls in Tomato Sauce)"
},
{
"code": null,
"e": 40152,
"s": 40070,
"text": "Spinach and Mushroom Lasagna (Baked sheets of flour separated by stew and cheese)"
},
{
"code": null,
"e": 40234,
"s": 40152,
"text": "Spinach and Mushroom Lasagna (Baked sheets of flour separated by stew and cheese)"
},
{
"code": null,
"e": 40519,
"s": 40234,
"text": "They say, Chinese food is the tastiest in the world. It includes soups, snacks, and meals prepared with rice, noodles, vegetables, meats, seafood, sauces, and seasonings. The stir frying manner of cooking brings crunchiness, texture, and adds a great flavor to various Chinese dishes."
},
{
"code": null,
"e": 40956,
"s": 40519,
"text": "Chinese food is prepared with crunchy or leafy vegetables, bean sprouts, a variety of mushrooms, bamboo shoots, tofu (soybean curds), and spices such as chilies, ginger, Chinese celery, and garlic. The food is consumed using traditional chopsticks and spoons. The table setting displays porcelain bowls and spoons for soup, a large bowl for food kept on the flat plate underneath, Rice bowl, and a pair of chopsticks with resting stand."
},
{
"code": null,
"e": 41008,
"s": 40956,
"text": "The following are some traditional Chinese dishes β"
},
{
"code": null,
"e": 41084,
"s": 41008,
"text": "Gong Bao Chicken (Diced chicken cooked with dried chili and fried peanuts)."
},
{
"code": null,
"e": 41160,
"s": 41084,
"text": "Gong Bao Chicken (Diced chicken cooked with dried chili and fried peanuts)."
},
{
"code": null,
"e": 41242,
"s": 41160,
"text": "Ma Po Tofu (Tofu cubes cooked with pepper powder, ground beef, and green onions)."
},
{
"code": null,
"e": 41324,
"s": 41242,
"text": "Ma Po Tofu (Tofu cubes cooked with pepper powder, ground beef, and green onions)."
},
{
"code": null,
"e": 41368,
"s": 41324,
"text": "Wontons (Triangles of flour added in soup)."
},
{
"code": null,
"e": 41412,
"s": 41368,
"text": "Wontons (Triangles of flour added in soup)."
},
{
"code": null,
"e": 41516,
"s": 41412,
"text": "Dumplings (Small dough disks filled with minced meat or spicy chopped vegetables, closed, and steamed)."
},
{
"code": null,
"e": 41620,
"s": 41516,
"text": "Dumplings (Small dough disks filled with minced meat or spicy chopped vegetables, closed, and steamed)."
},
{
"code": null,
"e": 41698,
"s": 41620,
"text": "Spring Rolls (fried cylindrical rolls that enwrap minced meat or vegetables)."
},
{
"code": null,
"e": 41776,
"s": 41698,
"text": "Spring Rolls (fried cylindrical rolls that enwrap minced meat or vegetables)."
},
{
"code": null,
"e": 41838,
"s": 41776,
"text": "Chow Mein (Cooked and stir fried vegetables in savory sauce)."
},
{
"code": null,
"e": 41900,
"s": 41838,
"text": "Chow Mein (Cooked and stir fried vegetables in savory sauce)."
},
{
"code": null,
"e": 42140,
"s": 41900,
"text": "Chinese food includes a cup of tea as beverage. No aerated drinks are served as part of authentic Chinese meal. Desserts are not commonly consumed in Chinese cuisine except on special occasions. The meal is generally completed with fruits."
},
{
"code": null,
"e": 42481,
"s": 42140,
"text": "Thai food is popular for the aroma it brings with the addition of lemongrass, lemon leaves, galangal, chili, and aromatic herbs. The base food is vegetables, meats, eggs, sauces, noodles, and rice. A complete Thai meal comprises of snacks, salads, soups, one-dish meals, and desserts. It makes a blend of great taste and treat for eyes too."
},
{
"code": null,
"e": 42691,
"s": 42481,
"text": "As per the traditional customs, the soups are enjoyed along with rice and noodles; not before. The rice or noodles are topped with the toppings of choice and consumed with spoon. Some popular Thai dishes are β"
},
{
"code": null,
"e": 42750,
"s": 42691,
"text": "Tom Yam Goong (Jumbo prawns in savory hot and spicy sauce)"
},
{
"code": null,
"e": 42809,
"s": 42750,
"text": "Tom Yam Goong (Jumbo prawns in savory hot and spicy sauce)"
},
{
"code": null,
"e": 42902,
"s": 42809,
"text": "Pad Thai (Noodles with tofu, sprouts, fried onion, chili sauce, and finely powdered peanuts)"
},
{
"code": null,
"e": 42995,
"s": 42902,
"text": "Pad Thai (Noodles with tofu, sprouts, fried onion, chili sauce, and finely powdered peanuts)"
},
{
"code": null,
"e": 43051,
"s": 42995,
"text": "Kuay Tiew (Noodles served in vegetables and meat broth)"
},
{
"code": null,
"e": 43107,
"s": 43051,
"text": "Kuay Tiew (Noodles served in vegetables and meat broth)"
},
{
"code": null,
"e": 43179,
"s": 43107,
"text": "Gai Med Ma Moung (Chicken in soy sauce, garlic, honey, and cashew nuts)"
},
{
"code": null,
"e": 43251,
"s": 43179,
"text": "Gai Med Ma Moung (Chicken in soy sauce, garlic, honey, and cashew nuts)"
},
{
"code": null,
"e": 43273,
"s": 43251,
"text": "Kao Phad (Fried rice)"
},
{
"code": null,
"e": 43295,
"s": 43273,
"text": "Kao Phad (Fried rice)"
},
{
"code": null,
"e": 43362,
"s": 43295,
"text": "Massaman Curry (Meat and potato cooked in cinnamon flavored curry)"
},
{
"code": null,
"e": 43429,
"s": 43362,
"text": "Massaman Curry (Meat and potato cooked in cinnamon flavored curry)"
},
{
"code": null,
"e": 43562,
"s": 43429,
"text": "Mexican line of food is famous for spicy and tangy taste. It includes salads, snacks, one-dish meals, elaborate meals, and desserts."
},
{
"code": null,
"e": 43608,
"s": 43562,
"text": "The basic food items in Mexican cuisine are β"
},
{
"code": null,
"e": 43652,
"s": 43608,
"text": "Tortillas (Corn flour or wheat flour disks)"
},
{
"code": null,
"e": 43696,
"s": 43652,
"text": "Tortillas (Corn flour or wheat flour disks)"
},
{
"code": null,
"e": 43731,
"s": 43696,
"text": "Fajitas (Grilled meat on tortilla)"
},
{
"code": null,
"e": 43766,
"s": 43731,
"text": "Fajitas (Grilled meat on tortilla)"
},
{
"code": null,
"e": 43822,
"s": 43766,
"text": "Tacos (Small tortilla partially enwrapping the filling)"
},
{
"code": null,
"e": 43878,
"s": 43822,
"text": "Tacos (Small tortilla partially enwrapping the filling)"
},
{
"code": null,
"e": 43957,
"s": 43878,
"text": "Quesadillas (Wheat or corn tortilla filled with cheese and meat or vegetables)"
},
{
"code": null,
"e": 44036,
"s": 43957,
"text": "Quesadillas (Wheat or corn tortilla filled with cheese and meat or vegetables)"
},
{
"code": null,
"e": 44114,
"s": 44036,
"text": "Nachos (A Texan-Mexican or Tex-Mex snack with savory flavored tortilla chips)"
},
{
"code": null,
"e": 44192,
"s": 44114,
"text": "Nachos (A Texan-Mexican or Tex-Mex snack with savory flavored tortilla chips)"
},
{
"code": null,
"e": 44339,
"s": 44192,
"text": "Enchiladas (Corn tortillas rolled around a filling of cooked meat, seafood, beans, or vegetables and covered with a chili pepper sauce and cheese)"
},
{
"code": null,
"e": 44486,
"s": 44339,
"text": "Enchiladas (Corn tortillas rolled around a filling of cooked meat, seafood, beans, or vegetables and covered with a chili pepper sauce and cheese)"
},
{
"code": null,
"e": 44537,
"s": 44486,
"text": "Empanadas (Baked or fried stuffed bread or pastry)"
},
{
"code": null,
"e": 44588,
"s": 44537,
"text": "Empanadas (Baked or fried stuffed bread or pastry)"
},
{
"code": null,
"e": 44731,
"s": 44588,
"text": "Corn, black beans, native fruits and vegetables, herbs, and meats are integral ingredients of Mexican food. A few popular Mexican dishes are β"
},
{
"code": null,
"e": 44760,
"s": 44731,
"text": "Chicken-mango-jalapeno salad"
},
{
"code": null,
"e": 44782,
"s": 44760,
"text": "Mango-pineapple salsa"
},
{
"code": null,
"e": 44814,
"s": 44782,
"text": "Prawn fajita with avocado cream"
},
{
"code": null,
"e": 44835,
"s": 44814,
"text": "Mexican chicken stew"
},
{
"code": null,
"e": 44857,
"s": 44835,
"text": "Grilled chicken nacho"
},
{
"code": null,
"e": 45186,
"s": 44857,
"text": "The courses of meal around the world vary in number from as small as just one to as wide as 17, in case of a traditional French meal. The courses are divided according to what food one eats. There are different food profiles according to the countryβs culture and customs. Generally, there are at least three courses of a meal β"
},
{
"code": null,
"e": 45378,
"s": 45186,
"text": "In this course, a welcoming appetizer that induces hunger is given to the guests. Also, the guests can prefer soups accompanied with the bite-size savory snacks as side orders in this course."
},
{
"code": null,
"e": 45556,
"s": 45378,
"text": "During this course, main dishes with vegetables or meats accompanied with rice and breads are served. In some cultures, such as Indian, the main dish is accompanied with salads."
},
{
"code": null,
"e": 45633,
"s": 45556,
"text": "This course signals the end of meal and is usually had with a cup of coffee."
},
{
"code": null,
"e": 45931,
"s": 45633,
"text": "Salads form an important part of diet in France. A typical French meal has an addition of Salad Course. It is often accompanied by other courses such as Fish Course and Cheese Course. There are cultures where people prefer to take one dish meal with no elaborate and distinguished courses of food."
},
{
"code": null,
"e": 46040,
"s": 45931,
"text": "Depending upon what and how the food is made available to the guests, there are following broad menu types β"
},
{
"code": null,
"e": 46451,
"s": 46040,
"text": "Table Dβhote is a menu where the meal is combined with a number of food options from each course. The guests can make their choice and order for a fixed price. Irrespective of what the guest chooses or declines, the price remains the same. Hence, it may also be called prix fixe or fixed price menu. Banquet menus, childrenβs menus, and occasion menus cater to special occasions and are offered at a set price."
},
{
"code": null,
"e": 46700,
"s": 46451,
"text": "A la carte is a multi-course or multi-category menu that comes with appetizers, starters, sea-food, meats, side dishes, beverages, and alike. Each dish is offered at a separate price. The guest can choose individual dishes to make own meal package."
},
{
"code": null,
"e": 46809,
"s": 46700,
"text": "In this menu, the typical types of meals are served yearlong with an occasional change on some special days."
},
{
"code": null,
"e": 47101,
"s": 46809,
"text": "Cycle menu includes different meals offered on different days of a week. The cafeterias at educational institutes and otherwise use this menu which they can repeat after a week or a month. Serving a feast on Sunday, offering special variants of chicken on Fridays can add to the cyclic menu."
},
{
"code": null,
"e": 47187,
"s": 47101,
"text": "Let us now look at a few other menus which boost your platter and the F & B Services."
},
{
"code": null,
"e": 47353,
"s": 47187,
"text": "This menu displays puddings, cakes, tarts, ice creams, smoothies, fondues, sundaes, sweet pies, and ice creams and frozen yogurts along with their respective prices."
},
{
"code": null,
"e": 47532,
"s": 47353,
"text": "Frozen Desserts β They are usually popular with people from all ages and walks of life. They are always served chilled. The following are some mouthwatering frozen desserts are β"
},
{
"code": null,
"e": 47885,
"s": 47532,
"text": "Ice Cream/Gelato (Italian for ice-cream) β They are primarily same with just a little difference in composition of milk, custard, water, and eggs. In India, frozen desserts are prepared with thick full cream milk and fruit pulp or crushed nuts and saffron. It is popularly known as βKulfiβ. Kulfi is served on stick or in terracotta pot called βMatkaβ."
},
{
"code": null,
"e": 48101,
"s": 47885,
"text": "Sorbet β It is a frozen dessert made of fruit juices, dessert wines, and ice shaves. It is flavored by a variety of edible food colors and essences. In contrast to ice cream, frozen dessert appears icier than milky."
},
{
"code": null,
"e": 48241,
"s": 48101,
"text": "Frozen Yogurt β It is made by freezing flavored yogurt. It also contains less fat, sugar, and thus less calories as compared to ice creams."
},
{
"code": null,
"e": 48483,
"s": 48241,
"text": "This menu includes variants of tea and coffee, hot chocolate, juices, milkshakes, mocktails, and so on. The wine menu includes wines, beers, liquors, types of water, cocktails, and spirits with their respective serving quantities and prices."
},
{
"code": null,
"e": 48605,
"s": 48483,
"text": "Beverage is any liquid consumed by humans for quenching thirst, or merely for pleasure. Beverages come in various types β"
},
{
"code": null,
"e": 48653,
"s": 48605,
"text": "There are two types of non-alcoholic beverages."
},
{
"code": null,
"e": 48822,
"s": 48653,
"text": "These are served hot. Hot beverages typically include tea, masala tea (spiced tea), milk, hot chocolate, and variants of coffee such as expresso, latte, and cappuccino."
},
{
"code": null,
"e": 49068,
"s": 48822,
"text": "These are served and consumed while chilled. Cold beverages include juices, mocktails, coolers, cold versions of tea and coffee, milkshakes, carbonated drinks, mocktails, and sherbets. The following beverages are famous in countries like India β"
},
{
"code": null,
"e": 49125,
"s": 49068,
"text": "Buttermilk with a dash of powdered cumin seeds and salt."
},
{
"code": null,
"e": 49182,
"s": 49125,
"text": "Buttermilk with a dash of powdered cumin seeds and salt."
},
{
"code": null,
"e": 49257,
"s": 49182,
"text": "Aam Panna, a sweet and sour raw mango juice with a dash of cardamom in it."
},
{
"code": null,
"e": 49332,
"s": 49257,
"text": "Aam Panna, a sweet and sour raw mango juice with a dash of cardamom in it."
},
{
"code": null,
"e": 49382,
"s": 49332,
"text": "Tender coconut water locally called Nariyal-Pani."
},
{
"code": null,
"e": 49432,
"s": 49382,
"text": "Tender coconut water locally called Nariyal-Pani."
},
{
"code": null,
"e": 49512,
"s": 49432,
"text": "Sol Kadhi, thin coconut milk flavored with Kokum and ginger-garlic-chili paste."
},
{
"code": null,
"e": 49592,
"s": 49512,
"text": "Sol Kadhi, thin coconut milk flavored with Kokum and ginger-garlic-chili paste."
},
{
"code": null,
"e": 49679,
"s": 49592,
"text": "There are a few cold beverages which come as cocktails and are prepared using alcohol."
},
{
"code": null,
"e": 50000,
"s": 49679,
"text": "These are served cold. Alcoholic beverages are intoxicating and contain ethanol, commonly known as alcohol. Such beverages need to undergo fermentation and distillation to generate alcohol contents. The percentage of alcohol varies in the range of 0.5% to 95% depending upon the methods of fermentation and distillation."
},
{
"code": null,
"e": 50058,
"s": 50000,
"text": "Wine, Cider, Perry, and Champaign are fermented alcohols."
},
{
"code": null,
"e": 50116,
"s": 50058,
"text": "Wine, Cider, Perry, and Champaign are fermented alcohols."
},
{
"code": null,
"e": 50172,
"s": 50116,
"text": "Beer, ale, and lager are fermented and brewed alcohols."
},
{
"code": null,
"e": 50228,
"s": 50172,
"text": "Beer, ale, and lager are fermented and brewed alcohols."
},
{
"code": null,
"e": 50297,
"s": 50228,
"text": "Gin, Vodka, Whisky, Rum, Brandy, and Tequila are distilled alcohols."
},
{
"code": null,
"e": 50366,
"s": 50297,
"text": "Gin, Vodka, Whisky, Rum, Brandy, and Tequila are distilled alcohols."
},
{
"code": null,
"e": 50674,
"s": 50366,
"text": "If a beverage contains at least 20% Alcohol by Volume (ABV), it is called spirit. Liquors are similar to spirits. The only difference is that liquors come with added sweetness and flavoring. Liquors and spirits, both are strong alcoholic beverages. The following are a few most popular alcoholic beverages β"
},
{
"code": null,
"e": 50878,
"s": 50674,
"text": "Due to the unwanted side effects of alcohol on consumer and the society, it is the responsibility of food and beverage service staff to verify the young customerβs age before serving alcoholic beverages."
},
{
"code": null,
"e": 51296,
"s": 50878,
"text": "The equipment forms an inevitable part of food and beverage service. It plays an important role to build the mood of the guests, to complement the outlet theme, and to elevate guest experience. Right from the largest commodities used for food preparation and interior decoration such as chandeliers or ovens to the smallest piece of cutlery, furniture, or linen participate in creating overall ambience of the outlet."
},
{
"code": null,
"e": 51372,
"s": 51296,
"text": "Let us discuss in detail the equipment used in food and beverage services β"
},
{
"code": null,
"e": 51637,
"s": 51372,
"text": "Furniture is an important part of any F&B Services outlet. It needs to be strong, easy to use and clean. The furniture plays an important role in bringing the look and creating an ambience of the outlet. The furniture, fixtures, and fittings are fixed commodities."
},
{
"code": null,
"e": 51713,
"s": 51637,
"text": "It mainly consists of tables, chairs, push-down chairs, racks, and lockers."
},
{
"code": null,
"e": 51863,
"s": 51713,
"text": "It needs to be sturdy as well as attractive. It includes coffee tables and chairs, bar chairs, dining sets, day beds, loungers, hammocks, and swings."
},
{
"code": null,
"e": 52046,
"s": 51863,
"text": "A fixture is any item bolted to the floor or walls. For example, air conditioners, electric plugs, sinks and toilets, art pieces, and television screens mounted on wall are fixtures."
},
{
"code": null,
"e": 52201,
"s": 52046,
"text": "A fitting is any free standing item or an item that can be hung by a nail or hook. For example, paintings, mirrors, curtain rails, and lamps are fittings."
},
{
"code": null,
"e": 52390,
"s": 52201,
"text": "Tableware consists of crockery, cutlery, glassware and linen used while serving and eating meals at a table. These are circulating equipment which can be grouped into the following types β"
},
{
"code": null,
"e": 52570,
"s": 52390,
"text": "This is a collection of fine dishes, bowls, food platters, section dishes, ramekins, cups and saucers, soup spoons, vases, and ash trays made using a translucent ceramic material."
},
{
"code": null,
"e": 52754,
"s": 52570,
"text": "This consists of containers such as serving bowls, pots, kettles, ice jugs, and water. These containers are either made from glass or metals such as copper, brass, or stainless steel."
},
{
"code": null,
"e": 52886,
"s": 52754,
"text": "This consists of articles made of fine glass. Glassware includes jugs, pitchers, drinkware, ash trays, vases, and similar articles."
},
{
"code": null,
"e": 53172,
"s": 52886,
"text": "The objects in silverware are made of Electro Plated Nickel Silver (EPNS). These are made from an alloy of brass, zinc, stainless steel or nickel with silver plating of 10 to 15 microns. Silverware includes spoons, forks, knives, hollowware, drinkware, tongs, ice bucket, and a salver."
},
{
"code": null,
"e": 53324,
"s": 53172,
"text": "These are food warming dishes. They keep the food warm for an adequate time and temperature. They come in two variants: electric or chafer fuel candle."
},
{
"code": null,
"e": 53540,
"s": 53324,
"text": "Chaffing dishes are available in multiple sizes, shapes, and lids. Modern-day chafing dishes are made of light metal or ceramic with handles, sometimes covered with a see-through lid. Here are some chaffing dishes β"
},
{
"code": null,
"e": 53767,
"s": 53540,
"text": "Cutlery comprises of any hand-held implement for eating or serving food. It includes various spoons, forks, knives, and tongs. It is also called silverware or flatware. Cutlery is made of metals like stainless steel or silver."
},
{
"code": null,
"e": 53902,
"s": 53767,
"text": "In modern days, cutlery has come up in wonderful combinations β spife (spoon + knife), spork (spoon + fork), and knork (knife + fork)."
},
{
"code": null,
"e": 54101,
"s": 53902,
"text": "There are different types of spoons for serving or eating different kinds of food. The forks often accompany spoons or help independently to pick food bites. The knives are used to portion the food."
},
{
"code": null,
"e": 54351,
"s": 54101,
"text": "Dinner Spoon (Table Spoon) β It has elongated round cup. It is used to eat main course food items. It can pick up just the right amount of rice, stew, or curry. It is always paired with a fork (with four tines) of the same length or a dessert knife."
},
{
"code": null,
"e": 54601,
"s": 54351,
"text": "Dinner Spoon (Table Spoon) β It has elongated round cup. It is used to eat main course food items. It can pick up just the right amount of rice, stew, or curry. It is always paired with a fork (with four tines) of the same length or a dessert knife."
},
{
"code": null,
"e": 54728,
"s": 54601,
"text": "Dessert Spoon, Dessert Knife, and Dessert Fork β These are smaller than their main course peers and are used to have desserts."
},
{
"code": null,
"e": 54855,
"s": 54728,
"text": "Dessert Spoon, Dessert Knife, and Dessert Fork β These are smaller than their main course peers and are used to have desserts."
},
{
"code": null,
"e": 54957,
"s": 54855,
"text": "Soup Spoon β It has a round cup bigger than that of the table spoon. It is as long as a dinner spoon."
},
{
"code": null,
"e": 55059,
"s": 54957,
"text": "Soup Spoon β It has a round cup bigger than that of the table spoon. It is as long as a dinner spoon."
},
{
"code": null,
"e": 55190,
"s": 55059,
"text": "Tea/Coffee Spoons β These are smaller than the dessert spoon in length and size of cup. We use these spoons to stir tea or coffee."
},
{
"code": null,
"e": 55321,
"s": 55190,
"text": "Tea/Coffee Spoons β These are smaller than the dessert spoon in length and size of cup. We use these spoons to stir tea or coffee."
},
{
"code": null,
"e": 55422,
"s": 55321,
"text": "Sugar Spoon β It has a flower shaped round cup. It is used to take sugar from sugar bowl of tea set."
},
{
"code": null,
"e": 55523,
"s": 55422,
"text": "Sugar Spoon β It has a flower shaped round cup. It is used to take sugar from sugar bowl of tea set."
},
{
"code": null,
"e": 55749,
"s": 55523,
"text": "Ice Cream Spoon β It is a small spoon with flat rim that can help to cut the right amount of ice cream. It can come in small, medium, and large sizes according to the quantity of the ice cream served and the size of the bowl."
},
{
"code": null,
"e": 55975,
"s": 55749,
"text": "Ice Cream Spoon β It is a small spoon with flat rim that can help to cut the right amount of ice cream. It can come in small, medium, and large sizes according to the quantity of the ice cream served and the size of the bowl."
},
{
"code": null,
"e": 56096,
"s": 55975,
"text": "Cocktail (Soda) Spoon β It is a drink spoon with a long handle that helps the spoon to reach the bottom of a tall glass."
},
{
"code": null,
"e": 56217,
"s": 56096,
"text": "Cocktail (Soda) Spoon β It is a drink spoon with a long handle that helps the spoon to reach the bottom of a tall glass."
},
{
"code": null,
"e": 56408,
"s": 56217,
"text": "Butter knife β It has short rectangular blade that is sharp on the lower side to form an edge. It is useful in cutting semi-firm pieces of butter and apply them on food items such as breads."
},
{
"code": null,
"e": 56599,
"s": 56408,
"text": "Butter knife β It has short rectangular blade that is sharp on the lower side to form an edge. It is useful in cutting semi-firm pieces of butter and apply them on food items such as breads."
},
{
"code": null,
"e": 56703,
"s": 56599,
"text": "Salad Spoon β It is always used in pair with salad fork. It helps mixing and serving salad efficiently."
},
{
"code": null,
"e": 56807,
"s": 56703,
"text": "Salad Spoon β It is always used in pair with salad fork. It helps mixing and serving salad efficiently."
},
{
"code": null,
"e": 56892,
"s": 56807,
"text": "Serving Spoon β It is a spoon with large round cup designed to serve stews and rice."
},
{
"code": null,
"e": 56977,
"s": 56892,
"text": "Serving Spoon β It is a spoon with large round cup designed to serve stews and rice."
},
{
"code": null,
"e": 57074,
"s": 56977,
"text": "Deli (Fruit) Fork β has two tines. It helps to pick thinly sliced food such as slices of fruits."
},
{
"code": null,
"e": 57171,
"s": 57074,
"text": "Deli (Fruit) Fork β has two tines. It helps to pick thinly sliced food such as slices of fruits."
},
{
"code": null,
"e": 57300,
"s": 57171,
"text": "Roast Fork β It is the largest fork. It has longer and stronger tines that help to hold and pick large meat or vegetable pieces."
},
{
"code": null,
"e": 57429,
"s": 57300,
"text": "Roast Fork β It is the largest fork. It has longer and stronger tines that help to hold and pick large meat or vegetable pieces."
},
{
"code": null,
"e": 57546,
"s": 57429,
"text": "Cake Knife β It is a flat, elongated triangle-shaped knife and is used to cut pieces of cake and handle it smoothly."
},
{
"code": null,
"e": 57663,
"s": 57546,
"text": "Cake Knife β It is a flat, elongated triangle-shaped knife and is used to cut pieces of cake and handle it smoothly."
},
{
"code": null,
"e": 57857,
"s": 57663,
"text": "The glasses and tumblers come in a wide variety of shapes and sizes. They are either footed with stem or non-footed. They can also be high-ball or low-ball. Some of the widely used shapes are β"
},
{
"code": null,
"e": 57916,
"s": 57857,
"text": "Cooler β It is used to serve welcome drinks or appetizers."
},
{
"code": null,
"e": 57975,
"s": 57916,
"text": "Cooler β It is used to serve welcome drinks or appetizers."
},
{
"code": null,
"e": 58052,
"s": 57975,
"text": "Flute β It is a glass with a long cup and is mainly used to serve champagne."
},
{
"code": null,
"e": 58129,
"s": 58052,
"text": "Flute β It is a glass with a long cup and is mainly used to serve champagne."
},
{
"code": null,
"e": 58284,
"s": 58129,
"text": "Goblet β It is a round glass with or without stem. The goblets with stem are used to serve wines and brandy. A non-footed version is used to serve whisky."
},
{
"code": null,
"e": 58439,
"s": 58284,
"text": "Goblet β It is a round glass with or without stem. The goblets with stem are used to serve wines and brandy. A non-footed version is used to serve whisky."
},
{
"code": null,
"e": 58572,
"s": 58439,
"text": "Margarita β It is a variant of goblet with a wide round dish-like cup. Margarita is used as a cocktail, mocktail, or a sorbet glass."
},
{
"code": null,
"e": 58705,
"s": 58572,
"text": "Margarita β It is a variant of goblet with a wide round dish-like cup. Margarita is used as a cocktail, mocktail, or a sorbet glass."
},
{
"code": null,
"e": 58738,
"s": 58705,
"text": "Mug β It is used to serve beers."
},
{
"code": null,
"e": 58771,
"s": 58738,
"text": "Mug β It is used to serve beers."
},
{
"code": null,
"e": 58849,
"s": 58771,
"text": "Nonic Glass β It is a tall glass with a broad rim. It is used to serve beers."
},
{
"code": null,
"e": 58927,
"s": 58849,
"text": "Nonic Glass β It is a tall glass with a broad rim. It is used to serve beers."
},
{
"code": null,
"e": 59074,
"s": 58927,
"text": "Pilsner β It is a high-ball glass used to serve cold coffee, iced tea, juices, and beer. A pilsner can support beers or aerated drinks gracefully."
},
{
"code": null,
"e": 59221,
"s": 59074,
"text": "Pilsner β It is a high-ball glass used to serve cold coffee, iced tea, juices, and beer. A pilsner can support beers or aerated drinks gracefully."
},
{
"code": null,
"e": 59293,
"s": 59221,
"text": "Pint β It is a glass used to pour distilled alcohol into other glasses."
},
{
"code": null,
"e": 59365,
"s": 59293,
"text": "Pint β It is a glass used to pour distilled alcohol into other glasses."
},
{
"code": null,
"e": 59562,
"s": 59365,
"text": "Shot Glass β It is a small glass used to consume fermented or distilled alcohol directly. It can also be used to pour distilled alcohol into other glasses for mixing with water or sparkling water."
},
{
"code": null,
"e": 59759,
"s": 59562,
"text": "Shot Glass β It is a small glass used to consume fermented or distilled alcohol directly. It can also be used to pour distilled alcohol into other glasses for mixing with water or sparkling water."
},
{
"code": null,
"e": 59798,
"s": 59759,
"text": "Snifter β It is used to serve spirits."
},
{
"code": null,
"e": 59837,
"s": 59798,
"text": "Snifter β It is used to serve spirits."
},
{
"code": null,
"e": 60029,
"s": 59837,
"text": "Thistle Glass β Its silhouette is shaped like a thistle flower. These glasses have tapered broad rims with round cups attached to a stem and disk. It is used to serve ales and aerated drinks."
},
{
"code": null,
"e": 60221,
"s": 60029,
"text": "Thistle Glass β Its silhouette is shaped like a thistle flower. These glasses have tapered broad rims with round cups attached to a stem and disk. It is used to serve ales and aerated drinks."
},
{
"code": null,
"e": 60284,
"s": 60221,
"text": "Tulip Glass β It is used to serve beer, cocktail, or mocktail."
},
{
"code": null,
"e": 60347,
"s": 60284,
"text": "Tulip Glass β It is used to serve beer, cocktail, or mocktail."
},
{
"code": null,
"e": 60437,
"s": 60347,
"text": "The linen at any food and beverage service outlet is either disposable or non-disposable."
},
{
"code": null,
"e": 60824,
"s": 60437,
"text": "This includes items that can be used only once. These items are made of recycled paper with high absorbing capacity. For example, table napkins, restroom tissues, wrappers, and facial tissues. Facial tissues soaked in Cologne water are given to the guests. It is considered a good welcome gesture. Disposable table linen is usually offered to guests in trains or aircrafts before meals."
},
{
"code": null,
"e": 61038,
"s": 60824,
"text": "The items in this category are made from flax. This includes table cover, dinner napkins, tea napkins, and table runners. Non-disposable linen must be clean and pleasantly scented. It must be starched if required."
},
{
"code": null,
"e": 61285,
"s": 61038,
"text": "Non-Disposable linen must be placed on the table tidily. The staff can fold them and arrange them in decorative shapes or just put them through decorative linen rings to catch guestsβ eyes and start imparting warm experience to them at the table."
},
{
"code": null,
"e": 61696,
"s": 61285,
"text": "Pantry is the adjoining area or room to the kitchen from where the finished food or a drink is ready to be served. This area serves as an ancillary capacity of the kitchen. The food is given final touch-up for presentation, and then handed over to the serving staff. The pantry is often equipped with a sink attached with normal water and hot water taps. The pantry mainly keeps the following necessary items β"
},
{
"code": null,
"e": 61709,
"s": 61696,
"text": "Refrigerator"
},
{
"code": null,
"e": 61723,
"s": 61709,
"text": "Electric oven"
},
{
"code": null,
"e": 61731,
"s": 61723,
"text": "Toaster"
},
{
"code": null,
"e": 61754,
"s": 61731,
"text": "Coffee Brewing Machine"
},
{
"code": null,
"e": 61762,
"s": 61754,
"text": "Blender"
},
{
"code": null,
"e": 61782,
"s": 61762,
"text": "Electric food whisk"
},
{
"code": null,
"e": 61809,
"s": 61782,
"text": "Knives and chopping boards"
},
{
"code": null,
"e": 61871,
"s": 61809,
"text": "Hollowware like casserole, bowls, and dishes of various sizes"
},
{
"code": null,
"e": 61880,
"s": 61871,
"text": "Crockery"
},
{
"code": null,
"e": 61890,
"s": 61880,
"text": "Drinkware"
},
{
"code": null,
"e": 61898,
"s": 61890,
"text": "Cutlery"
},
{
"code": null,
"e": 62053,
"s": 61898,
"text": "Sideboards are mainly shelves with drawers. These can be used to store hollowware and glassware. The following are the different varieties of sideboards β"
},
{
"code": null,
"e": 62099,
"s": 62053,
"text": "Buffet β It has high legs than the sideboard."
},
{
"code": null,
"e": 62145,
"s": 62099,
"text": "Buffet β It has high legs than the sideboard."
},
{
"code": null,
"e": 62238,
"s": 62145,
"text": "Credenza β They are the storage cabinets without legs. They mostly have sliding glass doors."
},
{
"code": null,
"e": 62331,
"s": 62238,
"text": "Credenza β They are the storage cabinets without legs. They mostly have sliding glass doors."
},
{
"code": null,
"e": 62414,
"s": 62331,
"text": "Server β A server is smaller, shorter, and more formal than a buffet or sideboard."
},
{
"code": null,
"e": 62497,
"s": 62414,
"text": "Server β A server is smaller, shorter, and more formal than a buffet or sideboard."
},
{
"code": null,
"e": 62528,
"s": 62497,
"text": "Sideboard β It has short legs."
},
{
"code": null,
"e": 62559,
"s": 62528,
"text": "Sideboard β It has short legs."
},
{
"code": null,
"e": 62929,
"s": 62559,
"text": "It is a serving cart used for serving as well as storing. It has wheels which enable it to move easily around the kitchen. It is also used in elite food and beverage outlets for serving the guests. It is available in various designs, sizes, and shapes. You can choose on number of shelves and sections, and burners. When not in use, it is preferably parked at the wall."
},
{
"code": null,
"e": 63236,
"s": 62929,
"text": "When the food is ready to arrive in the pantry, used utensils for food preparation are cleaned immediately and wiped off dry for later use. If any other ancillary serving item such as electric hand blender is damaged, it is reported to the concerned manager and replaced with a working one at the earliest."
},
{
"code": null,
"e": 63593,
"s": 63236,
"text": "When the guests complete their meals and leave the table, it is required to prepare the table immediately by clearing the used tableware. If any tableware is found broken or damaged, it is reported to the concerned store department and a request is made for its replacement. The table covers and runners are checked and replaced with fresh ones if need be."
},
{
"code": null,
"e": 63862,
"s": 63593,
"text": "The used tableware is handed over to the cleaning and washing staff. The linen is also handed over to the laundry department in the hotel. In case of other F&B Services businesses, the soiled linen can be stored separately and given away to contracted laundry service."
},
{
"code": null,
"e": 64150,
"s": 63862,
"text": "Today, many restaurants use Point-of-Sale (POS) equipment, a computer-based technology to take orders, record them, accept payments, and display or print their receipts. Restaurant servers, bartenders, and cashiers can use POS systems to enter and record food and beverage orders easily."
},
{
"code": null,
"e": 64327,
"s": 64150,
"text": "A POS system in the F&B Services can increase convenience and accuracy in order tracking, and can save time during rush hours. It can smoothly perform the following functions β"
},
{
"code": null,
"e": 64385,
"s": 64327,
"text": "Calculating cash due for every order entered for a table."
},
{
"code": null,
"e": 64418,
"s": 64385,
"text": "Recording the method of payment."
},
{
"code": null,
"e": 64441,
"s": 64418,
"text": "Tracking balance cash."
},
{
"code": null,
"e": 64474,
"s": 64441,
"text": "Creating periodic sales reports."
},
{
"code": null,
"e": 64510,
"s": 64474,
"text": "Calculating labor and payroll data."
},
{
"code": null,
"e": 64558,
"s": 64510,
"text": "Recording daily check averages for each worker."
},
{
"code": null,
"e": 64610,
"s": 64558,
"text": "Tracking the number of balance and sold food items."
},
{
"code": null,
"e": 64653,
"s": 64610,
"text": "Recording information of repeat customers."
},
{
"code": null,
"e": 64967,
"s": 64653,
"text": "The guestsβ experience of food and beverage starts when the serving staff brings beautifully garnished food with the appropriate accompaniments on their table. The service staff turns a guiding hand to the guests in suggesting which accompaniment will go well with the main food the guest is interested in having."
},
{
"code": null,
"e": 65174,
"s": 64967,
"text": "There are numerous interesting pairs of foods with their garnishes or accompaniments. Let us see in detail about garnishing, food accompaniments, and some typical food-garnishing paired with accompaniments."
},
{
"code": null,
"e": 65380,
"s": 65174,
"text": "It is the way of decorating the food or beverage so that it is aesthetically appealing for the guests/customers. It works on the plate. Garnishing also harmonizes color, flavor, and taste of the main dish."
},
{
"code": null,
"e": 65586,
"s": 65380,
"text": "Chopped herbs or small twigs of herbs, leafy vegetables, twirls of carrots or tomatoes, swirls of fresh cream, fruit glaze, chopped nuts, seedless berries, and lemon zest or slices are used for garnishing."
},
{
"code": null,
"e": 65762,
"s": 65586,
"text": "Desserts are garnished with dried fruits, fresh fruit zests, glazes, roasted or candied nuts, frostings, chocolate curls, chocolate coated buts, or small pieces of sugar arts."
},
{
"code": null,
"e": 65962,
"s": 65762,
"text": "Drinks like cocktails and mocktails are garnished using fruit pieces and zests, mint leaves, and castor sugar. Milk based drinks are garnished mostly with fruit pieces, cherries, chocolates, or nuts."
},
{
"code": null,
"e": 66048,
"s": 65962,
"text": "The following are some important Dos and Donβts to be understood in food garnishing β"
},
{
"code": null,
"e": 66086,
"s": 66048,
"text": "Place it where it seems just perfect."
},
{
"code": null,
"e": 66135,
"s": 66086,
"text": "Contrast color schemes work best for garnishing."
},
{
"code": null,
"e": 66193,
"s": 66135,
"text": "Do not overdo garnishing; this overshadows the main food."
},
{
"code": null,
"e": 66219,
"s": 66193,
"text": "Do not reuse the garnish."
},
{
"code": null,
"e": 66246,
"s": 66219,
"text": "Avoid being too elaborate."
},
{
"code": null,
"e": 66557,
"s": 66246,
"text": "There are dishes that come along with accompaniments. These accompaniments complement the main food and enrich its taste. It provides an aesthetic value to the main dish. The accompanying food or beverage itself can have a garnish of its own. An accompaniment can be inside the main dish or in a separate bowl."
},
{
"code": null,
"e": 66617,
"s": 66557,
"text": "The following are a few different types of accompaniments β"
},
{
"code": null,
"e": 66633,
"s": 66617,
"text": "Sauces and Dips"
},
{
"code": null,
"e": 66641,
"s": 66633,
"text": "Pickles"
},
{
"code": null,
"e": 66651,
"s": 66641,
"text": "Dressings"
},
{
"code": null,
"e": 66668,
"s": 66651,
"text": "Chips and Wedges"
},
{
"code": null,
"e": 66675,
"s": 66668,
"text": "Salads"
},
{
"code": null,
"e": 66683,
"s": 66675,
"text": "Gravies"
},
{
"code": null,
"e": 66722,
"s": 66683,
"text": "Beverages such as soft drinks or wines"
},
{
"code": null,
"e": 66729,
"s": 66722,
"text": "Breads"
},
{
"code": null,
"e": 66860,
"s": 66729,
"text": "For example, grilled Hake fish served with potato chips and Pizza served with garlic bread, cheese dip, and a carbonated beverage."
},
{
"code": null,
"e": 66946,
"s": 66860,
"text": "The following are a few popular food items with their garnishing and accompaniments β"
},
{
"code": null,
"e": 67098,
"s": 66946,
"text": "There are no stringent rules for which wine goes well with which cheese but one must observe the following guidelines while pairing wines with cheese β"
},
{
"code": null,
"e": 67155,
"s": 67098,
"text": "Select wine and cheese originating from the same region."
},
{
"code": null,
"e": 67236,
"s": 67155,
"text": "Dessert wines accompanying the desserts must be sweeter than the dessert itself."
},
{
"code": null,
"e": 67282,
"s": 67236,
"text": "Cheeses go well with wines of contrast taste."
},
{
"code": null,
"e": 67520,
"s": 67282,
"text": "Lighter chocolates contain more milk based-products and less chocolate. Chocolates with light and elegant tastes are paired best with light-bodied wines. The ones with more bitter taste are paired with intense flavored full-bodied wines."
},
{
"code": null,
"e": 67784,
"s": 67520,
"text": "A critical standardized recipe is one that, βhas been tried, adapted, and retried several times for use by a given food service operation and has been found to yield the same good results under same procedures, equipment, and quantity and quality of ingredients.β"
},
{
"code": null,
"e": 67883,
"s": 67784,
"text": "Generally, popular menu items are developed using standard recipes, ingredients, and presentation."
},
{
"code": null,
"e": 67943,
"s": 67883,
"text": "A standardized recipe can bring in the following benefits β"
},
{
"code": null,
"e": 67972,
"s": 67943,
"text": "Consistency in food quality."
},
{
"code": null,
"e": 68015,
"s": 67972,
"text": "Consistency in nutrients per unit serving."
},
{
"code": null,
"e": 68050,
"s": 68015,
"text": "Increase in customer satisfaction."
},
{
"code": null,
"e": 68075,
"s": 68050,
"text": "Control on cost of food."
},
{
"code": null,
"e": 68105,
"s": 68075,
"text": "Prediction of accurate yield."
},
{
"code": null,
"e": 68152,
"s": 68105,
"text": "Reduction in food leftover and record keeping."
},
{
"code": null,
"e": 68193,
"s": 68152,
"text": "Increase in the confidence of employees."
},
{
"code": null,
"e": 68266,
"s": 68193,
"text": "A typical standardized recipe is composed of the following description β"
},
{
"code": null,
"e": 68337,
"s": 68266,
"text": "Recipe name/title β It is the name that describes the recipe in brief."
},
{
"code": null,
"e": 68408,
"s": 68337,
"text": "Recipe name/title β It is the name that describes the recipe in brief."
},
{
"code": null,
"e": 68521,
"s": 68408,
"text": "Recipe section β It is the section that the recipe should be classified under (grains, starters, desserts, etc.)"
},
{
"code": null,
"e": 68634,
"s": 68521,
"text": "Recipe section β It is the section that the recipe should be classified under (grains, starters, desserts, etc.)"
},
{
"code": null,
"e": 68698,
"s": 68634,
"text": "Ingredients β Types (fresh/canned/cooked/uncooked/ground, etc.)"
},
{
"code": null,
"e": 68762,
"s": 68698,
"text": "Ingredients β Types (fresh/canned/cooked/uncooked/ground, etc.)"
},
{
"code": null,
"e": 68797,
"s": 68762,
"text": "Weight and measures of ingredients"
},
{
"code": null,
"e": 68832,
"s": 68797,
"text": "Weight and measures of ingredients"
},
{
"code": null,
"e": 69017,
"s": 68832,
"text": "Method β This is a set of instructions to prepare a particular recipe. A method includes guidelines for steps such as mixing, selecting pans, and setting the right cooking temperature."
},
{
"code": null,
"e": 69202,
"s": 69017,
"text": "Method β This is a set of instructions to prepare a particular recipe. A method includes guidelines for steps such as mixing, selecting pans, and setting the right cooking temperature."
},
{
"code": null,
"e": 69273,
"s": 69202,
"text": "Time β This includes preparation time, cooking time, and serving time."
},
{
"code": null,
"e": 69344,
"s": 69273,
"text": "Time β This includes preparation time, cooking time, and serving time."
},
{
"code": null,
"e": 69399,
"s": 69344,
"text": "Serving size β It is the portion of food to be served."
},
{
"code": null,
"e": 69454,
"s": 69399,
"text": "Serving size β It is the portion of food to be served."
},
{
"code": null,
"e": 69622,
"s": 69454,
"text": "Critical Control Points (CCP) β They are control measures taken to avoid food safety hazards. Every CCP includes control of time, preparation, and cooking temperature."
},
{
"code": null,
"e": 69790,
"s": 69622,
"text": "Critical Control Points (CCP) β They are control measures taken to avoid food safety hazards. Every CCP includes control of time, preparation, and cooking temperature."
},
{
"code": null,
"e": 69943,
"s": 69790,
"text": "Predicting the total yield for a particular number of customers and calculating weights of ingredients accordingly is important in standardized recipes."
},
{
"code": null,
"e": 70081,
"s": 69943,
"text": "For recipe to be prepared for new lot of customers, the total yield changes. The new yield can be calculated in the following two steps β"
},
{
"code": null,
"e": 70123,
"s": 70081,
"text": "Step 1 β Calculate conversion factor as β"
},
{
"code": null,
"e": 70166,
"s": 70123,
"text": "Conversion Factor = New Yield / Old Yield\n"
},
{
"code": null,
"e": 70266,
"s": 70166,
"text": "Step 2 β Multiply the measure of each ingredient by the conversion factor to obtain the new yield β"
},
{
"code": null,
"e": 70323,
"s": 70266,
"text": "New Yield = Old ingredient quantity x Conversion factor\n"
},
{
"code": null,
"e": 70499,
"s": 70323,
"text": "Beverages play an important role in accompanying food. Beverages also enhance flavor of main dish and help to cleanse the taste buds in between bites, and complement the dish."
},
{
"code": null,
"e": 70767,
"s": 70499,
"text": "Hot beverages such as hot tea or coffee, and hot chocolate are prepared in the kitchen and generally served from the kitchen pantry. Cold beverages such as mocktails and alcoholic beverages such as spirits, liquors, and cocktails come to the guestsβ tables from bars."
},
{
"code": null,
"e": 71155,
"s": 70767,
"text": "A bar is a place where non-alcoholic and alcoholic beverages are served. It is equipped with a back bar with necessary equipment such as bar tools, and glassware to serve the beverages. The customers sit on tall push-down chairs around the counter. The barmen or barmaids commonly known as bartenders prepare drinks and serve them to the customers. There are some typical types of bars β"
},
{
"code": null,
"e": 71238,
"s": 71155,
"text": "Public β It is a bar in a public house which is open for public and not exclusive."
},
{
"code": null,
"e": 71321,
"s": 71238,
"text": "Public β It is a bar in a public house which is open for public and not exclusive."
},
{
"code": null,
"e": 71356,
"s": 71321,
"text": "Service Bar β It is for the staff."
},
{
"code": null,
"e": 71391,
"s": 71356,
"text": "Service Bar β It is for the staff."
},
{
"code": null,
"e": 71465,
"s": 71391,
"text": "Portable β They are compact bars easy to set up for off-premise catering."
},
{
"code": null,
"e": 71539,
"s": 71465,
"text": "Portable β They are compact bars easy to set up for off-premise catering."
},
{
"code": null,
"e": 71624,
"s": 71539,
"text": "Mini β It is a private bar located in VIP rooms, suites, or penthouses of the hotel."
},
{
"code": null,
"e": 71709,
"s": 71624,
"text": "Mini β It is a private bar located in VIP rooms, suites, or penthouses of the hotel."
},
{
"code": null,
"e": 71773,
"s": 71709,
"text": "The following tools are necessary to serve beverages from bar β"
},
{
"code": null,
"e": 71880,
"s": 71773,
"text": "Bar Linen and Cocktail Napkins β They are used to save work area from any mess while pouring the beverage."
},
{
"code": null,
"e": 71987,
"s": 71880,
"text": "Bar Linen and Cocktail Napkins β They are used to save work area from any mess while pouring the beverage."
},
{
"code": null,
"e": 72079,
"s": 71987,
"text": "Pouring Spouts β They make smooth serving of beverage apportioned equally into the glasses."
},
{
"code": null,
"e": 72171,
"s": 72079,
"text": "Pouring Spouts β They make smooth serving of beverage apportioned equally into the glasses."
},
{
"code": null,
"e": 72269,
"s": 72171,
"text": "Juice Containers β They are useful to save bartending time by keeping most demanded juices handy."
},
{
"code": null,
"e": 72367,
"s": 72269,
"text": "Juice Containers β They are useful to save bartending time by keeping most demanded juices handy."
},
{
"code": null,
"e": 72467,
"s": 72367,
"text": "Cocktail Shaker Tins β They are suitable for mixing the ingredients of cocktails and martinis well."
},
{
"code": null,
"e": 72567,
"s": 72467,
"text": "Cocktail Shaker Tins β They are suitable for mixing the ingredients of cocktails and martinis well."
},
{
"code": null,
"e": 72646,
"s": 72567,
"text": "Short Shaker Tins β They are used to shake small amount of drinks efficiently."
},
{
"code": null,
"e": 72725,
"s": 72646,
"text": "Short Shaker Tins β They are used to shake small amount of drinks efficiently."
},
{
"code": null,
"e": 72791,
"s": 72725,
"text": "Cocktail Strainer β It is used to sieve cocktails before serving."
},
{
"code": null,
"e": 72857,
"s": 72791,
"text": "Cocktail Strainer β It is used to sieve cocktails before serving."
},
{
"code": null,
"e": 72929,
"s": 72857,
"text": "Corkscrew or Wine Opener β They are used to open corks of wine bottles."
},
{
"code": null,
"e": 73001,
"s": 72929,
"text": "Corkscrew or Wine Opener β They are used to open corks of wine bottles."
},
{
"code": null,
"e": 73066,
"s": 73001,
"text": "Bottle Opener β They are used to open caps of bottled beverages."
},
{
"code": null,
"e": 73131,
"s": 73066,
"text": "Bottle Opener β They are used to open caps of bottled beverages."
},
{
"code": null,
"e": 73182,
"s": 73131,
"text": "Jigger β It is an alcohol measuring two-sided cup."
},
{
"code": null,
"e": 73233,
"s": 73182,
"text": "Jigger β It is an alcohol measuring two-sided cup."
},
{
"code": null,
"e": 73283,
"s": 73233,
"text": "Lemon Zester β It is used for cutting lemon zest."
},
{
"code": null,
"e": 73333,
"s": 73283,
"text": "Lemon Zester β It is used for cutting lemon zest."
},
{
"code": null,
"e": 73404,
"s": 73333,
"text": "Bar Spoon β Also called muddler, is used for mixing beverages briefly."
},
{
"code": null,
"e": 73475,
"s": 73404,
"text": "Bar Spoon β Also called muddler, is used for mixing beverages briefly."
},
{
"code": null,
"e": 73561,
"s": 73475,
"text": "Masher β It is used to mash ingredients to help release oils and flavors effectively."
},
{
"code": null,
"e": 73647,
"s": 73561,
"text": "Masher β It is used to mash ingredients to help release oils and flavors effectively."
},
{
"code": null,
"e": 73925,
"s": 73647,
"text": "The Dram Shop Liability in US is the body of law that governs the liability of alcohol stores and the commercial establishments where alcohol is served. This body endeavors to protect the society from the unpleasant outcomes of serving alcohol to minors and intoxicated people."
},
{
"code": null,
"e": 74240,
"s": 73925,
"text": "The legal age of drinking alcohol is different in different countries. The minimum age to purchase and consume alcohol ranges from 16 years to 25 years. In some countries, this age limit varies according to strength of the alcohol, premises of consumption, or whether the young customer is accompanied by an adult."
},
{
"code": null,
"e": 74467,
"s": 74240,
"text": "When the customer looks underage, the beverage serving staff is compelled to ask for the customerβs driving license or any reliable identity card from a well-recognized institution as a proof of age before serving the alcohol."
},
{
"code": null,
"e": 74728,
"s": 74467,
"text": "It is up to the serving staff who has had enough drink as the drunk persons themselves often fail to be composed and know their own state. To keep the account of how much the customers are drinking, the bartenders must use standard measures for pouring drinks."
},
{
"code": null,
"e": 74902,
"s": 74728,
"text": "The bartending staff needs to cut off alcohol service if the customer is on the way of binge drinking and seems not able to handle it. Refusal of alcohol service should be β"
},
{
"code": null,
"e": 74994,
"s": 74902,
"text": "Executed professionally by speaking firmly and clearly with the drunk/under-aged customers."
},
{
"code": null,
"e": 75044,
"s": 74994,
"text": "Denied quietly without notifying other customers."
},
{
"code": null,
"e": 75414,
"s": 75044,
"text": "Imparting an out of the world meal experience requires a lot of preparation beforehand. Food and beverage businesses work to bring out the best possible experience for their guests and customers to achieve maximum customer satisfaction. All operations regarding food and beverage service need preparations by anticipating guest arrival at any time during working hours."
},
{
"code": null,
"e": 75478,
"s": 75414,
"text": "Let us see what all basic preparations are required to be done."
},
{
"code": null,
"e": 75632,
"s": 75478,
"text": "It is the activity of preparing the environment in the F&B Services establishment so that the guests and the service staff find it hygienic and pleasant."
},
{
"code": null,
"e": 75709,
"s": 75632,
"text": "To prepare the environment, the staff carries out the following activities β"
},
{
"code": null,
"e": 75807,
"s": 75709,
"text": "Opening all windows and doors before working hours to let fresh air and sunlight enter the venue."
},
{
"code": null,
"e": 75905,
"s": 75807,
"text": "Opening all windows and doors before working hours to let fresh air and sunlight enter the venue."
},
{
"code": null,
"e": 75967,
"s": 75905,
"text": "Ensuring menu cards and promotional material are presentable."
},
{
"code": null,
"e": 76029,
"s": 75967,
"text": "Ensuring menu cards and promotional material are presentable."
},
{
"code": null,
"e": 76149,
"s": 76029,
"text": "Removing the furniture that needs servicing and handing it over to the maintenance department or any outsourced agency."
},
{
"code": null,
"e": 76269,
"s": 76149,
"text": "Removing the furniture that needs servicing and handing it over to the maintenance department or any outsourced agency."
},
{
"code": null,
"e": 76295,
"s": 76269,
"text": "Vacuuming carpets if any."
},
{
"code": null,
"e": 76321,
"s": 76295,
"text": "Vacuuming carpets if any."
},
{
"code": null,
"e": 76369,
"s": 76321,
"text": "Switching on all lamps to check the fused ones."
},
{
"code": null,
"e": 76417,
"s": 76369,
"text": "Switching on all lamps to check the fused ones."
},
{
"code": null,
"e": 76560,
"s": 76417,
"text": "It is the activity of putting things in place to make the subsequent F&B Services smooth. The serving staff carries out the following duties β"
},
{
"code": null,
"e": 76626,
"s": 76560,
"text": "Removing all soiled linen and replacing them with the fresh ones."
},
{
"code": null,
"e": 76673,
"s": 76626,
"text": "Ensuring that the side board is well-equipped."
},
{
"code": null,
"e": 76733,
"s": 76673,
"text": "Replenishing condiment containers, shakers, and water jugs."
},
{
"code": null,
"e": 76766,
"s": 76733,
"text": "Polishing cutlery and glassware."
},
{
"code": null,
"e": 76810,
"s": 76766,
"text": "Replacing pale flowers with the fresh ones."
},
{
"code": null,
"e": 76999,
"s": 76810,
"text": "It is a piece of furniture with numerous compartments and shelves to keep condiments, water jug or bottles, cutlery, food platters, and linens. Side boards are allocated for every station."
},
{
"code": null,
"e": 77058,
"s": 76999,
"text": "To prepare the side boards, the serving staff must place β"
},
{
"code": null,
"e": 77119,
"s": 77058,
"text": "The replenished containers of water, butter, and condiments."
},
{
"code": null,
"e": 77180,
"s": 77119,
"text": "The replenished containers of water, butter, and condiments."
},
{
"code": null,
"e": 77265,
"s": 77180,
"text": "The dinner plates, side plates, glasses, mugs, and fingerbowls in the lower shelves."
},
{
"code": null,
"e": 77350,
"s": 77265,
"text": "The dinner plates, side plates, glasses, mugs, and fingerbowls in the lower shelves."
},
{
"code": null,
"e": 77407,
"s": 77350,
"text": "The linen, napkins, and dolly papers neatly and stalked."
},
{
"code": null,
"e": 77464,
"s": 77407,
"text": "The linen, napkins, and dolly papers neatly and stalked."
},
{
"code": null,
"e": 77538,
"s": 77464,
"text": "The cutlery in the appropriate sections separately according to the type."
},
{
"code": null,
"e": 77612,
"s": 77538,
"text": "The cutlery in the appropriate sections separately according to the type."
},
{
"code": null,
"e": 77738,
"s": 77612,
"text": "The condiments containers and shakers, water jug, butter dish, toothpick holders, straw holders, on the upper shelf or board."
},
{
"code": null,
"e": 77864,
"s": 77738,
"text": "The condiments containers and shakers, water jug, butter dish, toothpick holders, straw holders, on the upper shelf or board."
},
{
"code": null,
"e": 78146,
"s": 77864,
"text": "Ice and water are the preliminary requirements of any food and beverage service establishment. Clean drinkable water is obtained from the water purifiers installed in the service establishment. The purifiers are selected such that they can cater to large number of people per hour."
},
{
"code": null,
"e": 78398,
"s": 78146,
"text": "Crystal clear ice in the shape of large cubes can be prepared in-house if the size of F&B establishment is large enough to install the required equipment. The ice can also be purchased from an outsourced ice-making business and stored in the freezers."
},
{
"code": null,
"e": 78503,
"s": 78398,
"text": "When the guests are seated, they are first served water at adequate temperature according to the season."
},
{
"code": null,
"e": 78587,
"s": 78503,
"text": "Table setup plays an important role in contributing to the appearance of the table."
},
{
"code": null,
"e": 78641,
"s": 78587,
"text": "Each table cover needs space of 24 to 30 inches wide."
},
{
"code": null,
"e": 78719,
"s": 78641,
"text": "Crockery and cutlery must be placed 2 inches away from the edge of the table."
},
{
"code": null,
"e": 78808,
"s": 78719,
"text": "Knives are placed on the right of the dinner plate whereas forks are placed on the left."
},
{
"code": null,
"e": 78850,
"s": 78808,
"text": "Butter knife is placed on the side plate."
},
{
"code": null,
"e": 78908,
"s": 78850,
"text": "The cutting edge of the knives must be towards the plate."
},
{
"code": null,
"e": 78973,
"s": 78908,
"text": "Table napkin must be neatly folded and placed on the side plate."
},
{
"code": null,
"e": 79161,
"s": 78973,
"text": "This type of table setup is required for formal events like corporate lunch or dinner, or a wedding party. The formal dining contains multiple courses and second helpings are not offered."
},
{
"code": null,
"e": 79197,
"s": 79161,
"text": "This table setup looks as follows β"
},
{
"code": null,
"e": 79461,
"s": 79197,
"text": "This table setup is required for informal events like holiday parties and family gatherings. Casual dining can contain multiple courses and service staff offers or serves second rounds of helping when a guest requests for it. This table setup appears as follows β"
},
{
"code": null,
"e": 79659,
"s": 79461,
"text": "This set up is required for catering to large groups of people. Buffet table setting can be done in numerous ways depending upon the size and shape of the place, the menu, and the number of guests."
},
{
"code": null,
"e": 79771,
"s": 79659,
"text": "The food items are placed in a sequence from lightest to heaviest, starters to desserts, or coolest to warmest."
},
{
"code": null,
"e": 79810,
"s": 79771,
"text": "Cutlery is placed on the guest tables."
},
{
"code": null,
"e": 79889,
"s": 79810,
"text": "Glasses, cups, and saucers are placed on a separate table to avoid congestion."
},
{
"code": null,
"e": 79977,
"s": 79889,
"text": "Table decoration pieces are placed such that they do not interfere with the food items."
},
{
"code": null,
"e": 80031,
"s": 79977,
"text": "Plates are stacked not more than 15 plates per stack."
},
{
"code": null,
"e": 80076,
"s": 80031,
"text": "Paper napkins are placed between the plates."
},
{
"code": null,
"e": 80368,
"s": 80076,
"text": "The condiments are kept according to the theme of the F&B service. For example, if the establishment is serving Italian food, the staff needs to prepare shakers of dried herbs, salt, and pepper flakes. In European restaurants, they typically keep salt, sugar, and pepper as basic condiments."
},
{
"code": null,
"e": 80492,
"s": 80368,
"text": "When the guests leave the tables, the serving staff needs to check the condiment containers and replenish them if required."
},
{
"code": null,
"e": 80688,
"s": 80492,
"text": "Today, there are large varieties of napkins available in different colors and materials. Paper napkins are used majorly for informal dining whereas for formal dining, linen napkins are preferred."
},
{
"code": null,
"e": 80887,
"s": 80688,
"text": "Napkin can be folded in a number of attractive ways. They can be shaped as a flower, a character, or some object. A well-folded and well-placed napkin on the plate grabs the attention of the guests."
},
{
"code": null,
"e": 81219,
"s": 80887,
"text": "Presentation of a food or beverage is equally important as its recipe as the other senses are stimulated through sight and aroma. A well-prepared dish is complete only when it is presented with beautiful garnish in an appropriate food container or platter. The serving staff must follow the basic guidelines for food presentation β"
},
{
"code": null,
"e": 81269,
"s": 81219,
"text": "It must be presented at the required temperature."
},
{
"code": null,
"e": 81319,
"s": 81269,
"text": "It must be presented at the required temperature."
},
{
"code": null,
"e": 81371,
"s": 81319,
"text": "It must be presented according to the serving size."
},
{
"code": null,
"e": 81423,
"s": 81371,
"text": "It must be presented according to the serving size."
},
{
"code": null,
"e": 81488,
"s": 81423,
"text": "It must be presented in appropriate hollowware of suitable size."
},
{
"code": null,
"e": 81553,
"s": 81488,
"text": "It must be presented in appropriate hollowware of suitable size."
},
{
"code": null,
"e": 81704,
"s": 81553,
"text": "It is also recommended to serve food with the right garnish that adds to the catchiness of the dish. The garnish in contrast color is quite appealing."
},
{
"code": null,
"e": 81855,
"s": 81704,
"text": "It is also recommended to serve food with the right garnish that adds to the catchiness of the dish. The garnish in contrast color is quite appealing."
},
{
"code": null,
"e": 81921,
"s": 81855,
"text": "The garnish or accompaniment should not overshadow the main food."
},
{
"code": null,
"e": 81987,
"s": 81921,
"text": "The garnish or accompaniment should not overshadow the main food."
},
{
"code": null,
"e": 82142,
"s": 81987,
"text": "The cook needs to be creative at presenting the dish so well that the final result comes out as a treat for not only the taste buds but also for the eyes."
},
{
"code": null,
"e": 82470,
"s": 82142,
"text": "Beverage presentation gains a lot of importance in todayβs world. Beverages taste good if they are presented at the temperature at which they are meant to have. Right from selecting the appropriate service glassware, creating various pleasant color schemes of the ingredients, and serving the beverage with creative ideas pays."
},
{
"code": null,
"e": 82726,
"s": 82470,
"text": "For example, the coconut water from a tender coconut can be served in the neatly cut and clean tender coconut itself from which it is taken out. Also, mocktails or cocktails can be presented with straws and slices of fruits in different shapes and colors."
},
{
"code": null,
"e": 83029,
"s": 82726,
"text": "When few tasks in an organization are required to be conducted repetitively, it is a good idea to generate a set of Standard Operating Procedures (SOPs). These make the tasks in hand easy and effective, and save a great deal of time and effort. SOPs also help to train the staff and avoid silly errors."
},
{
"code": null,
"e": 83104,
"s": 83029,
"text": "Let us understand a few important SOPs set in F&B service establishments β"
},
{
"code": null,
"e": 83134,
"s": 83104,
"text": "The procedure is as follows β"
},
{
"code": null,
"e": 83226,
"s": 83134,
"text": "Check the table linen for cleanliness and spread it on the table neatly to remove wrinkles."
},
{
"code": null,
"e": 83318,
"s": 83226,
"text": "Check the table linen for cleanliness and spread it on the table neatly to remove wrinkles."
},
{
"code": null,
"e": 83362,
"s": 83318,
"text": "Replace the table soiled linen if required."
},
{
"code": null,
"e": 83406,
"s": 83362,
"text": "Replace the table soiled linen if required."
},
{
"code": null,
"e": 83482,
"s": 83406,
"text": "Ensure the dining type before the setting table layout: Formal or Informal."
},
{
"code": null,
"e": 83558,
"s": 83482,
"text": "Ensure the dining type before the setting table layout: Formal or Informal."
},
{
"code": null,
"e": 83617,
"s": 83558,
"text": "For a formal table setup, place the tableware as follows β"
},
{
"code": null,
"e": 83685,
"s": 83617,
"text": "Place the dinner plate one inch from the table edge near the chair."
},
{
"code": null,
"e": 83753,
"s": 83685,
"text": "Place the dinner plate one inch from the table edge near the chair."
},
{
"code": null,
"e": 83799,
"s": 83753,
"text": "Place the salad plate above the dinner plate."
},
{
"code": null,
"e": 83845,
"s": 83799,
"text": "Place the salad plate above the dinner plate."
},
{
"code": null,
"e": 83983,
"s": 83845,
"text": "Place the forks on left of the dinner plate. Arrange the forks according to their size with the largest fork nearest to the dinner plate."
},
{
"code": null,
"e": 84121,
"s": 83983,
"text": "Place the forks on left of the dinner plate. Arrange the forks according to their size with the largest fork nearest to the dinner plate."
},
{
"code": null,
"e": 84260,
"s": 84121,
"text": "Place the spoons and knives on the right side of the dinner plate according to their size with the largest spoon and knife near the plate."
},
{
"code": null,
"e": 84399,
"s": 84260,
"text": "Place the spoons and knives on the right side of the dinner plate according to their size with the largest spoon and knife near the plate."
},
{
"code": null,
"e": 84462,
"s": 84399,
"text": "Place the dessert spoon and fork above the plate horizontally."
},
{
"code": null,
"e": 84525,
"s": 84462,
"text": "Place the dessert spoon and fork above the plate horizontally."
},
{
"code": null,
"e": 84587,
"s": 84525,
"text": "Place the quarter plate on the left side of the dinner plate."
},
{
"code": null,
"e": 84649,
"s": 84587,
"text": "Place the quarter plate on the left side of the dinner plate."
},
{
"code": null,
"e": 84731,
"s": 84649,
"text": "Place the water and the wine glasses on the top-right corner of the dinner plate."
},
{
"code": null,
"e": 84813,
"s": 84731,
"text": "Place the water and the wine glasses on the top-right corner of the dinner plate."
},
{
"code": null,
"e": 84883,
"s": 84813,
"text": "Shape the clean linen aesthetically and place it on the extreme left."
},
{
"code": null,
"e": 84953,
"s": 84883,
"text": "Shape the clean linen aesthetically and place it on the extreme left."
},
{
"code": null,
"e": 85015,
"s": 84953,
"text": "For an informal table setup, place the tableware as follows β"
},
{
"code": null,
"e": 85085,
"s": 85015,
"text": "Place the dinner plate one inch inside the table edge near the chair."
},
{
"code": null,
"e": 85209,
"s": 85085,
"text": "Place the forks on the left side in descending order of their size with the largest fork to be closest to the dinner plate."
},
{
"code": null,
"e": 85272,
"s": 85209,
"text": "Place dinner spoon and knife on the dinner plateβs right side."
},
{
"code": null,
"e": 85348,
"s": 85272,
"text": "Place water and the wine glasses on the top-right side of the dinner plate."
},
{
"code": null,
"e": 85449,
"s": 85348,
"text": "Shape the clean linen aesthetically and place it on the extreme left on the top of the dinner plate."
},
{
"code": null,
"e": 85592,
"s": 85449,
"text": "The staff members who handle the telephone calls must be thoroughly aware of the work system. The procedure for handling calls is as follows β"
},
{
"code": null,
"e": 85706,
"s": 85592,
"text": "Always answer the phone call promptly, within three rings. If it takes time to answer, apologize to the customer."
},
{
"code": null,
"e": 85820,
"s": 85706,
"text": "Always answer the phone call promptly, within three rings. If it takes time to answer, apologize to the customer."
},
{
"code": null,
"e": 85891,
"s": 85820,
"text": "Speak with the caller attentively by avoiding any distractions around."
},
{
"code": null,
"e": 85962,
"s": 85891,
"text": "Speak with the caller attentively by avoiding any distractions around."
},
{
"code": null,
"e": 86045,
"s": 85962,
"text": "Always inform the caller before transferring his call and putting him/her on hold."
},
{
"code": null,
"e": 86128,
"s": 86045,
"text": "Always inform the caller before transferring his call and putting him/her on hold."
},
{
"code": null,
"e": 86232,
"s": 86128,
"text": "Always talk politely and respectfully to the customers by addressing women as βMadamβ and men as βSirβ."
},
{
"code": null,
"e": 86336,
"s": 86232,
"text": "Always talk politely and respectfully to the customers by addressing women as βMadamβ and men as βSirβ."
},
{
"code": null,
"e": 86431,
"s": 86336,
"text": "Ensure that you solve all the customer queries before terminating the telephonic conversation."
},
{
"code": null,
"e": 86526,
"s": 86431,
"text": "Ensure that you solve all the customer queries before terminating the telephonic conversation."
},
{
"code": null,
"e": 86586,
"s": 86526,
"text": "Speak clearly with a cooperative tone; do not speak loudly."
},
{
"code": null,
"e": 86646,
"s": 86586,
"text": "Speak clearly with a cooperative tone; do not speak loudly."
},
{
"code": null,
"e": 86796,
"s": 86646,
"text": "Avoid domain jargons and informal words such as βYupβ, βhang-onβ or yeah.β Instead, use formal words such as βabsolutelyβ, βplease waitβ, βYesβ, etc."
},
{
"code": null,
"e": 86946,
"s": 86796,
"text": "Avoid domain jargons and informal words such as βYupβ, βhang-onβ or yeah.β Instead, use formal words such as βabsolutelyβ, βplease waitβ, βYesβ, etc."
},
{
"code": null,
"e": 87021,
"s": 86946,
"text": "Always end the phone call by saying, βThank you for calling (sir/madam)!β."
},
{
"code": null,
"e": 87096,
"s": 87021,
"text": "Always end the phone call by saying, βThank you for calling (sir/madam)!β."
},
{
"code": null,
"e": 87232,
"s": 87096,
"text": "The orders for table reservation or food delivery can be taken on phone. Direct service orders are placed and taken to the guest table."
},
{
"code": null,
"e": 87400,
"s": 87232,
"text": "While taking orders on phone, the visual channel of communication is absent. Hence the staff needs to listen to the caller attentively while taking order on the phone."
},
{
"code": null,
"e": 87568,
"s": 87400,
"text": "Answer the customerβs call immediately and take the communication further cordially by saying, βGood (morning/afternoon/evening), I am (own name); How can I help you?β"
},
{
"code": null,
"e": 87736,
"s": 87568,
"text": "Answer the customerβs call immediately and take the communication further cordially by saying, βGood (morning/afternoon/evening), I am (own name); How can I help you?β"
},
{
"code": null,
"e": 87852,
"s": 87736,
"text": "Pay a complete ear to the customerβs requirement of food, beverage, table reservation, or any specific requirement."
},
{
"code": null,
"e": 87968,
"s": 87852,
"text": "Pay a complete ear to the customerβs requirement of food, beverage, table reservation, or any specific requirement."
},
{
"code": null,
"e": 88010,
"s": 87968,
"text": "Note down the order details on a notepad."
},
{
"code": null,
"e": 88052,
"s": 88010,
"text": "Note down the order details on a notepad."
},
{
"code": null,
"e": 88254,
"s": 88052,
"text": "Inform the customer about time estimation of delivery if it is home delivery order. If it is table reservation, confirm the timing of customerβs arrival and the total number of persons to the customer."
},
{
"code": null,
"e": 88456,
"s": 88254,
"text": "Inform the customer about time estimation of delivery if it is home delivery order. If it is table reservation, confirm the timing of customerβs arrival and the total number of persons to the customer."
},
{
"code": null,
"e": 88516,
"s": 88456,
"text": "Repeat the order to the customer and take his confirmation."
},
{
"code": null,
"e": 88576,
"s": 88516,
"text": "Repeat the order to the customer and take his confirmation."
},
{
"code": null,
"e": 88672,
"s": 88576,
"text": "Ask for the address or confirm the address and contact number if it is already in the database."
},
{
"code": null,
"e": 88768,
"s": 88672,
"text": "Ask for the address or confirm the address and contact number if it is already in the database."
},
{
"code": null,
"e": 88849,
"s": 88768,
"text": "End the conversation by greeting the customer and assuring him the best service."
},
{
"code": null,
"e": 88930,
"s": 88849,
"text": "End the conversation by greeting the customer and assuring him the best service."
},
{
"code": null,
"e": 89162,
"s": 88930,
"text": "Hand over the order to the kitchen staff. Inform the delivery staff member in case of home delivery. Inform the service staff members to prepare a table for the given number of persons and the occasion in case of table reservation."
},
{
"code": null,
"e": 89394,
"s": 89162,
"text": "Hand over the order to the kitchen staff. Inform the delivery staff member in case of home delivery. Inform the service staff members to prepare a table for the given number of persons and the occasion in case of table reservation."
},
{
"code": null,
"e": 89447,
"s": 89394,
"text": "This takes place when the guests are already seated."
},
{
"code": null,
"e": 89494,
"s": 89447,
"text": "Ensure that the guests are seated comfortably."
},
{
"code": null,
"e": 89541,
"s": 89494,
"text": "Ensure that the guests are seated comfortably."
},
{
"code": null,
"e": 89605,
"s": 89541,
"text": "At the start, offer them welcome drink if any or chilled water."
},
{
"code": null,
"e": 89669,
"s": 89605,
"text": "At the start, offer them welcome drink if any or chilled water."
},
{
"code": null,
"e": 89701,
"s": 89669,
"text": "Offer them food and wine menus."
},
{
"code": null,
"e": 89733,
"s": 89701,
"text": "Offer them food and wine menus."
},
{
"code": null,
"e": 89820,
"s": 89733,
"text": "Greet the guests and ask them courteously, βWhat would you like to have, (Sir/Madam)?β"
},
{
"code": null,
"e": 89907,
"s": 89820,
"text": "Greet the guests and ask them courteously, βWhat would you like to have, (Sir/Madam)?β"
},
{
"code": null,
"e": 89938,
"s": 89907,
"text": "Note down the order carefully."
},
{
"code": null,
"e": 89969,
"s": 89938,
"text": "Note down the order carefully."
},
{
"code": null,
"e": 90191,
"s": 89969,
"text": "Confirm which variant of the food or beverage they wish to have; if there are multiple variants of the same food item. Help the guests by suggesting the beverage or side dish that goes well with the main dish if required."
},
{
"code": null,
"e": 90413,
"s": 90191,
"text": "Confirm which variant of the food or beverage they wish to have; if there are multiple variants of the same food item. Help the guests by suggesting the beverage or side dish that goes well with the main dish if required."
},
{
"code": null,
"e": 90472,
"s": 90413,
"text": "Repeat the items ordered with their respective quantities."
},
{
"code": null,
"e": 90531,
"s": 90472,
"text": "Repeat the items ordered with their respective quantities."
},
{
"code": null,
"e": 90590,
"s": 90531,
"text": "Inform the guest about expected time of the order arrival."
},
{
"code": null,
"e": 90649,
"s": 90590,
"text": "Inform the guest about expected time of the order arrival."
},
{
"code": null,
"e": 90706,
"s": 90649,
"text": "Leave the guest table and send the order to the kitchen."
},
{
"code": null,
"e": 90763,
"s": 90706,
"text": "Leave the guest table and send the order to the kitchen."
},
{
"code": null,
"e": 90895,
"s": 90763,
"text": "Conversation with the guests is the backbone of any service-providing business. The guidelines for conversing with the guests are β"
},
{
"code": null,
"e": 90934,
"s": 90895,
"text": "Keep upright posture and smiling face."
},
{
"code": null,
"e": 90999,
"s": 90934,
"text": "Let them know that you are enthusiastic and eager to serve them."
},
{
"code": null,
"e": 91097,
"s": 90999,
"text": "Be respectful to elderly guests, friendly with the same-age guests, and jovial with the children."
},
{
"code": null,
"e": 91141,
"s": 91097,
"text": "Keep the voice of speech audible and clear."
},
{
"code": null,
"e": 91207,
"s": 91141,
"text": "Apologize if some food item or beverage has run out of the stock."
},
{
"code": null,
"e": 91314,
"s": 91207,
"text": "While the guests are having their meals, make a brief round at the table to observe if everything is fine."
},
{
"code": null,
"e": 91417,
"s": 91314,
"text": "The service staff actually must remain prepared to handle any unforeseen circumstances which include β"
},
{
"code": null,
"e": 91469,
"s": 91417,
"text": "Handling spill-over of food or drink while serving."
},
{
"code": null,
"e": 91502,
"s": 91469,
"text": "Dealing with highly drunk gusts."
},
{
"code": null,
"e": 91602,
"s": 91502,
"text": "Dealing with guests who are physically challenged or the ones who show difficulty in communicating."
},
{
"code": null,
"e": 91644,
"s": 91602,
"text": "Dealing with hyper-active toddler guests."
},
{
"code": null,
"e": 91707,
"s": 91644,
"text": "Dealing with unwelcomed situations such as large fire hazards."
},
{
"code": null,
"e": 91857,
"s": 91707,
"text": "The service staff needs to be careful while carrying the trays in their hands and going around the dining area. They need to follow the given rules β"
},
{
"code": null,
"e": 91883,
"s": 91857,
"text": "Do not overload the tray."
},
{
"code": null,
"e": 91953,
"s": 91883,
"text": "Place the items on the tray such that the load is evenly distributed."
},
{
"code": null,
"e": 92046,
"s": 91953,
"text": "Alter the position of drinks or food promptly every time something is removed from the tray."
},
{
"code": null,
"e": 92072,
"s": 92046,
"text": "Carry one tray at a time."
},
{
"code": null,
"e": 92143,
"s": 92072,
"text": "Carry the tray with a firm support of the palm with fingers wide open."
},
{
"code": null,
"e": 92203,
"s": 92143,
"text": "Hold the tray on the left palm slightly above the shoulder."
},
{
"code": null,
"e": 92265,
"s": 92203,
"text": "Hold it little away from neck and mouth for hygienic reasons."
},
{
"code": null,
"e": 92333,
"s": 92265,
"text": "Following are some meticulous ways while serving food or beverages."
},
{
"code": null,
"e": 92394,
"s": 92333,
"text": "Bring food to the guest table if it is not a buffet service."
},
{
"code": null,
"e": 92455,
"s": 92394,
"text": "Bring food to the guest table if it is not a buffet service."
},
{
"code": null,
"e": 92521,
"s": 92455,
"text": "Present the food from guestβs left side in case of formal dining."
},
{
"code": null,
"e": 92587,
"s": 92521,
"text": "Present the food from guestβs left side in case of formal dining."
},
{
"code": null,
"e": 92688,
"s": 92587,
"text": "Prepare the food plates from the kitchen and place them on the guest table in case of casual dining."
},
{
"code": null,
"e": 92789,
"s": 92688,
"text": "Prepare the food plates from the kitchen and place them on the guest table in case of casual dining."
},
{
"code": null,
"e": 92841,
"s": 92789,
"text": "Ask the guests if they need help to serve the food."
},
{
"code": null,
"e": 92893,
"s": 92841,
"text": "Ask the guests if they need help to serve the food."
},
{
"code": null,
"e": 92924,
"s": 92893,
"text": "Serve one food item at a time."
},
{
"code": null,
"e": 92955,
"s": 92924,
"text": "Serve one food item at a time."
},
{
"code": null,
"e": 93113,
"s": 92955,
"text": "Serve the eldest lady guest of the group first unless the lady herself is a host. After all ladies are served, serve the men guests starting from the oldest."
},
{
"code": null,
"e": 93271,
"s": 93113,
"text": "Serve the eldest lady guest of the group first unless the lady herself is a host. After all ladies are served, serve the men guests starting from the oldest."
},
{
"code": null,
"e": 93328,
"s": 93271,
"text": "Always present a dish with its respective serving spoon."
},
{
"code": null,
"e": 93385,
"s": 93328,
"text": "Always present a dish with its respective serving spoon."
},
{
"code": null,
"e": 93473,
"s": 93385,
"text": "Tilt the service bowl a little to bring east in serving and take it away after serving."
},
{
"code": null,
"e": 93561,
"s": 93473,
"text": "Tilt the service bowl a little to bring east in serving and take it away after serving."
},
{
"code": null,
"e": 93654,
"s": 93561,
"text": "Always present the ordered drink in an appropriate glass by informing its name to the guest."
},
{
"code": null,
"e": 93747,
"s": 93654,
"text": "Always present the ordered drink in an appropriate glass by informing its name to the guest."
},
{
"code": null,
"e": 93888,
"s": 93747,
"text": "When same wine is offered in consecutive courses, serve it in the same wine glass. If wine is changed then replace the glass with fresh one."
},
{
"code": null,
"e": 94029,
"s": 93888,
"text": "When same wine is offered in consecutive courses, serve it in the same wine glass. If wine is changed then replace the glass with fresh one."
},
{
"code": null,
"e": 94124,
"s": 94029,
"text": "Always tilt the glass while pouring drinks or fuzzy drinks so that its head and aroma is held."
},
{
"code": null,
"e": 94219,
"s": 94124,
"text": "Always tilt the glass while pouring drinks or fuzzy drinks so that its head and aroma is held."
},
{
"code": null,
"e": 94353,
"s": 94219,
"text": "Do not bend over served plates while serving other plates across the table. Move as near as possible to the plate in which you serve."
},
{
"code": null,
"e": 94487,
"s": 94353,
"text": "Do not bend over served plates while serving other plates across the table. Move as near as possible to the plate in which you serve."
},
{
"code": null,
"e": 94575,
"s": 94487,
"text": "It is important to clear the table between two dining sessions by following procedure β"
},
{
"code": null,
"e": 94639,
"s": 94575,
"text": "Clear the table first when the guests finish their main course."
},
{
"code": null,
"e": 94703,
"s": 94639,
"text": "Clear the table first when the guests finish their main course."
},
{
"code": null,
"e": 94772,
"s": 94703,
"text": "Clear it for the second time just before the guests leave the table."
},
{
"code": null,
"e": 94841,
"s": 94772,
"text": "Clear it for the second time just before the guests leave the table."
},
{
"code": null,
"e": 95007,
"s": 94841,
"text": "While clearing, first remove all the pieces of flatware and chinaware except table linen and center piece. Let the dessert flatware remain in case of first clearing."
},
{
"code": null,
"e": 95173,
"s": 95007,
"text": "While clearing, first remove all the pieces of flatware and chinaware except table linen and center piece. Let the dessert flatware remain in case of first clearing."
},
{
"code": null,
"e": 95234,
"s": 95173,
"text": "Let wine glasses be on the table even after the main course."
},
{
"code": null,
"e": 95295,
"s": 95234,
"text": "Let wine glasses be on the table even after the main course."
},
{
"code": null,
"e": 95487,
"s": 95295,
"text": "While clearing, pickup one plate at a time and place on the tray carefully. In case of formal dining, replace the removed plate by a fresh one so that table cover of the guest is never empty."
},
{
"code": null,
"e": 95679,
"s": 95487,
"text": "While clearing, pickup one plate at a time and place on the tray carefully. In case of formal dining, replace the removed plate by a fresh one so that table cover of the guest is never empty."
},
{
"code": null,
"e": 95774,
"s": 95679,
"text": "Do not overload the tray with pile of used plates; make extra rounds to the table if required."
},
{
"code": null,
"e": 95869,
"s": 95774,
"text": "Do not overload the tray with pile of used plates; make extra rounds to the table if required."
},
{
"code": null,
"e": 96237,
"s": 95869,
"text": "Before presenting bill to the guest, make sure the guests donβt want to order anything more. There are many policies of setting guest bills in the F&B establishments. Some prefer the guests pay cash at the cash collection counter. In such case, the serving staff must accompany the guest to the payment counter to ensure only the right amount is charged to the guest."
},
{
"code": null,
"e": 96409,
"s": 96237,
"text": "Some F&B Services businesses prefer to bring bills (or checks) to the guestsβ tables and get them settled. While presenting and settling the bill, follow the given steps β"
},
{
"code": null,
"e": 96465,
"s": 96409,
"text": "Ask politely, βShould I bring you the bill, Sir/Madam?β"
},
{
"code": null,
"e": 96521,
"s": 96465,
"text": "Ask politely, βShould I bring you the bill, Sir/Madam?β"
},
{
"code": null,
"e": 96634,
"s": 96521,
"text": "Once the guest confirms, ask how he/she would like to pay. It should be either credit card, debit card, or cash."
},
{
"code": null,
"e": 96747,
"s": 96634,
"text": "Once the guest confirms, ask how he/she would like to pay. It should be either credit card, debit card, or cash."
},
{
"code": null,
"e": 96794,
"s": 96747,
"text": "Go to the payment counter to prepare the bill."
},
{
"code": null,
"e": 96841,
"s": 96794,
"text": "Go to the payment counter to prepare the bill."
},
{
"code": null,
"e": 96913,
"s": 96841,
"text": "Cashier prepares the bill according to the table number told by waiter."
},
{
"code": null,
"e": 96985,
"s": 96913,
"text": "Cashier prepares the bill according to the table number told by waiter."
},
{
"code": null,
"e": 97064,
"s": 96985,
"text": "Present the bill in a small closed folder to the guest from his/her left side."
},
{
"code": null,
"e": 97143,
"s": 97064,
"text": "Present the bill in a small closed folder to the guest from his/her left side."
},
{
"code": null,
"e": 97200,
"s": 97143,
"text": "Stand beside the guest till the guest examines the bill."
},
{
"code": null,
"e": 97257,
"s": 97200,
"text": "Stand beside the guest till the guest examines the bill."
},
{
"code": null,
"e": 97580,
"s": 97257,
"text": "If the guest pays by cash, take it and deposit the amount at the payment counter. If the guest wishes to pay by card, take the guestβs signature on the bill, and take the card and bill to the payment counter. If the establishment has facility of mobile card-payment service, take the transaction device to the guest table."
},
{
"code": null,
"e": 97903,
"s": 97580,
"text": "If the guest pays by cash, take it and deposit the amount at the payment counter. If the guest wishes to pay by card, take the guestβs signature on the bill, and take the card and bill to the payment counter. If the establishment has facility of mobile card-payment service, take the transaction device to the guest table."
},
{
"code": null,
"e": 98045,
"s": 97903,
"text": "The cashier returns the balance amount if paid by cash. If the payment is by card, he ensures the cardβs expiry date and accepts the payment."
},
{
"code": null,
"e": 98187,
"s": 98045,
"text": "The cashier returns the balance amount if paid by cash. If the payment is by card, he ensures the cardβs expiry date and accepts the payment."
},
{
"code": null,
"e": 98264,
"s": 98187,
"text": "Bring back the copy of printed bill and any change or the card to the guest."
},
{
"code": null,
"e": 98341,
"s": 98264,
"text": "Bring back the copy of printed bill and any change or the card to the guest."
},
{
"code": null,
"e": 98417,
"s": 98341,
"text": "If the guest insists to take the tip, mention your thankfulness with smile."
},
{
"code": null,
"e": 98493,
"s": 98417,
"text": "If the guest insists to take the tip, mention your thankfulness with smile."
},
{
"code": null,
"e": 98628,
"s": 98493,
"text": "When the guest stands up to leave the table, pull the chair backwards by informing him/her to help to get out of the chair gracefully."
},
{
"code": null,
"e": 98763,
"s": 98628,
"text": "When the guest stands up to leave the table, pull the chair backwards by informing him/her to help to get out of the chair gracefully."
},
{
"code": null,
"e": 98832,
"s": 98763,
"text": "Thank the guest for his/her visit and invite him/her to visit again."
},
{
"code": null,
"e": 98901,
"s": 98832,
"text": "Thank the guest for his/her visit and invite him/her to visit again."
},
{
"code": null,
"e": 99266,
"s": 98901,
"text": "It is an extremely important responsibility of every F&B Services to serve their guests hygienic food and beverages. The guests keep faith in F&B Services businesses that they will provide them the best food and serve it the best careful manner. The F&B services are bound to provide safe-to-eat food that is prepared by following hygiene and sanitation practices."
},
{
"code": null,
"e": 99614,
"s": 99266,
"text": "F&B services have direct access to guestsβ health through food and beverages. The working staff handles every food and drink item closely that the guest is going to eat. Hence, if these services do not follow proper practices of hygiene and sanitation, the guests might get foodborne diseases such as food poisoning, nausea, diarrhea, or vomiting."
},
{
"code": null,
"e": 99862,
"s": 99614,
"text": "Food contamination can occur through unwashed vegetables, uncooked meat, soft cheeses, and unpasteurized milk. If the food preparation and serving equipment used in F&B Services are not clean, then they become primary source of food contamination."
},
{
"code": null,
"e": 99915,
"s": 99862,
"text": "There are three main sources of food contamination β"
},
{
"code": null,
"e": 100105,
"s": 99915,
"text": "Physical β This is accidental in nature and is caused by employee carelessness. The major culprits are air, dust, smoke, and dirt. To prevent this, food must be properly covered and stored."
},
{
"code": null,
"e": 100295,
"s": 100105,
"text": "Physical β This is accidental in nature and is caused by employee carelessness. The major culprits are air, dust, smoke, and dirt. To prevent this, food must be properly covered and stored."
},
{
"code": null,
"e": 100416,
"s": 100295,
"text": "Biological β This contamination is caused by pathogens and microorganisms such as bacteria, molds, parasites, and fungi."
},
{
"code": null,
"e": 100537,
"s": 100416,
"text": "Biological β This contamination is caused by pathogens and microorganisms such as bacteria, molds, parasites, and fungi."
},
{
"code": null,
"e": 100917,
"s": 100537,
"text": "Chemical β It is accidental contamination of food caused by cleaning solvents, pest control sprays, or other chemicals used in entire food production chain. This food contamination occurs when utensils or other tableware are not wiped dry after washing them using cleaning liquids. It also takes place when the food is not stored properly when pest control chemicals are sprayed."
},
{
"code": null,
"e": 101297,
"s": 100917,
"text": "Chemical β It is accidental contamination of food caused by cleaning solvents, pest control sprays, or other chemicals used in entire food production chain. This food contamination occurs when utensils or other tableware are not wiped dry after washing them using cleaning liquids. It also takes place when the food is not stored properly when pest control chemicals are sprayed."
},
{
"code": null,
"e": 101460,
"s": 101297,
"text": "Personal hygiene is essential when one handles the food or beverage that the other is going to consume. The service staff must follow the given basic principles β"
},
{
"code": null,
"e": 101565,
"s": 101460,
"text": "It is said that the hygiene starts from home. Perform your daily cleanliness regime without any excuses."
},
{
"code": null,
"e": 101670,
"s": 101565,
"text": "It is said that the hygiene starts from home. Perform your daily cleanliness regime without any excuses."
},
{
"code": null,
"e": 101914,
"s": 101670,
"text": "Wash hands and arms immediately β\n\nWhen you come from toilet.\nWhen you sneeze, blow nose, yawn, or cough covering your mouth with hands.\nAfter eating food, tobacco, or touching animals.\nAfter you touch hair, scalp, skin, or any body-opening.\n\n"
},
{
"code": null,
"e": 101948,
"s": 101914,
"text": "Wash hands and arms immediately β"
},
{
"code": null,
"e": 101975,
"s": 101948,
"text": "When you come from toilet."
},
{
"code": null,
"e": 102002,
"s": 101975,
"text": "When you come from toilet."
},
{
"code": null,
"e": 102077,
"s": 102002,
"text": "When you sneeze, blow nose, yawn, or cough covering your mouth with hands."
},
{
"code": null,
"e": 102152,
"s": 102077,
"text": "When you sneeze, blow nose, yawn, or cough covering your mouth with hands."
},
{
"code": null,
"e": 102201,
"s": 102152,
"text": "After eating food, tobacco, or touching animals."
},
{
"code": null,
"e": 102250,
"s": 102201,
"text": "After eating food, tobacco, or touching animals."
},
{
"code": null,
"e": 102306,
"s": 102250,
"text": "After you touch hair, scalp, skin, or any body-opening."
},
{
"code": null,
"e": 102362,
"s": 102306,
"text": "After you touch hair, scalp, skin, or any body-opening."
},
{
"code": null,
"e": 102445,
"s": 102362,
"text": "Wash hands with mild cleansing soap and warm water; not merely with running water."
},
{
"code": null,
"e": 102528,
"s": 102445,
"text": "Wash hands with mild cleansing soap and warm water; not merely with running water."
},
{
"code": null,
"e": 102546,
"s": 102528,
"text": "Wipe sweat often."
},
{
"code": null,
"e": 102564,
"s": 102546,
"text": "Wipe sweat often."
},
{
"code": null,
"e": 102607,
"s": 102564,
"text": "Do not smoke or eat tobacco while working."
},
{
"code": null,
"e": 102650,
"s": 102607,
"text": "Do not smoke or eat tobacco while working."
},
{
"code": null,
"e": 102692,
"s": 102650,
"text": "Cover cuts, burns, or wounds on the skin."
},
{
"code": null,
"e": 102734,
"s": 102692,
"text": "Cover cuts, burns, or wounds on the skin."
},
{
"code": null,
"e": 102763,
"s": 102734,
"text": "Keep hair and nails trimmed."
},
{
"code": null,
"e": 102792,
"s": 102763,
"text": "Keep hair and nails trimmed."
},
{
"code": null,
"e": 102865,
"s": 102792,
"text": "Try using hand gloves as much as possible. Kitchen staff must use toque."
},
{
"code": null,
"e": 102938,
"s": 102865,
"text": "Try using hand gloves as much as possible. Kitchen staff must use toque."
},
{
"code": null,
"e": 103057,
"s": 102938,
"text": "Do not work when facing cold, cough, or any other contagious diseases. Inform your superior staff if you are not well."
},
{
"code": null,
"e": 103176,
"s": 103057,
"text": "Do not work when facing cold, cough, or any other contagious diseases. Inform your superior staff if you are not well."
},
{
"code": null,
"e": 103293,
"s": 103176,
"text": "Do not touch ready-to-eat food directly. Always use gloves, serving tongs deli papers, or forks to handle such food."
},
{
"code": null,
"e": 103410,
"s": 103293,
"text": "Do not touch ready-to-eat food directly. Always use gloves, serving tongs deli papers, or forks to handle such food."
},
{
"code": null,
"e": 103548,
"s": 103410,
"text": "Do whatever required to let not your skin, body fluids, or any clothes you are wearing to come into contact with food or food containers."
},
{
"code": null,
"e": 103686,
"s": 103548,
"text": "Do whatever required to let not your skin, body fluids, or any clothes you are wearing to come into contact with food or food containers."
},
{
"code": null,
"e": 103710,
"s": 103686,
"text": "Ensure a clean uniform."
},
{
"code": null,
"e": 103734,
"s": 103710,
"text": "Ensure a clean uniform."
},
{
"code": null,
"e": 103782,
"s": 103734,
"text": "Do not wear loose jewelry. Avoid wrist jewelry."
},
{
"code": null,
"e": 103830,
"s": 103782,
"text": "Do not wear loose jewelry. Avoid wrist jewelry."
},
{
"code": null,
"e": 103874,
"s": 103830,
"text": "Any food business must be concerned about β"
},
{
"code": null,
"e": 103987,
"s": 103874,
"text": "Training all food handling and service staff with a detailed knowledge of food and equipment hygiene and safety."
},
{
"code": null,
"e": 104100,
"s": 103987,
"text": "Training all food handling and service staff with a detailed knowledge of food and equipment hygiene and safety."
},
{
"code": null,
"e": 104192,
"s": 104100,
"text": "Ensuring food handlers and servers not to handle food in case of contamination possibility."
},
{
"code": null,
"e": 104284,
"s": 104192,
"text": "Ensuring food handlers and servers not to handle food in case of contamination possibility."
},
{
"code": null,
"e": 104380,
"s": 104284,
"text": "Supplying hand-washing facilities with soap, running hot water, and paper towels for its staff."
},
{
"code": null,
"e": 104476,
"s": 104380,
"text": "Supplying hand-washing facilities with soap, running hot water, and paper towels for its staff."
},
{
"code": null,
"e": 104615,
"s": 104476,
"text": "Every F&B Services business must also be concerned about food safety and adhere to safety of food and beverage it serves. It must ensure β"
},
{
"code": null,
"e": 104816,
"s": 104615,
"text": "Marking Date on Food β The perishable ready-to-eat food refrigerated for more than 24 hours must be clearly marked at the time of preparation to indicate the date by which the food should be consumed."
},
{
"code": null,
"e": 105017,
"s": 104816,
"text": "Marking Date on Food β The perishable ready-to-eat food refrigerated for more than 24 hours must be clearly marked at the time of preparation to indicate the date by which the food should be consumed."
},
{
"code": null,
"e": 105169,
"s": 105017,
"text": "Storing of Food β Hot and cold foods and beverages need to be stored at the right temperature. The food temperature measuring devices must be accurate."
},
{
"code": null,
"e": 105321,
"s": 105169,
"text": "Storing of Food β Hot and cold foods and beverages need to be stored at the right temperature. The food temperature measuring devices must be accurate."
},
{
"code": null,
"e": 105492,
"s": 105321,
"text": "Cleaning Equipment β The area and facilities allocated for cleaning food preparation and service equipment must be large enough to immerse the utensils and sanitize them."
},
{
"code": null,
"e": 105663,
"s": 105492,
"text": "Cleaning Equipment β The area and facilities allocated for cleaning food preparation and service equipment must be large enough to immerse the utensils and sanitize them."
},
{
"code": null,
"e": 105814,
"s": 105663,
"text": "Limiting Cross-Contamination β Storing raw food such as raw meat or vegetables from cooked food is essential to avoid cross-contamination of the food."
},
{
"code": null,
"e": 105965,
"s": 105814,
"text": "Limiting Cross-Contamination β Storing raw food such as raw meat or vegetables from cooked food is essential to avoid cross-contamination of the food."
},
{
"code": null,
"e": 106093,
"s": 105965,
"text": "Employing FSS β The F&B Services businesses must employee at least one Food Safety Supervisor depending upon the business size."
},
{
"code": null,
"e": 106221,
"s": 106093,
"text": "Employing FSS β The F&B Services businesses must employee at least one Food Safety Supervisor depending upon the business size."
},
{
"code": null,
"e": 106393,
"s": 106221,
"text": "Hygiene and safety of food starts right from selecting raw material carefully, preparing food with health and safety cautiousness, and serving it in the clean environment."
},
{
"code": null,
"e": 106418,
"s": 106393,
"text": "The service staff must β"
},
{
"code": null,
"e": 106457,
"s": 106418,
"text": "Attend duty in clean and tidy uniform."
},
{
"code": null,
"e": 106547,
"s": 106457,
"text": "Wear less jewelry while working. This avoids entangling articles and calling for trouble."
},
{
"code": null,
"e": 106608,
"s": 106547,
"text": "Be aware of the equipment and their appropriate application."
},
{
"code": null,
"e": 106655,
"s": 106608,
"text": "Be careful of handling hot food and beverages."
},
{
"code": null,
"e": 106697,
"s": 106655,
"text": "Clear spillages on the floor immediately."
},
{
"code": null,
"e": 106725,
"s": 106697,
"text": "Never run in the workspace."
},
{
"code": null,
"e": 106758,
"s": 106725,
"text": "\n 18 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 106772,
"s": 106758,
"text": " Manish Gupta"
},
{
"code": null,
"e": 106809,
"s": 106772,
"text": "\n 185 Lectures \n 46.5 hours \n"
},
{
"code": null,
"e": 106825,
"s": 106809,
"text": " Nikhil Agarwal"
},
{
"code": null,
"e": 106857,
"s": 106825,
"text": "\n 10 Lectures \n 34 mins\n"
},
{
"code": null,
"e": 106873,
"s": 106857,
"text": " Faiq Ismayilov"
},
{
"code": null,
"e": 106904,
"s": 106873,
"text": "\n 7 Lectures \n 52 mins\n"
},
{
"code": null,
"e": 106916,
"s": 106904,
"text": " Dr. Harris"
},
{
"code": null,
"e": 106923,
"s": 106916,
"text": " Print"
},
{
"code": null,
"e": 106934,
"s": 106923,
"text": " Add Notes"
}
] |
How to use the submit button in HTML forms?
|
Submit button automatically submits a form on click. 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 the submit button in HTML forms. It is also created using HTML <input> tag but type attribute is set to button.
You can try to run the following code to use submit button to submit and reset a form. Under the action, attribute add the file, where you want to reach after clicking Submit button. Using get and post method, you can send the values to the PHP file added in action attribute.
Live Demo
<!DOCTYPE html>
<html>
<body>
<form action="/new.php">
Student Name:<br>
<input type="text" name="sname">
<br>
Student Subject:<br>
<input type="text" name="ssubject">
<br>
<input type="submit" value="Submit">
<input type="reset" value="Reset">
</form>
</body>
</html>
|
[
{
"code": null,
"e": 1329,
"s": 1062,
"text": "Submit button automatically submits a form on click. 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": 1470,
"s": 1329,
"text": "Letβs learn about how to use the submit button in HTML forms. It is also created using HTML <input> tag but type attribute is set to button."
},
{
"code": null,
"e": 1747,
"s": 1470,
"text": "You can try to run the following code to use submit button to submit and reset a form. Under the action, attribute add the file, where you want to reach after clicking Submit button. Using get and post method, you can send the values to the PHP file added in action attribute."
},
{
"code": null,
"e": 1757,
"s": 1747,
"text": "Live Demo"
},
{
"code": null,
"e": 2116,
"s": 1757,
"text": "<!DOCTYPE html>\n<html>\n <body>\n <form action=\"/new.php\">\n Student Name:<br>\n <input type=\"text\" name=\"sname\">\n <br>\n Student Subject:<br>\n <input type=\"text\" name=\"ssubject\">\n <br>\n <input type=\"submit\" value=\"Submit\">\n <input type=\"reset\" value=\"Reset\">\n </form>\n </body>\n</html>"
}
] |
Chunking & Information Extraction
|
Chunking, one of the important processes in natural language processing, is used to identify parts of speech (POS) and short phrases. In other simple words, with chunking, we can get the structure of the sentence. It is also called partial parsing.
Chunk patterns are the patterns of part-of-speech (POS) tags that define what kind of words made up a chunk. We can define chunk patterns with the help of modified regular expressions.
Moreover, we can also define patterns for what kind of words should not be in a chunk and these unchunked words are known as chinks.
In the example below, along with the result of parsing the sentence βthe book has many chaptersβ, there is a grammar for noun phrases that combines both a chunk and a chink pattern β
import nltk
sentence = [
("the", "DT"),
("book", "NN"),
("has","VBZ"),
("many","JJ"),
("chapters","NNS")
]
chunker = nltk.RegexpParser(
r'''
NP:{<DT><NN.*><.*>*<NN.*>}
}<VB.*>{
'''
)
chunker.parse(sentence)
Output = chunker.parse(sentence)
Output.draw()
As seen above, the pattern for specifying a chunk is to use curly braces as follows β
{<DT><NN>}
And to specify a chink, we can flip the braces such as follows β
}<VB>{.
Now, for a particular phrase type, these rules can be combined into a grammar.
We have gone through taggers as well as parsers that can be used to build information extraction engine. Let us see a basic information extraction pipeline β
Information extraction has many applications including β
Business intelligence
Resume harvesting
Media analysis
Sentiment detection
Patent search
Email scanning
Named-entity recognition (NER) is actually a way of extracting some of most common entities like names, organizations, location, etc. Let us see an example that took all the preprocessing steps such as sentence tokenization, POS tagging, chunking, NER, and follows the pipeline provided in the figure above.
Import nltk
file = open (
# provide here the absolute path for the file of text for which we want NER
)
data_text = file.read()
sentences = nltk.sent_tokenize(data_text)
tokenized_sentences = [nltk.word_tokenize(sentence) for sentence in sentences]
tagged_sentences = [nltk.pos_tag(sentence) for sentence in tokenized_sentences]
for sent in tagged_sentences:
print nltk.ne_chunk(sent)
Some of the modified Named-entity recognition (NER) can also be used to extract entities such as product names, bio-medical entities, brand name and much more.
Relation extraction, another commonly used information extraction operation, is the process of extracting the different relationships between various entities. There can be different relationships like inheritance, synonyms, analogous, etc., whose definition depends on the information need. For example, suppose if we want to look for write of a book then the authorship would be a relation between the author name and book name.
In the following example, we use the same IE pipeline, as shown in the above diagram, that we used till Named-entity relation (NER) and extend it with a relation pattern based on the NER tags.
import nltk
import re
IN = re.compile(r'.*\bin\b(?!\b.+ing)')
for doc in nltk.corpus.ieer.parsed_docs('NYT_19980315'):
for rel in nltk.sem.extract_rels('ORG', 'LOC', doc, corpus = 'ieer',
pattern = IN):
print(nltk.sem.rtuple(rel))
[ORG: 'WHYY'] 'in' [LOC: 'Philadelphia']
[ORG: 'McGlashan & Sarrail'] 'firm in' [LOC: 'San Mateo']
[ORG: 'Freedom Forum'] 'in' [LOC: 'Arlington']
[ORG: 'Brookings Institution'] ', the research group in' [LOC: 'Washington']
[ORG: 'Idealab'] ', a self-described business incubator based in' [LOC: 'Los Angeles']
[ORG: 'Open Text'] ', based in' [LOC: 'Waterloo']
[ORG: 'WGBH'] 'in' [LOC: 'Boston']
[ORG: 'Bastille Opera'] 'in' [LOC: 'Paris']
[ORG: 'Omnicom'] 'in' [LOC: 'New York']
[ORG: 'DDB Needham'] 'in' [LOC: 'New York']
[ORG: 'Kaplan Thaler Group'] 'in' [LOC: 'New York']
[ORG: 'BBDO South'] 'in' [LOC: 'Atlanta']
[ORG: 'Georgia-Pacific'] 'in' [LOC: 'Atlanta']
In the above code, we have used an inbuilt corpus named ieer. In this corpus, the sentences are tagged till Named-entity relation (NER). Here we only need to specify the relation pattern that we want and the kind of NER we want the relation to define. In our example, we defined relationship between an organization and a location. We extracted all the combinations of these patterns.
59 Lectures
2.5 hours
Mike West
17 Lectures
1 hours
Pranjal Srivastava
6 Lectures
1 hours
Prabh Kirpa Classes
12 Lectures
1 hours
Stone River ELearning
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2633,
"s": 2384,
"text": "Chunking, one of the important processes in natural language processing, is used to identify parts of speech (POS) and short phrases. In other simple words, with chunking, we can get the structure of the sentence. It is also called partial parsing."
},
{
"code": null,
"e": 2818,
"s": 2633,
"text": "Chunk patterns are the patterns of part-of-speech (POS) tags that define what kind of words made up a chunk. We can define chunk patterns with the help of modified regular expressions."
},
{
"code": null,
"e": 2951,
"s": 2818,
"text": "Moreover, we can also define patterns for what kind of words should not be in a chunk and these unchunked words are known as chinks."
},
{
"code": null,
"e": 3134,
"s": 2951,
"text": "In the example below, along with the result of parsing the sentence βthe book has many chaptersβ, there is a grammar for noun phrases that combines both a chunk and a chink pattern β"
},
{
"code": null,
"e": 3415,
"s": 3134,
"text": "import nltk\nsentence = [\n (\"the\", \"DT\"),\n (\"book\", \"NN\"),\n (\"has\",\"VBZ\"),\n (\"many\",\"JJ\"),\n (\"chapters\",\"NNS\")\n]\nchunker = nltk.RegexpParser(\n r'''\n NP:{<DT><NN.*><.*>*<NN.*>}\n }<VB.*>{\n '''\n)\nchunker.parse(sentence)\nOutput = chunker.parse(sentence)\nOutput.draw()"
},
{
"code": null,
"e": 3501,
"s": 3415,
"text": "As seen above, the pattern for specifying a chunk is to use curly braces as follows β"
},
{
"code": null,
"e": 3513,
"s": 3501,
"text": "{<DT><NN>}\n"
},
{
"code": null,
"e": 3578,
"s": 3513,
"text": "And to specify a chink, we can flip the braces such as follows β"
},
{
"code": null,
"e": 3587,
"s": 3578,
"text": "}<VB>{.\n"
},
{
"code": null,
"e": 3666,
"s": 3587,
"text": "Now, for a particular phrase type, these rules can be combined into a grammar."
},
{
"code": null,
"e": 3824,
"s": 3666,
"text": "We have gone through taggers as well as parsers that can be used to build information extraction engine. Let us see a basic information extraction pipeline β"
},
{
"code": null,
"e": 3881,
"s": 3824,
"text": "Information extraction has many applications including β"
},
{
"code": null,
"e": 3903,
"s": 3881,
"text": "Business intelligence"
},
{
"code": null,
"e": 3921,
"s": 3903,
"text": "Resume harvesting"
},
{
"code": null,
"e": 3936,
"s": 3921,
"text": "Media analysis"
},
{
"code": null,
"e": 3956,
"s": 3936,
"text": "Sentiment detection"
},
{
"code": null,
"e": 3970,
"s": 3956,
"text": "Patent search"
},
{
"code": null,
"e": 3985,
"s": 3970,
"text": "Email scanning"
},
{
"code": null,
"e": 4293,
"s": 3985,
"text": "Named-entity recognition (NER) is actually a way of extracting some of most common entities like names, organizations, location, etc. Let us see an example that took all the preprocessing steps such as sentence tokenization, POS tagging, chunking, NER, and follows the pipeline provided in the figure above."
},
{
"code": null,
"e": 4681,
"s": 4293,
"text": "Import nltk\nfile = open (\n # provide here the absolute path for the file of text for which we want NER\n)\ndata_text = file.read()\nsentences = nltk.sent_tokenize(data_text)\ntokenized_sentences = [nltk.word_tokenize(sentence) for sentence in sentences]\ntagged_sentences = [nltk.pos_tag(sentence) for sentence in tokenized_sentences]\nfor sent in tagged_sentences:\nprint nltk.ne_chunk(sent)"
},
{
"code": null,
"e": 4841,
"s": 4681,
"text": "Some of the modified Named-entity recognition (NER) can also be used to extract entities such as product names, bio-medical entities, brand name and much more."
},
{
"code": null,
"e": 5272,
"s": 4841,
"text": "Relation extraction, another commonly used information extraction operation, is the process of extracting the different relationships between various entities. There can be different relationships like inheritance, synonyms, analogous, etc., whose definition depends on the information need. For example, suppose if we want to look for write of a book then the authorship would be a relation between the author name and book name."
},
{
"code": null,
"e": 5465,
"s": 5272,
"text": "In the following example, we use the same IE pipeline, as shown in the above diagram, that we used till Named-entity relation (NER) and extend it with a relation pattern based on the NER tags."
},
{
"code": null,
"e": 5696,
"s": 5465,
"text": "import nltk\nimport re\nIN = re.compile(r'.*\\bin\\b(?!\\b.+ing)')\nfor doc in nltk.corpus.ieer.parsed_docs('NYT_19980315'):\nfor rel in nltk.sem.extract_rels('ORG', 'LOC', doc, corpus = 'ieer',\npattern = IN):\nprint(nltk.sem.rtuple(rel))"
},
{
"code": null,
"e": 6361,
"s": 5696,
"text": "[ORG: 'WHYY'] 'in' [LOC: 'Philadelphia']\n[ORG: 'McGlashan & Sarrail'] 'firm in' [LOC: 'San Mateo']\n[ORG: 'Freedom Forum'] 'in' [LOC: 'Arlington']\n[ORG: 'Brookings Institution'] ', the research group in' [LOC: 'Washington']\n[ORG: 'Idealab'] ', a self-described business incubator based in' [LOC: 'Los Angeles']\n[ORG: 'Open Text'] ', based in' [LOC: 'Waterloo']\n[ORG: 'WGBH'] 'in' [LOC: 'Boston']\n[ORG: 'Bastille Opera'] 'in' [LOC: 'Paris']\n[ORG: 'Omnicom'] 'in' [LOC: 'New York']\n[ORG: 'DDB Needham'] 'in' [LOC: 'New York']\n[ORG: 'Kaplan Thaler Group'] 'in' [LOC: 'New York']\n[ORG: 'BBDO South'] 'in' [LOC: 'Atlanta']\n[ORG: 'Georgia-Pacific'] 'in' [LOC: 'Atlanta']\n"
},
{
"code": null,
"e": 6746,
"s": 6361,
"text": "In the above code, we have used an inbuilt corpus named ieer. In this corpus, the sentences are tagged till Named-entity relation (NER). Here we only need to specify the relation pattern that we want and the kind of NER we want the relation to define. In our example, we defined relationship between an organization and a location. We extracted all the combinations of these patterns."
},
{
"code": null,
"e": 6781,
"s": 6746,
"text": "\n 59 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6792,
"s": 6781,
"text": " Mike West"
},
{
"code": null,
"e": 6825,
"s": 6792,
"text": "\n 17 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6845,
"s": 6825,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 6877,
"s": 6845,
"text": "\n 6 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6898,
"s": 6877,
"text": " Prabh Kirpa Classes"
},
{
"code": null,
"e": 6931,
"s": 6898,
"text": "\n 12 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6954,
"s": 6931,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 6961,
"s": 6954,
"text": " Print"
},
{
"code": null,
"e": 6972,
"s": 6961,
"text": " Add Notes"
}
] |
Count N-length strings consisting only of vowels sorted lexicographically - GeeksforGeeks
|
25 Oct, 2021
Given an integer N, the task is to count all possible strings of length N consisting of vowels {a, e, i, o, u} that can be formed such that each string is sorted in lexicographical order.
Examples:
Input: N = 2Output: 15Explanation: The strings of length 2 which are sorted in lexicographical order are [βaaβ, βaeβ, βaiβ, βaoβ, βauβ, βeeβ, βeiβ, βeoβ, βeuβ, βiiβ, βioβ, βiuβ, βooβ, βouβ, βuuβ].
Input: N = 1Output: 5Explanation: The strings of length 1 which are sorted in lexicographical order are [βaβ, βeβ, βiβ, βoβ, βuβ].
Naive Approach: The simplest approach is to generate all possible strings of length N such that each string is sorted in lexicographical order. Print the count obtained after completing the steps.
Recursive Approach: Keep track of the vowel added to the string so that the next vowel added to the string is always Lexicographically greater.
C++
Java
Python3
C#
Javascript
// C++ program to illustrate Count of N-length strings// consisting only of vowels sorted lexicographically #include <iostream>using namespace std;// to keep the string in lexicographically sorted order use// start index// to add the vowels starting the from that indexint countstrings(int n, int start){ // base case: if string length is 0 add to the count if (n == 0) { return 1; } int cnt = 0; // if last character in string is 'e' // add vowels starting from 'e' // i.e 'e','i','o','u' for (int i = start; i < 5; i++) { // decrease the length of string cnt += countstrings(n - 1, i); } return cnt;}int countVowelStrings(int n){ // char arr[5]={'a','e','i','o','u'}; // starting from index 0 add the vowels to strings return countstrings(n, 0);}int main(){ int n = 2; cout << countVowelStrings(n); return 0;}// This code is contributed by Deepak Chowdary
// Java program to illustrate Count of N-length strings// consisting only of vowels sorted lexicographicallyimport java.util.*;public class Main{ // to keep the string in lexicographically sorted order use // start index // to add the vowels starting the from that index static int countstrings(int n, int start) { // base case: if string length is 0 add to the count if (n == 0) { return 1; } int cnt = 0; // if last character in string is 'e' // add vowels starting from 'e' // i.e 'e','i','o','u' for (int i = start; i < 5; i++) { // decrease the length of string cnt += countstrings(n - 1, i); } return cnt; } static int countVowelStrings(int n) { // char arr[5]={'a','e','i','o','u'}; // starting from index 0 add the vowels to strings return countstrings(n, 0); } public static void main(String[] args) { int n = 2; System.out.print(countVowelStrings(n)); }} // This code is contributed by divyesh072019.
# Python3 program to illustrate Count of N-length strings# consisting only of vowels sorted lexicographically # to keep the string in lexicographically sorted order use# start index# to add the vowels starting the from that indexdef countstrings(n, start): # base case: if string length is 0 add to the count if n == 0: return 1 cnt = 0 # if last character in string is 'e' # add vowels starting from 'e' # i.e 'e','i','o','u' for i in range(start, 5): # decrease the length of string cnt += countstrings(n - 1, i) return cnt def countVowelStrings(n): # char arr[5]={'a','e','i','o','u'}; # starting from index 0 add the vowels to strings return countstrings(n, 0) n = 2print(countVowelStrings(n)) # This code is contributed by divyeshrabadiya07.
// C# program to illustrate Count of N-length strings// consisting only of vowels sorted lexicographicallyusing System;using System.Collections.Generic;class GFG { // to keep the string in lexicographically sorted order use // start index // to add the vowels starting the from that index static int countstrings(int n, int start) { // base case: if string length is 0 add to the count if (n == 0) { return 1; } int cnt = 0; // if last character in string is 'e' // add vowels starting from 'e' // i.e 'e','i','o','u' for (int i = start; i < 5; i++) { // decrease the length of string cnt += countstrings(n - 1, i); } return cnt; } static int countVowelStrings(int n) { // char arr[5]={'a','e','i','o','u'}; // starting from index 0 add the vowels to strings return countstrings(n, 0); } static void Main() { int n = 2; Console.Write(countVowelStrings(n)); }} // This code is contributed by decode2207.
<script> // Javascript program to illustrate Count of N-length strings // consisting only of vowels sorted lexicographically // to keep the string in lexicographically sorted order use // start index // to add the vowels starting the from that index function countstrings(n, start) { // base case: if string length is 0 add to the count if (n == 0) { return 1; } let cnt = 0; // if last character in string is 'e' // add vowels starting from 'e' // i.e 'e','i','o','u' for (let i = start; i < 5; i++) { // decrease the length of string cnt += countstrings(n - 1, i); } return cnt; } function countVowelStrings(n) { // char arr[5]={'a','e','i','o','u'}; // starting from index 0 add the vowels to strings return countstrings(n, 0); } let n = 2; document.write(countVowelStrings(n)); // This code is contributed by suresh07.</script>
15
Time Complexity: O(N!)Auxiliary Space: O(1)
Efficient Approach: To optimize the above approach, the idea is to use Dynamic Programming. Below are some observations to solve the given problem:
Count of lexicographically sorted strings of length 1 starting from characters a, e, i, o, and u is 1.
Count of strings of length 2 that are in lexicographical order starting from characters a, e, i, o, and u is given by:The count of lexicographically sorted strings of length 2 starting from characters a is given by the count of the lexicographical strings of length 1 starting from character greater than or equal to a. Therefore, the count is 5.The count of lexicographically sorted strings of length 2 starting from characters e is given by the count of the lexicographical strings of length 1 starting from character greater than or equal to e. Therefore, the count is 4.The count of lexicographically sorted strings of length 2 starting from characters i is given by the count of the lexicographical strings of length 1 starting from character greater than or equal to i. Therefore, the count is 3.The count of lexicographically sorted strings of length 2 starting from characters o is given by the count of the lexicographical strings of length 1 starting from character greater than or equal to o. Therefore, the count is 2.The count of lexicographically sorted strings of length 2 starting from characters u is given by the count of the lexicographical strings of length 1 starting from character greater than or equal to u. Therefore, the count is 1.
The count of lexicographically sorted strings of length 2 starting from characters a is given by the count of the lexicographical strings of length 1 starting from character greater than or equal to a. Therefore, the count is 5.
The count of lexicographically sorted strings of length 2 starting from characters e is given by the count of the lexicographical strings of length 1 starting from character greater than or equal to e. Therefore, the count is 4.
The count of lexicographically sorted strings of length 2 starting from characters i is given by the count of the lexicographical strings of length 1 starting from character greater than or equal to i. Therefore, the count is 3.
The count of lexicographically sorted strings of length 2 starting from characters o is given by the count of the lexicographical strings of length 1 starting from character greater than or equal to o. Therefore, the count is 2.
The count of lexicographically sorted strings of length 2 starting from characters u is given by the count of the lexicographical strings of length 1 starting from character greater than or equal to u. Therefore, the count is 1.
Therefore, the total count of strings length 2 is given by: 5 + 4 + 3 + 2 + 1 = 15.
By observing the above pattern the count of strings of length N starting from each vowel character ch is given by the sum of the count of the lexicographical strings of length (N β 1) starting from character greater than or equal to ch.
Follow the steps below to solve the problem:
Create a 2D array, dp[N + 1][6] where dp[i][j] represents the number of lexicographically sorted strings of length i that can be constructed using the first j vowels and initialize dp[1][1] with 1.
Iterate over the first row using variable j, set dp[1][j] = dp[1][j β 1] + 1 as the string of length 1 are always sorted in lexicographically order.
Traverse the 2D array dp[][] and update each dp state as dp[i][j] = dp[i][j β 1] + dp[i β 1][j], where dp[i][j β 1] will give the count of lexicographical string length N and dp[i β 1][j] will give the count of lexicographical string length (N β 1).
After the above steps, print the value of dp[N][5] as the total count of resultant strings.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to count N-length strings// consisting of vowels only sorted// lexicographicallyint findNumberOfStrings(int n){ // Stores count of strings consisting // of vowels sorted lexicographically // of all possible lengths vector<vector<int> > DP(n + 1, vector<int>(6)); // Initialize DP[1][1] DP[1][1] = 1; // Traverse the matrix row-wise for (int i = 1; i < n + 1; i++) { for (int j = 1; j < 6; j++) { // Base Case if (i == 1) { DP[i][j] = DP[i][j - 1] + 1; } else { DP[i][j] = DP[i][j - 1] + DP[i - 1][j]; } } } // Return the result return DP[n][5];} // Driver Codeint main(){ int N = 2; // Function Call cout << findNumberOfStrings(N); return 0;}
// Java program to implement// the above approachimport java.util.*;class GFG{ // Function to count N-length strings// consisting of vowels only sorted// lexicographicallystatic int findNumberOfStrings(int n){ // Stores count of strings consisting // of vowels sorted lexicographically // of all possible lengths int DP[][] = new int [n + 1][6]; // Initialize DP[1][1] DP[1][1] = 1; // Traverse the matrix row-wise for (int i = 1; i < n + 1; i++) { for (int j = 1; j < 6; j++) { // Base Case if (i == 1) { DP[i][j] = DP[i][j - 1] + 1; } else { DP[i][j] = DP[i][j - 1] + DP[i - 1][j]; } } } // Return the result return DP[n][5];} // Driver Codepublic static void main(String[] args){ int N = 2; // Function Call System.out.print(findNumberOfStrings(N));}} // This code is contributed by sanjoy_62
# Python3 program for the# above approach # Function to count N-length# strings consisting of vowels# only sorted lexicographicallydef findNumberOfStrings(n): # Stores count of strings # consisting of vowels # sorted lexicographically # of all possible lengths DP = [[0 for i in range(6)] for i in range(n + 1)] # Initialize DP[1][1] DP[1][1] = 1 # Traverse the matrix row-wise for i in range(1, n + 1): for j in range(1, 6): #Base Case if (i == 1): DP[i][j] = DP[i][j - 1] + 1 else: DP[i][j] = DP[i][j - 1]+ DP[i - 1][j] # Return the result return DP[n][5] # Driver Codeif __name__ == '__main__': N = 2 # Function Call print(findNumberOfStrings(N)) # This code is contributed by Mohit Kumar 29
// C# program to implement// the above approachusing System;class GFG{ // Function to count N-length strings// consisting of vowels only sorted// lexicographicallystatic int findNumberOfStrings(int n){ // Stores count of strings consisting // of vowels sorted lexicographically // of all possible lengths int[,] DP = new int [n + 1, 6]; // Initialize DP[1][1] DP[1, 1] = 1; // Traverse the matrix row-wise for (int i = 1; i < n + 1; i++) { for (int j = 1; j < 6; j++) { // Base Case if (i == 1) { DP[i, j] = DP[i, j - 1] + 1; } else { DP[i, j] = DP[i, j - 1] + DP[i - 1, j]; } } } // Return the result return DP[n, 5];} // Driver Codepublic static void Main(string[] args){ int N = 2; // Function Call Console.Write(findNumberOfStrings(N));}} // This code is contributed by Chitranayal
<script> // JavaScript program for the above approach // Function to count N-length strings// consisting of vowels only sorted// lexicographicallyfunction findNumberOfStrings(n){ // Stores count of strings consisting // of vowels sorted lexicographically // of all possible lengths let DP = new Array(n + 1); // Loop to create 2D array using 1D array for (var i = 0; i < DP.length; i++) { DP[i] = new Array(2); } for (var i = 0; i < DP.length; i++) { for (var j = 0; j < DP.length; j++) { DP[i][j] = 0; } } // Initialize DP[1][1] DP[1][1] = 1; // Traverse the matrix row-wise for (let i = 1; i < n + 1; i++) { for (let j = 1; j < 6; j++) { // Base Case if (i == 1) { DP[i][j] = DP[i][j - 1] + 1; } else { DP[i][j] = DP[i][j - 1] + DP[i - 1][j]; } } } // Return the result return DP[n][5];} // Driver Code let N = 2; // Function Call document.write(findNumberOfStrings(N)); </script>
15
Time Complexity: O(N*5)Auxiliary Space: O(N*5)
Efficient Approach: The above approach can further be simplified to linear time and constant space.
Here are some of the observations for different lengths of strings:-
It is seen that for each value of N, number of strings possible is dependent on the previous value of N (N-1).
Value of any column in the Nth row is the sum of all columns in the (N-1)th row, starting from right hand side upto that column number.
C++
Java
Python3
#include <bits/stdc++.h>using namespace std; // Function to count N-length strings// consisting of vowels only sorted// lexicographicallyint findNumberOfStrings(int N){ // Initializing vector to store count of strings. vector<int> counts(5, 1); for (int i = 2; i <= N; i++) { for (int j = 3; j >= 0; j--) counts[j] += counts[j + 1]; } int ans = 0; // Summing up the total number of combinations. for (auto c : counts) ans += c; // Return the result return ans;} // Driver Codeint main(){ int N = 2; // Function Call cout << findNumberOfStrings(N); return 0;} // This code is contributed by Sarvesh Roshan.
// Java program for the above approachimport java.util.*;public class Main{ // Function to count N-length strings // consisting of vowels only sorted // lexicographically static int findNumberOfStrings(int N) { // Initializing vector to store count of strings. Vector<Integer> counts = new Vector<Integer>(); for(int i = 0; i < 5; i++) { counts.add(1); } for (int i = 2; i <= N; i++) { for (int j = 3; j >= 0; j--) counts.set(j, counts.get(j) + counts.get(j + 1)); } int ans = 0; // Summing up the total number of combinations. for(Integer c : counts) ans += c; // Return the result return ans; } public static void main(String[] args) { int N = 2; // Function Call System.out.print(findNumberOfStrings(N)); }} // This code is contributed by mukesh07.
# Python3 program for the above approach # Function to count N-length strings# consisting of vowels only sorted# lexicographicallydef findNumberOfStrings(N): # Initializing vector to store count of strings. counts = [] for i in range(5): counts.append(1) for i in range(2, N + 1): for j in range(3, -1, -1): counts[j] += counts[j + 1] ans = 0 # Summing up the total number of combinations. for c in counts: ans += c # Return the result return ans N = 2 # Function Callprint(findNumberOfStrings(N)) # This code is contributed by decode2207.
15
Time Complexity: O(5*N)Space Complexity: O(1)
Efficient Approach: The same idea of the above dp approach can be implemented in constant time and constant space.
C++
Java
Python
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to count N-length strings// consisting of vowels only sorted// lexicographicallyint findNumberOfStrings(int n){ return (n+1)*(n+2)*(n+3)*(n+4)/24;} // Driver Codeint main(){ int N = 2; // Function Call cout << findNumberOfStrings(N); return 0;}// This code is contributed by Kartik Singh
// Java program to implement// the above approachimport java.util.*;class GFG{ // Function to count N-length strings// consisting of vowels only sorted// lexicographicallystatic int findNumberOfStrings(int n){ return (n+1)*(n+2)*(n+3)*(n+4)/24;} // Driver Codepublic static void main(String[] args){ int N = 2; // Function Call System.out.print(findNumberOfStrings(N));}} // This code is contributed by Kartik Singh
# Python3 program for the# above approach # Function to count N-length# strings consisting of vowels# only sorted lexicographicallydef findNumberOfStrings(n): return int((n+1)*(n+2)*(n+3)*(n+4)/24) # Driver Codeif __name__ == '__main__': N = 2 # Function Call print(findNumberOfStrings(N)) # This code is contributed by Kartik Singh
// C# program to implement// the above approachusing System;class GFG{ // Function to count N-length strings// consisting of vowels only sorted// lexicographicallystatic int findNumberOfStrings(int n){ return (n+1)*(n+2)*(n+3)*(n+4)/24;} // Driver Codepublic static void Main(string[] args){ int N = 2; // Function Call Console.Write(findNumberOfStrings(N));}} // This code is contributed by Kartik Singh
<script> // JavaScript program for the above approach // Function to count N-length strings// consisting of vowels only sorted// lexicographicallyfunction findNumberOfStrings(n){ return (n+1)*(n+2)*(n+3)*(n+4)/24;} // Driver Code let N = 2; // Function Call document.write(findNumberOfStrings(N)); </script>
15
Time Complexity: O(1)
Auxiliary Space: O(1)
mohit kumar 29
sanjoy_62
ukasp
avijitmondal1998
2019ucp1394
rones
kalrap615
deepakchowdary
decode2207
suresh07
divyesh072019
divyeshrabadiya07
mukesh07
rameshtravel07
lexicographic-ordering
Dynamic Programming
Mathematical
Pattern Searching
Recursion
Strings
Strings
Dynamic Programming
Mathematical
Recursion
Pattern Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Optimal Substructure Property in Dynamic Programming | DP-2
Min Cost Path | DP-6
Count All Palindrome Sub-Strings in a String | Set 1
Maximum sum such that no two elements are adjacent
Optimal Binary Search Tree | DP-24
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
|
[
{
"code": null,
"e": 24698,
"s": 24670,
"text": "\n25 Oct, 2021"
},
{
"code": null,
"e": 24886,
"s": 24698,
"text": "Given an integer N, the task is to count all possible strings of length N consisting of vowels {a, e, i, o, u} that can be formed such that each string is sorted in lexicographical order."
},
{
"code": null,
"e": 24896,
"s": 24886,
"text": "Examples:"
},
{
"code": null,
"e": 25093,
"s": 24896,
"text": "Input: N = 2Output: 15Explanation: The strings of length 2 which are sorted in lexicographical order are [βaaβ, βaeβ, βaiβ, βaoβ, βauβ, βeeβ, βeiβ, βeoβ, βeuβ, βiiβ, βioβ, βiuβ, βooβ, βouβ, βuuβ]."
},
{
"code": null,
"e": 25224,
"s": 25093,
"text": "Input: N = 1Output: 5Explanation: The strings of length 1 which are sorted in lexicographical order are [βaβ, βeβ, βiβ, βoβ, βuβ]."
},
{
"code": null,
"e": 25422,
"s": 25224,
"text": "Naive Approach: The simplest approach is to generate all possible strings of length N such that each string is sorted in lexicographical order. Print the count obtained after completing the steps. "
},
{
"code": null,
"e": 25566,
"s": 25422,
"text": "Recursive Approach: Keep track of the vowel added to the string so that the next vowel added to the string is always Lexicographically greater."
},
{
"code": null,
"e": 25570,
"s": 25566,
"text": "C++"
},
{
"code": null,
"e": 25575,
"s": 25570,
"text": "Java"
},
{
"code": null,
"e": 25583,
"s": 25575,
"text": "Python3"
},
{
"code": null,
"e": 25586,
"s": 25583,
"text": "C#"
},
{
"code": null,
"e": 25597,
"s": 25586,
"text": "Javascript"
},
{
"code": "// C++ program to illustrate Count of N-length strings// consisting only of vowels sorted lexicographically #include <iostream>using namespace std;// to keep the string in lexicographically sorted order use// start index// to add the vowels starting the from that indexint countstrings(int n, int start){ // base case: if string length is 0 add to the count if (n == 0) { return 1; } int cnt = 0; // if last character in string is 'e' // add vowels starting from 'e' // i.e 'e','i','o','u' for (int i = start; i < 5; i++) { // decrease the length of string cnt += countstrings(n - 1, i); } return cnt;}int countVowelStrings(int n){ // char arr[5]={'a','e','i','o','u'}; // starting from index 0 add the vowels to strings return countstrings(n, 0);}int main(){ int n = 2; cout << countVowelStrings(n); return 0;}// This code is contributed by Deepak Chowdary",
"e": 26529,
"s": 25597,
"text": null
},
{
"code": "// Java program to illustrate Count of N-length strings// consisting only of vowels sorted lexicographicallyimport java.util.*;public class Main{ // to keep the string in lexicographically sorted order use // start index // to add the vowels starting the from that index static int countstrings(int n, int start) { // base case: if string length is 0 add to the count if (n == 0) { return 1; } int cnt = 0; // if last character in string is 'e' // add vowels starting from 'e' // i.e 'e','i','o','u' for (int i = start; i < 5; i++) { // decrease the length of string cnt += countstrings(n - 1, i); } return cnt; } static int countVowelStrings(int n) { // char arr[5]={'a','e','i','o','u'}; // starting from index 0 add the vowels to strings return countstrings(n, 0); } public static void main(String[] args) { int n = 2; System.out.print(countVowelStrings(n)); }} // This code is contributed by divyesh072019.",
"e": 27667,
"s": 26529,
"text": null
},
{
"code": "# Python3 program to illustrate Count of N-length strings# consisting only of vowels sorted lexicographically # to keep the string in lexicographically sorted order use# start index# to add the vowels starting the from that indexdef countstrings(n, start): # base case: if string length is 0 add to the count if n == 0: return 1 cnt = 0 # if last character in string is 'e' # add vowels starting from 'e' # i.e 'e','i','o','u' for i in range(start, 5): # decrease the length of string cnt += countstrings(n - 1, i) return cnt def countVowelStrings(n): # char arr[5]={'a','e','i','o','u'}; # starting from index 0 add the vowels to strings return countstrings(n, 0) n = 2print(countVowelStrings(n)) # This code is contributed by divyeshrabadiya07.",
"e": 28495,
"s": 27667,
"text": null
},
{
"code": "// C# program to illustrate Count of N-length strings// consisting only of vowels sorted lexicographicallyusing System;using System.Collections.Generic;class GFG { // to keep the string in lexicographically sorted order use // start index // to add the vowels starting the from that index static int countstrings(int n, int start) { // base case: if string length is 0 add to the count if (n == 0) { return 1; } int cnt = 0; // if last character in string is 'e' // add vowels starting from 'e' // i.e 'e','i','o','u' for (int i = start; i < 5; i++) { // decrease the length of string cnt += countstrings(n - 1, i); } return cnt; } static int countVowelStrings(int n) { // char arr[5]={'a','e','i','o','u'}; // starting from index 0 add the vowels to strings return countstrings(n, 0); } static void Main() { int n = 2; Console.Write(countVowelStrings(n)); }} // This code is contributed by decode2207.",
"e": 29606,
"s": 28495,
"text": null
},
{
"code": "<script> // Javascript program to illustrate Count of N-length strings // consisting only of vowels sorted lexicographically // to keep the string in lexicographically sorted order use // start index // to add the vowels starting the from that index function countstrings(n, start) { // base case: if string length is 0 add to the count if (n == 0) { return 1; } let cnt = 0; // if last character in string is 'e' // add vowels starting from 'e' // i.e 'e','i','o','u' for (let i = start; i < 5; i++) { // decrease the length of string cnt += countstrings(n - 1, i); } return cnt; } function countVowelStrings(n) { // char arr[5]={'a','e','i','o','u'}; // starting from index 0 add the vowels to strings return countstrings(n, 0); } let n = 2; document.write(countVowelStrings(n)); // This code is contributed by suresh07.</script>",
"e": 30661,
"s": 29606,
"text": null
},
{
"code": null,
"e": 30664,
"s": 30661,
"text": "15"
},
{
"code": null,
"e": 30708,
"s": 30664,
"text": "Time Complexity: O(N!)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 30856,
"s": 30708,
"text": "Efficient Approach: To optimize the above approach, the idea is to use Dynamic Programming. Below are some observations to solve the given problem:"
},
{
"code": null,
"e": 30959,
"s": 30856,
"text": "Count of lexicographically sorted strings of length 1 starting from characters a, e, i, o, and u is 1."
},
{
"code": null,
"e": 32218,
"s": 30959,
"text": "Count of strings of length 2 that are in lexicographical order starting from characters a, e, i, o, and u is given by:The count of lexicographically sorted strings of length 2 starting from characters a is given by the count of the lexicographical strings of length 1 starting from character greater than or equal to a. Therefore, the count is 5.The count of lexicographically sorted strings of length 2 starting from characters e is given by the count of the lexicographical strings of length 1 starting from character greater than or equal to e. Therefore, the count is 4.The count of lexicographically sorted strings of length 2 starting from characters i is given by the count of the lexicographical strings of length 1 starting from character greater than or equal to i. Therefore, the count is 3.The count of lexicographically sorted strings of length 2 starting from characters o is given by the count of the lexicographical strings of length 1 starting from character greater than or equal to o. Therefore, the count is 2.The count of lexicographically sorted strings of length 2 starting from characters u is given by the count of the lexicographical strings of length 1 starting from character greater than or equal to u. Therefore, the count is 1."
},
{
"code": null,
"e": 32447,
"s": 32218,
"text": "The count of lexicographically sorted strings of length 2 starting from characters a is given by the count of the lexicographical strings of length 1 starting from character greater than or equal to a. Therefore, the count is 5."
},
{
"code": null,
"e": 32676,
"s": 32447,
"text": "The count of lexicographically sorted strings of length 2 starting from characters e is given by the count of the lexicographical strings of length 1 starting from character greater than or equal to e. Therefore, the count is 4."
},
{
"code": null,
"e": 32905,
"s": 32676,
"text": "The count of lexicographically sorted strings of length 2 starting from characters i is given by the count of the lexicographical strings of length 1 starting from character greater than or equal to i. Therefore, the count is 3."
},
{
"code": null,
"e": 33134,
"s": 32905,
"text": "The count of lexicographically sorted strings of length 2 starting from characters o is given by the count of the lexicographical strings of length 1 starting from character greater than or equal to o. Therefore, the count is 2."
},
{
"code": null,
"e": 33363,
"s": 33134,
"text": "The count of lexicographically sorted strings of length 2 starting from characters u is given by the count of the lexicographical strings of length 1 starting from character greater than or equal to u. Therefore, the count is 1."
},
{
"code": null,
"e": 33447,
"s": 33363,
"text": "Therefore, the total count of strings length 2 is given by: 5 + 4 + 3 + 2 + 1 = 15."
},
{
"code": null,
"e": 33684,
"s": 33447,
"text": "By observing the above pattern the count of strings of length N starting from each vowel character ch is given by the sum of the count of the lexicographical strings of length (N β 1) starting from character greater than or equal to ch."
},
{
"code": null,
"e": 33729,
"s": 33684,
"text": "Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 33927,
"s": 33729,
"text": "Create a 2D array, dp[N + 1][6] where dp[i][j] represents the number of lexicographically sorted strings of length i that can be constructed using the first j vowels and initialize dp[1][1] with 1."
},
{
"code": null,
"e": 34076,
"s": 33927,
"text": "Iterate over the first row using variable j, set dp[1][j] = dp[1][j β 1] + 1 as the string of length 1 are always sorted in lexicographically order."
},
{
"code": null,
"e": 34326,
"s": 34076,
"text": "Traverse the 2D array dp[][] and update each dp state as dp[i][j] = dp[i][j β 1] + dp[i β 1][j], where dp[i][j β 1] will give the count of lexicographical string length N and dp[i β 1][j] will give the count of lexicographical string length (N β 1)."
},
{
"code": null,
"e": 34418,
"s": 34326,
"text": "After the above steps, print the value of dp[N][5] as the total count of resultant strings."
},
{
"code": null,
"e": 34469,
"s": 34418,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 34473,
"s": 34469,
"text": "C++"
},
{
"code": null,
"e": 34478,
"s": 34473,
"text": "Java"
},
{
"code": null,
"e": 34486,
"s": 34478,
"text": "Python3"
},
{
"code": null,
"e": 34489,
"s": 34486,
"text": "C#"
},
{
"code": null,
"e": 34500,
"s": 34489,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to count N-length strings// consisting of vowels only sorted// lexicographicallyint findNumberOfStrings(int n){ // Stores count of strings consisting // of vowels sorted lexicographically // of all possible lengths vector<vector<int> > DP(n + 1, vector<int>(6)); // Initialize DP[1][1] DP[1][1] = 1; // Traverse the matrix row-wise for (int i = 1; i < n + 1; i++) { for (int j = 1; j < 6; j++) { // Base Case if (i == 1) { DP[i][j] = DP[i][j - 1] + 1; } else { DP[i][j] = DP[i][j - 1] + DP[i - 1][j]; } } } // Return the result return DP[n][5];} // Driver Codeint main(){ int N = 2; // Function Call cout << findNumberOfStrings(N); return 0;}",
"e": 35442,
"s": 34500,
"text": null
},
{
"code": "// Java program to implement// the above approachimport java.util.*;class GFG{ // Function to count N-length strings// consisting of vowels only sorted// lexicographicallystatic int findNumberOfStrings(int n){ // Stores count of strings consisting // of vowels sorted lexicographically // of all possible lengths int DP[][] = new int [n + 1][6]; // Initialize DP[1][1] DP[1][1] = 1; // Traverse the matrix row-wise for (int i = 1; i < n + 1; i++) { for (int j = 1; j < 6; j++) { // Base Case if (i == 1) { DP[i][j] = DP[i][j - 1] + 1; } else { DP[i][j] = DP[i][j - 1] + DP[i - 1][j]; } } } // Return the result return DP[n][5];} // Driver Codepublic static void main(String[] args){ int N = 2; // Function Call System.out.print(findNumberOfStrings(N));}} // This code is contributed by sanjoy_62",
"e": 36336,
"s": 35442,
"text": null
},
{
"code": "# Python3 program for the# above approach # Function to count N-length# strings consisting of vowels# only sorted lexicographicallydef findNumberOfStrings(n): # Stores count of strings # consisting of vowels # sorted lexicographically # of all possible lengths DP = [[0 for i in range(6)] for i in range(n + 1)] # Initialize DP[1][1] DP[1][1] = 1 # Traverse the matrix row-wise for i in range(1, n + 1): for j in range(1, 6): #Base Case if (i == 1): DP[i][j] = DP[i][j - 1] + 1 else: DP[i][j] = DP[i][j - 1]+ DP[i - 1][j] # Return the result return DP[n][5] # Driver Codeif __name__ == '__main__': N = 2 # Function Call print(findNumberOfStrings(N)) # This code is contributed by Mohit Kumar 29",
"e": 37166,
"s": 36336,
"text": null
},
{
"code": "// C# program to implement// the above approachusing System;class GFG{ // Function to count N-length strings// consisting of vowels only sorted// lexicographicallystatic int findNumberOfStrings(int n){ // Stores count of strings consisting // of vowels sorted lexicographically // of all possible lengths int[,] DP = new int [n + 1, 6]; // Initialize DP[1][1] DP[1, 1] = 1; // Traverse the matrix row-wise for (int i = 1; i < n + 1; i++) { for (int j = 1; j < 6; j++) { // Base Case if (i == 1) { DP[i, j] = DP[i, j - 1] + 1; } else { DP[i, j] = DP[i, j - 1] + DP[i - 1, j]; } } } // Return the result return DP[n, 5];} // Driver Codepublic static void Main(string[] args){ int N = 2; // Function Call Console.Write(findNumberOfStrings(N));}} // This code is contributed by Chitranayal",
"e": 38050,
"s": 37166,
"text": null
},
{
"code": "<script> // JavaScript program for the above approach // Function to count N-length strings// consisting of vowels only sorted// lexicographicallyfunction findNumberOfStrings(n){ // Stores count of strings consisting // of vowels sorted lexicographically // of all possible lengths let DP = new Array(n + 1); // Loop to create 2D array using 1D array for (var i = 0; i < DP.length; i++) { DP[i] = new Array(2); } for (var i = 0; i < DP.length; i++) { for (var j = 0; j < DP.length; j++) { DP[i][j] = 0; } } // Initialize DP[1][1] DP[1][1] = 1; // Traverse the matrix row-wise for (let i = 1; i < n + 1; i++) { for (let j = 1; j < 6; j++) { // Base Case if (i == 1) { DP[i][j] = DP[i][j - 1] + 1; } else { DP[i][j] = DP[i][j - 1] + DP[i - 1][j]; } } } // Return the result return DP[n][5];} // Driver Code let N = 2; // Function Call document.write(findNumberOfStrings(N)); </script>",
"e": 39081,
"s": 38050,
"text": null
},
{
"code": null,
"e": 39084,
"s": 39081,
"text": "15"
},
{
"code": null,
"e": 39131,
"s": 39084,
"text": "Time Complexity: O(N*5)Auxiliary Space: O(N*5)"
},
{
"code": null,
"e": 39231,
"s": 39131,
"text": "Efficient Approach: The above approach can further be simplified to linear time and constant space."
},
{
"code": null,
"e": 39300,
"s": 39231,
"text": "Here are some of the observations for different lengths of strings:-"
},
{
"code": null,
"e": 39411,
"s": 39300,
"text": "It is seen that for each value of N, number of strings possible is dependent on the previous value of N (N-1)."
},
{
"code": null,
"e": 39547,
"s": 39411,
"text": "Value of any column in the Nth row is the sum of all columns in the (N-1)th row, starting from right hand side upto that column number."
},
{
"code": null,
"e": 39551,
"s": 39547,
"text": "C++"
},
{
"code": null,
"e": 39556,
"s": 39551,
"text": "Java"
},
{
"code": null,
"e": 39564,
"s": 39556,
"text": "Python3"
},
{
"code": "#include <bits/stdc++.h>using namespace std; // Function to count N-length strings// consisting of vowels only sorted// lexicographicallyint findNumberOfStrings(int N){ // Initializing vector to store count of strings. vector<int> counts(5, 1); for (int i = 2; i <= N; i++) { for (int j = 3; j >= 0; j--) counts[j] += counts[j + 1]; } int ans = 0; // Summing up the total number of combinations. for (auto c : counts) ans += c; // Return the result return ans;} // Driver Codeint main(){ int N = 2; // Function Call cout << findNumberOfStrings(N); return 0;} // This code is contributed by Sarvesh Roshan.",
"e": 40240,
"s": 39564,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*;public class Main{ // Function to count N-length strings // consisting of vowels only sorted // lexicographically static int findNumberOfStrings(int N) { // Initializing vector to store count of strings. Vector<Integer> counts = new Vector<Integer>(); for(int i = 0; i < 5; i++) { counts.add(1); } for (int i = 2; i <= N; i++) { for (int j = 3; j >= 0; j--) counts.set(j, counts.get(j) + counts.get(j + 1)); } int ans = 0; // Summing up the total number of combinations. for(Integer c : counts) ans += c; // Return the result return ans; } public static void main(String[] args) { int N = 2; // Function Call System.out.print(findNumberOfStrings(N)); }} // This code is contributed by mukesh07.",
"e": 41200,
"s": 40240,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to count N-length strings# consisting of vowels only sorted# lexicographicallydef findNumberOfStrings(N): # Initializing vector to store count of strings. counts = [] for i in range(5): counts.append(1) for i in range(2, N + 1): for j in range(3, -1, -1): counts[j] += counts[j + 1] ans = 0 # Summing up the total number of combinations. for c in counts: ans += c # Return the result return ans N = 2 # Function Callprint(findNumberOfStrings(N)) # This code is contributed by decode2207.",
"e": 41813,
"s": 41200,
"text": null
},
{
"code": null,
"e": 41816,
"s": 41813,
"text": "15"
},
{
"code": null,
"e": 41862,
"s": 41816,
"text": "Time Complexity: O(5*N)Space Complexity: O(1)"
},
{
"code": null,
"e": 41977,
"s": 41862,
"text": "Efficient Approach: The same idea of the above dp approach can be implemented in constant time and constant space."
},
{
"code": null,
"e": 41981,
"s": 41977,
"text": "C++"
},
{
"code": null,
"e": 41986,
"s": 41981,
"text": "Java"
},
{
"code": null,
"e": 41993,
"s": 41986,
"text": "Python"
},
{
"code": null,
"e": 41996,
"s": 41993,
"text": "C#"
},
{
"code": null,
"e": 42007,
"s": 41996,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to count N-length strings// consisting of vowels only sorted// lexicographicallyint findNumberOfStrings(int n){ return (n+1)*(n+2)*(n+3)*(n+4)/24;} // Driver Codeint main(){ int N = 2; // Function Call cout << findNumberOfStrings(N); return 0;}// This code is contributed by Kartik Singh",
"e": 42406,
"s": 42007,
"text": null
},
{
"code": "// Java program to implement// the above approachimport java.util.*;class GFG{ // Function to count N-length strings// consisting of vowels only sorted// lexicographicallystatic int findNumberOfStrings(int n){ return (n+1)*(n+2)*(n+3)*(n+4)/24;} // Driver Codepublic static void main(String[] args){ int N = 2; // Function Call System.out.print(findNumberOfStrings(N));}} // This code is contributed by Kartik Singh",
"e": 42828,
"s": 42406,
"text": null
},
{
"code": "# Python3 program for the# above approach # Function to count N-length# strings consisting of vowels# only sorted lexicographicallydef findNumberOfStrings(n): return int((n+1)*(n+2)*(n+3)*(n+4)/24) # Driver Codeif __name__ == '__main__': N = 2 # Function Call print(findNumberOfStrings(N)) # This code is contributed by Kartik Singh",
"e": 43177,
"s": 42828,
"text": null
},
{
"code": "// C# program to implement// the above approachusing System;class GFG{ // Function to count N-length strings// consisting of vowels only sorted// lexicographicallystatic int findNumberOfStrings(int n){ return (n+1)*(n+2)*(n+3)*(n+4)/24;} // Driver Codepublic static void Main(string[] args){ int N = 2; // Function Call Console.Write(findNumberOfStrings(N));}} // This code is contributed by Kartik Singh",
"e": 43589,
"s": 43177,
"text": null
},
{
"code": "<script> // JavaScript program for the above approach // Function to count N-length strings// consisting of vowels only sorted// lexicographicallyfunction findNumberOfStrings(n){ return (n+1)*(n+2)*(n+3)*(n+4)/24;} // Driver Code let N = 2; // Function Call document.write(findNumberOfStrings(N)); </script>",
"e": 43911,
"s": 43589,
"text": null
},
{
"code": null,
"e": 43914,
"s": 43911,
"text": "15"
},
{
"code": null,
"e": 43936,
"s": 43914,
"text": "Time Complexity: O(1)"
},
{
"code": null,
"e": 43958,
"s": 43936,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 43973,
"s": 43958,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 43983,
"s": 43973,
"text": "sanjoy_62"
},
{
"code": null,
"e": 43989,
"s": 43983,
"text": "ukasp"
},
{
"code": null,
"e": 44006,
"s": 43989,
"text": "avijitmondal1998"
},
{
"code": null,
"e": 44018,
"s": 44006,
"text": "2019ucp1394"
},
{
"code": null,
"e": 44024,
"s": 44018,
"text": "rones"
},
{
"code": null,
"e": 44034,
"s": 44024,
"text": "kalrap615"
},
{
"code": null,
"e": 44049,
"s": 44034,
"text": "deepakchowdary"
},
{
"code": null,
"e": 44060,
"s": 44049,
"text": "decode2207"
},
{
"code": null,
"e": 44069,
"s": 44060,
"text": "suresh07"
},
{
"code": null,
"e": 44083,
"s": 44069,
"text": "divyesh072019"
},
{
"code": null,
"e": 44101,
"s": 44083,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 44110,
"s": 44101,
"text": "mukesh07"
},
{
"code": null,
"e": 44125,
"s": 44110,
"text": "rameshtravel07"
},
{
"code": null,
"e": 44148,
"s": 44125,
"text": "lexicographic-ordering"
},
{
"code": null,
"e": 44168,
"s": 44148,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 44181,
"s": 44168,
"text": "Mathematical"
},
{
"code": null,
"e": 44199,
"s": 44181,
"text": "Pattern Searching"
},
{
"code": null,
"e": 44209,
"s": 44199,
"text": "Recursion"
},
{
"code": null,
"e": 44217,
"s": 44209,
"text": "Strings"
},
{
"code": null,
"e": 44225,
"s": 44217,
"text": "Strings"
},
{
"code": null,
"e": 44245,
"s": 44225,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 44258,
"s": 44245,
"text": "Mathematical"
},
{
"code": null,
"e": 44268,
"s": 44258,
"text": "Recursion"
},
{
"code": null,
"e": 44286,
"s": 44268,
"text": "Pattern Searching"
},
{
"code": null,
"e": 44384,
"s": 44286,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 44444,
"s": 44384,
"text": "Optimal Substructure Property in Dynamic Programming | DP-2"
},
{
"code": null,
"e": 44465,
"s": 44444,
"text": "Min Cost Path | DP-6"
},
{
"code": null,
"e": 44518,
"s": 44465,
"text": "Count All Palindrome Sub-Strings in a String | Set 1"
},
{
"code": null,
"e": 44569,
"s": 44518,
"text": "Maximum sum such that no two elements are adjacent"
},
{
"code": null,
"e": 44604,
"s": 44569,
"text": "Optimal Binary Search Tree | DP-24"
},
{
"code": null,
"e": 44664,
"s": 44604,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 44679,
"s": 44664,
"text": "C++ Data Types"
},
{
"code": null,
"e": 44722,
"s": 44679,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 44746,
"s": 44722,
"text": "Merge two sorted arrays"
}
] |
Collinearity Measures. Metrics and approaches towards... | by ShengJun | Towards Data Science
|
Feature selection is a process where the predictor variables that contribute most significantly towards the prediction/ classification of the target variable are selected. In feature selection for linear regression models, we are concerned with four aspects regarding the variables. Framed as a mnemonic βLINEβ, these are:
Linearity. The selected variable possesses a linear relationship with the target variable.Independence of predictor variables. Selected variables to be independent of each other.Normality. Residuals generally follow a normal distribution (mean of zero).Equality of variance. The residual errors are generally consistent across the values of predictor variables (i.e. Homoscedasticity).
Linearity. The selected variable possesses a linear relationship with the target variable.
Independence of predictor variables. Selected variables to be independent of each other.
Normality. Residuals generally follow a normal distribution (mean of zero).
Equality of variance. The residual errors are generally consistent across the values of predictor variables (i.e. Homoscedasticity).
In cases where selected predictor variables are not independent of each other, we would not be able to clearly determine or attribute the contribution from the various predictor variables towards the target variable β interpretability of the model coefficients becomes an issue.
One approach in feature selection would be through the use of p-values; where variables with p-values above a certain threshold (typically +/- 0.05) are surfaced as not significantly contributing towards the target variable, and hence can be dropped to reduce model complexity. However, this approach has its own challenges when multicollinearity exists among the predictor variables as illustrated through the Boston housing dataset in sklearn.
# Original (full) set of variablesX_o = df_wdummy[['CRIM', 'ZN', 'INDUS', 'NOX', 'RM', 'AGE', 'DIS', 'RAD', 'TAX', 'PTRATIO', 'B', 'LSTAT', 'CHAS_1.0']]X_o = sm.add_constant(X_o)y_o = df_wdummy['MEDV']# Baseline resultsmodel_o = sm.OLS(y_o, X_o)results_o = model_o.fit()results_o.summary()
Based on the p-values, we remove variables INDUS and AGE and review the updated p-values.
# Remove Age -> Remove INDUS, based on p-values. X_r0 = df_wdummy[['CRIM', 'ZN', 'NOX', 'RM', 'DIS', 'RAD', 'TAX', 'PTRATIO', 'B', 'LSTAT', 'CHAS_1.0']]X_r0 = sm.add_constant(X_r0)y_r0 = df_wdummy['MEDV']# resultsmodel_r0 = sm.OLS(y_r0, X_r0)results_r0 = model_r0.fit()results_r0.summary()
Though all p-values are lower than 0.05, multicollinearity still exists (between TAX and RAD variables.) The presence of multicollinearity can mask the importance of the respective variable contributions to the target variable, where the interpretability of p-values then becomes challenging. We could use correlation measures and matrices to help visualize and mitigate multicollinearity. Such an approach is fine until we need to use different correlation measures (i.e. Spearman, Pearson, Kendall) due to the inherent attributes of the variables. In the example above, the variable RAD (index of accessibility to radial highways) is an ordinal variable. TAX (full-value property-tax rate per $10,000) is a continuous variable (not normally distributed). Using the different correlation measures and matrices, one could potentially overlook correlation among different categories of variables.
Another approach to identify multicollinearity is via the Variance Inflation Factor. VIF indicates the percentage of the variance inflated for each variableβs coefficient. Beginning at a value of 1 (no collinearity), a VIF between 1β5 indicates moderate collinearity while values above 5 indicate high collinearity. Some cases where high VIF would be acceptable include the use of interaction terms, polynomial terms, or dummy variables (nominal variables with three or more categories). Correlation matrices enable identification of correlation among variable pairs while VIF enables the overall assessment of multicollinearity. The correlation matrix for most of the continuous variables is presented below to highlight the various collinear variable pairs. VIF can be calculated using the statsmodels package; the code block below presents the VIF values with collinear variables included (left) and removed (right).
# Setting the predictor variablesX_o = df_wdummy[['CRIM', 'ZN', 'INDUS', 'NOX', 'RM', 'AGE', 'DIS', 'RAD', 'TAX', 'PTRATIO', 'B', 'LSTAT', 'CHAS_1.0']]X_r1 = df_wdummy[['CRIM', 'ZN', 'INDUS', 'RM', 'AGE', 'DIS', 'TAX', 'PTRATIO', 'B', 'LSTAT', 'CHAS_1.0']]# from statsmodels.stats.outliers_influence import variance_inflation_factorvif = pd.Series([variance_inflation_factor(X_o.values, i) for i in range(X_o.shape[1])], index=X_o.columns, name='vif_full')vif_r = pd.Series([variance_inflation_factor(X_r1.values, i) for i in range(X_r1.shape[1])], index=X_r1.columns, name='vif_collinear_rvmd')pd.concat([vif, vif_r], axis=1)
The VIF values correspond with the correlation matrix; for example, variable-pair NOX and INDUS, the correlation coefficient is above 0.5 (0.61), and the respective VIF values are above 5. The removal of the collinear variables RAD and NOX improved the VIF figures. Dropping collinear variables solely based on the highest VIF figure is not a guaranteed way towards building the best performing model, as elaborated in the next section.
We build a baseline model by dropping all collinear variables identified in the correlation matrix (shown above), pending TAX and RAD to be dropped next.
# Baseline variables X_bl = df_wdummy[['INDUS', 'RM', 'AGE', 'RAD', 'TAX', 'PTRATIO', 'LSTAT']]y_bl = df_wdummy['MEDV']# Explore mitigating multi-collinearityvif_bl = pd.Series([variance_inflation_factor(X_bl.values, i) for i in range(X_bl.shape[1])], index=X_bl.columns, name='vif_bl')X_noTAX = X_bl.drop(['TAX'],axis=1)X_noRAD = X_bl.drop(['RAD'],axis=1)vif_noTAX = pd.Series([variance_inflation_factor(X_noTAX.values, i) for i in range(X_noTAX.shape[1])], index=X_noTAX.columns, name='vif_noTAX')vif_noRAD = pd.Series([variance_inflation_factor(X_noRAD.values, i) for i in range(X_noRAD.shape[1])], index=X_noRAD.columns, name='vif_noRAD')pd.concat([vif_bl, vif_noTAX, vif_noRAD], axis=1)
While it appears dropping the TAX variable based on VIF seems to be better, a prudent approach is to check via the adjusted R-squared metric (adjusted for the number of predictors, the metric increases only if the next added variable improves the model more than would be expected by chance).
# Without TAXmodel = sm.OLS(y, sm.add_constant(X_noTAX)).fit()print_model = model.summary()print(print_model)
# Without RADmodel = sm.OLS(y, sm.add_constant(X_noRAD)).fit()print_model = model.summary()print(print_model)
From the higher adjusted R-squared figure, we can infer that the model performs better with the RAD variable dropped! With multicollinearity issue addressed, the next step could be to explore the addition of interaction terms to potentially boost model performance.
In summary, the presence of multicollinearity can mask the importance of predictor variables to the target variable. The use of both Correlation matrices and VIF can help identify correlated variable pairs and assess multicollinearity among selected variables (features). While some iterations would still be necessary to assess model performance, with VIF and correlation matrices, we would be able to make a better-informed decision for feature selection.
Codes are hosted here: https://github.com/AngShengJun/petProj/tree/master/eda_viz
References:
Correlation methods 1 https://datascience.stackexchange.com/questions/64260/pearson-vs-spearman-vs-kendallCorrelation methods 2 https://support.minitab.com/en-us/minitab-express/1/help-and-how-to/modeling-statistics/regression/supporting-topics/basics/a-comparison-of-the-pearson-and-spearman-correlation-methods/
Correlation methods 1 https://datascience.stackexchange.com/questions/64260/pearson-vs-spearman-vs-kendall
Correlation methods 2 https://support.minitab.com/en-us/minitab-express/1/help-and-how-to/modeling-statistics/regression/supporting-topics/basics/a-comparison-of-the-pearson-and-spearman-correlation-methods/
|
[
{
"code": null,
"e": 495,
"s": 172,
"text": "Feature selection is a process where the predictor variables that contribute most significantly towards the prediction/ classification of the target variable are selected. In feature selection for linear regression models, we are concerned with four aspects regarding the variables. Framed as a mnemonic βLINEβ, these are:"
},
{
"code": null,
"e": 881,
"s": 495,
"text": "Linearity. The selected variable possesses a linear relationship with the target variable.Independence of predictor variables. Selected variables to be independent of each other.Normality. Residuals generally follow a normal distribution (mean of zero).Equality of variance. The residual errors are generally consistent across the values of predictor variables (i.e. Homoscedasticity)."
},
{
"code": null,
"e": 972,
"s": 881,
"text": "Linearity. The selected variable possesses a linear relationship with the target variable."
},
{
"code": null,
"e": 1061,
"s": 972,
"text": "Independence of predictor variables. Selected variables to be independent of each other."
},
{
"code": null,
"e": 1137,
"s": 1061,
"text": "Normality. Residuals generally follow a normal distribution (mean of zero)."
},
{
"code": null,
"e": 1270,
"s": 1137,
"text": "Equality of variance. The residual errors are generally consistent across the values of predictor variables (i.e. Homoscedasticity)."
},
{
"code": null,
"e": 1549,
"s": 1270,
"text": "In cases where selected predictor variables are not independent of each other, we would not be able to clearly determine or attribute the contribution from the various predictor variables towards the target variable β interpretability of the model coefficients becomes an issue."
},
{
"code": null,
"e": 1995,
"s": 1549,
"text": "One approach in feature selection would be through the use of p-values; where variables with p-values above a certain threshold (typically +/- 0.05) are surfaced as not significantly contributing towards the target variable, and hence can be dropped to reduce model complexity. However, this approach has its own challenges when multicollinearity exists among the predictor variables as illustrated through the Boston housing dataset in sklearn."
},
{
"code": null,
"e": 2285,
"s": 1995,
"text": "# Original (full) set of variablesX_o = df_wdummy[['CRIM', 'ZN', 'INDUS', 'NOX', 'RM', 'AGE', 'DIS', 'RAD', 'TAX', 'PTRATIO', 'B', 'LSTAT', 'CHAS_1.0']]X_o = sm.add_constant(X_o)y_o = df_wdummy['MEDV']# Baseline resultsmodel_o = sm.OLS(y_o, X_o)results_o = model_o.fit()results_o.summary()"
},
{
"code": null,
"e": 2375,
"s": 2285,
"text": "Based on the p-values, we remove variables INDUS and AGE and review the updated p-values."
},
{
"code": null,
"e": 2671,
"s": 2375,
"text": "# Remove Age -> Remove INDUS, based on p-values. X_r0 = df_wdummy[['CRIM', 'ZN', 'NOX', 'RM', 'DIS', 'RAD', 'TAX', 'PTRATIO', 'B', 'LSTAT', 'CHAS_1.0']]X_r0 = sm.add_constant(X_r0)y_r0 = df_wdummy['MEDV']# resultsmodel_r0 = sm.OLS(y_r0, X_r0)results_r0 = model_r0.fit()results_r0.summary()"
},
{
"code": null,
"e": 3567,
"s": 2671,
"text": "Though all p-values are lower than 0.05, multicollinearity still exists (between TAX and RAD variables.) The presence of multicollinearity can mask the importance of the respective variable contributions to the target variable, where the interpretability of p-values then becomes challenging. We could use correlation measures and matrices to help visualize and mitigate multicollinearity. Such an approach is fine until we need to use different correlation measures (i.e. Spearman, Pearson, Kendall) due to the inherent attributes of the variables. In the example above, the variable RAD (index of accessibility to radial highways) is an ordinal variable. TAX (full-value property-tax rate per $10,000) is a continuous variable (not normally distributed). Using the different correlation measures and matrices, one could potentially overlook correlation among different categories of variables."
},
{
"code": null,
"e": 4487,
"s": 3567,
"text": "Another approach to identify multicollinearity is via the Variance Inflation Factor. VIF indicates the percentage of the variance inflated for each variableβs coefficient. Beginning at a value of 1 (no collinearity), a VIF between 1β5 indicates moderate collinearity while values above 5 indicate high collinearity. Some cases where high VIF would be acceptable include the use of interaction terms, polynomial terms, or dummy variables (nominal variables with three or more categories). Correlation matrices enable identification of correlation among variable pairs while VIF enables the overall assessment of multicollinearity. The correlation matrix for most of the continuous variables is presented below to highlight the various collinear variable pairs. VIF can be calculated using the statsmodels package; the code block below presents the VIF values with collinear variables included (left) and removed (right)."
},
{
"code": null,
"e": 5147,
"s": 4487,
"text": "# Setting the predictor variablesX_o = df_wdummy[['CRIM', 'ZN', 'INDUS', 'NOX', 'RM', 'AGE', 'DIS', 'RAD', 'TAX', 'PTRATIO', 'B', 'LSTAT', 'CHAS_1.0']]X_r1 = df_wdummy[['CRIM', 'ZN', 'INDUS', 'RM', 'AGE', 'DIS', 'TAX', 'PTRATIO', 'B', 'LSTAT', 'CHAS_1.0']]# from statsmodels.stats.outliers_influence import variance_inflation_factorvif = pd.Series([variance_inflation_factor(X_o.values, i) for i in range(X_o.shape[1])], index=X_o.columns, name='vif_full')vif_r = pd.Series([variance_inflation_factor(X_r1.values, i) for i in range(X_r1.shape[1])], index=X_r1.columns, name='vif_collinear_rvmd')pd.concat([vif, vif_r], axis=1)"
},
{
"code": null,
"e": 5584,
"s": 5147,
"text": "The VIF values correspond with the correlation matrix; for example, variable-pair NOX and INDUS, the correlation coefficient is above 0.5 (0.61), and the respective VIF values are above 5. The removal of the collinear variables RAD and NOX improved the VIF figures. Dropping collinear variables solely based on the highest VIF figure is not a guaranteed way towards building the best performing model, as elaborated in the next section."
},
{
"code": null,
"e": 5738,
"s": 5584,
"text": "We build a baseline model by dropping all collinear variables identified in the correlation matrix (shown above), pending TAX and RAD to be dropped next."
},
{
"code": null,
"e": 6488,
"s": 5738,
"text": "# Baseline variables X_bl = df_wdummy[['INDUS', 'RM', 'AGE', 'RAD', 'TAX', 'PTRATIO', 'LSTAT']]y_bl = df_wdummy['MEDV']# Explore mitigating multi-collinearityvif_bl = pd.Series([variance_inflation_factor(X_bl.values, i) for i in range(X_bl.shape[1])], index=X_bl.columns, name='vif_bl')X_noTAX = X_bl.drop(['TAX'],axis=1)X_noRAD = X_bl.drop(['RAD'],axis=1)vif_noTAX = pd.Series([variance_inflation_factor(X_noTAX.values, i) for i in range(X_noTAX.shape[1])], index=X_noTAX.columns, name='vif_noTAX')vif_noRAD = pd.Series([variance_inflation_factor(X_noRAD.values, i) for i in range(X_noRAD.shape[1])], index=X_noRAD.columns, name='vif_noRAD')pd.concat([vif_bl, vif_noTAX, vif_noRAD], axis=1)"
},
{
"code": null,
"e": 6781,
"s": 6488,
"text": "While it appears dropping the TAX variable based on VIF seems to be better, a prudent approach is to check via the adjusted R-squared metric (adjusted for the number of predictors, the metric increases only if the next added variable improves the model more than would be expected by chance)."
},
{
"code": null,
"e": 6891,
"s": 6781,
"text": "# Without TAXmodel = sm.OLS(y, sm.add_constant(X_noTAX)).fit()print_model = model.summary()print(print_model)"
},
{
"code": null,
"e": 7001,
"s": 6891,
"text": "# Without RADmodel = sm.OLS(y, sm.add_constant(X_noRAD)).fit()print_model = model.summary()print(print_model)"
},
{
"code": null,
"e": 7267,
"s": 7001,
"text": "From the higher adjusted R-squared figure, we can infer that the model performs better with the RAD variable dropped! With multicollinearity issue addressed, the next step could be to explore the addition of interaction terms to potentially boost model performance."
},
{
"code": null,
"e": 7725,
"s": 7267,
"text": "In summary, the presence of multicollinearity can mask the importance of predictor variables to the target variable. The use of both Correlation matrices and VIF can help identify correlated variable pairs and assess multicollinearity among selected variables (features). While some iterations would still be necessary to assess model performance, with VIF and correlation matrices, we would be able to make a better-informed decision for feature selection."
},
{
"code": null,
"e": 7807,
"s": 7725,
"text": "Codes are hosted here: https://github.com/AngShengJun/petProj/tree/master/eda_viz"
},
{
"code": null,
"e": 7819,
"s": 7807,
"text": "References:"
},
{
"code": null,
"e": 8133,
"s": 7819,
"text": "Correlation methods 1 https://datascience.stackexchange.com/questions/64260/pearson-vs-spearman-vs-kendallCorrelation methods 2 https://support.minitab.com/en-us/minitab-express/1/help-and-how-to/modeling-statistics/regression/supporting-topics/basics/a-comparison-of-the-pearson-and-spearman-correlation-methods/"
},
{
"code": null,
"e": 8240,
"s": 8133,
"text": "Correlation methods 1 https://datascience.stackexchange.com/questions/64260/pearson-vs-spearman-vs-kendall"
}
] |
Node.js Stream readable.pipe() Method - GeeksforGeeks
|
13 May, 2022
The readable.pipe() method in a Readable Stream is used to attach a Writable stream to the readable stream so that it consequently switches into flowing mode and then pushes all the data that it has to the attached Writable.
Syntax:
readable.pipe( destination, options )
Parameters: This method accept two parameters as mentioned above and described below:
destination: This parameter holds the destination of writing data.
options: This parameter holds the pipe options.
Return Value: It returns the stream.Writable destination, allowing for a chain of pipes if it is a Duplex or a Transform stream. Below examples illustrate the use of readable.pipe() method in Node.js:
Example 1:
javascript
// Node.js program to demonstrate the // readable.pipe() method // Accessing fs modulevar fs = require("fs"); // Create a readable streamvar readable = fs.createReadStream('input.txt'); // Create a writable streamvar writable = fs.createWriteStream('output.txt'); // Calling pipe methodreadable.pipe(writable); console.log("Program Ended");
Output:
Program Ended
So, after the piping method the file named βoutput.textβ must contain the data that was in the file βinput.textβ.
Example 2:
javascript
// Node.js program to demonstrate // the chaining of streams using// readable.pipe() method // Accessing fs and zlib modulevar fs = require("fs");var zlib = require('zlib'); // Compress the file input.text to// input.txt.gz using pipe() methodfs.createReadStream('input.text') .pipe(zlib.createGzip()) .pipe(fs.createWriteStream('input.text.gz')); console.log("File Compressed.");
Output:
File Compressed.
Reference: https://nodejs.org/api/stream.html#stream_readable_pipe_destination_options.
gigicampagnola
Node.js-Stream-module
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
How to use an ES6 import in Node.js?
How to read and write Excel file in Node.js ?
Express.js res.render() Function
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 25809,
"s": 25781,
"text": "\n13 May, 2022"
},
{
"code": null,
"e": 26035,
"s": 25809,
"text": "The readable.pipe() method in a Readable Stream is used to attach a Writable stream to the readable stream so that it consequently switches into flowing mode and then pushes all the data that it has to the attached Writable. "
},
{
"code": null,
"e": 26043,
"s": 26035,
"text": "Syntax:"
},
{
"code": null,
"e": 26081,
"s": 26043,
"text": "readable.pipe( destination, options )"
},
{
"code": null,
"e": 26167,
"s": 26081,
"text": "Parameters: This method accept two parameters as mentioned above and described below:"
},
{
"code": null,
"e": 26234,
"s": 26167,
"text": "destination: This parameter holds the destination of writing data."
},
{
"code": null,
"e": 26282,
"s": 26234,
"text": "options: This parameter holds the pipe options."
},
{
"code": null,
"e": 26484,
"s": 26282,
"text": "Return Value: It returns the stream.Writable destination, allowing for a chain of pipes if it is a Duplex or a Transform stream. Below examples illustrate the use of readable.pipe() method in Node.js: "
},
{
"code": null,
"e": 26496,
"s": 26484,
"text": "Example 1: "
},
{
"code": null,
"e": 26507,
"s": 26496,
"text": "javascript"
},
{
"code": "// Node.js program to demonstrate the // readable.pipe() method // Accessing fs modulevar fs = require(\"fs\"); // Create a readable streamvar readable = fs.createReadStream('input.txt'); // Create a writable streamvar writable = fs.createWriteStream('output.txt'); // Calling pipe methodreadable.pipe(writable); console.log(\"Program Ended\");",
"e": 26852,
"s": 26507,
"text": null
},
{
"code": null,
"e": 26860,
"s": 26852,
"text": "Output:"
},
{
"code": null,
"e": 26874,
"s": 26860,
"text": "Program Ended"
},
{
"code": null,
"e": 26989,
"s": 26874,
"text": "So, after the piping method the file named βoutput.textβ must contain the data that was in the file βinput.textβ. "
},
{
"code": null,
"e": 27001,
"s": 26989,
"text": "Example 2: "
},
{
"code": null,
"e": 27012,
"s": 27001,
"text": "javascript"
},
{
"code": "// Node.js program to demonstrate // the chaining of streams using// readable.pipe() method // Accessing fs and zlib modulevar fs = require(\"fs\");var zlib = require('zlib'); // Compress the file input.text to// input.txt.gz using pipe() methodfs.createReadStream('input.text') .pipe(zlib.createGzip()) .pipe(fs.createWriteStream('input.text.gz')); console.log(\"File Compressed.\");",
"e": 27403,
"s": 27012,
"text": null
},
{
"code": null,
"e": 27411,
"s": 27403,
"text": "Output:"
},
{
"code": null,
"e": 27428,
"s": 27411,
"text": "File Compressed."
},
{
"code": null,
"e": 27516,
"s": 27428,
"text": "Reference: https://nodejs.org/api/stream.html#stream_readable_pipe_destination_options."
},
{
"code": null,
"e": 27531,
"s": 27516,
"text": "gigicampagnola"
},
{
"code": null,
"e": 27553,
"s": 27531,
"text": "Node.js-Stream-module"
},
{
"code": null,
"e": 27561,
"s": 27553,
"text": "Node.js"
},
{
"code": null,
"e": 27578,
"s": 27561,
"text": "Web Technologies"
},
{
"code": null,
"e": 27676,
"s": 27578,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27733,
"s": 27676,
"text": "How to install the previous version of node.js and npm ?"
},
{
"code": null,
"e": 27787,
"s": 27733,
"text": "Difference between promise and async await in Node.js"
},
{
"code": null,
"e": 27824,
"s": 27787,
"text": "How to use an ES6 import in Node.js?"
},
{
"code": null,
"e": 27870,
"s": 27824,
"text": "How to read and write Excel file in Node.js ?"
},
{
"code": null,
"e": 27903,
"s": 27870,
"text": "Express.js res.render() Function"
},
{
"code": null,
"e": 27943,
"s": 27903,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 27988,
"s": 27943,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28031,
"s": 27988,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28081,
"s": 28031,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Python - Database Manager (dbm) package - GeeksforGeeks
|
14 Aug, 2021
In this article we will learn about dbm, a package in built-in library of python. dbm package in python provides a simple dictionary like interface of the form DBM (DataBase Manager) generally used in Unix operating system. dbm stores data in simple key β value pair form like a dictionary which makes it easier to insert, edit and retrieve data from database. It stores data by the use of a single primary key (βkeyβ) in fixed size blocks.
There are three types of sub modules in dbm package :
dbm.gnu: GNUβs reinterpretation of dbmdbm.ndbm: Interface based on ndbmdbm.dumb: Portable DBM implementation
dbm.gnu: GNUβs reinterpretation of dbm
dbm.ndbm: Interface based on ndbm
dbm.dumb: Portable DBM implementation
Following are the main functions available in dbm package :
This function is used to open a dbm database or create a new database if not exist.
Syntax: dbm.open(file, flag=βrβ, mode=0o666)
Parameters: This function take following parameters:
file: name of the file.
flag: mode of permissions. which can be βrβ, βwβ, βcβ, or βnβ.βrβ: open the existing database with permission to read only.βwβ: open the existing database with permission to read and write.βcβ: open the database for read and write, also create a new one if it doesnβt exists.βnβ: Always create a new database with permission to both read and write.
βrβ: open the existing database with permission to read only.
βwβ: open the existing database with permission to read and write.
βcβ: open the database for read and write, also create a new one if it doesnβt exists.
βnβ: Always create a new database with permission to both read and write.
mode: The Unix mode of the argument which is a octal form default set to 0o666, used only when new database is to be created.
Return: The corresponding object address of the database file.
This function attempts to guess which of the several simple database modules available- dbm.gnu, dbm.ndbm, or dbm.dumb- should be used to open a given file.
Syntax: dbm.whichdb(filename)
Parameter: filename- Name of the file.
Returns: The function returns one of the following values :
None: If the database doesnβt exists or it canβt be opened.
(β β): An empty string, if the file exists but the file format canβt be guessed else
The required module name: If the type is successfully detected then one of the string names is returned, βdbm.gnuβ, βdbm.ndbmβ or βdbm.dumbβ.
Following are the built-in methods for dbm objects :
items(): This method returns the items contained in the database of caller object in form of key value pairs. (db is the caller object database).
clear(): clear all the values present in the database.
get(key): returns the value corresponding to key given in argument.
keys(), iterkeys(): returns an iterable list containing keys of the dictionary.
pop(key): Deletes / pops the key, value pair corresponding to key given in argument.
setdefault(): set a default primary key given in the argument.
sync(): Helps to synchronize data files and on disk directory.
update(): updates the existing key value. Just like dictionary object.
values(): iterate through all the values present in database.
close(): Doesnβt take any argument nor returns anything. Just closes the caller object database. (db in this case)
Below is the implementation of all the above discuss methods/functions:
Code:
Python3
# importing the dbm packageimport dbm # using the open function# to create a new database named# 'mydb' in 'n' mode, object# returned in db variable.db = dbm.open('mydb','n') # inserting the new key and# values in the database.db['name'] = 'GeeksforGeeks'db['phone'] = '8888'db['Short name'] = 'GfG'db['Date'] = '01/01/2000' # getting and printing# the value through get method.print(db.get('name'))print() # printing the values of# database through values()# method (iterator).for value in db.values(): print(value)print() # printing the values through# key iterator.for key in db.keys(): print(db.get(key))print() # poping out the key, value# pair corresponding to# 'phone' key.db.pop('phone') # printing the key, value# pairs present in database.for key, value in db.items(): print(key, value) # clearing all the key values# in database.db.clear() # Below loop will print nothing# as database is cleared above.for key, value in db.items(): print(key, value) # closing the database.db.close() # This code is contributed by Amit Mangal.
Output :
b'GeeksforGeeks'
b'GeeksforGeeks'
b'8888'
b'GfG'
b'01/01/2000'
b'GeeksforGeeks'
b'8888'
b'GfG'
b'01/01/2000'
b'name' b'GeeksforGeeks'
b'Short name' b'GfG'
b'Date' b'01/01/2000'
varshagumber28
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
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": 25555,
"s": 25527,
"text": "\n14 Aug, 2021"
},
{
"code": null,
"e": 25997,
"s": 25555,
"text": "In this article we will learn about dbm, a package in built-in library of python. dbm package in python provides a simple dictionary like interface of the form DBM (DataBase Manager) generally used in Unix operating system. dbm stores data in simple key β value pair form like a dictionary which makes it easier to insert, edit and retrieve data from database. It stores data by the use of a single primary key (βkeyβ) in fixed size blocks. "
},
{
"code": null,
"e": 26051,
"s": 25997,
"text": "There are three types of sub modules in dbm package :"
},
{
"code": null,
"e": 26160,
"s": 26051,
"text": "dbm.gnu: GNUβs reinterpretation of dbmdbm.ndbm: Interface based on ndbmdbm.dumb: Portable DBM implementation"
},
{
"code": null,
"e": 26199,
"s": 26160,
"text": "dbm.gnu: GNUβs reinterpretation of dbm"
},
{
"code": null,
"e": 26233,
"s": 26199,
"text": "dbm.ndbm: Interface based on ndbm"
},
{
"code": null,
"e": 26271,
"s": 26233,
"text": "dbm.dumb: Portable DBM implementation"
},
{
"code": null,
"e": 26331,
"s": 26271,
"text": "Following are the main functions available in dbm package :"
},
{
"code": null,
"e": 26415,
"s": 26331,
"text": "This function is used to open a dbm database or create a new database if not exist."
},
{
"code": null,
"e": 26460,
"s": 26415,
"text": "Syntax: dbm.open(file, flag=βrβ, mode=0o666)"
},
{
"code": null,
"e": 26514,
"s": 26460,
"text": "Parameters: This function take following parameters: "
},
{
"code": null,
"e": 26538,
"s": 26514,
"text": "file: name of the file."
},
{
"code": null,
"e": 26887,
"s": 26538,
"text": "flag: mode of permissions. which can be βrβ, βwβ, βcβ, or βnβ.βrβ: open the existing database with permission to read only.βwβ: open the existing database with permission to read and write.βcβ: open the database for read and write, also create a new one if it doesnβt exists.βnβ: Always create a new database with permission to both read and write."
},
{
"code": null,
"e": 26949,
"s": 26887,
"text": "βrβ: open the existing database with permission to read only."
},
{
"code": null,
"e": 27016,
"s": 26949,
"text": "βwβ: open the existing database with permission to read and write."
},
{
"code": null,
"e": 27103,
"s": 27016,
"text": "βcβ: open the database for read and write, also create a new one if it doesnβt exists."
},
{
"code": null,
"e": 27177,
"s": 27103,
"text": "βnβ: Always create a new database with permission to both read and write."
},
{
"code": null,
"e": 27303,
"s": 27177,
"text": "mode: The Unix mode of the argument which is a octal form default set to 0o666, used only when new database is to be created."
},
{
"code": null,
"e": 27367,
"s": 27303,
"text": "Return: The corresponding object address of the database file. "
},
{
"code": null,
"e": 27524,
"s": 27367,
"text": "This function attempts to guess which of the several simple database modules available- dbm.gnu, dbm.ndbm, or dbm.dumb- should be used to open a given file."
},
{
"code": null,
"e": 27555,
"s": 27524,
"text": "Syntax: dbm.whichdb(filename) "
},
{
"code": null,
"e": 27594,
"s": 27555,
"text": "Parameter: filename- Name of the file."
},
{
"code": null,
"e": 27654,
"s": 27594,
"text": "Returns: The function returns one of the following values :"
},
{
"code": null,
"e": 27714,
"s": 27654,
"text": "None: If the database doesnβt exists or it canβt be opened."
},
{
"code": null,
"e": 27799,
"s": 27714,
"text": "(β β): An empty string, if the file exists but the file format canβt be guessed else"
},
{
"code": null,
"e": 27941,
"s": 27799,
"text": "The required module name: If the type is successfully detected then one of the string names is returned, βdbm.gnuβ, βdbm.ndbmβ or βdbm.dumbβ."
},
{
"code": null,
"e": 27994,
"s": 27941,
"text": "Following are the built-in methods for dbm objects :"
},
{
"code": null,
"e": 28140,
"s": 27994,
"text": "items(): This method returns the items contained in the database of caller object in form of key value pairs. (db is the caller object database)."
},
{
"code": null,
"e": 28195,
"s": 28140,
"text": "clear(): clear all the values present in the database."
},
{
"code": null,
"e": 28263,
"s": 28195,
"text": "get(key): returns the value corresponding to key given in argument."
},
{
"code": null,
"e": 28343,
"s": 28263,
"text": "keys(), iterkeys(): returns an iterable list containing keys of the dictionary."
},
{
"code": null,
"e": 28428,
"s": 28343,
"text": "pop(key): Deletes / pops the key, value pair corresponding to key given in argument."
},
{
"code": null,
"e": 28491,
"s": 28428,
"text": "setdefault(): set a default primary key given in the argument."
},
{
"code": null,
"e": 28554,
"s": 28491,
"text": "sync(): Helps to synchronize data files and on disk directory."
},
{
"code": null,
"e": 28625,
"s": 28554,
"text": "update(): updates the existing key value. Just like dictionary object."
},
{
"code": null,
"e": 28687,
"s": 28625,
"text": "values(): iterate through all the values present in database."
},
{
"code": null,
"e": 28802,
"s": 28687,
"text": "close(): Doesnβt take any argument nor returns anything. Just closes the caller object database. (db in this case)"
},
{
"code": null,
"e": 28874,
"s": 28802,
"text": "Below is the implementation of all the above discuss methods/functions:"
},
{
"code": null,
"e": 28880,
"s": 28874,
"text": "Code:"
},
{
"code": null,
"e": 28888,
"s": 28880,
"text": "Python3"
},
{
"code": "# importing the dbm packageimport dbm # using the open function# to create a new database named# 'mydb' in 'n' mode, object# returned in db variable.db = dbm.open('mydb','n') # inserting the new key and# values in the database.db['name'] = 'GeeksforGeeks'db['phone'] = '8888'db['Short name'] = 'GfG'db['Date'] = '01/01/2000' # getting and printing# the value through get method.print(db.get('name'))print() # printing the values of# database through values()# method (iterator).for value in db.values(): print(value)print() # printing the values through# key iterator.for key in db.keys(): print(db.get(key))print() # poping out the key, value# pair corresponding to# 'phone' key.db.pop('phone') # printing the key, value# pairs present in database.for key, value in db.items(): print(key, value) # clearing all the key values# in database.db.clear() # Below loop will print nothing# as database is cleared above.for key, value in db.items(): print(key, value) # closing the database.db.close() # This code is contributed by Amit Mangal.",
"e": 29938,
"s": 28888,
"text": null
},
{
"code": null,
"e": 29947,
"s": 29938,
"text": "Output :"
},
{
"code": null,
"e": 30128,
"s": 29947,
"text": "b'GeeksforGeeks'\n\nb'GeeksforGeeks'\nb'8888'\nb'GfG'\nb'01/01/2000'\n\nb'GeeksforGeeks'\nb'8888'\nb'GfG'\nb'01/01/2000'\n\nb'name' b'GeeksforGeeks'\nb'Short name' b'GfG'\nb'Date' b'01/01/2000' "
},
{
"code": null,
"e": 30143,
"s": 30128,
"text": "varshagumber28"
},
{
"code": null,
"e": 30158,
"s": 30143,
"text": "python-utility"
},
{
"code": null,
"e": 30165,
"s": 30158,
"text": "Python"
},
{
"code": null,
"e": 30263,
"s": 30165,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30295,
"s": 30263,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 30337,
"s": 30295,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 30379,
"s": 30337,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 30435,
"s": 30379,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 30462,
"s": 30435,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 30493,
"s": 30462,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 30532,
"s": 30493,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 30561,
"s": 30532,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 30583,
"s": 30561,
"text": "Defaultdict in Python"
}
] |
PyQt5 β Set fix window size for height or width - GeeksforGeeks
|
26 Mar, 2020
When we create a window, by default the window size is resizable although, we can use setFixedSize() method to set the fixed size of the window but if we want to set only fix length of height or width only we cant use this method. We want to set one length fixed and other be variable in order to do so we have to use setFixedWidth() method to set fix length of width and setFizedHeight() method to set fix length of height.
Syntax :
self.setFixedWidth(width)
self.setFixedHeight(height)
Argument : Both take integer as argument.
Action performed:setFixedWidth() sets the constant width.setFixedWidth() sets the constant height.
Code for fixed width β
# importing the required libraries from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # set the title self.setWindowTitle("Python") width = 500 # setting the fixed width of window self.setFixedWidth(width) # creating a label widget self.label_1 = QLabel("Fixed width", self) # moving position self.label_1.move(0, 0) # setting up the border self.label_1.setStyleSheet("border :3px solid black;") # resizing label self.label_1.resize(120, 80) # show all the widgets self.show() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output : Code for fixed height β
# importing the required libraries from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # set the title self.setWindowTitle("Python") height = 400 # setting the fixed height of window self.setFixedHeight(height) # creating a label widget self.label_1 = QLabel("Fixed height", self) # moving position self.label_1.move(0, 0) # setting up the border self.label_1.setStyleSheet("border :3px solid black;") # resizing label self.label_1.resize(120, 80) # show all the widgets self.show() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
|
[
{
"code": null,
"e": 26209,
"s": 26181,
"text": "\n26 Mar, 2020"
},
{
"code": null,
"e": 26634,
"s": 26209,
"text": "When we create a window, by default the window size is resizable although, we can use setFixedSize() method to set the fixed size of the window but if we want to set only fix length of height or width only we cant use this method. We want to set one length fixed and other be variable in order to do so we have to use setFixedWidth() method to set fix length of width and setFizedHeight() method to set fix length of height."
},
{
"code": null,
"e": 26643,
"s": 26634,
"text": "Syntax :"
},
{
"code": null,
"e": 26698,
"s": 26643,
"text": "self.setFixedWidth(width)\nself.setFixedHeight(height)\n"
},
{
"code": null,
"e": 26740,
"s": 26698,
"text": "Argument : Both take integer as argument."
},
{
"code": null,
"e": 26839,
"s": 26740,
"text": "Action performed:setFixedWidth() sets the constant width.setFixedWidth() sets the constant height."
},
{
"code": null,
"e": 26862,
"s": 26839,
"text": "Code for fixed width β"
},
{
"code": "# importing the required libraries from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # set the title self.setWindowTitle(\"Python\") width = 500 # setting the fixed width of window self.setFixedWidth(width) # creating a label widget self.label_1 = QLabel(\"Fixed width\", self) # moving position self.label_1.move(0, 0) # setting up the border self.label_1.setStyleSheet(\"border :3px solid black;\") # resizing label self.label_1.resize(120, 80) # show all the widgets self.show() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 27737,
"s": 26862,
"text": null
},
{
"code": null,
"e": 27770,
"s": 27737,
"text": "Output : Code for fixed height β"
},
{
"code": "# importing the required libraries from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # set the title self.setWindowTitle(\"Python\") height = 400 # setting the fixed height of window self.setFixedHeight(height) # creating a label widget self.label_1 = QLabel(\"Fixed height\", self) # moving position self.label_1.move(0, 0) # setting up the border self.label_1.setStyleSheet(\"border :3px solid black;\") # resizing label self.label_1.resize(120, 80) # show all the widgets self.show() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 28640,
"s": 27770,
"text": null
},
{
"code": null,
"e": 28649,
"s": 28640,
"text": "Output :"
},
{
"code": null,
"e": 28660,
"s": 28649,
"text": "Python-gui"
},
{
"code": null,
"e": 28672,
"s": 28660,
"text": "Python-PyQt"
},
{
"code": null,
"e": 28679,
"s": 28672,
"text": "Python"
},
{
"code": null,
"e": 28777,
"s": 28679,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28795,
"s": 28777,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28830,
"s": 28795,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28862,
"s": 28830,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28884,
"s": 28862,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28926,
"s": 28884,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28956,
"s": 28926,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28982,
"s": 28956,
"text": "Python String | replace()"
},
{
"code": null,
"e": 29011,
"s": 28982,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 29055,
"s": 29011,
"text": "Reading and Writing to text files in Python"
}
] |
Java.util.GregorianCalendar Class in Java - GeeksforGeeks
|
30 Nov, 2021
Prerequisites : java.util.Locale, java.util.TimeZone, Calendar.get()GregorianCalendar is a concrete subclass(one which has implementation of all of its inherited members either from interface or abstract class) of a Calendar that implements the most widely used Gregorian Calendar with which we are familiar.
java.util.GregorianCalendar vs java.util.Calendar
The major difference between GregorianCalendar and Calendar classes are that the Calendar Class being an abstract class cannot be instantiated. So an object of the Calendar Class is initialized as:
Calendar cal = Calendar.getInstance();
Here, an object named cal of Calendar Class is initialized with the current date and time in the default locale and timezone. Whereas, GregorianCalendar Class being a concrete class, can be instantiated. So an object of the GregorianCalendar Class is initialized as:
GregorianCalendar gcal = new GregorianCalendar();
Here, an object named gcal of GregorianCalendar Class is initialized with the current date and time in the default locale and timezone.Fields defined :
GregorianCalendar Class defines two fields:
AD : referring to the common era(anno Domini)
BC : referring to before common era(Before Christ)
Constructors : There are several constructors for GregorianCalendar objects. Broadly classifying, constructors for GregorianCalendar either initialize the object with the user specified date and/or time in the default locale and time zone, or initialize the object with default date and time in the user specified locale and/or time zone. These are as follows:
Methods from(), toZonedDateTime(), getCalendarType() were introduced in JDK 8.
Java
// Java Program to show that Calendar class with// default instantiation and GregorianCalendar class// with default constructor is basically the same as both// return the Gregorian Calendar for the default// date, time, time zone and locale import java.util.Calendar;import java.util.GregorianCalendar; class CalendarGFG { public static void main(String[] args) { // Creating an object of Calendar Class Calendar cal = Calendar.getInstance(); /* Creating an object of GregorianCalendar Class */ GregorianCalendar gcal = new GregorianCalendar(); /* Displaying Current Date using Calendar Class */ System.out.println("Calendar date: " + cal.getTime()); /* Displaying Current Date using GregorianCalendar Class */ System.out.print("Gregorian date: " + gcal.getTime()); } // end of main function} // end of class
Output:
Calendar date: Sat Apr 28 13:36:37 UTC 2018
Gregorian date: Sat Apr 28 13:36:37 UTC 2018
Example to demonstrate the usage of various constructors: 1. Using default constructor
Java
// Java program to demonstrate simple GregorianCalendar// operationsimport java.util.Locale;import java.util.TimeZone;import java.util.Calendar;import java.util.GregorianCalendar; public class GregorianCalendarGFG { public static void main(String args[]) { // declaring an array to store month abbreviations String month[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; // declaring an array to store AM or PM String amPm[] = { "AM", "PM" }; /* Creating an object of GregorianCalendar class using default constructor*/ GregorianCalendar gcal = new GregorianCalendar(); // displaying the date, time, time zone and locale System.out.print("Date: " + month[gcal.get(Calendar.MONTH)] + " " + gcal.get(Calendar.DATE) + ", " + gcal.get(Calendar.YEAR) + "\n" + "Time: " + gcal.get(Calendar.HOUR) + ":" + gcal.get(Calendar.MINUTE) + ":" + gcal.get(Calendar.SECOND) + " " + amPm[gcal.get(Calendar.AM_PM)] + "\n" + "Time Zone: " + gcal.getTimeZone().getDisplayName() + "\n" + "Locale: " + Locale.getDefault().getDisplayName()); } // end of main function} // end of class
Output:
Date: Apr 30, 2018
Time: 10:21:51 PM
Time Zone: Coordinated Universal Time
Locale: English (United States)
2. By passing year, month, dayOfMonth as parameters:
Java
// Java program to demonstrate simple GregorianCalendar// operationsimport java.util.Locale;import java.util.TimeZone;import java.util.Calendar;import java.util.GregorianCalendar; public class GregorianCalendarGFG { public static void main(String args[]) { // declaring an array to store month abbreviations String month[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; // declaring an array to store AM or PM String amPm[] = { "AM", "PM" }; /* Creating an object of GregorianCalendar class by specifying year, month and dayOfMonth */ GregorianCalendar gcal = new GregorianCalendar(2018, 3, 30); // displaying the date, time, time zone and locale System.out.print("Date: " + month[gcal.get(Calendar.MONTH)] + " " + gcal.get(Calendar.DATE) + ", " + gcal.get(Calendar.YEAR) + "\n" + "Time: " + gcal.get(Calendar.HOUR) + ":" + gcal.get(Calendar.MINUTE) + ":" + gcal.get(Calendar.SECOND) + " " + amPm[gcal.get(Calendar.AM_PM)] + "\n" + "Time Zone: " + gcal.getTimeZone().getDisplayName() + "\n" + "Locale: " + Locale.getDefault().getDisplayName()); } // end of main function} // end of class
Output:
Date: Apr 30, 2018
Time: 0:0:0 AM
Time Zone: Coordinated Universal Time
Locale: English (United States)
3. By passing year, month, dayOfMonth, hourOfDay, minute:
Java
// Java program to demonstrate simple GregorianCalendar// operationsimport java.util.Locale;import java.util.TimeZone;import java.util.Calendar;import java.util.GregorianCalendar; public class GregorianCalendarGFG { public static void main(String args[]) { // declaring an array to store month abbreviations String month[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; // declaring an array to store AM or PM String amPm[] = { "AM", "PM" }; /* Creating an object of GregorianCalendar class by specifying year, month, dayOfMonth, hourOfDay and minute */ GregorianCalendar gcal = new GregorianCalendar(2018, 3, 30, 10, 21); // displaying the date, time, time zone and locale System.out.print("Date: " + month[gcal.get(Calendar.MONTH)] + " " + gcal.get(Calendar.DATE) + ", " + gcal.get(Calendar.YEAR) + "\n" + "Time: " + gcal.get(Calendar.HOUR) + ":" + gcal.get(Calendar.MINUTE) + ":" + gcal.get(Calendar.SECOND) + " " + amPm[gcal.get(Calendar.AM_PM)] + "\n" + "Time Zone: " + gcal.getTimeZone().getDisplayName() + "\n" + "Locale: " + Locale.getDefault().getDisplayName()); } // end of main function} // end of class
Output:
Date: Apr 30, 2018
Time: 10:21:0 AM
Time Zone: Coordinated Universal Time
Locale: English (United States)
4. By passing year, month, dayOfMonth, hourOfDay, minute, second:
Java
// Java program to demonstrate simple GregorianCalendar// operationsimport java.util.Locale;import java.util.TimeZone;import java.util.Calendar;import java.util.GregorianCalendar; public class GregorianCalendarGFG { public static void main(String args[]) { // declaring an array to store month abbreviations String month[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; // declaring an array to store AM or PM String amPm[] = { "AM", "PM" }; /* Creating an object of GregorianCalendar class by specifying year, month, dayOfMonth, hourOfDay, minute and second */ GregorianCalendar gcal = new GregorianCalendar(2018, 3, 30, 10, 21, 51); // displaying the date, time, time zone and locale System.out.print("Date: " + month[gcal.get(Calendar.MONTH)] + " " + gcal.get(Calendar.DATE) + ", " + gcal.get(Calendar.YEAR) + "\n" + "Time: " + gcal.get(Calendar.HOUR) + ":" + gcal.get(Calendar.MINUTE) + ":" + gcal.get(Calendar.SECOND) + " " + amPm[gcal.get(Calendar.AM_PM)] + "\n" + "Time Zone: " + gcal.getTimeZone().getDisplayName() + "\n" + "Locale: " + Locale.getDefault().getDisplayName()); } // end of main function} // end of class
Output:
Date: Apr 30, 2018
Time: 10:21:51 AM
Time Zone: Coordinated Universal Time
Locale: English (United States)
5. By passing timeZone as parameter:
Java
// Java program to demonstrate simple GregorianCalendar// operationsimport java.util.TimeZone;import java.util.Locale;import java.util.Calendar;import java.util.GregorianCalendar; public class GregorianCalendarTest { public static void main(String args[]) { // declaring an array to store month abbreviations String month[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; // declaring an array to store AM or PM String amPm[] = { "AM", "PM" }; /* Creating an object of TimeZone class to create an object of GregorianCalendar class to assign an user defined time zone (GMT + 5:30)*/ TimeZone tz = TimeZone.getTimeZone("GMT+5:30"); GregorianCalendar gcal = new GregorianCalendar(tz); // displaying the date, time, time zone and locale System.out.print("Date: " + month[gcal.get(Calendar.MONTH)] + " " + gcal.get(Calendar.DATE) + ", " + gcal.get(Calendar.YEAR) + "\n" + "Time: " + gcal.get(Calendar.HOUR) + ":" + gcal.get(Calendar.MINUTE) + ":" + gcal.get(Calendar.SECOND) + " " + amPm[gcal.get(Calendar.AM_PM)] + "\n" + "Time Zone: " + gcal.getTimeZone().getDisplayName() + "\n" + "Locale: " + Locale.getDefault().getDisplayCountry()); } // end of main function} // end of class
Output:
Date: May 1, 2018
Time: 4:24:7 AM
Time Zone: GMT+05:30
Locale: United States
6. By passing the locale as a parameter:
Java
// Java program to demonstrate simple GregorianCalendar// operationsimport java.util.TimeZone;import java.util.Locale;import java.util.Calendar;import java.util.GregorianCalendar; public class GregorianCalendarTest { public static void main(String args[]) { // declaring an array to store month abbreviations String month[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; // declaring an array to store AM or PM String amPm[] = { "AM", "PM" }; /* Creating an object of Locale class to create an object of GregorianCalendar class to assign an user defined locale (India)*/ Locale l = new Locale("en", "IN"); GregorianCalendar gcal = new GregorianCalendar(l); // displaying the date, time, time zone and locale System.out.print("Date: " + month[gcal.get(Calendar.MONTH)] + " " + gcal.get(Calendar.DATE) + ", " + gcal.get(Calendar.YEAR) + "\n" + "Time: " + gcal.get(Calendar.HOUR) + ":" + gcal.get(Calendar.MINUTE) + ":" + gcal.get(Calendar.SECOND) + " " + amPm[gcal.get(Calendar.AM_PM)] + "\n" + "Time Zone: " + gcal.getTimeZone().getDisplayName() + "\n" + "Locale: " + l.getDisplayCountry()); } // end of main function} // end of class
Output:
Date: Apr 30, 2018
Time: 10:58:30 PM
Time Zone: Coordinated Universal Time
Locale: India
7. By passing timeZone and locale as parameters:
Java
// Java program to demonstrate simple GregorianCalendar// operationsimport java.util.TimeZone;import java.util.Locale;import java.util.Calendar;import java.util.GregorianCalendar; public class GregorianCalendarTest { public static void main(String args[]) { // declaring an array to store month abbreviations String month[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; // declaring an array to store AM or PM String amPm[] = { "AM", "PM" }; /* Creating an object of TimeZone class and Locale class to create an object of GregorianCalendar class to assign an user defined time zone (GMT + 5:30) and locale (India)*/ TimeZone tz = TimeZone.getTimeZone("GMT+5:30"); Locale l = new Locale("en", "IN"); GregorianCalendar gcal = new GregorianCalendar(tz, l); // displaying the date, time, time zone and locale System.out.print("Date: " + month[gcal.get(Calendar.MONTH)] + " " + gcal.get(Calendar.DATE) + ", " + gcal.get(Calendar.YEAR) + "\n" + "Time: " + gcal.get(Calendar.HOUR) + ":" + gcal.get(Calendar.MINUTE) + ":" + gcal.get(Calendar.SECOND) + " " + amPm[gcal.get(Calendar.AM_PM)] + "\n" + "Time Zone: " + gcal.getTimeZone().getDisplayName() + "\n" + "Locale: " + l.getDisplayCountry()); } // end of main function} // end of class
Output:
Date: May 1, 2018
Time: 4:34:59 AM
Time Zone: GMT+05:30
Locale: India
Reference: GregorianCalendar (Java Platform SE 8 ) β Oracle Help Center
clintra
sumitgumber28
Java - util package
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
Interfaces 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
|
[
{
"code": null,
"e": 25733,
"s": 25705,
"text": "\n30 Nov, 2021"
},
{
"code": null,
"e": 26043,
"s": 25733,
"text": "Prerequisites : java.util.Locale, java.util.TimeZone, Calendar.get()GregorianCalendar is a concrete subclass(one which has implementation of all of its inherited members either from interface or abstract class) of a Calendar that implements the most widely used Gregorian Calendar with which we are familiar. "
},
{
"code": null,
"e": 26093,
"s": 26043,
"text": "java.util.GregorianCalendar vs java.util.Calendar"
},
{
"code": null,
"e": 26293,
"s": 26093,
"text": "The major difference between GregorianCalendar and Calendar classes are that the Calendar Class being an abstract class cannot be instantiated. So an object of the Calendar Class is initialized as: "
},
{
"code": null,
"e": 26332,
"s": 26293,
"text": "Calendar cal = Calendar.getInstance();"
},
{
"code": null,
"e": 26601,
"s": 26332,
"text": "Here, an object named cal of Calendar Class is initialized with the current date and time in the default locale and timezone. Whereas, GregorianCalendar Class being a concrete class, can be instantiated. So an object of the GregorianCalendar Class is initialized as: "
},
{
"code": null,
"e": 26651,
"s": 26601,
"text": "GregorianCalendar gcal = new GregorianCalendar();"
},
{
"code": null,
"e": 26805,
"s": 26651,
"text": "Here, an object named gcal of GregorianCalendar Class is initialized with the current date and time in the default locale and timezone.Fields defined : "
},
{
"code": null,
"e": 26946,
"s": 26805,
"text": "GregorianCalendar Class defines two fields:\nAD : referring to the common era(anno Domini)\nBC : referring to before common era(Before Christ)"
},
{
"code": null,
"e": 27308,
"s": 26946,
"text": "Constructors : There are several constructors for GregorianCalendar objects. Broadly classifying, constructors for GregorianCalendar either initialize the object with the user specified date and/or time in the default locale and time zone, or initialize the object with default date and time in the user specified locale and/or time zone. These are as follows: "
},
{
"code": null,
"e": 27387,
"s": 27308,
"text": "Methods from(), toZonedDateTime(), getCalendarType() were introduced in JDK 8."
},
{
"code": null,
"e": 27392,
"s": 27387,
"text": "Java"
},
{
"code": "// Java Program to show that Calendar class with// default instantiation and GregorianCalendar class// with default constructor is basically the same as both// return the Gregorian Calendar for the default// date, time, time zone and locale import java.util.Calendar;import java.util.GregorianCalendar; class CalendarGFG { public static void main(String[] args) { // Creating an object of Calendar Class Calendar cal = Calendar.getInstance(); /* Creating an object of GregorianCalendar Class */ GregorianCalendar gcal = new GregorianCalendar(); /* Displaying Current Date using Calendar Class */ System.out.println(\"Calendar date: \" + cal.getTime()); /* Displaying Current Date using GregorianCalendar Class */ System.out.print(\"Gregorian date: \" + gcal.getTime()); } // end of main function} // end of class",
"e": 28355,
"s": 27392,
"text": null
},
{
"code": null,
"e": 28365,
"s": 28355,
"text": "Output: "
},
{
"code": null,
"e": 28454,
"s": 28365,
"text": "Calendar date: Sat Apr 28 13:36:37 UTC 2018\nGregorian date: Sat Apr 28 13:36:37 UTC 2018"
},
{
"code": null,
"e": 28542,
"s": 28454,
"text": "Example to demonstrate the usage of various constructors: 1. Using default constructor "
},
{
"code": null,
"e": 28547,
"s": 28542,
"text": "Java"
},
{
"code": "// Java program to demonstrate simple GregorianCalendar// operationsimport java.util.Locale;import java.util.TimeZone;import java.util.Calendar;import java.util.GregorianCalendar; public class GregorianCalendarGFG { public static void main(String args[]) { // declaring an array to store month abbreviations String month[] = { \"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\" }; // declaring an array to store AM or PM String amPm[] = { \"AM\", \"PM\" }; /* Creating an object of GregorianCalendar class using default constructor*/ GregorianCalendar gcal = new GregorianCalendar(); // displaying the date, time, time zone and locale System.out.print(\"Date: \" + month[gcal.get(Calendar.MONTH)] + \" \" + gcal.get(Calendar.DATE) + \", \" + gcal.get(Calendar.YEAR) + \"\\n\" + \"Time: \" + gcal.get(Calendar.HOUR) + \":\" + gcal.get(Calendar.MINUTE) + \":\" + gcal.get(Calendar.SECOND) + \" \" + amPm[gcal.get(Calendar.AM_PM)] + \"\\n\" + \"Time Zone: \" + gcal.getTimeZone().getDisplayName() + \"\\n\" + \"Locale: \" + Locale.getDefault().getDisplayName()); } // end of main function} // end of class",
"e": 30071,
"s": 28547,
"text": null
},
{
"code": null,
"e": 30081,
"s": 30071,
"text": "Output: "
},
{
"code": null,
"e": 30188,
"s": 30081,
"text": "Date: Apr 30, 2018\nTime: 10:21:51 PM\nTime Zone: Coordinated Universal Time\nLocale: English (United States)"
},
{
"code": null,
"e": 30242,
"s": 30188,
"text": "2. By passing year, month, dayOfMonth as parameters: "
},
{
"code": null,
"e": 30247,
"s": 30242,
"text": "Java"
},
{
"code": "// Java program to demonstrate simple GregorianCalendar// operationsimport java.util.Locale;import java.util.TimeZone;import java.util.Calendar;import java.util.GregorianCalendar; public class GregorianCalendarGFG { public static void main(String args[]) { // declaring an array to store month abbreviations String month[] = { \"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\" }; // declaring an array to store AM or PM String amPm[] = { \"AM\", \"PM\" }; /* Creating an object of GregorianCalendar class by specifying year, month and dayOfMonth */ GregorianCalendar gcal = new GregorianCalendar(2018, 3, 30); // displaying the date, time, time zone and locale System.out.print(\"Date: \" + month[gcal.get(Calendar.MONTH)] + \" \" + gcal.get(Calendar.DATE) + \", \" + gcal.get(Calendar.YEAR) + \"\\n\" + \"Time: \" + gcal.get(Calendar.HOUR) + \":\" + gcal.get(Calendar.MINUTE) + \":\" + gcal.get(Calendar.SECOND) + \" \" + amPm[gcal.get(Calendar.AM_PM)] + \"\\n\" + \"Time Zone: \" + gcal.getTimeZone().getDisplayName() + \"\\n\" + \"Locale: \" + Locale.getDefault().getDisplayName()); } // end of main function} // end of class",
"e": 31796,
"s": 30247,
"text": null
},
{
"code": null,
"e": 31806,
"s": 31796,
"text": "Output: "
},
{
"code": null,
"e": 31910,
"s": 31806,
"text": "Date: Apr 30, 2018\nTime: 0:0:0 AM\nTime Zone: Coordinated Universal Time\nLocale: English (United States)"
},
{
"code": null,
"e": 31969,
"s": 31910,
"text": "3. By passing year, month, dayOfMonth, hourOfDay, minute: "
},
{
"code": null,
"e": 31974,
"s": 31969,
"text": "Java"
},
{
"code": "// Java program to demonstrate simple GregorianCalendar// operationsimport java.util.Locale;import java.util.TimeZone;import java.util.Calendar;import java.util.GregorianCalendar; public class GregorianCalendarGFG { public static void main(String args[]) { // declaring an array to store month abbreviations String month[] = { \"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\" }; // declaring an array to store AM or PM String amPm[] = { \"AM\", \"PM\" }; /* Creating an object of GregorianCalendar class by specifying year, month, dayOfMonth, hourOfDay and minute */ GregorianCalendar gcal = new GregorianCalendar(2018, 3, 30, 10, 21); // displaying the date, time, time zone and locale System.out.print(\"Date: \" + month[gcal.get(Calendar.MONTH)] + \" \" + gcal.get(Calendar.DATE) + \", \" + gcal.get(Calendar.YEAR) + \"\\n\" + \"Time: \" + gcal.get(Calendar.HOUR) + \":\" + gcal.get(Calendar.MINUTE) + \":\" + gcal.get(Calendar.SECOND) + \" \" + amPm[gcal.get(Calendar.AM_PM)] + \"\\n\" + \"Time Zone: \" + gcal.getTimeZone().getDisplayName() + \"\\n\" + \"Locale: \" + Locale.getDefault().getDisplayName()); } // end of main function} // end of class",
"e": 33560,
"s": 31974,
"text": null
},
{
"code": null,
"e": 33570,
"s": 33560,
"text": "Output: "
},
{
"code": null,
"e": 33676,
"s": 33570,
"text": "Date: Apr 30, 2018\nTime: 10:21:0 AM\nTime Zone: Coordinated Universal Time\nLocale: English (United States)"
},
{
"code": null,
"e": 33743,
"s": 33676,
"text": "4. By passing year, month, dayOfMonth, hourOfDay, minute, second: "
},
{
"code": null,
"e": 33748,
"s": 33743,
"text": "Java"
},
{
"code": "// Java program to demonstrate simple GregorianCalendar// operationsimport java.util.Locale;import java.util.TimeZone;import java.util.Calendar;import java.util.GregorianCalendar; public class GregorianCalendarGFG { public static void main(String args[]) { // declaring an array to store month abbreviations String month[] = { \"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\" }; // declaring an array to store AM or PM String amPm[] = { \"AM\", \"PM\" }; /* Creating an object of GregorianCalendar class by specifying year, month, dayOfMonth, hourOfDay, minute and second */ GregorianCalendar gcal = new GregorianCalendar(2018, 3, 30, 10, 21, 51); // displaying the date, time, time zone and locale System.out.print(\"Date: \" + month[gcal.get(Calendar.MONTH)] + \" \" + gcal.get(Calendar.DATE) + \", \" + gcal.get(Calendar.YEAR) + \"\\n\" + \"Time: \" + gcal.get(Calendar.HOUR) + \":\" + gcal.get(Calendar.MINUTE) + \":\" + gcal.get(Calendar.SECOND) + \" \" + amPm[gcal.get(Calendar.AM_PM)] + \"\\n\" + \"Time Zone: \" + gcal.getTimeZone().getDisplayName() + \"\\n\" + \"Locale: \" + Locale.getDefault().getDisplayName()); } // end of main function} // end of class",
"e": 35346,
"s": 33748,
"text": null
},
{
"code": null,
"e": 35356,
"s": 35346,
"text": "Output: "
},
{
"code": null,
"e": 35463,
"s": 35356,
"text": "Date: Apr 30, 2018\nTime: 10:21:51 AM\nTime Zone: Coordinated Universal Time\nLocale: English (United States)"
},
{
"code": null,
"e": 35501,
"s": 35463,
"text": "5. By passing timeZone as parameter: "
},
{
"code": null,
"e": 35506,
"s": 35501,
"text": "Java"
},
{
"code": "// Java program to demonstrate simple GregorianCalendar// operationsimport java.util.TimeZone;import java.util.Locale;import java.util.Calendar;import java.util.GregorianCalendar; public class GregorianCalendarTest { public static void main(String args[]) { // declaring an array to store month abbreviations String month[] = { \"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\" }; // declaring an array to store AM or PM String amPm[] = { \"AM\", \"PM\" }; /* Creating an object of TimeZone class to create an object of GregorianCalendar class to assign an user defined time zone (GMT + 5:30)*/ TimeZone tz = TimeZone.getTimeZone(\"GMT+5:30\"); GregorianCalendar gcal = new GregorianCalendar(tz); // displaying the date, time, time zone and locale System.out.print(\"Date: \" + month[gcal.get(Calendar.MONTH)] + \" \" + gcal.get(Calendar.DATE) + \", \" + gcal.get(Calendar.YEAR) + \"\\n\" + \"Time: \" + gcal.get(Calendar.HOUR) + \":\" + gcal.get(Calendar.MINUTE) + \":\" + gcal.get(Calendar.SECOND) + \" \" + amPm[gcal.get(Calendar.AM_PM)] + \"\\n\" + \"Time Zone: \" + gcal.getTimeZone().getDisplayName() + \"\\n\" + \"Locale: \" + Locale.getDefault().getDisplayCountry()); } // end of main function} // end of class",
"e": 37140,
"s": 35506,
"text": null
},
{
"code": null,
"e": 37150,
"s": 37140,
"text": "Output: "
},
{
"code": null,
"e": 37227,
"s": 37150,
"text": "Date: May 1, 2018\nTime: 4:24:7 AM\nTime Zone: GMT+05:30\nLocale: United States"
},
{
"code": null,
"e": 37269,
"s": 37227,
"text": "6. By passing the locale as a parameter: "
},
{
"code": null,
"e": 37274,
"s": 37269,
"text": "Java"
},
{
"code": "// Java program to demonstrate simple GregorianCalendar// operationsimport java.util.TimeZone;import java.util.Locale;import java.util.Calendar;import java.util.GregorianCalendar; public class GregorianCalendarTest { public static void main(String args[]) { // declaring an array to store month abbreviations String month[] = { \"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\" }; // declaring an array to store AM or PM String amPm[] = { \"AM\", \"PM\" }; /* Creating an object of Locale class to create an object of GregorianCalendar class to assign an user defined locale (India)*/ Locale l = new Locale(\"en\", \"IN\"); GregorianCalendar gcal = new GregorianCalendar(l); // displaying the date, time, time zone and locale System.out.print(\"Date: \" + month[gcal.get(Calendar.MONTH)] + \" \" + gcal.get(Calendar.DATE) + \", \" + gcal.get(Calendar.YEAR) + \"\\n\" + \"Time: \" + gcal.get(Calendar.HOUR) + \":\" + gcal.get(Calendar.MINUTE) + \":\" + gcal.get(Calendar.SECOND) + \" \" + amPm[gcal.get(Calendar.AM_PM)] + \"\\n\" + \"Time Zone: \" + gcal.getTimeZone().getDisplayName() + \"\\n\" + \"Locale: \" + l.getDisplayCountry()); } // end of main function} // end of class",
"e": 38890,
"s": 37274,
"text": null
},
{
"code": null,
"e": 38900,
"s": 38890,
"text": "Output: "
},
{
"code": null,
"e": 38989,
"s": 38900,
"text": "Date: Apr 30, 2018\nTime: 10:58:30 PM\nTime Zone: Coordinated Universal Time\nLocale: India"
},
{
"code": null,
"e": 39039,
"s": 38989,
"text": "7. By passing timeZone and locale as parameters: "
},
{
"code": null,
"e": 39044,
"s": 39039,
"text": "Java"
},
{
"code": "// Java program to demonstrate simple GregorianCalendar// operationsimport java.util.TimeZone;import java.util.Locale;import java.util.Calendar;import java.util.GregorianCalendar; public class GregorianCalendarTest { public static void main(String args[]) { // declaring an array to store month abbreviations String month[] = { \"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\" }; // declaring an array to store AM or PM String amPm[] = { \"AM\", \"PM\" }; /* Creating an object of TimeZone class and Locale class to create an object of GregorianCalendar class to assign an user defined time zone (GMT + 5:30) and locale (India)*/ TimeZone tz = TimeZone.getTimeZone(\"GMT+5:30\"); Locale l = new Locale(\"en\", \"IN\"); GregorianCalendar gcal = new GregorianCalendar(tz, l); // displaying the date, time, time zone and locale System.out.print(\"Date: \" + month[gcal.get(Calendar.MONTH)] + \" \" + gcal.get(Calendar.DATE) + \", \" + gcal.get(Calendar.YEAR) + \"\\n\" + \"Time: \" + gcal.get(Calendar.HOUR) + \":\" + gcal.get(Calendar.MINUTE) + \":\" + gcal.get(Calendar.SECOND) + \" \" + amPm[gcal.get(Calendar.AM_PM)] + \"\\n\" + \"Time Zone: \" + gcal.getTimeZone().getDisplayName() + \"\\n\" + \"Locale: \" + l.getDisplayCountry()); } // end of main function} // end of class",
"e": 40777,
"s": 39044,
"text": null
},
{
"code": null,
"e": 40787,
"s": 40777,
"text": "Output: "
},
{
"code": null,
"e": 40857,
"s": 40787,
"text": "Date: May 1, 2018\nTime: 4:34:59 AM\nTime Zone: GMT+05:30\nLocale: India"
},
{
"code": null,
"e": 40929,
"s": 40857,
"text": "Reference: GregorianCalendar (Java Platform SE 8 ) β Oracle Help Center"
},
{
"code": null,
"e": 40937,
"s": 40929,
"text": "clintra"
},
{
"code": null,
"e": 40951,
"s": 40937,
"text": "sumitgumber28"
},
{
"code": null,
"e": 40971,
"s": 40951,
"text": "Java - util package"
},
{
"code": null,
"e": 40976,
"s": 40971,
"text": "Java"
},
{
"code": null,
"e": 40981,
"s": 40976,
"text": "Java"
},
{
"code": null,
"e": 41079,
"s": 40981,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 41130,
"s": 41079,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 41160,
"s": 41130,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 41175,
"s": 41160,
"text": "Stream In Java"
},
{
"code": null,
"e": 41194,
"s": 41175,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 41225,
"s": 41194,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 41243,
"s": 41225,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 41275,
"s": 41243,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 41295,
"s": 41275,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 41327,
"s": 41295,
"text": "Multidimensional Arrays in Java"
}
] |
Python program to multiply two matrices - GeeksforGeeks
|
23 Apr, 2022
Given two matrix the task is that we will have to create a program to multiply two matrices in python. Examples:
Input : X = [[1, 7, 3],
[3, 5, 6],
[6, 8, 9]]
Y = [[1, 1, 1, 2],
[6, 7, 3, 0],
[4, 5, 9, 1]]
Output : [55, 65, 49, 5]
[57, 68, 72, 12]
[90, 107, 111, 21]
Using Simple Nested Loops In this program we have to use nested for loops to iterate through each row and each column.
Python3
# Program to multiply two matrices using nested loops # take a 3x3 matrixA = [[12, 7, 3], [4, 5, 6], [7, 8, 9]] # take a 3x4 matrix B = [[5, 8, 1, 2], [6, 7, 3, 0], [4, 5, 9, 1]] result = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] # iterating by row of Afor i in range(len(A)): # iterating by column by B for j in range(len(B[0])): # iterating by rows of B for k in range(len(B)): result[i][j] += A[i][k] * B[k][j] for r in result: print(r)
Output:
[114, 160, 60, 27]
[74, 97, 73, 14]
[119, 157, 112, 23]
Time Complexity: O(M*M*N), as we are using nested loop traversing, M*M*N.
Auxiliary Space: O(M*N), as we are using a result matrix which is extra space.
Method 2: Matrix Multiplication Using Nested List. We use zip in Python.
Python3
# Program to multiply two matrices using list comprehension # take a 3x3 matrixA = [[12, 7, 3], [4, 5, 6], [7, 8, 9]] # take a 3x4 matrixB = [[5, 8, 1, 2], [6, 7, 3, 0], [4, 5, 9, 1]] # result will be 3x4result = [[sum(a * b for a, b in zip(A_row, B_col)) for B_col in zip(*B)] for A_row in A] for r in result: print(r)
Output:
[114, 160, 60, 27]
[74, 97, 73, 14]
[119, 157, 112, 23]
Time Complexity: O(M*M*N), as we are using nested loop traversing, M*M*N.
Auxiliary Space: O(M*N), as we are using a result matrix which is extra space.Method 3: Matrix Multiplication (Vectorized implementation).
Python3
# Program to multiply two matrices (vectorized implementation) # Program to multiply two matrices (vectorized implementation)import numpy as np# take a 3x3 matrixA = [[12, 7, 3], [4, 5, 6], [7, 8, 9]] # take a 3x4 matrixB = [[5, 8, 1, 2], [6, 7, 3, 0], [4, 5, 9, 1]] # result will be 3x4 result= [[0,0,0,0], [0,0,0,0], [0,0,0,0]] result = np.dot(A,B) for r in result: print(r)
Output:
[114, 160, 60, 27]
[74, 97, 73, 14]
[119, 157, 112, 23]
Time Complexity: O(M*M*N), as we are using nested loop traversing, M*M*N.
Auxiliary Space: O(M*N), as we are using a result matrix which is extra space.
psbishnu1
anikakapoor
rohitsingh07052
Python matrix-program
Matrix
Python
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sudoku | Backtracking-7
Inplace rotate square matrix by 90 degrees | Set 1
Count all possible paths from top left to bottom right of a mXn matrix
Min Cost Path | DP-6
Printing all solutions in N-Queen Problem
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 26547,
"s": 26519,
"text": "\n23 Apr, 2022"
},
{
"code": null,
"e": 26662,
"s": 26547,
"text": "Given two matrix the task is that we will have to create a program to multiply two matrices in python. Examples: "
},
{
"code": null,
"e": 26891,
"s": 26662,
"text": "Input : X = [[1, 7, 3],\n [3, 5, 6],\n [6, 8, 9]]\n Y = [[1, 1, 1, 2],\n [6, 7, 3, 0],\n [4, 5, 9, 1]]\n \nOutput : [55, 65, 49, 5]\n [57, 68, 72, 12]\n [90, 107, 111, 21]"
},
{
"code": null,
"e": 27013,
"s": 26893,
"text": "Using Simple Nested Loops In this program we have to use nested for loops to iterate through each row and each column. "
},
{
"code": null,
"e": 27021,
"s": 27013,
"text": "Python3"
},
{
"code": "# Program to multiply two matrices using nested loops # take a 3x3 matrixA = [[12, 7, 3], [4, 5, 6], [7, 8, 9]] # take a 3x4 matrix B = [[5, 8, 1, 2], [6, 7, 3, 0], [4, 5, 9, 1]] result = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] # iterating by row of Afor i in range(len(A)): # iterating by column by B for j in range(len(B[0])): # iterating by rows of B for k in range(len(B)): result[i][j] += A[i][k] * B[k][j] for r in result: print(r)",
"e": 27530,
"s": 27021,
"text": null
},
{
"code": null,
"e": 27540,
"s": 27530,
"text": "Output: "
},
{
"code": null,
"e": 27596,
"s": 27540,
"text": "[114, 160, 60, 27]\n[74, 97, 73, 14]\n[119, 157, 112, 23]"
},
{
"code": null,
"e": 27670,
"s": 27596,
"text": "Time Complexity: O(M*M*N), as we are using nested loop traversing, M*M*N."
},
{
"code": null,
"e": 27749,
"s": 27670,
"text": "Auxiliary Space: O(M*N), as we are using a result matrix which is extra space."
},
{
"code": null,
"e": 27823,
"s": 27749,
"text": "Method 2: Matrix Multiplication Using Nested List. We use zip in Python. "
},
{
"code": null,
"e": 27831,
"s": 27823,
"text": "Python3"
},
{
"code": "# Program to multiply two matrices using list comprehension # take a 3x3 matrixA = [[12, 7, 3], [4, 5, 6], [7, 8, 9]] # take a 3x4 matrixB = [[5, 8, 1, 2], [6, 7, 3, 0], [4, 5, 9, 1]] # result will be 3x4result = [[sum(a * b for a, b in zip(A_row, B_col)) for B_col in zip(*B)] for A_row in A] for r in result: print(r)",
"e": 28220,
"s": 27831,
"text": null
},
{
"code": null,
"e": 28230,
"s": 28220,
"text": "Output: "
},
{
"code": null,
"e": 28286,
"s": 28230,
"text": "[114, 160, 60, 27]\n[74, 97, 73, 14]\n[119, 157, 112, 23]"
},
{
"code": null,
"e": 28360,
"s": 28286,
"text": "Time Complexity: O(M*M*N), as we are using nested loop traversing, M*M*N."
},
{
"code": null,
"e": 28501,
"s": 28360,
"text": "Auxiliary Space: O(M*N), as we are using a result matrix which is extra space.Method 3: Matrix Multiplication (Vectorized implementation). "
},
{
"code": null,
"e": 28509,
"s": 28501,
"text": "Python3"
},
{
"code": "# Program to multiply two matrices (vectorized implementation) # Program to multiply two matrices (vectorized implementation)import numpy as np# take a 3x3 matrixA = [[12, 7, 3], [4, 5, 6], [7, 8, 9]] # take a 3x4 matrixB = [[5, 8, 1, 2], [6, 7, 3, 0], [4, 5, 9, 1]] # result will be 3x4 result= [[0,0,0,0], [0,0,0,0], [0,0,0,0]] result = np.dot(A,B) for r in result: print(r)",
"e": 28915,
"s": 28509,
"text": null
},
{
"code": null,
"e": 28925,
"s": 28915,
"text": "Output: "
},
{
"code": null,
"e": 28981,
"s": 28925,
"text": "[114, 160, 60, 27]\n[74, 97, 73, 14]\n[119, 157, 112, 23]"
},
{
"code": null,
"e": 29055,
"s": 28981,
"text": "Time Complexity: O(M*M*N), as we are using nested loop traversing, M*M*N."
},
{
"code": null,
"e": 29134,
"s": 29055,
"text": "Auxiliary Space: O(M*N), as we are using a result matrix which is extra space."
},
{
"code": null,
"e": 29144,
"s": 29134,
"text": "psbishnu1"
},
{
"code": null,
"e": 29156,
"s": 29144,
"text": "anikakapoor"
},
{
"code": null,
"e": 29172,
"s": 29156,
"text": "rohitsingh07052"
},
{
"code": null,
"e": 29194,
"s": 29172,
"text": "Python matrix-program"
},
{
"code": null,
"e": 29201,
"s": 29194,
"text": "Matrix"
},
{
"code": null,
"e": 29208,
"s": 29201,
"text": "Python"
},
{
"code": null,
"e": 29215,
"s": 29208,
"text": "Matrix"
},
{
"code": null,
"e": 29313,
"s": 29215,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29337,
"s": 29313,
"text": "Sudoku | Backtracking-7"
},
{
"code": null,
"e": 29388,
"s": 29337,
"text": "Inplace rotate square matrix by 90 degrees | Set 1"
},
{
"code": null,
"e": 29459,
"s": 29388,
"text": "Count all possible paths from top left to bottom right of a mXn matrix"
},
{
"code": null,
"e": 29480,
"s": 29459,
"text": "Min Cost Path | DP-6"
},
{
"code": null,
"e": 29522,
"s": 29480,
"text": "Printing all solutions in N-Queen Problem"
},
{
"code": null,
"e": 29550,
"s": 29522,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 29600,
"s": 29550,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 29622,
"s": 29600,
"text": "Python map() function"
}
] |
Different types of Procedures in MySQL
|
02 Jul, 2019
A procedure is a subroutine (like a subprogram) in a regular scripting language, stored in a database. In the case of MySQL, procedures are written in MySQL and stored in the MySQL database/server. A MySQL procedure has a name, a parameter list, and SQL statement(s).
There are four different types of MySQL procedures:
1. Procedure with no parameters:A procedure without parameters does not take any input or casts an output indirectly. It is simply called with its procedure name followed by () (without any parameters). It is used for simple queries.
Example:Consider two tables author and book:
create table author (author_id integer primary key,
authorName varchar(30),
email varchar (25), gender varchar (6));
create table book (BookId integer not null unique,
ISBN integer primary key,
book_name varchar (30) not null,
author integer, ed_num integer,
price integer, pages integer,
foreign key (author) references author (author_id) on delete cascade);
Inserting values into them:
insert into author values
(1, "Kraig Muller", "Wordnewton@gmail.com", "Male");
insert into author values
(2, "Karrie Nicolette", "karrie23@gmail.com", "Female");
insert into book values
(1, 001, "Glimpses of the past", 1, 1, 650, 396);
insert into book values
(2, 002, "Beyond The Horizons of Venus", 1, 1, 650, 396);
insert into book values
(3, 003, "Ultrasonic Aquaculture", 2, 1, 799, 500);
insert into book values
(4, 004, "Cyrogenic Engines", 2, 1, 499, 330);
Procedure (with no parameters) to display all the books:
delimiter //
create procedure display_book()
-> begin
-> select *from book;
-> end //
call display_book(); //
Output:
+--------+------+------------------------------+--------+--------+-------+-------+
| BookId | ISBN | book_name | author | ed_num | price | pages |
+--------+------+------------------------------+--------+--------+-------+-------+
| 1 | 1 | Glimpses of the past | 1 | 1 | 650 | 396 |
| 2 | 2 | Beyond The Horizons of Venus | 1 | 1 | 650 | 396 |
| 3 | 3 | Ultrasonic Aquaculture | 2 | 1 | 799 | 500 |
| 4 | 4 | Cyrogenic Engines | 2 | 1 | 499 | 330 |
+--------+------+------------------------------+--------+--------+-------+-------+
4 rows in set (0.0012 sec)
2. Procedure with IN parameter:An IN parameter is used to take a parameter as input such as an attribute. When we define an IN parameter in a procedure, the calling program has to pass an argument to the stored procedure. In addition, the value of an IN parameter is protected. It means that even if the value of the IN parameter is changed inside the procedure, its original value is retained after the procedure ends (like pass by value). In other words, the procedure only works on the copy of the IN parameter.
Example:Procedure to update price of a book taking ISBN of the book and its new price as input: (considering the tables above)
delimiter //
create procedure update_price (IN temp_ISBN varchar(10), IN new_price integer)
-> begin
-> update book set price=new_price where ISBN=temp_ISBN;
-> end; //
call update_price(001, 600); //
We changed the price of book with ISBN β001β(Glimpses of the past) to 600 (from its default price 650).
Output:
delimiter ;
select *from book;
+--------+------+------------------------------+--------+--------+-------+-------+
| BookId | ISBN | book_name | author | ed_num | price | pages |
+--------+------+------------------------------+--------+--------+-------+-------+
| 1 | 1 | Glimpses of the past | 1 | 1 | 600 | 396 |
| 2 | 2 | Beyond The Horizons of Venus | 1 | 1 | 650 | 396 |
| 3 | 3 | Ultrasonic Aquaculture | 2 | 1 | 799 | 500 |
| 4 | 4 | Cyrogenic Engines | 2 | 1 | 499 | 330 |
+--------+------+------------------------------+--------+--------+-------+-------+
4 rows in set (0.0013 sec)
3. Procedure with OUT parameter:An OUT parameter is used to pass a parameter as output or display like the select operator, but implicitly (through a set value). The value of an OUT parameter can be changed inside the procedure and its new value is passed back to the calling program. A procedure cannot access the initial value of the OUT parameter when it starts.
Example:Procedure to display the highest price among all the books with an output parameter:
delimiter //
create procedure disp_max(OUT highestprice integer)
-> begin
-> select max(price) into highestprice from book;
-> end; //
call disp_max(@M); //
select @M;
Output:The highest price from our book database is of the book with ISBN 003 (Ultrasonic Aquaculture) with a price of 799, which is displayed.
+-----+
| @M |
+-----+
| 799 |
+-----+
1 row in set (0.0005 sec)
4. Procedure with IN-OUT parameter:An INOUT parameter is a combination of IN and OUT parameters. It means that the calling program may pass the argument, and the stored procedure can modify the INOUT parameter and pass the new value back to the calling program.
Example:Procedure to take gender type input (βMaleβ/βFemaleβ here) with an in-out parameter which reflects the number of authors falling in that gender category/type:
delimiter //
create procedure disp_gender(INOUT mfgender integer, IN emp_gender varchar(6))
-> begin
-> select COUNT(gender)
INTO mfgender FROM author where gender = emp_gender;
-> end; //
delimiter ;
call disp_gender(@M, "Male");
select @M;
call disp_gender(@F, "Female");
select @F;
Output:We have two authors, one being male and one being female as per insertions in the table author. Hence, output is 1 for one male author and 1 for one female author respectively.
+----+
| @M |
+----+
| 1 |
+----+
1 row in set (0.0004 sec)
+----+
| @F |
+----+
| 1 |
+----+
1 row in set (0.0005 sec)
mysql
SQL-Server
DBMS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n02 Jul, 2019"
},
{
"code": null,
"e": 320,
"s": 52,
"text": "A procedure is a subroutine (like a subprogram) in a regular scripting language, stored in a database. In the case of MySQL, procedures are written in MySQL and stored in the MySQL database/server. A MySQL procedure has a name, a parameter list, and SQL statement(s)."
},
{
"code": null,
"e": 372,
"s": 320,
"text": "There are four different types of MySQL procedures:"
},
{
"code": null,
"e": 606,
"s": 372,
"text": "1. Procedure with no parameters:A procedure without parameters does not take any input or casts an output indirectly. It is simply called with its procedure name followed by () (without any parameters). It is used for simple queries."
},
{
"code": null,
"e": 651,
"s": 606,
"text": "Example:Consider two tables author and book:"
},
{
"code": null,
"e": 1177,
"s": 651,
"text": "create table author (author_id integer primary key, \n authorName varchar(30), \n email varchar (25), gender varchar (6));\n\ncreate table book (BookId integer not null unique, \n ISBN integer primary key, \n book_name varchar (30) not null, \n author integer, ed_num integer, \n price integer, pages integer, \n foreign key (author) references author (author_id) on delete cascade);"
},
{
"code": null,
"e": 1205,
"s": 1177,
"text": "Inserting values into them:"
},
{
"code": null,
"e": 1756,
"s": 1205,
"text": "insert into author values \n (1, \"Kraig Muller\", \"Wordnewton@gmail.com\", \"Male\");\ninsert into author values\n (2, \"Karrie Nicolette\", \"karrie23@gmail.com\", \"Female\");\ninsert into book values\n (1, 001, \"Glimpses of the past\", 1, 1, 650, 396);\ninsert into book values\n (2, 002, \"Beyond The Horizons of Venus\", 1, 1, 650, 396);\ninsert into book values\n (3, 003, \"Ultrasonic Aquaculture\", 2, 1, 799, 500);\ninsert into book values\n (4, 004, \"Cyrogenic Engines\", 2, 1, 499, 330); "
},
{
"code": null,
"e": 1813,
"s": 1756,
"text": "Procedure (with no parameters) to display all the books:"
},
{
"code": null,
"e": 1992,
"s": 1813,
"text": "delimiter //\ncreate procedure display_book() \n -> begin \n -> select *from book; \n -> end //\ncall display_book(); //"
},
{
"code": null,
"e": 2000,
"s": 1992,
"text": "Output:"
},
{
"code": null,
"e": 2692,
"s": 2000,
"text": "+--------+------+------------------------------+--------+--------+-------+-------+\n| BookId | ISBN | book_name | author | ed_num | price | pages |\n+--------+------+------------------------------+--------+--------+-------+-------+\n| 1 | 1 | Glimpses of the past | 1 | 1 | 650 | 396 |\n| 2 | 2 | Beyond The Horizons of Venus | 1 | 1 | 650 | 396 |\n| 3 | 3 | Ultrasonic Aquaculture | 2 | 1 | 799 | 500 |\n| 4 | 4 | Cyrogenic Engines | 2 | 1 | 499 | 330 |\n+--------+------+------------------------------+--------+--------+-------+-------+\n4 rows in set (0.0012 sec)\n"
},
{
"code": null,
"e": 3207,
"s": 2692,
"text": "2. Procedure with IN parameter:An IN parameter is used to take a parameter as input such as an attribute. When we define an IN parameter in a procedure, the calling program has to pass an argument to the stored procedure. In addition, the value of an IN parameter is protected. It means that even if the value of the IN parameter is changed inside the procedure, its original value is retained after the procedure ends (like pass by value). In other words, the procedure only works on the copy of the IN parameter."
},
{
"code": null,
"e": 3334,
"s": 3207,
"text": "Example:Procedure to update price of a book taking ISBN of the book and its new price as input: (considering the tables above)"
},
{
"code": null,
"e": 3581,
"s": 3334,
"text": "delimiter //\ncreate procedure update_price (IN temp_ISBN varchar(10), IN new_price integer)\n -> begin\n -> update book set price=new_price where ISBN=temp_ISBN;\n -> end; //\ncall update_price(001, 600); //\n"
},
{
"code": null,
"e": 3685,
"s": 3581,
"text": "We changed the price of book with ISBN β001β(Glimpses of the past) to 600 (from its default price 650)."
},
{
"code": null,
"e": 3693,
"s": 3685,
"text": "Output:"
},
{
"code": null,
"e": 4415,
"s": 3693,
"text": "delimiter ;\nselect *from book;\n+--------+------+------------------------------+--------+--------+-------+-------+\n| BookId | ISBN | book_name | author | ed_num | price | pages |\n+--------+------+------------------------------+--------+--------+-------+-------+\n| 1 | 1 | Glimpses of the past | 1 | 1 | 600 | 396 |\n| 2 | 2 | Beyond The Horizons of Venus | 1 | 1 | 650 | 396 |\n| 3 | 3 | Ultrasonic Aquaculture | 2 | 1 | 799 | 500 |\n| 4 | 4 | Cyrogenic Engines | 2 | 1 | 499 | 330 |\n+--------+------+------------------------------+--------+--------+-------+-------+\n4 rows in set (0.0013 sec)"
},
{
"code": null,
"e": 4781,
"s": 4415,
"text": "3. Procedure with OUT parameter:An OUT parameter is used to pass a parameter as output or display like the select operator, but implicitly (through a set value). The value of an OUT parameter can be changed inside the procedure and its new value is passed back to the calling program. A procedure cannot access the initial value of the OUT parameter when it starts."
},
{
"code": null,
"e": 4874,
"s": 4781,
"text": "Example:Procedure to display the highest price among all the books with an output parameter:"
},
{
"code": null,
"e": 5094,
"s": 4874,
"text": "delimiter //\ncreate procedure disp_max(OUT highestprice integer)\n -> begin\n -> select max(price) into highestprice from book;\n -> end; //\ncall disp_max(@M); //\nselect @M; "
},
{
"code": null,
"e": 5237,
"s": 5094,
"text": "Output:The highest price from our book database is of the book with ISBN 003 (Ultrasonic Aquaculture) with a price of 799, which is displayed."
},
{
"code": null,
"e": 5304,
"s": 5237,
"text": "+-----+\n| @M |\n+-----+\n| 799 |\n+-----+\n1 row in set (0.0005 sec) "
},
{
"code": null,
"e": 5566,
"s": 5304,
"text": "4. Procedure with IN-OUT parameter:An INOUT parameter is a combination of IN and OUT parameters. It means that the calling program may pass the argument, and the stored procedure can modify the INOUT parameter and pass the new value back to the calling program."
},
{
"code": null,
"e": 5733,
"s": 5566,
"text": "Example:Procedure to take gender type input (βMaleβ/βFemaleβ here) with an in-out parameter which reflects the number of authors falling in that gender category/type:"
},
{
"code": null,
"e": 6114,
"s": 5733,
"text": "delimiter //\ncreate procedure disp_gender(INOUT mfgender integer, IN emp_gender varchar(6)) \n -> begin \n -> select COUNT(gender) \n INTO mfgender FROM author where gender = emp_gender; \n -> end; //\ndelimiter ;\ncall disp_gender(@M, \"Male\");\nselect @M;\ncall disp_gender(@F, \"Female\");\nselect @F; "
},
{
"code": null,
"e": 6298,
"s": 6114,
"text": "Output:We have two authors, one being male and one being female as per insertions in the table author. Hence, output is 1 for one male author and 1 for one female author respectively."
},
{
"code": null,
"e": 6421,
"s": 6298,
"text": "+----+\n| @M |\n+----+\n| 1 |\n+----+\n1 row in set (0.0004 sec)\n+----+\n| @F |\n+----+\n| 1 |\n+----+\n1 row in set (0.0005 sec)\n"
},
{
"code": null,
"e": 6427,
"s": 6421,
"text": "mysql"
},
{
"code": null,
"e": 6438,
"s": 6427,
"text": "SQL-Server"
},
{
"code": null,
"e": 6443,
"s": 6438,
"text": "DBMS"
},
{
"code": null,
"e": 6448,
"s": 6443,
"text": "DBMS"
}
] |
Lodash _.debounce() Method
|
23 Sep, 2020
Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc.
The _.debounce() method of Function in lodash is used to create a debounced function which delays the given func until after the stated wait time in milliseconds have passed since the last time this debounced function was called. The debounced function has a cancel method that can be used to cancel the func calls that are delayed and a flush method which is used to immediately call the delayed func.
It also provides some options that can be used to imply whether the func stated should be called on the leading and/or the trailing edge of the wait timeout.
Note:
The func is called with the last arguments that are given to the debounced function. However, consequent calls to the debounced function returns the result of the last func call.
When the leading and the trailing options are true, then func is called on the trailing edge of the timeout if and only if the debounced function is called more than once throughout the wait timeout.
When the wait time is 0 and the leading option is false, then the func call is deferred until to the next tick.
Syntax:
_.debounce( func, wait, options )
Parameters: This method accepts three parameters as mentioned above and described below:
func: It is the function that has to be debounced.
wait: It is the number of milliseconds for which the calls are to be delayed. It is an optional parameter. The default value is 0.
options: It is the options object that can be used for changing the behaviour of the method. It is an optional parameter.
The options object has the following parameters:
leading: It defines the calling on the leading edge of the timeout. It is an optional parameter. The default value is false.
maxWait: It is the maximum number of time for which the func is allowed to be delayed before it is called. It is an optional parameter.
trailing: It defines the calling on the trailing edge of the timeout. It is an optional parameter. The default value is true.
Return Value: This method returns the new debounced function.
Example 1: In this example, one can enter the REPL again in 1000m after the function call as the waiting time is 1000ms.
Javascript
// Requiring lodash libraryconst _ = require('lodash'); // Using _.debounce() method// with its parametersvar debounce_fun = _.debounce(function () { console.log('Function debounced after 1000ms!'); }, 1000); debounce_fun();
Output:
Function debounced after 1000ms!
Example 2: In this example, the loop does not stop until it is stopped manually.
Javascript
// Requiring lodash libraryconst _ = require('lodash'); // Using _.debounce() method// with its parametersvar debounce_fun = _.debounce(function() { console.log('Function debounced after 1000ms!'); }, 4, 1000, {'leading': false}); // Defining loopvar loop = function() { setTimeout(loop, 3) debounce_fun();}; // Calling loop to startloop();
Output:
Function debounced after 1000ms!
Function debounced after 1000ms!
Function debounced after 1000ms!
Function debounced after 1000ms!
Function debounced after 1000ms!
Function debounced after 1000ms!
Function debounced after 1000ms!
Function debounced after 1000ms!
.
.
.
.
// Will go on unless stopped manually
JavaScript-Lodash
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
Roadmap to Learn JavaScript For Beginners
Hide or show elements in HTML using display property
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n23 Sep, 2020"
},
{
"code": null,
"e": 193,
"s": 53,
"text": "Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc."
},
{
"code": null,
"e": 597,
"s": 193,
"text": "The _.debounce() method of Function in lodash is used to create a debounced function which delays the given func until after the stated wait time in milliseconds have passed since the last time this debounced function was called. The debounced function has a cancel method that can be used to cancel the func calls that are delayed and a flush method which is used to immediately call the delayed func. "
},
{
"code": null,
"e": 755,
"s": 597,
"text": "It also provides some options that can be used to imply whether the func stated should be called on the leading and/or the trailing edge of the wait timeout."
},
{
"code": null,
"e": 761,
"s": 755,
"text": "Note:"
},
{
"code": null,
"e": 940,
"s": 761,
"text": "The func is called with the last arguments that are given to the debounced function. However, consequent calls to the debounced function returns the result of the last func call."
},
{
"code": null,
"e": 1140,
"s": 940,
"text": "When the leading and the trailing options are true, then func is called on the trailing edge of the timeout if and only if the debounced function is called more than once throughout the wait timeout."
},
{
"code": null,
"e": 1252,
"s": 1140,
"text": "When the wait time is 0 and the leading option is false, then the func call is deferred until to the next tick."
},
{
"code": null,
"e": 1260,
"s": 1252,
"text": "Syntax:"
},
{
"code": null,
"e": 1295,
"s": 1260,
"text": "_.debounce( func, wait, options )\n"
},
{
"code": null,
"e": 1384,
"s": 1295,
"text": "Parameters: This method accepts three parameters as mentioned above and described below:"
},
{
"code": null,
"e": 1435,
"s": 1384,
"text": "func: It is the function that has to be debounced."
},
{
"code": null,
"e": 1566,
"s": 1435,
"text": "wait: It is the number of milliseconds for which the calls are to be delayed. It is an optional parameter. The default value is 0."
},
{
"code": null,
"e": 1688,
"s": 1566,
"text": "options: It is the options object that can be used for changing the behaviour of the method. It is an optional parameter."
},
{
"code": null,
"e": 1737,
"s": 1688,
"text": "The options object has the following parameters:"
},
{
"code": null,
"e": 1862,
"s": 1737,
"text": "leading: It defines the calling on the leading edge of the timeout. It is an optional parameter. The default value is false."
},
{
"code": null,
"e": 1998,
"s": 1862,
"text": "maxWait: It is the maximum number of time for which the func is allowed to be delayed before it is called. It is an optional parameter."
},
{
"code": null,
"e": 2124,
"s": 1998,
"text": "trailing: It defines the calling on the trailing edge of the timeout. It is an optional parameter. The default value is true."
},
{
"code": null,
"e": 2186,
"s": 2124,
"text": "Return Value: This method returns the new debounced function."
},
{
"code": null,
"e": 2307,
"s": 2186,
"text": "Example 1: In this example, one can enter the REPL again in 1000m after the function call as the waiting time is 1000ms."
},
{
"code": null,
"e": 2318,
"s": 2307,
"text": "Javascript"
},
{
"code": "// Requiring lodash libraryconst _ = require('lodash'); // Using _.debounce() method// with its parametersvar debounce_fun = _.debounce(function () { console.log('Function debounced after 1000ms!'); }, 1000); debounce_fun();",
"e": 2547,
"s": 2318,
"text": null
},
{
"code": null,
"e": 2555,
"s": 2547,
"text": "Output:"
},
{
"code": null,
"e": 2589,
"s": 2555,
"text": "Function debounced after 1000ms!\n"
},
{
"code": null,
"e": 2670,
"s": 2589,
"text": "Example 2: In this example, the loop does not stop until it is stopped manually."
},
{
"code": null,
"e": 2681,
"s": 2670,
"text": "Javascript"
},
{
"code": "// Requiring lodash libraryconst _ = require('lodash'); // Using _.debounce() method// with its parametersvar debounce_fun = _.debounce(function() { console.log('Function debounced after 1000ms!'); }, 4, 1000, {'leading': false}); // Defining loopvar loop = function() { setTimeout(loop, 3) debounce_fun();}; // Calling loop to startloop();",
"e": 3033,
"s": 2681,
"text": null
},
{
"code": null,
"e": 3041,
"s": 3033,
"text": "Output:"
},
{
"code": null,
"e": 3352,
"s": 3041,
"text": "Function debounced after 1000ms!\nFunction debounced after 1000ms!\nFunction debounced after 1000ms!\nFunction debounced after 1000ms!\nFunction debounced after 1000ms!\nFunction debounced after 1000ms!\nFunction debounced after 1000ms!\nFunction debounced after 1000ms!\n.\n.\n.\n.\n// Will go on unless stopped manually\n"
},
{
"code": null,
"e": 3370,
"s": 3352,
"text": "JavaScript-Lodash"
},
{
"code": null,
"e": 3381,
"s": 3370,
"text": "JavaScript"
},
{
"code": null,
"e": 3398,
"s": 3381,
"text": "Web Technologies"
},
{
"code": null,
"e": 3496,
"s": 3398,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3557,
"s": 3496,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3629,
"s": 3557,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 3669,
"s": 3629,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 3711,
"s": 3669,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 3764,
"s": 3711,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 3797,
"s": 3764,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3859,
"s": 3797,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3920,
"s": 3859,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3970,
"s": 3920,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Matplotlib.figure.Figure.clear() in Python
|
30 Apr, 2020
Matplotlib is a library in Python and it is numerical β mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements.
The clear() method figure module of matplotlib library is used to Clear the figure.
Syntax: clear(self, keep_observers=False)
Parameters: This accept the following parameters that are described below:
keep_observers: This parameter is the boolean value.
Returns: This method does not return any value.
Below examples illustrate the matplotlib.figure.Figure.clear() function in matplotlib.figure:
Example 1:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt fig, ax = plt.subplots() ax.set_xlabel('x-axis')ax.set_ylabel('y-axis') ax.plot([1, 2, 3])ax.grid(True) fig.clear(True) fig.suptitle('matplotlib.figure.Figure.clear() \function Example\n\n', fontweight ="bold") plt.show()
Output:
Example 2:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt t = np.linspace(0.0, 2.0, 201)s = np.sin(2 * np.pi * t) fig, [ax, ax1] = plt.subplots(2, 1, sharex = True) ax.set_ylabel('y-axis')ax.plot(t, s)ax.grid(True)ax.set_title('Sample Example', fontsize = 12, fontweight ='bold') ax1.set_ylabel('y-axis')ax1.plot(t, s)ax1.grid(True) fig.clear(False) fig.suptitle('matplotlib.figure.Figure.clear() \function Example\n\n', fontweight ="bold") plt.show()
Output:
Matplotlib figure-class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Convert integer to string in Python
Python OOPs Concepts
Python | os.path.join() method
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Apr, 2020"
},
{
"code": null,
"e": 339,
"s": 28,
"text": "Matplotlib is a library in Python and it is numerical β mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements."
},
{
"code": null,
"e": 423,
"s": 339,
"text": "The clear() method figure module of matplotlib library is used to Clear the figure."
},
{
"code": null,
"e": 465,
"s": 423,
"text": "Syntax: clear(self, keep_observers=False)"
},
{
"code": null,
"e": 540,
"s": 465,
"text": "Parameters: This accept the following parameters that are described below:"
},
{
"code": null,
"e": 593,
"s": 540,
"text": "keep_observers: This parameter is the boolean value."
},
{
"code": null,
"e": 641,
"s": 593,
"text": "Returns: This method does not return any value."
},
{
"code": null,
"e": 735,
"s": 641,
"text": "Below examples illustrate the matplotlib.figure.Figure.clear() function in matplotlib.figure:"
},
{
"code": null,
"e": 746,
"s": 735,
"text": "Example 1:"
},
{
"code": "# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt fig, ax = plt.subplots() ax.set_xlabel('x-axis')ax.set_ylabel('y-axis') ax.plot([1, 2, 3])ax.grid(True) fig.clear(True) fig.suptitle('matplotlib.figure.Figure.clear() \\function Example\\n\\n', fontweight =\"bold\") plt.show()",
"e": 1068,
"s": 746,
"text": null
},
{
"code": null,
"e": 1076,
"s": 1068,
"text": "Output:"
},
{
"code": null,
"e": 1087,
"s": 1076,
"text": "Example 2:"
},
{
"code": "# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt t = np.linspace(0.0, 2.0, 201)s = np.sin(2 * np.pi * t) fig, [ax, ax1] = plt.subplots(2, 1, sharex = True) ax.set_ylabel('y-axis')ax.plot(t, s)ax.grid(True)ax.set_title('Sample Example', fontsize = 12, fontweight ='bold') ax1.set_ylabel('y-axis')ax1.plot(t, s)ax1.grid(True) fig.clear(False) fig.suptitle('matplotlib.figure.Figure.clear() \\function Example\\n\\n', fontweight =\"bold\") plt.show()",
"e": 1639,
"s": 1087,
"text": null
},
{
"code": null,
"e": 1647,
"s": 1639,
"text": "Output:"
},
{
"code": null,
"e": 1671,
"s": 1647,
"text": "Matplotlib figure-class"
},
{
"code": null,
"e": 1689,
"s": 1671,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 1696,
"s": 1689,
"text": "Python"
},
{
"code": null,
"e": 1794,
"s": 1696,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1812,
"s": 1794,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1854,
"s": 1812,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1876,
"s": 1854,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1902,
"s": 1876,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1934,
"s": 1902,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1963,
"s": 1934,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 1990,
"s": 1963,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2026,
"s": 1990,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 2047,
"s": 2026,
"text": "Python OOPs Concepts"
}
] |
numpy.logical_or() in Python
|
29 Nov, 2018
numpy.logical_or(arr1, arr2, out=None, where = True, casting = βsame_kindβ, order = βKβ, dtype = None, ufunc βlogical_orβ) : This is a logical function and it helps user to find out the truth value of arr1 OR arr2 element-wise. Both the arrays must be of same shape.
Parameters :
arr1 : [array_like]Input array.arr2 : [array_like]Input array.
out : [ndarray, optional]Output array with same dimensions as Input array, placed with result.
**kwargs : allows you to pass keyword variable length of argument to a function. It is used when we want to handle named argument in a function.
where : [array_like, optional]True value means to calculate the universal functions(ufunc) at that position, False value means to leave the value in the output alone.
Return :
An array with Boolean results of arr1 OR arr2 element-wise(of the same shape).
Code 1 : Working
# Python program explaining# logical_or() functionimport numpy as np # inputarr1 = [1, 3, False, 4]arr2 = [3, 0, True, False] # outputout_arr = np.logical_or(arr1, arr2) print ("Output Array : ", out_arr)
Output :
Output Array : [ True True True True]
Code 2 : Value Error if input arrayβs have different shapes
# Python program explaining# logical_or() functionimport numpy as np # inputarr1 = [8, 2, False, 4]arr2 = [3, 0, False, False, 8] # outputout_arr = np.logical_or(arr1, arr2) print ("Output Array : ", out_arr)
Output :
ValueError: operands could not be broadcast together with shapes (4,) (5,)
References :https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.logical_or.html#numpy.logical_or.
Python numpy-Logic Functions
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 | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
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
Create a directory in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Nov, 2018"
},
{
"code": null,
"e": 295,
"s": 28,
"text": "numpy.logical_or(arr1, arr2, out=None, where = True, casting = βsame_kindβ, order = βKβ, dtype = None, ufunc βlogical_orβ) : This is a logical function and it helps user to find out the truth value of arr1 OR arr2 element-wise. Both the arrays must be of same shape."
},
{
"code": null,
"e": 308,
"s": 295,
"text": "Parameters :"
},
{
"code": null,
"e": 371,
"s": 308,
"text": "arr1 : [array_like]Input array.arr2 : [array_like]Input array."
},
{
"code": null,
"e": 466,
"s": 371,
"text": "out : [ndarray, optional]Output array with same dimensions as Input array, placed with result."
},
{
"code": null,
"e": 611,
"s": 466,
"text": "**kwargs : allows you to pass keyword variable length of argument to a function. It is used when we want to handle named argument in a function."
},
{
"code": null,
"e": 778,
"s": 611,
"text": "where : [array_like, optional]True value means to calculate the universal functions(ufunc) at that position, False value means to leave the value in the output alone."
},
{
"code": null,
"e": 787,
"s": 778,
"text": "Return :"
},
{
"code": null,
"e": 869,
"s": 787,
"text": "An array with Boolean results of arr1 OR arr2 element-wise(of the same shape). \n"
},
{
"code": null,
"e": 887,
"s": 869,
"text": " Code 1 : Working"
},
{
"code": "# Python program explaining# logical_or() functionimport numpy as np # inputarr1 = [1, 3, False, 4]arr2 = [3, 0, True, False] # outputout_arr = np.logical_or(arr1, arr2) print (\"Output Array : \", out_arr)",
"e": 1095,
"s": 887,
"text": null
},
{
"code": null,
"e": 1104,
"s": 1095,
"text": "Output :"
},
{
"code": null,
"e": 1147,
"s": 1104,
"text": "Output Array : [ True True True True]\n"
},
{
"code": null,
"e": 1208,
"s": 1147,
"text": " Code 2 : Value Error if input arrayβs have different shapes"
},
{
"code": "# Python program explaining# logical_or() functionimport numpy as np # inputarr1 = [8, 2, False, 4]arr2 = [3, 0, False, False, 8] # outputout_arr = np.logical_or(arr1, arr2) print (\"Output Array : \", out_arr)",
"e": 1420,
"s": 1208,
"text": null
},
{
"code": null,
"e": 1429,
"s": 1420,
"text": "Output :"
},
{
"code": null,
"e": 1506,
"s": 1429,
"text": "ValueError: operands could not be broadcast together with shapes (4,) (5,) "
},
{
"code": null,
"e": 1618,
"s": 1506,
"text": "References :https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.logical_or.html#numpy.logical_or."
},
{
"code": null,
"e": 1647,
"s": 1618,
"text": "Python numpy-Logic Functions"
},
{
"code": null,
"e": 1660,
"s": 1647,
"text": "Python-numpy"
},
{
"code": null,
"e": 1667,
"s": 1660,
"text": "Python"
},
{
"code": null,
"e": 1765,
"s": 1667,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1797,
"s": 1765,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1824,
"s": 1797,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1855,
"s": 1824,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1878,
"s": 1855,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1899,
"s": 1878,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1955,
"s": 1899,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1997,
"s": 1955,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2039,
"s": 1997,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2078,
"s": 2039,
"text": "Python | Get unique values from a list"
}
] |
PHP | imagefill() Function
|
23 Aug, 2019
The imagefill() function is an inbuilt function in PHP which is used to fill the image with the given color. This function performs a flood fill starting at the given coordinate (top left is 0, 0) with the given color in the image.
Syntax:
bool imagefill( $image, $x, $y, $color )
Parameters:This function accepts four parameters as mentioned above and described below:
$image: It is returned by one of the image creation functions, such as imagecreatetruecolor(). It is used to create size of image.
$x: This parameter is used to set x-coordinate of starting point.
$y: This parameter is used to set y-coordinate of starting point.
$color: It sets the color of image. A color identifier created by imagecolorallocate() function.
Return Value: This function returns True on success of False on failure.
Below programs illustrate the imagefill() function in PHP:
Program 1:
<?php // Create an image of given size$image = imagecreatetruecolor(500, 400); // Sets background to green$green = imagecolorallocate($image, 0, 153, 0);imagefill($image, 0, 0, $green); header('Content-type: image/png');imagepng($image);imagedestroy($image);?>
Output:
Program 2:
<?php // It create the size of image or blank image.$image = imagecreatetruecolor(500, 300); // Set the background color of image.$bg = imagecolorallocate($image, 205, 220, 200); // Fill background with above selected color.imagefill($image, 0, 0, $bg); // Set the color of an ellipse.$col_ellipse = imagecolorallocate($image, 0, 102, 0); // Function to draw the filled ellipse.imagefilledellipse($image, 250, 150, 400, 250, $col_ellipse); // Output of the image.header("Content-type: image/png");imagepng($image); ?>
Output:
Related Articles:
PHP | imagecolorallocatealpha() Function
PHP | imagearc() Function
PHP | imageellipse() Function
Reference: http://php.net/manual/en/function.imagefill.php
Image-Processing
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
PHP | Converting string to Date and DateTime
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Aug, 2019"
},
{
"code": null,
"e": 260,
"s": 28,
"text": "The imagefill() function is an inbuilt function in PHP which is used to fill the image with the given color. This function performs a flood fill starting at the given coordinate (top left is 0, 0) with the given color in the image."
},
{
"code": null,
"e": 268,
"s": 260,
"text": "Syntax:"
},
{
"code": null,
"e": 309,
"s": 268,
"text": "bool imagefill( $image, $x, $y, $color )"
},
{
"code": null,
"e": 398,
"s": 309,
"text": "Parameters:This function accepts four parameters as mentioned above and described below:"
},
{
"code": null,
"e": 529,
"s": 398,
"text": "$image: It is returned by one of the image creation functions, such as imagecreatetruecolor(). It is used to create size of image."
},
{
"code": null,
"e": 595,
"s": 529,
"text": "$x: This parameter is used to set x-coordinate of starting point."
},
{
"code": null,
"e": 661,
"s": 595,
"text": "$y: This parameter is used to set y-coordinate of starting point."
},
{
"code": null,
"e": 758,
"s": 661,
"text": "$color: It sets the color of image. A color identifier created by imagecolorallocate() function."
},
{
"code": null,
"e": 831,
"s": 758,
"text": "Return Value: This function returns True on success of False on failure."
},
{
"code": null,
"e": 890,
"s": 831,
"text": "Below programs illustrate the imagefill() function in PHP:"
},
{
"code": null,
"e": 901,
"s": 890,
"text": "Program 1:"
},
{
"code": "<?php // Create an image of given size$image = imagecreatetruecolor(500, 400); // Sets background to green$green = imagecolorallocate($image, 0, 153, 0);imagefill($image, 0, 0, $green); header('Content-type: image/png');imagepng($image);imagedestroy($image);?>",
"e": 1165,
"s": 901,
"text": null
},
{
"code": null,
"e": 1173,
"s": 1165,
"text": "Output:"
},
{
"code": null,
"e": 1184,
"s": 1173,
"text": "Program 2:"
},
{
"code": "<?php // It create the size of image or blank image.$image = imagecreatetruecolor(500, 300); // Set the background color of image.$bg = imagecolorallocate($image, 205, 220, 200); // Fill background with above selected color.imagefill($image, 0, 0, $bg); // Set the color of an ellipse.$col_ellipse = imagecolorallocate($image, 0, 102, 0); // Function to draw the filled ellipse.imagefilledellipse($image, 250, 150, 400, 250, $col_ellipse); // Output of the image.header(\"Content-type: image/png\");imagepng($image); ?>",
"e": 1722,
"s": 1184,
"text": null
},
{
"code": null,
"e": 1730,
"s": 1722,
"text": "Output:"
},
{
"code": null,
"e": 1748,
"s": 1730,
"text": "Related Articles:"
},
{
"code": null,
"e": 1789,
"s": 1748,
"text": "PHP | imagecolorallocatealpha() Function"
},
{
"code": null,
"e": 1815,
"s": 1789,
"text": "PHP | imagearc() Function"
},
{
"code": null,
"e": 1845,
"s": 1815,
"text": "PHP | imageellipse() Function"
},
{
"code": null,
"e": 1904,
"s": 1845,
"text": "Reference: http://php.net/manual/en/function.imagefill.php"
},
{
"code": null,
"e": 1921,
"s": 1904,
"text": "Image-Processing"
},
{
"code": null,
"e": 1934,
"s": 1921,
"text": "PHP-function"
},
{
"code": null,
"e": 1938,
"s": 1934,
"text": "PHP"
},
{
"code": null,
"e": 1955,
"s": 1938,
"text": "Web Technologies"
},
{
"code": null,
"e": 1959,
"s": 1955,
"text": "PHP"
},
{
"code": null,
"e": 2057,
"s": 1959,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2107,
"s": 2057,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 2147,
"s": 2107,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 2208,
"s": 2147,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 2258,
"s": 2208,
"text": "How to check whether an array is empty using PHP?"
},
{
"code": null,
"e": 2303,
"s": 2258,
"text": "PHP | Converting string to Date and DateTime"
},
{
"code": null,
"e": 2336,
"s": 2303,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2398,
"s": 2336,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2459,
"s": 2398,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2509,
"s": 2459,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Program to calculate volume of Octahedron
|
21 Jun, 2022
Given the side of the Octahedron then calculate the volume of Octahedron.Examples:
Input : 3
Output : 12.7279
Input : 7
Output : 161.692
A regular Octahedron has eight faces,twelve edges and six vertices. It has eight triangles with edges of equal length and effectively two square pyramids meeting at their bases.
Image Source : Wikimedia
Properties of Octahedron: Number of faces: 8 Number of edges: 12 Number of vertices: 6 Volume = β2/3 Γ a3 where a is the side of Octahedron
CPP
Java
Python3
C#
PHP
Javascript
// CPP Program to calculate// volume of Octahedron#include <bits/stdc++.h>using namespace std; // utility Functiondouble vol_of_octahedron(double side){ return ((side*side*side)*(sqrt(2)/3));} // Driver Functionint main(){ double side = 3; cout << "Volume of octahedron =" << vol_of_octahedron(side) << endl;}
// Java Program to calculate// volume of Octahedron import java.io.*;class GFG{ public static void main (String[] args) { // Driver Function double side = 3; System.out.print("Volume of octahedron = "); System.out.println(vol_of_octahedron(side)); } // utility Function static double vol_of_octahedron(double side) { return ((side*side*side)*(Math.sqrt(2)/3)); }} // This code is contributed// by Azkia Anam.
# Python3 Program to calculate# volume of Octahedron import math # utility Functiondef vol_of_octahedron(side): return ((side*side*side)*(math.sqrt(2)/3)) # Driver Functionside = 3print("Volume of octahedron =", round(vol_of_octahedron(side),4)) # This code is contributed# by Azkia Anam.
// C# Program to calculate// volume of Octahedronusing System; class GFG{ public static void Main () { // Driver Function double side = 3; Console.Write("Volume of octahedron = "); Console.WriteLine(vol_of_octahedron(side)); } // utility Function static double vol_of_octahedron(double side) { return ((side*side*side)*(Math.Sqrt(2)/3)); }} // This code is contributed// by vt_m.
<?php// PHP Program to calculate// volume of Octahedron // utility Functionfunction vol_of_octahedron( $side){ return (($side * $side * $side) * (sqrt(2) / 3));} // Driver Function $side = 3; echo ("Volume of octahedron ="); echo(vol_of_octahedron($side)); // This code is contributed// by vt_m.?>
<script>// javascript Program to calculate// volume of Octahedron // utility Functionfunction vol_of_octahedron( side){ return ((side*side*side)*(Math.sqrt(2)/3));} // Driver Function let side = 3; document.write("Volume of octahedron = " + vol_of_octahedron(side).toFixed(4)); // This code is contributed by gauravrajput1</script>
Output:
Volume of octahedron = 12.7279
Time complexity : O(1) Auxiliary Space : O(1)
vt_m
GauravRajput1
krishnav4
area-volume-programs
Geometric
School Programming
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program for distance between two points on earth
Find if two rectangles overlap
Check whether triangle is valid or not if sides are given
Line Clipping | Set 1 (CohenβSutherland Algorithm)
Program for Point of Intersection of Two Lines
Python Dictionary
Reverse a string in Java
Arrays in C/C++
Introduction To PYTHON
Interfaces in Java
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n21 Jun, 2022"
},
{
"code": null,
"e": 137,
"s": 52,
"text": "Given the side of the Octahedron then calculate the volume of Octahedron.Examples: "
},
{
"code": null,
"e": 192,
"s": 137,
"text": "Input : 3\nOutput : 12.7279\n\nInput : 7\nOutput : 161.692"
},
{
"code": null,
"e": 373,
"s": 194,
"text": "A regular Octahedron has eight faces,twelve edges and six vertices. It has eight triangles with edges of equal length and effectively two square pyramids meeting at their bases. "
},
{
"code": null,
"e": 399,
"s": 373,
"text": "Image Source : Wikimedia "
},
{
"code": null,
"e": 541,
"s": 399,
"text": "Properties of Octahedron: Number of faces: 8 Number of edges: 12 Number of vertices: 6 Volume = β2/3 Γ a3 where a is the side of Octahedron "
},
{
"code": null,
"e": 547,
"s": 543,
"text": "CPP"
},
{
"code": null,
"e": 552,
"s": 547,
"text": "Java"
},
{
"code": null,
"e": 560,
"s": 552,
"text": "Python3"
},
{
"code": null,
"e": 563,
"s": 560,
"text": "C#"
},
{
"code": null,
"e": 567,
"s": 563,
"text": "PHP"
},
{
"code": null,
"e": 578,
"s": 567,
"text": "Javascript"
},
{
"code": "// CPP Program to calculate// volume of Octahedron#include <bits/stdc++.h>using namespace std; // utility Functiondouble vol_of_octahedron(double side){ return ((side*side*side)*(sqrt(2)/3));} // Driver Functionint main(){ double side = 3; cout << \"Volume of octahedron =\" << vol_of_octahedron(side) << endl;}",
"e": 913,
"s": 578,
"text": null
},
{
"code": "// Java Program to calculate// volume of Octahedron import java.io.*;class GFG{ public static void main (String[] args) { // Driver Function double side = 3; System.out.print(\"Volume of octahedron = \"); System.out.println(vol_of_octahedron(side)); } // utility Function static double vol_of_octahedron(double side) { return ((side*side*side)*(Math.sqrt(2)/3)); }} // This code is contributed// by Azkia Anam.",
"e": 1392,
"s": 913,
"text": null
},
{
"code": "# Python3 Program to calculate# volume of Octahedron import math # utility Functiondef vol_of_octahedron(side): return ((side*side*side)*(math.sqrt(2)/3)) # Driver Functionside = 3print(\"Volume of octahedron =\", round(vol_of_octahedron(side),4)) # This code is contributed# by Azkia Anam.",
"e": 1689,
"s": 1392,
"text": null
},
{
"code": "// C# Program to calculate// volume of Octahedronusing System; class GFG{ public static void Main () { // Driver Function double side = 3; Console.Write(\"Volume of octahedron = \"); Console.WriteLine(vol_of_octahedron(side)); } // utility Function static double vol_of_octahedron(double side) { return ((side*side*side)*(Math.Sqrt(2)/3)); }} // This code is contributed// by vt_m.",
"e": 2127,
"s": 1689,
"text": null
},
{
"code": "<?php// PHP Program to calculate// volume of Octahedron // utility Functionfunction vol_of_octahedron( $side){ return (($side * $side * $side) * (sqrt(2) / 3));} // Driver Function $side = 3; echo (\"Volume of octahedron =\"); echo(vol_of_octahedron($side)); // This code is contributed// by vt_m.?>",
"e": 2461,
"s": 2127,
"text": null
},
{
"code": "<script>// javascript Program to calculate// volume of Octahedron // utility Functionfunction vol_of_octahedron( side){ return ((side*side*side)*(Math.sqrt(2)/3));} // Driver Function let side = 3; document.write(\"Volume of octahedron = \" + vol_of_octahedron(side).toFixed(4)); // This code is contributed by gauravrajput1</script>",
"e": 2813,
"s": 2461,
"text": null
},
{
"code": null,
"e": 2823,
"s": 2813,
"text": "Output: "
},
{
"code": null,
"e": 2855,
"s": 2823,
"text": " Volume of octahedron = 12.7279"
},
{
"code": null,
"e": 2901,
"s": 2855,
"text": "Time complexity : O(1) Auxiliary Space : O(1)"
},
{
"code": null,
"e": 2906,
"s": 2901,
"text": "vt_m"
},
{
"code": null,
"e": 2920,
"s": 2906,
"text": "GauravRajput1"
},
{
"code": null,
"e": 2930,
"s": 2920,
"text": "krishnav4"
},
{
"code": null,
"e": 2951,
"s": 2930,
"text": "area-volume-programs"
},
{
"code": null,
"e": 2961,
"s": 2951,
"text": "Geometric"
},
{
"code": null,
"e": 2980,
"s": 2961,
"text": "School Programming"
},
{
"code": null,
"e": 2990,
"s": 2980,
"text": "Geometric"
},
{
"code": null,
"e": 3088,
"s": 2990,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3137,
"s": 3088,
"text": "Program for distance between two points on earth"
},
{
"code": null,
"e": 3168,
"s": 3137,
"text": "Find if two rectangles overlap"
},
{
"code": null,
"e": 3226,
"s": 3168,
"text": "Check whether triangle is valid or not if sides are given"
},
{
"code": null,
"e": 3277,
"s": 3226,
"text": "Line Clipping | Set 1 (CohenβSutherland Algorithm)"
},
{
"code": null,
"e": 3324,
"s": 3277,
"text": "Program for Point of Intersection of Two Lines"
},
{
"code": null,
"e": 3342,
"s": 3324,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3367,
"s": 3342,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 3383,
"s": 3367,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 3406,
"s": 3383,
"text": "Introduction To PYTHON"
}
] |
PHP | explode() Function
|
03 Jan, 2022
explode() is a built in function in PHP used to split a string in different strings. The explode() function splits a string based on a string delimiter, i.e. it splits the string wherever the delimiter character occurs. This functions returns an array containing the strings formed by splitting the original string.
Syntax :
array explode(separator, OriginalString, NoOfElements)
Parameters : The explode function accepts three parameters of which two are compulsory and one is optional. All the three parameters are described below
separator : This character specifies the critical points or points at which the string will split, i.e. whenever this character is found in the string it symbolizes end of one element of the array and start of another.OriginalString : The input string which is to be split in array.NoOfElements : This is optional. It is used to specify the number of elements of the array. This parameter can be any integer ( positive , negative or zero)Positive (N): When this parameter is passed with a positive value it means that the array will contain this number of elements. If the number of elements after separating with respect to the separator emerges to be greater than this value the first N-1 elements remain the same and the last element is the whole remaining string.Negative (N):If negative value is passed as parameter then the last N element of the array will be trimmed out and the remaining part of the array shall be returned as a single array.Zero : If this parameter is Zero then the array returned will have only one element i.e. the whole string.When this parameter is not provided the array returned contains the total number of element formed after separating the string with the separator.
separator : This character specifies the critical points or points at which the string will split, i.e. whenever this character is found in the string it symbolizes end of one element of the array and start of another.
OriginalString : The input string which is to be split in array.
NoOfElements : This is optional. It is used to specify the number of elements of the array. This parameter can be any integer ( positive , negative or zero)Positive (N): When this parameter is passed with a positive value it means that the array will contain this number of elements. If the number of elements after separating with respect to the separator emerges to be greater than this value the first N-1 elements remain the same and the last element is the whole remaining string.Negative (N):If negative value is passed as parameter then the last N element of the array will be trimmed out and the remaining part of the array shall be returned as a single array.Zero : If this parameter is Zero then the array returned will have only one element i.e. the whole string.When this parameter is not provided the array returned contains the total number of element formed after separating the string with the separator.
Positive (N): When this parameter is passed with a positive value it means that the array will contain this number of elements. If the number of elements after separating with respect to the separator emerges to be greater than this value the first N-1 elements remain the same and the last element is the whole remaining string.
Negative (N):If negative value is passed as parameter then the last N element of the array will be trimmed out and the remaining part of the array shall be returned as a single array.
Zero : If this parameter is Zero then the array returned will have only one element i.e. the whole string.
When this parameter is not provided the array returned contains the total number of element formed after separating the string with the separator.
Return Type: The return type of explode() function is array of strings.
Examples:
Input : explode(" ","Geeks for Geeks")
Output : Array
(
[0] => Geeks
[1] => for
[2] => Geeks
)
Below program illustrates the working of explode() in PHP:
PHP
<?php // original string $OriginalString = "Hello, How can we help you?"; // Without optional parameter NoOfElements print_r(explode(" ",$OriginalString)); // with positive NoOfElements print_r(explode(" ",$OriginalString,3)); // with negative NoOfElements print_r(explode(" ",$OriginalString,-1)); ?>
Output:
Array
(
[0] => Hello,
[1] => How
[2] => can
[3] => we
[4] => help
[5] => you?
)
Array
(
[0] => Hello,
[1] => How
[2] => can we help you?
)
Array
(
[0] => Hello,
[1] => How
[2] => can
[3] => we
[4] => help
)
Reference: http://php.net/manual/en/function.explode.php
JaiwardhanSwarnakar
gabaa406
PHP-string
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
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
REST API (Introduction)
Node.js fs.readFileSync() Method
How to set the default value for an HTML <select> element ?
Roadmap to Learn JavaScript For Beginners
How to create footer to stay at the bottom of a Web page?
How to set input type date in dd-mm-yyyy format using HTML ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Jan, 2022"
},
{
"code": null,
"e": 344,
"s": 28,
"text": "explode() is a built in function in PHP used to split a string in different strings. The explode() function splits a string based on a string delimiter, i.e. it splits the string wherever the delimiter character occurs. This functions returns an array containing the strings formed by splitting the original string."
},
{
"code": null,
"e": 353,
"s": 344,
"text": "Syntax :"
},
{
"code": null,
"e": 409,
"s": 353,
"text": "array explode(separator, OriginalString, NoOfElements)\n"
},
{
"code": null,
"e": 562,
"s": 409,
"text": "Parameters : The explode function accepts three parameters of which two are compulsory and one is optional. All the three parameters are described below"
},
{
"code": null,
"e": 1765,
"s": 562,
"text": "separator : This character specifies the critical points or points at which the string will split, i.e. whenever this character is found in the string it symbolizes end of one element of the array and start of another.OriginalString : The input string which is to be split in array.NoOfElements : This is optional. It is used to specify the number of elements of the array. This parameter can be any integer ( positive , negative or zero)Positive (N): When this parameter is passed with a positive value it means that the array will contain this number of elements. If the number of elements after separating with respect to the separator emerges to be greater than this value the first N-1 elements remain the same and the last element is the whole remaining string.Negative (N):If negative value is passed as parameter then the last N element of the array will be trimmed out and the remaining part of the array shall be returned as a single array.Zero : If this parameter is Zero then the array returned will have only one element i.e. the whole string.When this parameter is not provided the array returned contains the total number of element formed after separating the string with the separator."
},
{
"code": null,
"e": 1984,
"s": 1765,
"text": "separator : This character specifies the critical points or points at which the string will split, i.e. whenever this character is found in the string it symbolizes end of one element of the array and start of another."
},
{
"code": null,
"e": 2049,
"s": 1984,
"text": "OriginalString : The input string which is to be split in array."
},
{
"code": null,
"e": 2970,
"s": 2049,
"text": "NoOfElements : This is optional. It is used to specify the number of elements of the array. This parameter can be any integer ( positive , negative or zero)Positive (N): When this parameter is passed with a positive value it means that the array will contain this number of elements. If the number of elements after separating with respect to the separator emerges to be greater than this value the first N-1 elements remain the same and the last element is the whole remaining string.Negative (N):If negative value is passed as parameter then the last N element of the array will be trimmed out and the remaining part of the array shall be returned as a single array.Zero : If this parameter is Zero then the array returned will have only one element i.e. the whole string.When this parameter is not provided the array returned contains the total number of element formed after separating the string with the separator."
},
{
"code": null,
"e": 3300,
"s": 2970,
"text": "Positive (N): When this parameter is passed with a positive value it means that the array will contain this number of elements. If the number of elements after separating with respect to the separator emerges to be greater than this value the first N-1 elements remain the same and the last element is the whole remaining string."
},
{
"code": null,
"e": 3484,
"s": 3300,
"text": "Negative (N):If negative value is passed as parameter then the last N element of the array will be trimmed out and the remaining part of the array shall be returned as a single array."
},
{
"code": null,
"e": 3591,
"s": 3484,
"text": "Zero : If this parameter is Zero then the array returned will have only one element i.e. the whole string."
},
{
"code": null,
"e": 3738,
"s": 3591,
"text": "When this parameter is not provided the array returned contains the total number of element formed after separating the string with the separator."
},
{
"code": null,
"e": 3810,
"s": 3738,
"text": "Return Type: The return type of explode() function is array of strings."
},
{
"code": null,
"e": 3820,
"s": 3810,
"text": "Examples:"
},
{
"code": null,
"e": 3968,
"s": 3820,
"text": "Input : explode(\" \",\"Geeks for Geeks\")\nOutput : Array\n (\n [0] => Geeks\n [1] => for\n [2] => Geeks\n )\n"
},
{
"code": null,
"e": 4027,
"s": 3968,
"text": "Below program illustrates the working of explode() in PHP:"
},
{
"code": null,
"e": 4031,
"s": 4027,
"text": "PHP"
},
{
"code": "<?php // original string $OriginalString = \"Hello, How can we help you?\"; // Without optional parameter NoOfElements print_r(explode(\" \",$OriginalString)); // with positive NoOfElements print_r(explode(\" \",$OriginalString,3)); // with negative NoOfElements print_r(explode(\" \",$OriginalString,-1)); ?>",
"e": 4370,
"s": 4031,
"text": null
},
{
"code": null,
"e": 4378,
"s": 4370,
"text": "Output:"
},
{
"code": null,
"e": 4642,
"s": 4378,
"text": "Array\n(\n [0] => Hello,\n [1] => How\n [2] => can\n [3] => we\n [4] => help\n [5] => you?\n)\nArray\n(\n [0] => Hello,\n [1] => How\n [2] => can we help you?\n)\nArray\n(\n [0] => Hello,\n [1] => How\n [2] => can\n [3] => we\n [4] => help\n)\n"
},
{
"code": null,
"e": 4699,
"s": 4642,
"text": "Reference: http://php.net/manual/en/function.explode.php"
},
{
"code": null,
"e": 4719,
"s": 4699,
"text": "JaiwardhanSwarnakar"
},
{
"code": null,
"e": 4728,
"s": 4719,
"text": "gabaa406"
},
{
"code": null,
"e": 4739,
"s": 4728,
"text": "PHP-string"
},
{
"code": null,
"e": 4756,
"s": 4739,
"text": "Web Technologies"
},
{
"code": null,
"e": 4854,
"s": 4756,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4915,
"s": 4854,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4958,
"s": 4915,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 5030,
"s": 4958,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 5070,
"s": 5030,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 5094,
"s": 5070,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 5127,
"s": 5094,
"text": "Node.js fs.readFileSync() Method"
},
{
"code": null,
"e": 5187,
"s": 5127,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 5229,
"s": 5187,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 5287,
"s": 5229,
"text": "How to create footer to stay at the bottom of a Web page?"
}
] |
Insert multiple values into multiple tables using a single statement in SQL Server
|
12 Feb, 2022
The T-SQL function OUTPUT, which was introduced in 2005, can be used to insert multiple values into multiple tables in a single statement. The output values of each row that was part of an INSERT, UPDATE or DELETE operation are returned by the OUTPUT clause.
Syntax:
INSERT INTO Table1 (Col1, Col2)
OUTPUT inserted.Col1, inserted.Col2
INTO Table2
VALUES()
GO
Example: In this example, we are creating 2 sample tables using the below queries:
CREATE TABLE GeekTable1 (Id1 INT, Name1 VARCHAR(200), City1 VARCHAR(200))
GO
CREATE TABLE GeekTable2 (Id2 INT, Name2 VARCHAR(200), City2 VARCHAR(200))
GO
Now, let us Insert values into two tables together:
INSERT INTO GeekTable1 (Id1, Name1, City1)
OUTPUT inserted.Id1, inserted.Name1, inserted.City1
INTO GeekTable2
VALUES(1,'Komal','Delhi'), (2, 'Khushi','Noida')
GO
Select data from both the tables:
SELECT * FROM GeekTable1 ;
GO
SELECT * FROM GeekTable2 ;
GO
Output: When we run the above query, we will see that there are two rows each in the table:
GeekTable1:
GeekTable2:
armaantojain
DBMS-SQL
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
How to Update Multiple Columns in Single Update Statement in SQL?
SQL Interview Questions
SQL | Views
Difference between DELETE, DROP and TRUNCATE
Window functions in SQL
MySQL | Group_CONCAT() Function
SQL | GROUP BY
Difference between DDL and DML in DBMS
Difference between DELETE and TRUNCATE
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Feb, 2022"
},
{
"code": null,
"e": 287,
"s": 28,
"text": "The T-SQL function OUTPUT, which was introduced in 2005, can be used to insert multiple values into multiple tables in a single statement. The output values of each row that was part of an INSERT, UPDATE or DELETE operation are returned by the OUTPUT clause."
},
{
"code": null,
"e": 295,
"s": 287,
"text": "Syntax:"
},
{
"code": null,
"e": 387,
"s": 295,
"text": "INSERT INTO Table1 (Col1, Col2)\nOUTPUT inserted.Col1, inserted.Col2\nINTO Table2\nVALUES()\nGO"
},
{
"code": null,
"e": 470,
"s": 387,
"text": "Example: In this example, we are creating 2 sample tables using the below queries:"
},
{
"code": null,
"e": 624,
"s": 470,
"text": "CREATE TABLE GeekTable1 (Id1 INT, Name1 VARCHAR(200), City1 VARCHAR(200))\nGO\nCREATE TABLE GeekTable2 (Id2 INT, Name2 VARCHAR(200), City2 VARCHAR(200))\nGO"
},
{
"code": null,
"e": 676,
"s": 624,
"text": "Now, let us Insert values into two tables together:"
},
{
"code": null,
"e": 839,
"s": 676,
"text": "INSERT INTO GeekTable1 (Id1, Name1, City1)\nOUTPUT inserted.Id1, inserted.Name1, inserted.City1\nINTO GeekTable2\nVALUES(1,'Komal','Delhi'), (2, 'Khushi','Noida')\nGO"
},
{
"code": null,
"e": 873,
"s": 839,
"text": "Select data from both the tables:"
},
{
"code": null,
"e": 933,
"s": 873,
"text": "SELECT * FROM GeekTable1 ;\nGO\nSELECT * FROM GeekTable2 ;\nGO"
},
{
"code": null,
"e": 1025,
"s": 933,
"text": "Output: When we run the above query, we will see that there are two rows each in the table:"
},
{
"code": null,
"e": 1037,
"s": 1025,
"text": "GeekTable1:"
},
{
"code": null,
"e": 1049,
"s": 1037,
"text": "GeekTable2:"
},
{
"code": null,
"e": 1062,
"s": 1049,
"text": "armaantojain"
},
{
"code": null,
"e": 1071,
"s": 1062,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 1082,
"s": 1071,
"text": "SQL-Server"
},
{
"code": null,
"e": 1086,
"s": 1082,
"text": "SQL"
},
{
"code": null,
"e": 1090,
"s": 1086,
"text": "SQL"
},
{
"code": null,
"e": 1188,
"s": 1090,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1199,
"s": 1188,
"text": "CTE in SQL"
},
{
"code": null,
"e": 1265,
"s": 1199,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 1289,
"s": 1265,
"text": "SQL Interview Questions"
},
{
"code": null,
"e": 1301,
"s": 1289,
"text": "SQL | Views"
},
{
"code": null,
"e": 1346,
"s": 1301,
"text": "Difference between DELETE, DROP and TRUNCATE"
},
{
"code": null,
"e": 1370,
"s": 1346,
"text": "Window functions in SQL"
},
{
"code": null,
"e": 1402,
"s": 1370,
"text": "MySQL | Group_CONCAT() Function"
},
{
"code": null,
"e": 1417,
"s": 1402,
"text": "SQL | GROUP BY"
},
{
"code": null,
"e": 1456,
"s": 1417,
"text": "Difference between DDL and DML in DBMS"
}
] |
isinf() function in C++
|
27 Sep, 2018
This function is defined in <cmath.h> .The isinf() function is use to determine whether the given number is infinity or not i.e positive infinity or negative infinity both. This function returns 1 if the given number is infinite otherwise this function returns zero.
Syntax:
bool isinf( float arg );
or
bool isinf( double arg );
or
bool isinf( long double arg );
Parameter: This function takes a mandatory parameter x which represents the given floating point value.
Return: This function returns 1 if the given number is infinite else return zero.
Below programs illustrate the isinf() function in C++:
Example 1:- To show infinite case which returns 1
// c++ program to demonstrate// example of isnormal() function. #include <bits/stdc++.h> using namespace std; int main(){ float f = 6.0F; // check for +ve infinite value cout << "isinf(6.0/0.0) is = " << isinf(f/0.0) << endl; // check for -ve infinite value f = -1.2F; cout << "isinf(-1.2/0.0) is = " << isinf(f/0.0) << endl; return 0;}
isinf(6.0/0.0) is = 1
isinf(-1.2/0.0) is = 1
Explanation: In example 1 the floating point number represents infinity thatβs why function returns 1.
Example 2:- To show non-infinite case which returns 0
// c++ program to demonstrate// example of isinf() function. #include <bits/stdc++.h>using namespace std; int main(){ cout << "isinf(0.0) is = " << isinf(0.0) << endl; cout << "isinf(sqrt(-1.0)) is = " << isinf(sqrt(-1.0)) << endl; return 0;}
isinf(0.0) is = 0
isinf(sqrt(-1.0)) is = 0
Exception: In example 2 the given floating point number is not representing infinity thatβs why function returns zero.
CPP-Library
cpp-numerics-library
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bitwise Operators in C/C++
Set in C++ Standard Template Library (STL)
vector erase() and clear() in C++
unordered_map in C++ STL
Inheritance in C++
Priority Queue in C++ Standard Template Library (STL)
The C++ Standard Template Library (STL)
Sorting a vector in C++
Substring in C++
C++ Classes and Objects
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Sep, 2018"
},
{
"code": null,
"e": 295,
"s": 28,
"text": "This function is defined in <cmath.h> .The isinf() function is use to determine whether the given number is infinity or not i.e positive infinity or negative infinity both. This function returns 1 if the given number is infinite otherwise this function returns zero."
},
{
"code": null,
"e": 303,
"s": 295,
"text": "Syntax:"
},
{
"code": null,
"e": 328,
"s": 303,
"text": "bool isinf( float arg );"
},
{
"code": null,
"e": 331,
"s": 328,
"text": "or"
},
{
"code": null,
"e": 357,
"s": 331,
"text": "bool isinf( double arg );"
},
{
"code": null,
"e": 360,
"s": 357,
"text": "or"
},
{
"code": null,
"e": 391,
"s": 360,
"text": "bool isinf( long double arg );"
},
{
"code": null,
"e": 495,
"s": 391,
"text": "Parameter: This function takes a mandatory parameter x which represents the given floating point value."
},
{
"code": null,
"e": 577,
"s": 495,
"text": "Return: This function returns 1 if the given number is infinite else return zero."
},
{
"code": null,
"e": 632,
"s": 577,
"text": "Below programs illustrate the isinf() function in C++:"
},
{
"code": null,
"e": 682,
"s": 632,
"text": "Example 1:- To show infinite case which returns 1"
},
{
"code": "// c++ program to demonstrate// example of isnormal() function. #include <bits/stdc++.h> using namespace std; int main(){ float f = 6.0F; // check for +ve infinite value cout << \"isinf(6.0/0.0) is = \" << isinf(f/0.0) << endl; // check for -ve infinite value f = -1.2F; cout << \"isinf(-1.2/0.0) is = \" << isinf(f/0.0) << endl; return 0;}",
"e": 1051,
"s": 682,
"text": null
},
{
"code": null,
"e": 1097,
"s": 1051,
"text": "isinf(6.0/0.0) is = 1\nisinf(-1.2/0.0) is = 1\n"
},
{
"code": null,
"e": 1200,
"s": 1097,
"text": "Explanation: In example 1 the floating point number represents infinity thatβs why function returns 1."
},
{
"code": null,
"e": 1254,
"s": 1200,
"text": "Example 2:- To show non-infinite case which returns 0"
},
{
"code": "// c++ program to demonstrate// example of isinf() function. #include <bits/stdc++.h>using namespace std; int main(){ cout << \"isinf(0.0) is = \" << isinf(0.0) << endl; cout << \"isinf(sqrt(-1.0)) is = \" << isinf(sqrt(-1.0)) << endl; return 0;}",
"e": 1509,
"s": 1254,
"text": null
},
{
"code": null,
"e": 1553,
"s": 1509,
"text": "isinf(0.0) is = 0\nisinf(sqrt(-1.0)) is = 0\n"
},
{
"code": null,
"e": 1672,
"s": 1553,
"text": "Exception: In example 2 the given floating point number is not representing infinity thatβs why function returns zero."
},
{
"code": null,
"e": 1684,
"s": 1672,
"text": "CPP-Library"
},
{
"code": null,
"e": 1705,
"s": 1684,
"text": "cpp-numerics-library"
},
{
"code": null,
"e": 1709,
"s": 1705,
"text": "C++"
},
{
"code": null,
"e": 1713,
"s": 1709,
"text": "CPP"
},
{
"code": null,
"e": 1811,
"s": 1713,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1838,
"s": 1811,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 1881,
"s": 1838,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 1915,
"s": 1881,
"text": "vector erase() and clear() in C++"
},
{
"code": null,
"e": 1940,
"s": 1915,
"text": "unordered_map in C++ STL"
},
{
"code": null,
"e": 1959,
"s": 1940,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 2013,
"s": 1959,
"text": "Priority Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 2053,
"s": 2013,
"text": "The C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 2077,
"s": 2053,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 2094,
"s": 2077,
"text": "Substring in C++"
}
] |
The @SuppressWarnings Annotation in Java
|
24 Oct, 2021
Annotations are a very important part of Java in modern technologies, Most of the technologies such as Hibernate, Spring, Spring Boot, JPA, and so Many other Libraries are using annotations and making developersβ life a lot easy. In Java, built-in General Annotations are β
@Override@Deprecated@FunctionalInterface@SuppressWarnings
@Override
@Deprecated
@FunctionalInterface
@SuppressWarnings
Syntax: The signature for Java @SuppressWarnings annotation is as follows:
@Retention(value=SOURCE)
@Target(value = {TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE })
public @interface SuppressWarnings {
String[] value;
}
As we can see, the above signature has only one element, which is Array of String, with multiple possible values.
All annotations have two properties :
Target (@Target(value = {TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE })) β It will be used with almost everything, wherever you want to suppress warnings.Retention (@Retention(value=SOURCE)): Retention policy of functional Interface βSOURCEβ, which means annotation wonβt go till compiler.
Target (@Target(value = {TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE })) β It will be used with almost everything, wherever you want to suppress warnings.
Retention (@Retention(value=SOURCE)): Retention policy of functional Interface βSOURCEβ, which means annotation wonβt go till compiler.
Illustrations:
Use of @SuppressWarnings is to suppress or ignore warnings coming from the compiler, i.e., the compiler will ignore warnings if any for that piece of code.
1. @SuppressWarnings("unchecked")
public class Calculator {
}
- Here, it will ignore all unchecked warnings coming from that class. (All methods, variables, constructors).
2. public class Calculator {
@SuppressWarnings("unchecked")
public int sum(x,y) {
.
}
}
- It will stop warning from that function only, and not from other functions of Calculator class.
This annotation is dangerous because a warning is something potentially wrong with the code. So if weβre getting any warning, the first approach should be resolving those errors. But if weβre suppressing any warnings, we have to have some solid reason. The reason should be commented near to the annotation every time it is used.
Possible Values Inside @SuppressWarnings Annotation Element are as follows:
Note: The primary and most important benefit of using @SuppressWarnings Annotation is that if we stuck because of some known warning, then this will ignore the warning and move ahead. E.g. β deprecated and unchecked warnings.
Example:
Java
// Java Program to demonstrate Use of @SuppressWarnings// Annotation // Importing required packagesimport java.io.*;import java.lang.*;import java.util.*; // Class 1// Helper classclass Addition { // Method 1 public static int sum(int n1, int n2) { // Return the final sum return n1 + n2; } // Method 2 public static int sum(int... nums) { int sum = 0; for (int i : nums) { sum += i; } // Return the final sum return sum; }} // Class 2// Main class// To test suppress warningspublic class GFG { // Does not check if data type is Object or primitive @SuppressWarnings("unchecked") // Main driver method public static void main(String[] args) { // Creating an object of above class in main() // method Addition add = new Addition(); // Ignore when we're using a deprecated // (no longer important) method or type @SuppressWarnings("deprecation") int sum = Addition.sum(10, 20); // Print and display the sum System.out.println("Sum of 10 and 20 : " + sum); @SuppressWarnings("rawtypes") // Raw data type being used instead of generic List list = new ArrayList(); // Custom input entries list.add(12); list.add(120); // Print and display List elements System.out.println("List items : " + list); }}
Sum of 10 and 20 : 30
List items : [12, 120]
sooda367
Picked
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n24 Oct, 2021"
},
{
"code": null,
"e": 327,
"s": 52,
"text": "Annotations are a very important part of Java in modern technologies, Most of the technologies such as Hibernate, Spring, Spring Boot, JPA, and so Many other Libraries are using annotations and making developersβ life a lot easy. In Java, built-in General Annotations are β "
},
{
"code": null,
"e": 385,
"s": 327,
"text": "@Override@Deprecated@FunctionalInterface@SuppressWarnings"
},
{
"code": null,
"e": 395,
"s": 385,
"text": "@Override"
},
{
"code": null,
"e": 407,
"s": 395,
"text": "@Deprecated"
},
{
"code": null,
"e": 428,
"s": 407,
"text": "@FunctionalInterface"
},
{
"code": null,
"e": 446,
"s": 428,
"text": "@SuppressWarnings"
},
{
"code": null,
"e": 521,
"s": 446,
"text": "Syntax: The signature for Java @SuppressWarnings annotation is as follows:"
},
{
"code": null,
"e": 692,
"s": 521,
"text": "@Retention(value=SOURCE)\n@Target(value = {TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE })\npublic @interface SuppressWarnings {\n String[] value;\n }"
},
{
"code": null,
"e": 806,
"s": 692,
"text": "As we can see, the above signature has only one element, which is Array of String, with multiple possible values."
},
{
"code": null,
"e": 844,
"s": 806,
"text": "All annotations have two properties :"
},
{
"code": null,
"e": 1151,
"s": 844,
"text": "Target (@Target(value = {TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE })) β It will be used with almost everything, wherever you want to suppress warnings.Retention (@Retention(value=SOURCE)): Retention policy of functional Interface βSOURCEβ, which means annotation wonβt go till compiler."
},
{
"code": null,
"e": 1323,
"s": 1151,
"text": "Target (@Target(value = {TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE })) β It will be used with almost everything, wherever you want to suppress warnings."
},
{
"code": null,
"e": 1459,
"s": 1323,
"text": "Retention (@Retention(value=SOURCE)): Retention policy of functional Interface βSOURCEβ, which means annotation wonβt go till compiler."
},
{
"code": null,
"e": 1475,
"s": 1459,
"text": "Illustrations: "
},
{
"code": null,
"e": 1631,
"s": 1475,
"text": "Use of @SuppressWarnings is to suppress or ignore warnings coming from the compiler, i.e., the compiler will ignore warnings if any for that piece of code."
},
{
"code": null,
"e": 1827,
"s": 1631,
"text": "1. @SuppressWarnings(\"unchecked\")\n public class Calculator {\n }\n \n- Here, it will ignore all unchecked warnings coming from that class. (All methods, variables, constructors)."
},
{
"code": null,
"e": 2043,
"s": 1827,
"text": "2. public class Calculator {\n @SuppressWarnings(\"unchecked\")\n public int sum(x,y) {\n .\n }\n }\n \n- It will stop warning from that function only, and not from other functions of Calculator class."
},
{
"code": null,
"e": 2373,
"s": 2043,
"text": "This annotation is dangerous because a warning is something potentially wrong with the code. So if weβre getting any warning, the first approach should be resolving those errors. But if weβre suppressing any warnings, we have to have some solid reason. The reason should be commented near to the annotation every time it is used."
},
{
"code": null,
"e": 2450,
"s": 2373,
"text": "Possible Values Inside @SuppressWarnings Annotation Element are as follows:"
},
{
"code": null,
"e": 2676,
"s": 2450,
"text": "Note: The primary and most important benefit of using @SuppressWarnings Annotation is that if we stuck because of some known warning, then this will ignore the warning and move ahead. E.g. β deprecated and unchecked warnings."
},
{
"code": null,
"e": 2685,
"s": 2676,
"text": "Example:"
},
{
"code": null,
"e": 2690,
"s": 2685,
"text": "Java"
},
{
"code": "// Java Program to demonstrate Use of @SuppressWarnings// Annotation // Importing required packagesimport java.io.*;import java.lang.*;import java.util.*; // Class 1// Helper classclass Addition { // Method 1 public static int sum(int n1, int n2) { // Return the final sum return n1 + n2; } // Method 2 public static int sum(int... nums) { int sum = 0; for (int i : nums) { sum += i; } // Return the final sum return sum; }} // Class 2// Main class// To test suppress warningspublic class GFG { // Does not check if data type is Object or primitive @SuppressWarnings(\"unchecked\") // Main driver method public static void main(String[] args) { // Creating an object of above class in main() // method Addition add = new Addition(); // Ignore when we're using a deprecated // (no longer important) method or type @SuppressWarnings(\"deprecation\") int sum = Addition.sum(10, 20); // Print and display the sum System.out.println(\"Sum of 10 and 20 : \" + sum); @SuppressWarnings(\"rawtypes\") // Raw data type being used instead of generic List list = new ArrayList(); // Custom input entries list.add(12); list.add(120); // Print and display List elements System.out.println(\"List items : \" + list); }}",
"e": 4120,
"s": 2690,
"text": null
},
{
"code": null,
"e": 4168,
"s": 4123,
"text": "Sum of 10 and 20 : 30\nList items : [12, 120]"
},
{
"code": null,
"e": 4179,
"s": 4170,
"text": "sooda367"
},
{
"code": null,
"e": 4186,
"s": 4179,
"text": "Picked"
},
{
"code": null,
"e": 4191,
"s": 4186,
"text": "Java"
},
{
"code": null,
"e": 4196,
"s": 4191,
"text": "Java"
}
] |
Python | Test if String contains Alphabets and Spaces - GeeksforGeeks
|
17 Dec, 2021
Sometimes, while testing of credibility of string being a part of containing just alphabets, an exception of spaces has to be mentioned explicitly and becomes a problem. This can occur in domains that deal with data. Lets discuss certain ways in which this task can be performed.
Method #1 : Using all() + isspace() + isalpha() This is one of the way in which this task can be performed. In this, we compare the string for all elements being alphabets or space only.
Python3
# Python3 code to demonstrate working of # Test if String contains Alphabets and Spaces# Using isspace() + isalpha() + all()import re # initializing stringtest_str = 'geeksforgeeks is best for geeks' # printing original stringprint("The original string is : " + test_str) # Test if String contains Alphabets and Spaces# Using isspace() + isalpha() + all()res = test_str != '' and all(chr.isalpha() or chr.isspace() for chr in test_str) # printing result print("Does String contain only space and alphabets : " + str(res))
The original string is : geeksforgeeks is best for geeks
Does String contain only space and alphabets : True
Method #1 : Using regex This problem can also be solved by employing regex to include only space and alphabets in a string.
Python3
# Python3 code to demonstrate working of # Test if String contains Alphabets and Spaces# Using regeximport re # initializing stringtest_str = 'geeksforgeeks is best for geeks' # printing original stringprint("The original string is : " + test_str) # Test if String contains Alphabets and Spaces# Using regexres = bool(re.match('[a-zA-Z\s]+$', test_str)) # printing result print("Does String contain only space and alphabets : " + str(res))
The original string is : geeksforgeeks is best for geeks
Does String contain only space and alphabets : True
arorakashish0911
Python string-programs
Python
Python Programs
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 ?
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 | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not
|
[
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n17 Dec, 2021"
},
{
"code": null,
"e": 24181,
"s": 23901,
"text": "Sometimes, while testing of credibility of string being a part of containing just alphabets, an exception of spaces has to be mentioned explicitly and becomes a problem. This can occur in domains that deal with data. Lets discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 24368,
"s": 24181,
"text": "Method #1 : Using all() + isspace() + isalpha() This is one of the way in which this task can be performed. In this, we compare the string for all elements being alphabets or space only."
},
{
"code": null,
"e": 24376,
"s": 24368,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of # Test if String contains Alphabets and Spaces# Using isspace() + isalpha() + all()import re # initializing stringtest_str = 'geeksforgeeks is best for geeks' # printing original stringprint(\"The original string is : \" + test_str) # Test if String contains Alphabets and Spaces# Using isspace() + isalpha() + all()res = test_str != '' and all(chr.isalpha() or chr.isspace() for chr in test_str) # printing result print(\"Does String contain only space and alphabets : \" + str(res))",
"e": 24906,
"s": 24376,
"text": null
},
{
"code": null,
"e": 25015,
"s": 24906,
"text": "The original string is : geeksforgeeks is best for geeks\nDoes String contain only space and alphabets : True"
},
{
"code": null,
"e": 25141,
"s": 25017,
"text": "Method #1 : Using regex This problem can also be solved by employing regex to include only space and alphabets in a string."
},
{
"code": null,
"e": 25149,
"s": 25141,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of # Test if String contains Alphabets and Spaces# Using regeximport re # initializing stringtest_str = 'geeksforgeeks is best for geeks' # printing original stringprint(\"The original string is : \" + test_str) # Test if String contains Alphabets and Spaces# Using regexres = bool(re.match('[a-zA-Z\\s]+$', test_str)) # printing result print(\"Does String contain only space and alphabets : \" + str(res))",
"e": 25597,
"s": 25149,
"text": null
},
{
"code": null,
"e": 25706,
"s": 25597,
"text": "The original string is : geeksforgeeks is best for geeks\nDoes String contain only space and alphabets : True"
},
{
"code": null,
"e": 25725,
"s": 25708,
"text": "arorakashish0911"
},
{
"code": null,
"e": 25748,
"s": 25725,
"text": "Python string-programs"
},
{
"code": null,
"e": 25755,
"s": 25748,
"text": "Python"
},
{
"code": null,
"e": 25771,
"s": 25755,
"text": "Python Programs"
},
{
"code": null,
"e": 25869,
"s": 25771,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25878,
"s": 25869,
"text": "Comments"
},
{
"code": null,
"e": 25891,
"s": 25878,
"text": "Old Comments"
},
{
"code": null,
"e": 25923,
"s": 25891,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25979,
"s": 25923,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26021,
"s": 25979,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26063,
"s": 26021,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26099,
"s": 26063,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 26121,
"s": 26099,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26160,
"s": 26121,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 26206,
"s": 26160,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 26244,
"s": 26206,
"text": "Python | Convert a list to dictionary"
}
] |
How to cut only the first character in MySQL string?
|
To cut only the first character, use the substr() function with UPDATE command. The syntax is as follows.
UPDATE yourTableName set yourColumnName=substr(yourColumnName,2);
To understand the above syntax, let us first create a table. The query to create a table is as follows.
mysql> create table CutStringDemo
-> (
-> Value varchar(100)
-> );
Query OK, 0 rows affected (0.66 sec)
Now you can insert some records in the table using insert command. The query is as follows.
mysql> insert into CutStringDemo values(',12,3456');
Query OK, 1 row affected (0.14 sec)
mysql> insert into CutStringDemo values(',23,9867');
Query OK, 1 row affected (0.16 sec)
mysql> insert into CutStringDemo values(',20,3212');
Query OK, 1 row affected (0.12 sec)
mysql> insert into CutStringDemo values(',23456,1234');
Query OK, 1 row affected (0.14 sec)
Now you can display all records from the table using select statement. The query is as follows.
mysql> select *from CutStringDemo;
The following is the output.
+-------------+
| Value |
+-------------+
| ,12,3456 |
| ,23,9867 |
| ,20,3212 |
| ,23456,1234 |
+-------------+
4 rows in set (0.00 sec)
Now let us cut the first character from the column Value. The query is as follows.
mysql> update CutStringDemo set Value=substr(Value,2);
Query OK, 4 rows affected (0.20 sec)
Rows matched: 4 Changed: 4 Warnings: 0
Now you can check that the first character has been removed from the column Value or not. To display all records from the table, use the SELECT statement. The query is as follows.
mysql> select *from CutStringDemo;
The following is the output displaying that the first character successfully removed.
+------------+
| Value |
+------------+
| 12,3456 |
| 23,9867 |
| 20,3212 |
| 23456,1234 |
+------------+
4 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1168,
"s": 1062,
"text": "To cut only the first character, use the substr() function with UPDATE command. The syntax is as follows."
},
{
"code": null,
"e": 1234,
"s": 1168,
"text": "UPDATE yourTableName set yourColumnName=substr(yourColumnName,2);"
},
{
"code": null,
"e": 1338,
"s": 1234,
"text": "To understand the above syntax, let us first create a table. The query to create a table is as follows."
},
{
"code": null,
"e": 1442,
"s": 1338,
"text": "mysql> create table CutStringDemo\n-> (\n-> Value varchar(100)\n-> );\nQuery OK, 0 rows affected (0.66 sec)"
},
{
"code": null,
"e": 1534,
"s": 1442,
"text": "Now you can insert some records in the table using insert command. The query is as follows."
},
{
"code": null,
"e": 1896,
"s": 1534,
"text": "mysql> insert into CutStringDemo values(',12,3456');\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into CutStringDemo values(',23,9867');\nQuery OK, 1 row affected (0.16 sec)\n\nmysql> insert into CutStringDemo values(',20,3212');\nQuery OK, 1 row affected (0.12 sec)\n\nmysql> insert into CutStringDemo values(',23456,1234');\nQuery OK, 1 row affected (0.14 sec)"
},
{
"code": null,
"e": 1992,
"s": 1896,
"text": "Now you can display all records from the table using select statement. The query is as follows."
},
{
"code": null,
"e": 2027,
"s": 1992,
"text": "mysql> select *from CutStringDemo;"
},
{
"code": null,
"e": 2056,
"s": 2027,
"text": "The following is the output."
},
{
"code": null,
"e": 2209,
"s": 2056,
"text": "+-------------+\n| Value |\n+-------------+\n| ,12,3456 |\n| ,23,9867 |\n| ,20,3212 |\n| ,23456,1234 |\n+-------------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2292,
"s": 2209,
"text": "Now let us cut the first character from the column Value. The query is as follows."
},
{
"code": null,
"e": 2423,
"s": 2292,
"text": "mysql> update CutStringDemo set Value=substr(Value,2);\nQuery OK, 4 rows affected (0.20 sec)\nRows matched: 4 Changed: 4 Warnings: 0"
},
{
"code": null,
"e": 2603,
"s": 2423,
"text": "Now you can check that the first character has been removed from the column Value or not. To display all records from the table, use the SELECT statement. The query is as follows."
},
{
"code": null,
"e": 2638,
"s": 2603,
"text": "mysql> select *from CutStringDemo;"
},
{
"code": null,
"e": 2724,
"s": 2638,
"text": "The following is the output displaying that the first character successfully removed."
},
{
"code": null,
"e": 2869,
"s": 2724,
"text": "+------------+\n| Value |\n+------------+\n| 12,3456 |\n| 23,9867 |\n| 20,3212 |\n| 23456,1234 |\n+------------+\n4 rows in set (0.00 sec)"
}
] |
Explain union operation in relational algebra (DBMS)?
|
Query is a question or requesting information. Query language is a language which is used to retrieve information from a database.
Query language is divided into two types β
Procedural language
Procedural language
Non-procedural language
Non-procedural language
Information is retrieved from the database by specifying the sequence of operations to be performed.
For Example β Relational algebra.
Structure Query language (SQL) is based on relational algebra.
Relational algebra consists of a set of operations that take one or two relations as an input and produces a new relation as output.
The different types of relational algebra operations are as follows β
Select operation
Select operation
Project operation
Project operation
Rename operation
Rename operation
Union operation
Union operation
Intersection operation
Intersection operation
Difference operation
Difference operation
Cartesian product operation
Cartesian product operation
Join operation
Join operation
Division operation
Division operation
Union, intersection, difference, cartesian, join, division comes under binary operation (operate on two tables).
Union operation combines values in R1, R2 by removing duplicate ones.
βregno(R1) βͺ βregno(R2)
It displays all the regno of R1 and R2.
Consider two tables R1 and R2 β
Table R1 is as follows β
Table R2 is as follows β
To display all the regno of R1 and R2, use the following command β
βregno(R1) βͺ βregno(R2)
To retrieve branch and section of student from table R1 and R2, use the below mentioned command β
β branch, section (R1) βͺ β branch, section (R2)
No repletion allowed for entry.
Union All β It is used for duplicate entries. The common entries will be shown if the common intersection is used.
|
[
{
"code": null,
"e": 1193,
"s": 1062,
"text": "Query is a question or requesting information. Query language is a language which is used to retrieve information from a database."
},
{
"code": null,
"e": 1236,
"s": 1193,
"text": "Query language is divided into two types β"
},
{
"code": null,
"e": 1256,
"s": 1236,
"text": "Procedural language"
},
{
"code": null,
"e": 1276,
"s": 1256,
"text": "Procedural language"
},
{
"code": null,
"e": 1300,
"s": 1276,
"text": "Non-procedural language"
},
{
"code": null,
"e": 1324,
"s": 1300,
"text": "Non-procedural language"
},
{
"code": null,
"e": 1425,
"s": 1324,
"text": "Information is retrieved from the database by specifying the sequence of operations to be performed."
},
{
"code": null,
"e": 1459,
"s": 1425,
"text": "For Example β Relational algebra."
},
{
"code": null,
"e": 1522,
"s": 1459,
"text": "Structure Query language (SQL) is based on relational algebra."
},
{
"code": null,
"e": 1655,
"s": 1522,
"text": "Relational algebra consists of a set of operations that take one or two relations as an input and produces a new relation as output."
},
{
"code": null,
"e": 1725,
"s": 1655,
"text": "The different types of relational algebra operations are as follows β"
},
{
"code": null,
"e": 1742,
"s": 1725,
"text": "Select operation"
},
{
"code": null,
"e": 1759,
"s": 1742,
"text": "Select operation"
},
{
"code": null,
"e": 1777,
"s": 1759,
"text": "Project operation"
},
{
"code": null,
"e": 1795,
"s": 1777,
"text": "Project operation"
},
{
"code": null,
"e": 1812,
"s": 1795,
"text": "Rename operation"
},
{
"code": null,
"e": 1829,
"s": 1812,
"text": "Rename operation"
},
{
"code": null,
"e": 1845,
"s": 1829,
"text": "Union operation"
},
{
"code": null,
"e": 1861,
"s": 1845,
"text": "Union operation"
},
{
"code": null,
"e": 1884,
"s": 1861,
"text": "Intersection operation"
},
{
"code": null,
"e": 1907,
"s": 1884,
"text": "Intersection operation"
},
{
"code": null,
"e": 1928,
"s": 1907,
"text": "Difference operation"
},
{
"code": null,
"e": 1949,
"s": 1928,
"text": "Difference operation"
},
{
"code": null,
"e": 1977,
"s": 1949,
"text": "Cartesian product operation"
},
{
"code": null,
"e": 2005,
"s": 1977,
"text": "Cartesian product operation"
},
{
"code": null,
"e": 2020,
"s": 2005,
"text": "Join operation"
},
{
"code": null,
"e": 2035,
"s": 2020,
"text": "Join operation"
},
{
"code": null,
"e": 2054,
"s": 2035,
"text": "Division operation"
},
{
"code": null,
"e": 2073,
"s": 2054,
"text": "Division operation"
},
{
"code": null,
"e": 2186,
"s": 2073,
"text": "Union, intersection, difference, cartesian, join, division comes under binary operation (operate on two tables)."
},
{
"code": null,
"e": 2256,
"s": 2186,
"text": "Union operation combines values in R1, R2 by removing duplicate ones."
},
{
"code": null,
"e": 2280,
"s": 2256,
"text": "βregno(R1) βͺ βregno(R2)"
},
{
"code": null,
"e": 2320,
"s": 2280,
"text": "It displays all the regno of R1 and R2."
},
{
"code": null,
"e": 2352,
"s": 2320,
"text": "Consider two tables R1 and R2 β"
},
{
"code": null,
"e": 2377,
"s": 2352,
"text": "Table R1 is as follows β"
},
{
"code": null,
"e": 2402,
"s": 2377,
"text": "Table R2 is as follows β"
},
{
"code": null,
"e": 2469,
"s": 2402,
"text": "To display all the regno of R1 and R2, use the following command β"
},
{
"code": null,
"e": 2493,
"s": 2469,
"text": "βregno(R1) βͺ βregno(R2)"
},
{
"code": null,
"e": 2591,
"s": 2493,
"text": "To retrieve branch and section of student from table R1 and R2, use the below mentioned command β"
},
{
"code": null,
"e": 2639,
"s": 2591,
"text": "β branch, section (R1) βͺ β branch, section (R2)"
},
{
"code": null,
"e": 2671,
"s": 2639,
"text": "No repletion allowed for entry."
},
{
"code": null,
"e": 2786,
"s": 2671,
"text": "Union All β It is used for duplicate entries. The common entries will be shown if the common intersection is used."
}
] |
Creating a RESTful Serverless API with Azure Functions and MongoDB | by Will Velida | Towards Data Science
|
In this tutorial, weβre going to build a Serverless API using HTTP Triggers in Azure Functions that uses a MongoDB Atlas backend. Weβre going to build an API for a hypothetical music library that stores information about Albums.
Weβre going to build this API using C#, so youβd need to at least understand the C# syntax to follow along. Iβm not going to go dive into huge detail about Azure Functions and the complexities behind MongoDB, Iβll just be keeping it simple enough to demonstrate how they can all work together to make a simplistic API.
If you want to learn more about MongoDB, Iβd highly recommend that you check out MongoDB University. They provide fantastic free courses for both developers and DBAβs who want to learn all about MongoDB. If you like this article and want to learn more about Azure Functions, I suggest you check out the docs.
What is MongoDB?
MongoDB is a NoSQL document database that provides developers with flexibility when it comes to indexing and querying. Data is stored in JSON documents, which allows us to change data structures over time.
MongoDB Atlas is essentially the managed service for MongoDB that we can use for our MongoDB clusters. We can host our MongoDB Atlas clusters on Azure, AWS or GCP.
For C# development, we can use the MongoDB Driver to connect to our MongoDB cluster. Itβs important when using it during development to use a compatible driver with the Mongo version that your Atlas cluster is using.
What are Azure Functions?
Azure Functions are small pieces of code that we can run in Azure without worrying too much about application infrastructure (this βworryβ varies from scenario to scenario. It really depends on the situation and your requirements).
We can use specific events to trigger actions in our Functions. For this tutorial, weβll be triggering events based off HTTP requests.
Set up the MongoDB Atlas Cluster
Before we start coding, we need to set up our MongoDB Atlas cluster. The MongoDB documentation has a fantastic guide on how to set up your Atlas cluster, so if you havenβt got one already, check out this guide.
Create the Azure Function
Once youβve created your cluster, letβs create our Azure Function. Iβm going to use Visual Studio 2019 to develop my function. In order to develop Azure Functions using Visual Studio, make sure that you have the Azure Development workload enabled.
Create a βNew Projectβ and click on βAzure Functionsβ. Like I said earlier, weβre going to be doing this project in C# so make sure thatβs the language selected in the templates.
Now that youβve selected the right template, give your API a name and set an easy to find location to save the project it.
Now, we can select what type of Function that we wish to create. Since this is an API, Iβm going to create a Function with HTTP Triggers. When you create HTTP Trigger Functions, you can set what Storage account that the Function will use along with the Authorization level.
Weβre not going to be doing anything with Authorization here, so just set it to βAnonymousβ. A quick comment about authorization, if you create a Function with a certain level but decide you need to change it later, you can do this in the code, so donβt fret about this setting too much. Itβs just to help Visual Studio generate a template for you.
Click Create and congrats! You now have an Azure Function. Itβs not great though so letβs do something about that.
Connect to MongoDB Cluster
Sweet, now that weβve set up our function, letβs grab our connection string to our MongoDB Atlas cluster.
Head to your Atlas portal (if youβre not there already) and sign in. Click the βconnectβ button as seen below:
Since weβre connecting an application to our cluster, select the Connect Your Application option for our connection method:
Now we have to select a driver version. Choose βC#/.NETβ as the driver and β2.5 or laterβ as the version. Copy the connection string as weβll need it for later.
Now, letβs create a new class called Startup.cs. This class will allow us to use Dependency Injection in our Functions.
In my Startup class, Iβm instantiating a Singleton instance of my MongoClient so all functions can use it. All we need here is to get our connection setting for our MongoDB Atlas cluster and pass it through as a string parameter.
Iβve put this actual connection string in my local.settings.json file which is picked up in the IConfiguration instance of config. Itβs not a good idea to hard code connection strings or settings into your code, so this is one method in your code that you can use to protect secrets needed for your application.
Setting up our Album Class
Now letβs set up our Album class. Weβre not going to do anything too amazing with this class. Iβve kept it simple just to highlight a couple of things we need/can do to make this model work with the MongoDB Driver. The definition for our class is as follows:
In this class, Iβve given my Album an Id, Name, Artist, Price, ReleaseDate and Genre. Real simple. The two things I want to highlight here are the Id property and the AlbumName property.
For the Id property, Iβve assigned this property to be our ObjectId. This acts as the Primary Key for our MongoDB Document. The MongoDB Driver will generate this for us.
For the AlbumName property, Iβve decorated the property as a BsonElement called Name. This is what the property will be called in our document when itβs persisted to MongoDB.
Create the RESTful methods
Weβve got pretty much everything we need to make our RESTful API, so letβs start building it. For all our functions, Iβve created a constructor that takes in the following parameters which will help inject our dependencies:
MongoClient: To connect to our database.
ILogger: So we can log activity in our Function. If you deploy a Function to Azure and enable Application Insights, you this where the logs get sent to.
IConfiguration: This is what Iβm using to manage all the secrets needed in our Functions. As I mentioned before, these values are kept in local.settings.json for local debugging.
Iβve also created a IMongoCollection<Album> so we can work with our Album collection within our MongoDB database.
For all our functions, so we get an Exception, Iβve just logged the exception message and set our IActionResult returnValue to throw a 500 error response. Nothing complex, but simple enough for this example.
Now letβs dive into each function π
CreateAlbum.cs
In this function, we pass through a request of type HttpRequest and read the body of that request. Iβve used Newtonsoft.Json to deserialize my request into my Album object and Iβm creating a new album object with the values of our input.
Iβm then using the .InsertOne() method to insert our new Album object into our MongoDB and setting my return value to a new OkObjectResult with our album object.
GetAlbum.cs
In this function, Iβm passing through an id that will represent the id of our document. Within our try/catch statement, Iβll attempt to find the album document with that id using the .Find() method on our MongoCollection and return it to the user. If we canβt find it, weβll send a log message saying we canβt find it and throw a 404.
GetAllAlbum.cs
In these functions, all weβre doing here is using the Find() function to find all the albums within our Album collection and return those to the user as a list. If there are albums in the collection, weβll return a 404.
UpdateAlbum.cs
The UpdateAlbum is a little different. Here weβre passing through our request body and an id. Iβm deserializing our body into an Album object and then setting the id that we pass through to our updatedResult item.
I use the ReplaceOne() method to do two things. Firstly, use the id to find the album in our collection with that id and then secondly, I pass through our updatedResult Album object to replace the existing item. If we canβt find this item, Iβll throw a 404.
DeleteAlbum.cs
In our DeleteAlbum function, again we pass through the id of the document that we wish to delete and use the DeleteOne() function to find the album that has that id and then delete it.
Testing our API using POSTMAN
All our methods are in place, so we can now start testing our API using Postman. Letβs test each one of our functions in turn. Press F5 in Visual Studio to start our Function.
It shouldnβt take too long, but once it has finished, you should be given some URLβs for each Function like so:
Keep this console window open as these URLβs are mapped to each function and weβll need to use these to trigger our Functions.
For our CreateAlbum function, weβll need to send the following JSON payload to insert an Album into our collection. This is the payload that Iβve sent:
{ "albumName": "No.6 Collaborations Project", "artist": "Ed Sheeran", "price": 15.99, "releaseDate": "2019-12-06T11:00:00Z", "genre": "Pop"}
Paste the URL into the textbox and make sure the type is set to POST. Click βSend βand we should get the following response:
Looks like it worked! Head back to your Atlas cluster, navigate to your Albums collections and click βFindβ. We should be able to see the inserted documents with the values that we sent as part of our JSON payload.
Letβs attempt to read the item that weβve just created! Copy and paste the _id field of the item and then use it as the id paramter in our GetAlbum URL. Change the request type to GET and click βSendβ.
As you can see, we should see the document of the created album returned to us in the body.
After a quick look on Wikipedia, this album covers a few more genres so we need to update our document. Using the same id, change the request type to PUT and update the body like so:
{ "albumName": "No.6 Collaborations Project", "artist": "Ed Sheeran", "price": 15.99, "releaseDate": "2019-12-06T11:00:00Z", "genre": "Pop, Rap, Hip-Hop"}
Click βSend βto update our document:
Head to your collection in Atlas and click βFindβ. We should see the updated document persisted in MongoDB.
Now letβs test our Function to see if we can delete documents. Use the Id as the id parameter and set the request type to DELETE. Click βSend βto delete the document.
Head back to Atlas and click βFind βagain. If it worked, the document should be deleted from our Album collection.
Conclusion
In this tutorial, we learnt how we can build a really simple API using Azure Functions that uses MongoDB as a datastore. While this was a very simple project to do, hopefully, this tutorial has given you some ideas as to how you can use MongoDB in your Azure Functions.
If you want to see the whole sample, check out the code on GitHub!
If you have any questions, please let me know in the comment section below!
|
[
{
"code": null,
"e": 401,
"s": 172,
"text": "In this tutorial, weβre going to build a Serverless API using HTTP Triggers in Azure Functions that uses a MongoDB Atlas backend. Weβre going to build an API for a hypothetical music library that stores information about Albums."
},
{
"code": null,
"e": 720,
"s": 401,
"text": "Weβre going to build this API using C#, so youβd need to at least understand the C# syntax to follow along. Iβm not going to go dive into huge detail about Azure Functions and the complexities behind MongoDB, Iβll just be keeping it simple enough to demonstrate how they can all work together to make a simplistic API."
},
{
"code": null,
"e": 1029,
"s": 720,
"text": "If you want to learn more about MongoDB, Iβd highly recommend that you check out MongoDB University. They provide fantastic free courses for both developers and DBAβs who want to learn all about MongoDB. If you like this article and want to learn more about Azure Functions, I suggest you check out the docs."
},
{
"code": null,
"e": 1046,
"s": 1029,
"text": "What is MongoDB?"
},
{
"code": null,
"e": 1252,
"s": 1046,
"text": "MongoDB is a NoSQL document database that provides developers with flexibility when it comes to indexing and querying. Data is stored in JSON documents, which allows us to change data structures over time."
},
{
"code": null,
"e": 1416,
"s": 1252,
"text": "MongoDB Atlas is essentially the managed service for MongoDB that we can use for our MongoDB clusters. We can host our MongoDB Atlas clusters on Azure, AWS or GCP."
},
{
"code": null,
"e": 1633,
"s": 1416,
"text": "For C# development, we can use the MongoDB Driver to connect to our MongoDB cluster. Itβs important when using it during development to use a compatible driver with the Mongo version that your Atlas cluster is using."
},
{
"code": null,
"e": 1659,
"s": 1633,
"text": "What are Azure Functions?"
},
{
"code": null,
"e": 1891,
"s": 1659,
"text": "Azure Functions are small pieces of code that we can run in Azure without worrying too much about application infrastructure (this βworryβ varies from scenario to scenario. It really depends on the situation and your requirements)."
},
{
"code": null,
"e": 2026,
"s": 1891,
"text": "We can use specific events to trigger actions in our Functions. For this tutorial, weβll be triggering events based off HTTP requests."
},
{
"code": null,
"e": 2059,
"s": 2026,
"text": "Set up the MongoDB Atlas Cluster"
},
{
"code": null,
"e": 2270,
"s": 2059,
"text": "Before we start coding, we need to set up our MongoDB Atlas cluster. The MongoDB documentation has a fantastic guide on how to set up your Atlas cluster, so if you havenβt got one already, check out this guide."
},
{
"code": null,
"e": 2296,
"s": 2270,
"text": "Create the Azure Function"
},
{
"code": null,
"e": 2544,
"s": 2296,
"text": "Once youβve created your cluster, letβs create our Azure Function. Iβm going to use Visual Studio 2019 to develop my function. In order to develop Azure Functions using Visual Studio, make sure that you have the Azure Development workload enabled."
},
{
"code": null,
"e": 2723,
"s": 2544,
"text": "Create a βNew Projectβ and click on βAzure Functionsβ. Like I said earlier, weβre going to be doing this project in C# so make sure thatβs the language selected in the templates."
},
{
"code": null,
"e": 2846,
"s": 2723,
"text": "Now that youβve selected the right template, give your API a name and set an easy to find location to save the project it."
},
{
"code": null,
"e": 3120,
"s": 2846,
"text": "Now, we can select what type of Function that we wish to create. Since this is an API, Iβm going to create a Function with HTTP Triggers. When you create HTTP Trigger Functions, you can set what Storage account that the Function will use along with the Authorization level."
},
{
"code": null,
"e": 3469,
"s": 3120,
"text": "Weβre not going to be doing anything with Authorization here, so just set it to βAnonymousβ. A quick comment about authorization, if you create a Function with a certain level but decide you need to change it later, you can do this in the code, so donβt fret about this setting too much. Itβs just to help Visual Studio generate a template for you."
},
{
"code": null,
"e": 3584,
"s": 3469,
"text": "Click Create and congrats! You now have an Azure Function. Itβs not great though so letβs do something about that."
},
{
"code": null,
"e": 3611,
"s": 3584,
"text": "Connect to MongoDB Cluster"
},
{
"code": null,
"e": 3717,
"s": 3611,
"text": "Sweet, now that weβve set up our function, letβs grab our connection string to our MongoDB Atlas cluster."
},
{
"code": null,
"e": 3828,
"s": 3717,
"text": "Head to your Atlas portal (if youβre not there already) and sign in. Click the βconnectβ button as seen below:"
},
{
"code": null,
"e": 3952,
"s": 3828,
"text": "Since weβre connecting an application to our cluster, select the Connect Your Application option for our connection method:"
},
{
"code": null,
"e": 4113,
"s": 3952,
"text": "Now we have to select a driver version. Choose βC#/.NETβ as the driver and β2.5 or laterβ as the version. Copy the connection string as weβll need it for later."
},
{
"code": null,
"e": 4233,
"s": 4113,
"text": "Now, letβs create a new class called Startup.cs. This class will allow us to use Dependency Injection in our Functions."
},
{
"code": null,
"e": 4463,
"s": 4233,
"text": "In my Startup class, Iβm instantiating a Singleton instance of my MongoClient so all functions can use it. All we need here is to get our connection setting for our MongoDB Atlas cluster and pass it through as a string parameter."
},
{
"code": null,
"e": 4775,
"s": 4463,
"text": "Iβve put this actual connection string in my local.settings.json file which is picked up in the IConfiguration instance of config. Itβs not a good idea to hard code connection strings or settings into your code, so this is one method in your code that you can use to protect secrets needed for your application."
},
{
"code": null,
"e": 4802,
"s": 4775,
"text": "Setting up our Album Class"
},
{
"code": null,
"e": 5061,
"s": 4802,
"text": "Now letβs set up our Album class. Weβre not going to do anything too amazing with this class. Iβve kept it simple just to highlight a couple of things we need/can do to make this model work with the MongoDB Driver. The definition for our class is as follows:"
},
{
"code": null,
"e": 5248,
"s": 5061,
"text": "In this class, Iβve given my Album an Id, Name, Artist, Price, ReleaseDate and Genre. Real simple. The two things I want to highlight here are the Id property and the AlbumName property."
},
{
"code": null,
"e": 5418,
"s": 5248,
"text": "For the Id property, Iβve assigned this property to be our ObjectId. This acts as the Primary Key for our MongoDB Document. The MongoDB Driver will generate this for us."
},
{
"code": null,
"e": 5593,
"s": 5418,
"text": "For the AlbumName property, Iβve decorated the property as a BsonElement called Name. This is what the property will be called in our document when itβs persisted to MongoDB."
},
{
"code": null,
"e": 5620,
"s": 5593,
"text": "Create the RESTful methods"
},
{
"code": null,
"e": 5844,
"s": 5620,
"text": "Weβve got pretty much everything we need to make our RESTful API, so letβs start building it. For all our functions, Iβve created a constructor that takes in the following parameters which will help inject our dependencies:"
},
{
"code": null,
"e": 5885,
"s": 5844,
"text": "MongoClient: To connect to our database."
},
{
"code": null,
"e": 6038,
"s": 5885,
"text": "ILogger: So we can log activity in our Function. If you deploy a Function to Azure and enable Application Insights, you this where the logs get sent to."
},
{
"code": null,
"e": 6217,
"s": 6038,
"text": "IConfiguration: This is what Iβm using to manage all the secrets needed in our Functions. As I mentioned before, these values are kept in local.settings.json for local debugging."
},
{
"code": null,
"e": 6331,
"s": 6217,
"text": "Iβve also created a IMongoCollection<Album> so we can work with our Album collection within our MongoDB database."
},
{
"code": null,
"e": 6539,
"s": 6331,
"text": "For all our functions, so we get an Exception, Iβve just logged the exception message and set our IActionResult returnValue to throw a 500 error response. Nothing complex, but simple enough for this example."
},
{
"code": null,
"e": 6575,
"s": 6539,
"text": "Now letβs dive into each function π"
},
{
"code": null,
"e": 6590,
"s": 6575,
"text": "CreateAlbum.cs"
},
{
"code": null,
"e": 6828,
"s": 6590,
"text": "In this function, we pass through a request of type HttpRequest and read the body of that request. Iβve used Newtonsoft.Json to deserialize my request into my Album object and Iβm creating a new album object with the values of our input."
},
{
"code": null,
"e": 6990,
"s": 6828,
"text": "Iβm then using the .InsertOne() method to insert our new Album object into our MongoDB and setting my return value to a new OkObjectResult with our album object."
},
{
"code": null,
"e": 7002,
"s": 6990,
"text": "GetAlbum.cs"
},
{
"code": null,
"e": 7337,
"s": 7002,
"text": "In this function, Iβm passing through an id that will represent the id of our document. Within our try/catch statement, Iβll attempt to find the album document with that id using the .Find() method on our MongoCollection and return it to the user. If we canβt find it, weβll send a log message saying we canβt find it and throw a 404."
},
{
"code": null,
"e": 7352,
"s": 7337,
"text": "GetAllAlbum.cs"
},
{
"code": null,
"e": 7572,
"s": 7352,
"text": "In these functions, all weβre doing here is using the Find() function to find all the albums within our Album collection and return those to the user as a list. If there are albums in the collection, weβll return a 404."
},
{
"code": null,
"e": 7587,
"s": 7572,
"text": "UpdateAlbum.cs"
},
{
"code": null,
"e": 7801,
"s": 7587,
"text": "The UpdateAlbum is a little different. Here weβre passing through our request body and an id. Iβm deserializing our body into an Album object and then setting the id that we pass through to our updatedResult item."
},
{
"code": null,
"e": 8059,
"s": 7801,
"text": "I use the ReplaceOne() method to do two things. Firstly, use the id to find the album in our collection with that id and then secondly, I pass through our updatedResult Album object to replace the existing item. If we canβt find this item, Iβll throw a 404."
},
{
"code": null,
"e": 8074,
"s": 8059,
"text": "DeleteAlbum.cs"
},
{
"code": null,
"e": 8259,
"s": 8074,
"text": "In our DeleteAlbum function, again we pass through the id of the document that we wish to delete and use the DeleteOne() function to find the album that has that id and then delete it."
},
{
"code": null,
"e": 8289,
"s": 8259,
"text": "Testing our API using POSTMAN"
},
{
"code": null,
"e": 8465,
"s": 8289,
"text": "All our methods are in place, so we can now start testing our API using Postman. Letβs test each one of our functions in turn. Press F5 in Visual Studio to start our Function."
},
{
"code": null,
"e": 8577,
"s": 8465,
"text": "It shouldnβt take too long, but once it has finished, you should be given some URLβs for each Function like so:"
},
{
"code": null,
"e": 8704,
"s": 8577,
"text": "Keep this console window open as these URLβs are mapped to each function and weβll need to use these to trigger our Functions."
},
{
"code": null,
"e": 8856,
"s": 8704,
"text": "For our CreateAlbum function, weβll need to send the following JSON payload to insert an Album into our collection. This is the payload that Iβve sent:"
},
{
"code": null,
"e": 9002,
"s": 8856,
"text": "{ \"albumName\": \"No.6 Collaborations Project\", \"artist\": \"Ed Sheeran\", \"price\": 15.99, \"releaseDate\": \"2019-12-06T11:00:00Z\", \"genre\": \"Pop\"}"
},
{
"code": null,
"e": 9127,
"s": 9002,
"text": "Paste the URL into the textbox and make sure the type is set to POST. Click βSend βand we should get the following response:"
},
{
"code": null,
"e": 9342,
"s": 9127,
"text": "Looks like it worked! Head back to your Atlas cluster, navigate to your Albums collections and click βFindβ. We should be able to see the inserted documents with the values that we sent as part of our JSON payload."
},
{
"code": null,
"e": 9544,
"s": 9342,
"text": "Letβs attempt to read the item that weβve just created! Copy and paste the _id field of the item and then use it as the id paramter in our GetAlbum URL. Change the request type to GET and click βSendβ."
},
{
"code": null,
"e": 9636,
"s": 9544,
"text": "As you can see, we should see the document of the created album returned to us in the body."
},
{
"code": null,
"e": 9819,
"s": 9636,
"text": "After a quick look on Wikipedia, this album covers a few more genres so we need to update our document. Using the same id, change the request type to PUT and update the body like so:"
},
{
"code": null,
"e": 9979,
"s": 9819,
"text": "{ \"albumName\": \"No.6 Collaborations Project\", \"artist\": \"Ed Sheeran\", \"price\": 15.99, \"releaseDate\": \"2019-12-06T11:00:00Z\", \"genre\": \"Pop, Rap, Hip-Hop\"}"
},
{
"code": null,
"e": 10016,
"s": 9979,
"text": "Click βSend βto update our document:"
},
{
"code": null,
"e": 10124,
"s": 10016,
"text": "Head to your collection in Atlas and click βFindβ. We should see the updated document persisted in MongoDB."
},
{
"code": null,
"e": 10291,
"s": 10124,
"text": "Now letβs test our Function to see if we can delete documents. Use the Id as the id parameter and set the request type to DELETE. Click βSend βto delete the document."
},
{
"code": null,
"e": 10406,
"s": 10291,
"text": "Head back to Atlas and click βFind βagain. If it worked, the document should be deleted from our Album collection."
},
{
"code": null,
"e": 10417,
"s": 10406,
"text": "Conclusion"
},
{
"code": null,
"e": 10687,
"s": 10417,
"text": "In this tutorial, we learnt how we can build a really simple API using Azure Functions that uses MongoDB as a datastore. While this was a very simple project to do, hopefully, this tutorial has given you some ideas as to how you can use MongoDB in your Azure Functions."
},
{
"code": null,
"e": 10754,
"s": 10687,
"text": "If you want to see the whole sample, check out the code on GitHub!"
}
] |
MYBATIS - Mapper XML
|
In the previous chapter, we have seen how to configure MyBatis using an XML file. This chapter discusses the Mapper XML file and various mapped SQL statements provided by it.
Before proceeding to mapped statements, assume that the following table named Student exists in the MYSQL database β
+----+-------+--------+------------+-----------+---------------+
| ID | NAME | BRANCH | PERCENTAGE | PHONE | EMAIL |
+----+-------+--------+------------+-----------+---------------+
| 1 | Shyam | it | 80 | 954788457 | mail@mail.com |
+----+-------+--------+------------+-----------+---------------+
Also assume that POJO class also exists named Student with respect to the above table as shown below β
public class Student {
private int id;
private String name;
private String branch;
private int percentage;
private int phone;
private String email;
//Setters and getters
}
Mapper XML is an important file in MyBatis, which contains a set of statements to configure various SQL statements such as select, insert, update, and delete. These statements are known as Mapped Statements or Mapped SQL Statements.
All the statements have unique id. To execute any of these statements you just need to pass the appropriate id to the methods in Java Application.(This is discussed clearly in later chapters).
All the statements have unique id. To execute any of these statements you just need to pass the appropriate id to the methods in Java Application.(This is discussed clearly in later chapters).
mapper XML file prevents the burden of writing SQL statements repeatedly in the application. In comparison to JDBC, almost 95% of the code is reduced using Mapper XML file in MyBatis.
mapper XML file prevents the burden of writing SQL statements repeatedly in the application. In comparison to JDBC, almost 95% of the code is reduced using Mapper XML file in MyBatis.
All these Mapped SQL statements are resided within the element named<mapper>. This element contains an attribute called βnamespaceβ.
All these Mapped SQL statements are resided within the element named<mapper>. This element contains an attribute called βnamespaceβ.
<mapper namespace = "Student">
//mapped statements and result maps
<mapper>
All the Mapped SQL statements are discussed below with examples.
In MyBatis, to insert values into the table, we have to configure the insert mapped query. MyBatis provides various attributes for insert mapper, but largely we use id and parameter type.
id is unique identifier used to identify the insert statement. On the other hand, parametertype is the class name or the alias of the parameter that will be passed into the statement. Below given is an example of insert mapped query β
<insert id = "insert" parameterType = "Student">
INSERT INTO STUDENT1 (NAME, BRANCH, PERCENTAGE, PHONE, EMAIL )
VALUES (#{name}, #{branch}, #{percentage}, #{phone}, #{email});
</insert>
In the given example, we use the parameter of type Student (class). The class student is a POJO class, which represents the Student record with name, branch, percentage, phone, and email as parameters.
You can invoke the βinsertβ mapped query using Java API as shown below β
//Assume session is an SqlSession object.
session.insert("Student.insert", student);
To update values of an existing record using MyBatis, the mapped query update is configured. The attributes of update mapped query are same as the insert mapped query. Following is the example of the update mapped query β
<update id = "update" parameterType = "Student">
UPDATE STUDENT SET EMAIL = #{email}, NAME = #{name}, BRANCH = #{branch}, PERCENTAGE = #{percentage}, PHONE = #{phone} WHERE ID = #{id};
</update>
To invoke the update query, instantiate Student class, set the values for the variables representing columns which need to be updated, and pass this object as parameter to update() method. You can invoke the update mapped query using Java API as shown below β
//Assume session is an SqlSession object.
session.update("Student.update",student);
To delete the values of an existing record using MyBatis, the mapped query βdeleteβ is configured. The attributes of βdeleteβ mapped query are same as the insert and update mapped queries. Following is the example of the delete mapped query β
<delete id = "deleteById" parameterType = "int">
DELETE from STUDENT WHERE ID = #{id};
</delete>
You can invoke the delete mapped query using the delete method of SqlSession interface provided by MyBatis Java API as shown below β
//Assume session is an SqlSession object.
session.delete("Student.deleteById", 18);
To retrieve data, βselectβ mapper statement is used. Following is the example of select mapped query to retrieve all the records in a table β
<select id = "getAll" resultMap = "result">
SELECT * FROM STUDENT;
</select>
You can retrieve the data returned by the select query using the method selectList(). This method returns the data of the selected record in the form of List as shown below β
List<Student> list = session.selectList("Student.getAll");
It is the most important and powerful elements in MyBatis. The results of SQL SELECT statements are mapped to Java objects (beans/POJO). Once the result map is defined, we can refer these from several SELECT statements. Following is the example of result Map query; it maps the results of the select queries to the Student class β
<resultMap id = "result" type = "Student">
<result property = "id" column = "ID"/>
<result property = "name" column = "NAME"/>
<result property = "branch" column = "BRANCH"/>
<result property = "percentage" column = "PERCENTAGE"/>
<result property = "phone" column = "PHONE"/>
<result property = "email" column = "EMAIL"/>
</resultMap>
<select id = "getAll" resultMap = "result">
SELECT * FROM STUDENT;
</select>
<select id = "getById" parameterType = "int" resultMap = "result">
SELECT * FROM STUDENT WHERE ID = #{id};
</select>
Note β It is not mandatory to write the column attribute of the resultMap if both the property and the column name of the table are same.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2046,
"s": 1871,
"text": "In the previous chapter, we have seen how to configure MyBatis using an XML file. This chapter discusses the Mapper XML file and various mapped SQL statements provided by it."
},
{
"code": null,
"e": 2163,
"s": 2046,
"text": "Before proceeding to mapped statements, assume that the following table named Student exists in the MYSQL database β"
},
{
"code": null,
"e": 2489,
"s": 2163,
"text": "+----+-------+--------+------------+-----------+---------------+\n| ID | NAME | BRANCH | PERCENTAGE | PHONE | EMAIL |\n+----+-------+--------+------------+-----------+---------------+\n| 1 | Shyam | it | 80 | 954788457 | mail@mail.com |\n+----+-------+--------+------------+-----------+---------------+\n"
},
{
"code": null,
"e": 2592,
"s": 2489,
"text": "Also assume that POJO class also exists named Student with respect to the above table as shown below β"
},
{
"code": null,
"e": 2792,
"s": 2592,
"text": "public class Student {\n private int id;\n private String name;\n private String branch;\n private int percentage;\n private int phone;\n private String email;\n \n //Setters and getters \n}"
},
{
"code": null,
"e": 3025,
"s": 2792,
"text": "Mapper XML is an important file in MyBatis, which contains a set of statements to configure various SQL statements such as select, insert, update, and delete. These statements are known as Mapped Statements or Mapped SQL Statements."
},
{
"code": null,
"e": 3218,
"s": 3025,
"text": "All the statements have unique id. To execute any of these statements you just need to pass the appropriate id to the methods in Java Application.(This is discussed clearly in later chapters)."
},
{
"code": null,
"e": 3411,
"s": 3218,
"text": "All the statements have unique id. To execute any of these statements you just need to pass the appropriate id to the methods in Java Application.(This is discussed clearly in later chapters)."
},
{
"code": null,
"e": 3595,
"s": 3411,
"text": "mapper XML file prevents the burden of writing SQL statements repeatedly in the application. In comparison to JDBC, almost 95% of the code is reduced using Mapper XML file in MyBatis."
},
{
"code": null,
"e": 3779,
"s": 3595,
"text": "mapper XML file prevents the burden of writing SQL statements repeatedly in the application. In comparison to JDBC, almost 95% of the code is reduced using Mapper XML file in MyBatis."
},
{
"code": null,
"e": 3912,
"s": 3779,
"text": "All these Mapped SQL statements are resided within the element named<mapper>. This element contains an attribute called βnamespaceβ."
},
{
"code": null,
"e": 4045,
"s": 3912,
"text": "All these Mapped SQL statements are resided within the element named<mapper>. This element contains an attribute called βnamespaceβ."
},
{
"code": null,
"e": 4125,
"s": 4045,
"text": "<mapper namespace = \"Student\">\n //mapped statements and result maps\n<mapper> "
},
{
"code": null,
"e": 4190,
"s": 4125,
"text": "All the Mapped SQL statements are discussed below with examples."
},
{
"code": null,
"e": 4378,
"s": 4190,
"text": "In MyBatis, to insert values into the table, we have to configure the insert mapped query. MyBatis provides various attributes for insert mapper, but largely we use id and parameter type."
},
{
"code": null,
"e": 4613,
"s": 4378,
"text": "id is unique identifier used to identify the insert statement. On the other hand, parametertype is the class name or the alias of the parameter that will be passed into the statement. Below given is an example of insert mapped query β"
},
{
"code": null,
"e": 4810,
"s": 4613,
"text": "<insert id = \"insert\" parameterType = \"Student\">\n INSERT INTO STUDENT1 (NAME, BRANCH, PERCENTAGE, PHONE, EMAIL ) \n VALUES (#{name}, #{branch}, #{percentage}, #{phone}, #{email}); \n</insert>"
},
{
"code": null,
"e": 5012,
"s": 4810,
"text": "In the given example, we use the parameter of type Student (class). The class student is a POJO class, which represents the Student record with name, branch, percentage, phone, and email as parameters."
},
{
"code": null,
"e": 5085,
"s": 5012,
"text": "You can invoke the βinsertβ mapped query using Java API as shown below β"
},
{
"code": null,
"e": 5173,
"s": 5085,
"text": "//Assume session is an SqlSession object. \nsession.insert(\"Student.insert\", student);\n"
},
{
"code": null,
"e": 5395,
"s": 5173,
"text": "To update values of an existing record using MyBatis, the mapped query update is configured. The attributes of update mapped query are same as the insert mapped query. Following is the example of the update mapped query β"
},
{
"code": null,
"e": 5593,
"s": 5395,
"text": "<update id = \"update\" parameterType = \"Student\">\n UPDATE STUDENT SET EMAIL = #{email}, NAME = #{name}, BRANCH = #{branch}, PERCENTAGE = #{percentage}, PHONE = #{phone} WHERE ID = #{id};\n</update>"
},
{
"code": null,
"e": 5853,
"s": 5593,
"text": "To invoke the update query, instantiate Student class, set the values for the variables representing columns which need to be updated, and pass this object as parameter to update() method. You can invoke the update mapped query using Java API as shown below β"
},
{
"code": null,
"e": 5940,
"s": 5853,
"text": "//Assume session is an SqlSession object. \nsession.update(\"Student.update\",student);\n"
},
{
"code": null,
"e": 6183,
"s": 5940,
"text": "To delete the values of an existing record using MyBatis, the mapped query βdeleteβ is configured. The attributes of βdeleteβ mapped query are same as the insert and update mapped queries. Following is the example of the delete mapped query β"
},
{
"code": null,
"e": 6283,
"s": 6183,
"text": "<delete id = \"deleteById\" parameterType = \"int\">\n DELETE from STUDENT WHERE ID = #{id};\n</delete>"
},
{
"code": null,
"e": 6416,
"s": 6283,
"text": "You can invoke the delete mapped query using the delete method of SqlSession interface provided by MyBatis Java API as shown below β"
},
{
"code": null,
"e": 6503,
"s": 6416,
"text": "//Assume session is an SqlSession object. \nsession.delete(\"Student.deleteById\", 18);\n"
},
{
"code": null,
"e": 6645,
"s": 6503,
"text": "To retrieve data, βselectβ mapper statement is used. Following is the example of select mapped query to retrieve all the records in a table β"
},
{
"code": null,
"e": 6726,
"s": 6645,
"text": "<select id = \"getAll\" resultMap = \"result\">\n SELECT * FROM STUDENT; \n</select>"
},
{
"code": null,
"e": 6901,
"s": 6726,
"text": "You can retrieve the data returned by the select query using the method selectList(). This method returns the data of the selected record in the form of List as shown below β"
},
{
"code": null,
"e": 6961,
"s": 6901,
"text": "List<Student> list = session.selectList(\"Student.getAll\");\n"
},
{
"code": null,
"e": 7292,
"s": 6961,
"text": "It is the most important and powerful elements in MyBatis. The results of SQL SELECT statements are mapped to Java objects (beans/POJO). Once the result map is defined, we can refer these from several SELECT statements. Following is the example of result Map query; it maps the results of the select queries to the Student class β"
},
{
"code": null,
"e": 7849,
"s": 7292,
"text": "<resultMap id = \"result\" type = \"Student\">\n <result property = \"id\" column = \"ID\"/>\n <result property = \"name\" column = \"NAME\"/>\n <result property = \"branch\" column = \"BRANCH\"/>\n <result property = \"percentage\" column = \"PERCENTAGE\"/>\n <result property = \"phone\" column = \"PHONE\"/>\n <result property = \"email\" column = \"EMAIL\"/>\n</resultMap>\n\n<select id = \"getAll\" resultMap = \"result\">\n SELECT * FROM STUDENT; \n</select>\n\n<select id = \"getById\" parameterType = \"int\" resultMap = \"result\">\n SELECT * FROM STUDENT WHERE ID = #{id};\n</select>"
},
{
"code": null,
"e": 7987,
"s": 7849,
"text": "Note β It is not mandatory to write the column attribute of the resultMap if both the property and the column name of the table are same."
},
{
"code": null,
"e": 7994,
"s": 7987,
"text": " Print"
},
{
"code": null,
"e": 8005,
"s": 7994,
"text": " Add Notes"
}
] |
How to get the return value from a function in a class in Python?
|
The following code shows how to get return value from a function in a Python class
class Score():
def __init__(self):
self.score = 0
self.num_enemies = 5
self.num_lives = 3
def setScore(self, num):
self.score = num
def getScore(self):
return self.score
def getEnemies(self):
return self.num_enemies
def getLives(self):
return self.num_lives
s = Score()
s.setScore(9)
print s.getScore()
print s.getEnemies()
print s.getLives()
9
5
3
|
[
{
"code": null,
"e": 1145,
"s": 1062,
"text": "The following code shows how to get return value from a function in a Python class"
},
{
"code": null,
"e": 1574,
"s": 1145,
"text": "class Score():\n def __init__(self):\n self.score = 0\n self.num_enemies = 5\n self.num_lives = 3\n\n def setScore(self, num):\n self.score = num\n def getScore(self):\n return self.score\n def getEnemies(self):\n return self.num_enemies\n def getLives(self):\n return self.num_lives\n \ns = Score()\ns.setScore(9)\nprint s.getScore()\nprint s.getEnemies()\nprint s.getLives()"
},
{
"code": null,
"e": 1580,
"s": 1574,
"text": "9\n5\n3"
}
] |
How to create UI Datepicker using jQuery ? - GeeksforGeeks
|
27 Apr, 2020
Localization means browser to display data in a different languages as per browser setting or manual setting inside the application. To implement jQuery UI Datepicker to display in different languages as per browser settings follow the steps:
Approach:
Add the following JavaScript references.<script src= "https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script src= "http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script> <link href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" /> <script src= "https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/i18n/jquery-ui-i18n.min.js"></script>
<script src= "https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script src= "http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script> <link href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" /> <script src= "https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/i18n/jquery-ui-i18n.min.js"></script>
Fetch browser language version using JavaScript. Here is the code:var userLang = navigator.language || navigator.userLanguage;
var userLang = navigator.language || navigator.userLanguage;
Add the following JavaScript code to implement localization in jQuery Datepicker. Here we are using extend property to set regional language as per the browser setting (Step 2).var options = $.extend( {}, // empty object $.datepicker.regional[userLang], // Dynamically { dateFormat: "mm/dd/yy" } // your custom options ); $("#calendar").datepicker(options);
var options = $.extend( {}, // empty object $.datepicker.regional[userLang], // Dynamically { dateFormat: "mm/dd/yy" } // your custom options ); $("#calendar").datepicker(options);
Example:
<!doctype html> <html lang="en"> <head> <title>Localization JQuery UI Datepicker </title> <meta charset="utf-8"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"> </script> <script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"> </script> <link href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" /> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/i18n/jquery-ui-i18n.min.js"> </script> <script type="text/javascript"> $(document).ready(function() { var userLang = navigator.language || navigator.userLanguage; var options = $.extend({}, // empty object $.datepicker.regional[userLang], { dateFormat: "mm/dd/yy" } // your custom options ); $("#calendar").datepicker(options); }); </script> </head> <body> <div class="container"> <h3>JQuery UI Datepicker Localization</h3> <div id="calendar"> </div> </div> </body> </html>
Letβs see the following figures how it is showing when the language change:
Output 1: When changing regional language as English using βen-USβ in the following code:
var options = $.extend( {}, // empty object $.datepicker.regional["en-US"], // Dynamically { dateFormat: "mm/dd/yy"} // your custom options );
Output 2: When changing regional language as Hindi using βhiβ in the following code:
var options = $.extend( {}, // empty object $.datepicker.regional["hi"], // Dynamically { dateFormat: "mm/dd/yy"} // your custom options );
You can use regional language code as per your need from the following link : List of ISO 639-1 codes
HTML-Misc
JavaScript-Misc
jQuery-Misc
Picked
HTML
JavaScript
JQuery
Web Technologies
Web technologies Questions
Write From Home
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to set the default value for an HTML <select> element ?
How to update Node.js and NPM to next version ?
How to set input type date in dd-mm-yyyy format using HTML ?
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
File uploading in React.js
|
[
{
"code": null,
"e": 40332,
"s": 40304,
"text": "\n27 Apr, 2020"
},
{
"code": null,
"e": 40575,
"s": 40332,
"text": "Localization means browser to display data in a different languages as per browser setting or manual setting inside the application. To implement jQuery UI Datepicker to display in different languages as per browser settings follow the steps:"
},
{
"code": null,
"e": 40585,
"s": 40575,
"text": "Approach:"
},
{
"code": null,
"e": 41041,
"s": 40585,
"text": "Add the following JavaScript references.<script src= \"https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js\"></script> <script src= \"http://code.jquery.com/ui/1.11.4/jquery-ui.js\"></script> <link href=\"http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css\" rel=\"stylesheet\" type=\"text/css\" /> <script src= \"https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/i18n/jquery-ui-i18n.min.js\"></script> "
},
{
"code": "<script src= \"https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js\"></script> <script src= \"http://code.jquery.com/ui/1.11.4/jquery-ui.js\"></script> <link href=\"http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css\" rel=\"stylesheet\" type=\"text/css\" /> <script src= \"https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/i18n/jquery-ui-i18n.min.js\"></script> ",
"e": 41457,
"s": 41041,
"text": null
},
{
"code": null,
"e": 41584,
"s": 41457,
"text": "Fetch browser language version using JavaScript. Here is the code:var userLang = navigator.language || navigator.userLanguage;"
},
{
"code": null,
"e": 41645,
"s": 41584,
"text": "var userLang = navigator.language || navigator.userLanguage;"
},
{
"code": null,
"e": 42019,
"s": 41645,
"text": "Add the following JavaScript code to implement localization in jQuery Datepicker. Here we are using extend property to set regional language as per the browser setting (Step 2).var options = $.extend( {}, // empty object $.datepicker.regional[userLang], // Dynamically { dateFormat: \"mm/dd/yy\" } // your custom options ); $(\"#calendar\").datepicker(options);"
},
{
"code": "var options = $.extend( {}, // empty object $.datepicker.regional[userLang], // Dynamically { dateFormat: \"mm/dd/yy\" } // your custom options ); $(\"#calendar\").datepicker(options);",
"e": 42216,
"s": 42019,
"text": null
},
{
"code": null,
"e": 42225,
"s": 42216,
"text": "Example:"
},
{
"code": "<!doctype html> <html lang=\"en\"> <head> <title>Localization JQuery UI Datepicker </title> <meta charset=\"utf-8\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js\"> </script> <script src=\"http://code.jquery.com/ui/1.11.4/jquery-ui.js\"> </script> <link href=\"http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css\" rel=\"stylesheet\" type=\"text/css\" /> <script src=\"https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/i18n/jquery-ui-i18n.min.js\"> </script> <script type=\"text/javascript\"> $(document).ready(function() { var userLang = navigator.language || navigator.userLanguage; var options = $.extend({}, // empty object $.datepicker.regional[userLang], { dateFormat: \"mm/dd/yy\" } // your custom options ); $(\"#calendar\").datepicker(options); }); </script> </head> <body> <div class=\"container\"> <h3>JQuery UI Datepicker Localization</h3> <div id=\"calendar\"> </div> </div> </body> </html> ",
"e": 43403,
"s": 42225,
"text": null
},
{
"code": null,
"e": 43479,
"s": 43403,
"text": "Letβs see the following figures how it is showing when the language change:"
},
{
"code": null,
"e": 43569,
"s": 43479,
"text": "Output 1: When changing regional language as English using βen-USβ in the following code:"
},
{
"code": "var options = $.extend( {}, // empty object $.datepicker.regional[\"en-US\"], // Dynamically { dateFormat: \"mm/dd/yy\"} // your custom options ); ",
"e": 43751,
"s": 43569,
"text": null
},
{
"code": null,
"e": 43836,
"s": 43751,
"text": "Output 2: When changing regional language as Hindi using βhiβ in the following code:"
},
{
"code": "var options = $.extend( {}, // empty object $.datepicker.regional[\"hi\"], // Dynamically { dateFormat: \"mm/dd/yy\"} // your custom options ); ",
"e": 44015,
"s": 43836,
"text": null
},
{
"code": null,
"e": 44117,
"s": 44015,
"text": "You can use regional language code as per your need from the following link : List of ISO 639-1 codes"
},
{
"code": null,
"e": 44127,
"s": 44117,
"text": "HTML-Misc"
},
{
"code": null,
"e": 44143,
"s": 44127,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 44155,
"s": 44143,
"text": "jQuery-Misc"
},
{
"code": null,
"e": 44162,
"s": 44155,
"text": "Picked"
},
{
"code": null,
"e": 44167,
"s": 44162,
"text": "HTML"
},
{
"code": null,
"e": 44178,
"s": 44167,
"text": "JavaScript"
},
{
"code": null,
"e": 44185,
"s": 44178,
"text": "JQuery"
},
{
"code": null,
"e": 44202,
"s": 44185,
"text": "Web Technologies"
},
{
"code": null,
"e": 44229,
"s": 44202,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 44245,
"s": 44229,
"text": "Write From Home"
},
{
"code": null,
"e": 44250,
"s": 44245,
"text": "HTML"
},
{
"code": null,
"e": 44348,
"s": 44250,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 44357,
"s": 44348,
"text": "Comments"
},
{
"code": null,
"e": 44370,
"s": 44357,
"text": "Old Comments"
},
{
"code": null,
"e": 44432,
"s": 44370,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 44482,
"s": 44432,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 44542,
"s": 44482,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 44590,
"s": 44542,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 44651,
"s": 44590,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 44712,
"s": 44651,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 44757,
"s": 44712,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 44829,
"s": 44757,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 44898,
"s": 44829,
"text": "How to calculate the number of days between two dates in javascript?"
}
] |
Counting Inversions using Set in C++ STL - GeeksforGeeks
|
28 Jun, 2021
Inversion Count for an array indicates β how far (or close) the array is from being sorted. If array is already sorted then inversion count is 0. If array is sorted in reverse order that inversion count is the maximum.
Two elements a[i] and a[j] form an inversion if
a[i] > a[j] and i < j. For simplicity, we may
assume that all elements are unique.
Example:
Input: arr[] = {8, 4, 2, 1}
Output: 6
Given array has six inversions (8,4), (4,2),
(8,2), (8,1), (4,1), (2,1).
We have already discussed below approaches.1) Naive and Merge Sort based approaches.2) AVL Tree based approach.
In this post an easy implementation of approach 2 using Set in C++ STL is discussed.
1) Create an empty Set in C++ STL (Note that a Set in C++ STL is
implemented using Self-Balancing Binary Search Tree). And insert
first element of array into the set.
2) Initialize inversion count as 0.
3) Iterate from 1 to n-1 and do following for every element in arr[i]
a) Insert arr[i] into the set.
b) Find the first element greater than arr[i] in set
using upper_bound() defined Set STL.
c) Find distance of above found element from last element in set
and add this distance to inversion count.
4) Return inversion count.
// A STL Set based approach for inversion count #include<bits/stdc++.h>using namespace std; // Returns inversion count in arr[0..n-1]int getInvCount(int arr[],int n){ // Create an empty set and insert first element in it multiset<int> set1; set1.insert(arr[0]); int invcount = 0; // Initialize result multiset<int>::iterator itset1; // Iterator for the set // Traverse all elements starting from second for (int i=1; i<n; i++) { // Insert arr[i] in set (Note that set maintains // sorted order) set1.insert(arr[i]); // Set the iterator to first greater element than arr[i] // in set (Note that set stores arr[0],.., arr[i-1] itset1 = set1.upper_bound(arr[i]); // Get distance of first greater element from end // and this distance is count of greater elements // on left side of arr[i] invcount += distance(itset1, set1.end()); } return invcount;} // Driver program to test aboveint main(){ int arr[] = {8, 4, 2, 1}; int n = sizeof(arr)/sizeof(int); cout << "Number of inversions count are : " << getInvCount(arr,n); return 0;}
Output:
Number of inversions count are : 6
Note that the worst case time complexity of above implementation is O(n2) as distance function in STL takes O(n) time worst case, but this implementation is much simpler than other implementations and would take much less time than Naive method on average.
This article is contributed by Abhiraj Smit. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
ManasChhabra2
RajSheth
cpp-set
inversion
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Inheritance in C++
Map in C++ Standard Template Library (STL)
C++ Classes and Objects
Operator Overloading in C++
Bitwise Operators in C/C++
Socket Programming in C/C++
Constructors in C++
Virtual Function in C++
Multidimensional Arrays in C / C++
Templates in C++ with Examples
|
[
{
"code": null,
"e": 24240,
"s": 24212,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 24459,
"s": 24240,
"text": "Inversion Count for an array indicates β how far (or close) the array is from being sorted. If array is already sorted then inversion count is 0. If array is sorted in reverse order that inversion count is the maximum."
},
{
"code": null,
"e": 24759,
"s": 24459,
"text": " Two elements a[i] and a[j] form an inversion if \n a[i] > a[j] and i < j. For simplicity, we may \n assume that all elements are unique.\n\n Example:\n Input: arr[] = {8, 4, 2, 1}\n Output: 6\n Given array has six inversions (8,4), (4,2),\n (8,2), (8,1), (4,1), (2,1). \n"
},
{
"code": null,
"e": 24871,
"s": 24759,
"text": "We have already discussed below approaches.1) Naive and Merge Sort based approaches.2) AVL Tree based approach."
},
{
"code": null,
"e": 24956,
"s": 24871,
"text": "In this post an easy implementation of approach 2 using Set in C++ STL is discussed."
},
{
"code": null,
"e": 25526,
"s": 24956,
"text": "1) Create an empty Set in C++ STL (Note that a Set in C++ STL is \n implemented using Self-Balancing Binary Search Tree). And insert\n first element of array into the set.\n\n2) Initialize inversion count as 0.\n\n3) Iterate from 1 to n-1 and do following for every element in arr[i]\n a) Insert arr[i] into the set.\n b) Find the first element greater than arr[i] in set\n using upper_bound() defined Set STL.\n c) Find distance of above found element from last element in set\n and add this distance to inversion count.\n\n4) Return inversion count.\n"
},
{
"code": "// A STL Set based approach for inversion count #include<bits/stdc++.h>using namespace std; // Returns inversion count in arr[0..n-1]int getInvCount(int arr[],int n){ // Create an empty set and insert first element in it multiset<int> set1; set1.insert(arr[0]); int invcount = 0; // Initialize result multiset<int>::iterator itset1; // Iterator for the set // Traverse all elements starting from second for (int i=1; i<n; i++) { // Insert arr[i] in set (Note that set maintains // sorted order) set1.insert(arr[i]); // Set the iterator to first greater element than arr[i] // in set (Note that set stores arr[0],.., arr[i-1] itset1 = set1.upper_bound(arr[i]); // Get distance of first greater element from end // and this distance is count of greater elements // on left side of arr[i] invcount += distance(itset1, set1.end()); } return invcount;} // Driver program to test aboveint main(){ int arr[] = {8, 4, 2, 1}; int n = sizeof(arr)/sizeof(int); cout << \"Number of inversions count are : \" << getInvCount(arr,n); return 0;}",
"e": 26688,
"s": 25526,
"text": null
},
{
"code": null,
"e": 26696,
"s": 26688,
"text": "Output:"
},
{
"code": null,
"e": 26731,
"s": 26696,
"text": "Number of inversions count are : 6"
},
{
"code": null,
"e": 26988,
"s": 26731,
"text": "Note that the worst case time complexity of above implementation is O(n2) as distance function in STL takes O(n) time worst case, but this implementation is much simpler than other implementations and would take much less time than Naive method on average."
},
{
"code": null,
"e": 27157,
"s": 26988,
"text": "This article is contributed by Abhiraj Smit. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 27171,
"s": 27157,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 27180,
"s": 27171,
"text": "RajSheth"
},
{
"code": null,
"e": 27188,
"s": 27180,
"text": "cpp-set"
},
{
"code": null,
"e": 27198,
"s": 27188,
"text": "inversion"
},
{
"code": null,
"e": 27202,
"s": 27198,
"text": "STL"
},
{
"code": null,
"e": 27206,
"s": 27202,
"text": "C++"
},
{
"code": null,
"e": 27210,
"s": 27206,
"text": "STL"
},
{
"code": null,
"e": 27214,
"s": 27210,
"text": "CPP"
},
{
"code": null,
"e": 27312,
"s": 27214,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27331,
"s": 27312,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 27374,
"s": 27331,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 27398,
"s": 27374,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 27426,
"s": 27398,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 27453,
"s": 27426,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 27481,
"s": 27453,
"text": "Socket Programming in C/C++"
},
{
"code": null,
"e": 27501,
"s": 27481,
"text": "Constructors in C++"
},
{
"code": null,
"e": 27525,
"s": 27501,
"text": "Virtual Function in C++"
},
{
"code": null,
"e": 27560,
"s": 27525,
"text": "Multidimensional Arrays in C / C++"
}
] |
Difference between Context Free Grammar and Regular Grammar - GeeksforGeeks
|
31 May, 2021
Noam Chomsky has divided grammar into four types :
Type
Name
0
1
2
3
Chomsky Hierarchy
1. Context Free Grammar :
Language generated by Context Free Grammar is accepted by Pushdown Automata
It is a subset of Type 0 and Type 1 grammar and a superset of Type 3 grammar.
Also called phase structured grammar.
Different context-free grammars can generate the same context-free language.
Classification of Context Free Grammar is done on the basis of the number of parse trees.
Only one parse tree->Unambiguous.
More than one parse tree->Ambiguous.
Productions are in the form β
A->B;
AβN i.e A is a non-terminal.
BβV*(Any string).
Example β
S β> AB
A β> a
B β> b
2. Regular Grammar :
It is accepted by Finite State Automata.
It is a subset of Type 0 ,Type 1 and Type 2 grammar.
The language it generates is called Regular Language.
Regular languages are closed under operations like Union, Intersection, Complement etc.
They are the most restricted form of grammar.
Productions are in the form β
V β> VT / T (left-linear grammar)
(or)
V β> TV /T (right-linear grammar)
Example β
1. S β> ab.
2. S -> aS | bS | β
Difference Between Context Free Grammar and Regular Grammar:
GATE CS
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between Clustered and Non-clustered index
Phases of a Compiler
Preemptive and Non-Preemptive Scheduling
Differences between IPv4 and IPv6
Introduction of Process Synchronization
Regular Expressions, Regular Grammar and Regular Languages
Difference between DFA and NFA
Introduction of Finite Automata
Difference between Mealy machine and Moore machine
Pumping Lemma in Theory of Computation
|
[
{
"code": null,
"e": 24376,
"s": 24348,
"text": "\n31 May, 2021"
},
{
"code": null,
"e": 24427,
"s": 24376,
"text": "Noam Chomsky has divided grammar into four types :"
},
{
"code": null,
"e": 24432,
"s": 24427,
"text": "Type"
},
{
"code": null,
"e": 24437,
"s": 24432,
"text": "Name"
},
{
"code": null,
"e": 24439,
"s": 24437,
"text": "0"
},
{
"code": null,
"e": 24441,
"s": 24439,
"text": "1"
},
{
"code": null,
"e": 24443,
"s": 24441,
"text": "2"
},
{
"code": null,
"e": 24445,
"s": 24443,
"text": "3"
},
{
"code": null,
"e": 24463,
"s": 24445,
"text": "Chomsky Hierarchy"
},
{
"code": null,
"e": 24489,
"s": 24463,
"text": "1. Context Free Grammar :"
},
{
"code": null,
"e": 24565,
"s": 24489,
"text": "Language generated by Context Free Grammar is accepted by Pushdown Automata"
},
{
"code": null,
"e": 24643,
"s": 24565,
"text": "It is a subset of Type 0 and Type 1 grammar and a superset of Type 3 grammar."
},
{
"code": null,
"e": 24681,
"s": 24643,
"text": "Also called phase structured grammar."
},
{
"code": null,
"e": 24758,
"s": 24681,
"text": "Different context-free grammars can generate the same context-free language."
},
{
"code": null,
"e": 24848,
"s": 24758,
"text": "Classification of Context Free Grammar is done on the basis of the number of parse trees."
},
{
"code": null,
"e": 24882,
"s": 24848,
"text": "Only one parse tree->Unambiguous."
},
{
"code": null,
"e": 24919,
"s": 24882,
"text": "More than one parse tree->Ambiguous."
},
{
"code": null,
"e": 24949,
"s": 24919,
"text": "Productions are in the form β"
},
{
"code": null,
"e": 25002,
"s": 24949,
"text": "A->B;\nAβN i.e A is a non-terminal.\nBβV*(Any string)."
},
{
"code": null,
"e": 25012,
"s": 25002,
"text": "Example β"
},
{
"code": null,
"e": 25034,
"s": 25012,
"text": "S β> AB\nA β> a\nB β> b"
},
{
"code": null,
"e": 25055,
"s": 25034,
"text": "2. Regular Grammar :"
},
{
"code": null,
"e": 25096,
"s": 25055,
"text": "It is accepted by Finite State Automata."
},
{
"code": null,
"e": 25149,
"s": 25096,
"text": "It is a subset of Type 0 ,Type 1 and Type 2 grammar."
},
{
"code": null,
"e": 25203,
"s": 25149,
"text": "The language it generates is called Regular Language."
},
{
"code": null,
"e": 25291,
"s": 25203,
"text": "Regular languages are closed under operations like Union, Intersection, Complement etc."
},
{
"code": null,
"e": 25337,
"s": 25291,
"text": "They are the most restricted form of grammar."
},
{
"code": null,
"e": 25367,
"s": 25337,
"text": "Productions are in the form β"
},
{
"code": null,
"e": 25442,
"s": 25367,
"text": "V β> VT / T (left-linear grammar)\n (or)\nV β> TV /T (right-linear grammar)"
},
{
"code": null,
"e": 25452,
"s": 25442,
"text": "Example β"
},
{
"code": null,
"e": 25486,
"s": 25452,
"text": "1. S β> ab. \n2. S -> aS | bS | β "
},
{
"code": null,
"e": 25547,
"s": 25486,
"text": "Difference Between Context Free Grammar and Regular Grammar:"
},
{
"code": null,
"e": 25555,
"s": 25547,
"text": "GATE CS"
},
{
"code": null,
"e": 25588,
"s": 25555,
"text": "Theory of Computation & Automata"
},
{
"code": null,
"e": 25686,
"s": 25588,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25739,
"s": 25686,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 25760,
"s": 25739,
"text": "Phases of a Compiler"
},
{
"code": null,
"e": 25801,
"s": 25760,
"text": "Preemptive and Non-Preemptive Scheduling"
},
{
"code": null,
"e": 25835,
"s": 25801,
"text": "Differences between IPv4 and IPv6"
},
{
"code": null,
"e": 25875,
"s": 25835,
"text": "Introduction of Process Synchronization"
},
{
"code": null,
"e": 25934,
"s": 25875,
"text": "Regular Expressions, Regular Grammar and Regular Languages"
},
{
"code": null,
"e": 25965,
"s": 25934,
"text": "Difference between DFA and NFA"
},
{
"code": null,
"e": 25997,
"s": 25965,
"text": "Introduction of Finite Automata"
},
{
"code": null,
"e": 26048,
"s": 25997,
"text": "Difference between Mealy machine and Moore machine"
}
] |
How can we apply AUTO_INCREMENT to a column?
|
AUTO_INCREMENT means that the column will get the value automatically. To illustrate it we have created a table βemployeesβ as follows β
mysql> Show Create Table employees\G
*************************** 1. row ***************************
Table: employees
Create Table: CREATE TABLE `employees` (
`Id` int(11) NOT NULL AUTO_INCREMENT,
`Name` varchar(35) DEFAULT NULL,
PRIMARY KEY (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
1 row in set (0.00 sec)
From the above result set, we can see that column id is given the auto-increment option. Now, when we will insert the value in Name field, the id field will get the values automatically β
mysql> Insert Into employees(Name) Values('Ram');
Query OK, 1 row affected (0.09 sec)
mysql> Insert Into employees(Name) Values('Shyam');
Query OK, 1 row affected (0.03 sec)
mysql> Insert Into employees(Name) Values('Mohan');
Query OK, 1 row affected (0.04 sec)
mysql> Insert Into employees(Name) Values('Sohan');
Query OK, 1 row affected (0.04 sec)
mysql> Select * from employees;
+----+-------+
| Id | Name |
+----+-------+
| 1 | Ram |
| 2 | Shyam |
| 3 | Mohan |
| 4 | Sohan |
+----+-------+
4 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1199,
"s": 1062,
"text": "AUTO_INCREMENT means that the column will get the value automatically. To illustrate it we have created a table βemployeesβ as follows β"
},
{
"code": null,
"e": 1522,
"s": 1199,
"text": "mysql> Show Create Table employees\\G\n\n*************************** 1. row ***************************\nTable: employees\n\nCreate Table: CREATE TABLE `employees` (\n `Id` int(11) NOT NULL AUTO_INCREMENT,\n `Name` varchar(35) DEFAULT NULL,\n PRIMARY KEY (`Id`)\n) ENGINE=InnoDB DEFAULT CHARSET=latin1\n\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 1710,
"s": 1522,
"text": "From the above result set, we can see that column id is given the auto-increment option. Now, when we will insert the value in Name field, the id field will get the values automatically β"
},
{
"code": null,
"e": 2243,
"s": 1710,
"text": "mysql> Insert Into employees(Name) Values('Ram');\nQuery OK, 1 row affected (0.09 sec)\n\nmysql> Insert Into employees(Name) Values('Shyam');\nQuery OK, 1 row affected (0.03 sec)\n\nmysql> Insert Into employees(Name) Values('Mohan');\nQuery OK, 1 row affected (0.04 sec)\n\nmysql> Insert Into employees(Name) Values('Sohan');\nQuery OK, 1 row affected (0.04 sec)\n\nmysql> Select * from employees;\n\n+----+-------+\n| Id | Name |\n+----+-------+\n| 1 | Ram |\n| 2 | Shyam |\n| 3 | Mohan |\n| 4 | Sohan |\n+----+-------+\n\n4 rows in set (0.00 sec)"
}
] |
How to import csv file data from Github in R?
|
If you have a csv file on Github then it can be directly imported in R by using its URL but make sure that you click on Raw option on Github page where the data is stored. Many people do not click on Raw option therefore they read HTML instead of CSV and get confused. Here, I am sharing a public data set that contains the list of data sets. This data set has 12 variables. Now letβs import it β
> Data<-read.csv("https://raw.githubusercontent.com/curran/data/gh-pages/dataSoup/datasets.csv")
> str(Data)
'data.frame': 57 obs. of 12 variables:
$ Dataset.Name : Factor w/ 57 levels " ","2008 Election Results",..: 2 33 32 36 52 49 50 23 25 41 ...
$ Person.Adding : Factor w/ 11 levels "Curran","EJ",..: 2 2 2 6 6 6 6 6 6 6 ...
$ Date.Added : Factor w/ 14 levels "1/1/2013","11/7/2012",..: 2 2 2 2 2 2 2 2 2 2 ...
$ Dataset.Link : Factor w/ 57 levels "ask Jan...","http://api.occupy-data.org/v1/",..: 35 38 2 8 15 42 40 39 22 28 ...
$ Most.Recent.Year.in.Data: Factor w/ 9 levels "","2007","2008",..: 3 6 5 6 6 4 2 5 6 5 ...
$ Earliest.Year.In.Data : int NA NA 2003 1789 1996 1946 1960 1989 2000 2000 ...
$ Status : Factor w/ 6 levels "","much talked about",..: 5 5 5 5 5 5 5 5 5 5 ...
$ Dataset.Type : Factor w/ 8 levels "","API","Dataset",..: 3 3 2 3 3 3 3 1 1 5 ...
$ Documentation : Factor w/ 18 levels "","http://data.gov/metric",..: 1 1 17 1 6 3 1 1 1 1 ...
$ Existing.Work : Factor w/ 10 levels "","http://databits.io/challenges/airbnb-user-pathways-challenge",..: 1 1 7 1 1 1 1 1 1 1 ...
$ Tags : Factor w/ 12 levels "","astronomy",..: 11 7 8 9 1 1 1 1 1 2 ...
$ Active : Factor w/ 3 levels "","n","y": 2 2 3 3 2 3 2 2 2 2 ...
> head(Data)
Dataset.Name Person.Adding Date.Added
1 2008 Election Results EJ 11/7/2012
2 Occupy Oakland Finances EJ 11/7/2012
3 NYPD Stop-and-Frisk DB API EJ 11/7/2012
4 Presidential Speech Archive Kai 11/7/2012
5 USDA National Nutrient Database Kai 11/7/2012
6 US Foreign Aid Kai 11/7/2012
Dataset.Link
1 https://docs.google.com/spreadsheet/ccc?key=0ApAkxBfw1JT4dFliRjhYOW5WLXk1WkZfNFFQTGxmSGc#gid=0
2 https://docs.google.com/spreadsheet/pub?key=0ApAkxBfw1JT4dHhNSkpva0RrQUFfcDIyUHl3LWFCVEE&output=html
3 http://api.occupy-data.org/v1/
4 http://millercenter.org/president/speeches
5 http://www.ars.usda.gov/Services/docs.htm?docid=8964
6 https://explore.data.gov/Foreign-Commerce-and-Aid/U-S-Overseas-Loans-and-Grants-Greenbook-/5gah-bvex
Most.Recent.Year.in.Data Earliest.Year.In.Data Status Dataset.Type
1 2008 NA Unused Dataset
2 2012 NA Unused Dataset
3 2011 2003 Unused API
4 2012 1789 Unused Dataset
5 2012 1996 Unused Dataset
6 2010 1946 Unused Dataset
Documentation
1
2
3 https://github.com/stopfrisknyc/docs
4
5 http://www.ars.usda.gov/SP2UserFiles/Place/12354500/Data/SR25/sr25_doc.pdf
6 http://gbk.eads.usaidallnet.gov/about/
Existing.Work
1
2
3 http://www.forbes.com/sites/jasonoberholtzer/2012/07/17/stop-and-frisk-by-the-numbers/,http://www.dnainfo.com/new-york/20120604/new-york-city/port-authority-is-top-stop-and-frisk-hotspot-regardless-of-race
4
5
6
Tags Active
1 state-scale,politics n
2 historical,money n
3 historical,people y
4 historical,text y
5 n
6 y
|
[
{
"code": null,
"e": 1459,
"s": 1062,
"text": "If you have a csv file on Github then it can be directly imported in R by using its URL but make sure that you click on Raw option on Github page where the data is stored. Many people do not click on Raw option therefore they read HTML instead of CSV and get confused. Here, I am sharing a public data set that contains the list of data sets. This data set has 12 variables. Now letβs import it β"
},
{
"code": null,
"e": 4316,
"s": 1459,
"text": "> Data<-read.csv(\"https://raw.githubusercontent.com/curran/data/gh-pages/dataSoup/datasets.csv\")\n\n> str(Data)\n'data.frame': 57 obs. of 12 variables:\n$ Dataset.Name : Factor w/ 57 levels \" \",\"2008 Election Results\",..: 2 33 32 36 52 49 50 23 25 41 ...\n$ Person.Adding : Factor w/ 11 levels \"Curran\",\"EJ\",..: 2 2 2 6 6 6 6 6 6 6 ...\n$ Date.Added : Factor w/ 14 levels \"1/1/2013\",\"11/7/2012\",..: 2 2 2 2 2 2 2 2 2 2 ...\n$ Dataset.Link : Factor w/ 57 levels \"ask Jan...\",\"http://api.occupy-data.org/v1/\",..: 35 38 2 8 15 42 40 39 22 28 ...\n$ Most.Recent.Year.in.Data: Factor w/ 9 levels \"\",\"2007\",\"2008\",..: 3 6 5 6 6 4 2 5 6 5 ...\n$ Earliest.Year.In.Data : int NA NA 2003 1789 1996 1946 1960 1989 2000 2000 ...\n$ Status : Factor w/ 6 levels \"\",\"much talked about\",..: 5 5 5 5 5 5 5 5 5 5 ...\n$ Dataset.Type : Factor w/ 8 levels \"\",\"API\",\"Dataset\",..: 3 3 2 3 3 3 3 1 1 5 ...\n$ Documentation : Factor w/ 18 levels \"\",\"http://data.gov/metric\",..: 1 1 17 1 6 3 1 1 1 1 ...\n$ Existing.Work : Factor w/ 10 levels \"\",\"http://databits.io/challenges/airbnb-user-pathways-challenge\",..: 1 1 7 1 1 1 1 1 1 1 ...\n$ Tags : Factor w/ 12 levels \"\",\"astronomy\",..: 11 7 8 9 1 1 1 1 1 2 ...\n$ Active : Factor w/ 3 levels \"\",\"n\",\"y\": 2 2 3 3 2 3 2 2 2 2 ...\n> head(Data)\nDataset.Name Person.Adding Date.Added\n1 2008 Election Results EJ 11/7/2012\n2 Occupy Oakland Finances EJ 11/7/2012\n3 NYPD Stop-and-Frisk DB API EJ 11/7/2012\n4 Presidential Speech Archive Kai 11/7/2012\n5 USDA National Nutrient Database Kai 11/7/2012\n6 US Foreign Aid Kai 11/7/2012\nDataset.Link\n1 https://docs.google.com/spreadsheet/ccc?key=0ApAkxBfw1JT4dFliRjhYOW5WLXk1WkZfNFFQTGxmSGc#gid=0\n2 https://docs.google.com/spreadsheet/pub?key=0ApAkxBfw1JT4dHhNSkpva0RrQUFfcDIyUHl3LWFCVEE&output=html\n3 http://api.occupy-data.org/v1/\n4 http://millercenter.org/president/speeches\n5 http://www.ars.usda.gov/Services/docs.htm?docid=8964\n6 https://explore.data.gov/Foreign-Commerce-and-Aid/U-S-Overseas-Loans-and-Grants-Greenbook-/5gah-bvex\nMost.Recent.Year.in.Data Earliest.Year.In.Data Status Dataset.Type\n1 2008 NA Unused Dataset\n2 2012 NA Unused Dataset\n3 2011 2003 Unused API\n4 2012 1789 Unused Dataset\n5 2012 1996 Unused Dataset\n6 2010 1946 Unused Dataset\n Documentation\n1\n2\n3 https://github.com/stopfrisknyc/docs\n4\n5 http://www.ars.usda.gov/SP2UserFiles/Place/12354500/Data/SR25/sr25_doc.pdf\n6 http://gbk.eads.usaidallnet.gov/about/\nExisting.Work\n1\n2\n3 http://www.forbes.com/sites/jasonoberholtzer/2012/07/17/stop-and-frisk-by-the-numbers/,http://www.dnainfo.com/new-york/20120604/new-york-city/port-authority-is-top-stop-and-frisk-hotspot-regardless-of-race\n4\n5\n6\nTags Active\n1 state-scale,politics n\n2 historical,money n\n3 historical,people y\n4 historical,text y\n5 n\n6 y"
}
] |
Ant - Building Projects
|
Now that we have learnt about the data types in Ant, it is time to put that knowledge into action. We will build a project in this chapter. The aim of this chapter is to build an Ant file that compiles the java classes and places them in the WEB-INF\classes folder.
Consider the following project structure β
The database scripts are stored in the db folder.
The database scripts are stored in the db folder.
The java source code is stored in the src folder.
The java source code is stored in the src folder.
The images, js, META-INF, styles (css) are stored in the war folder.
The images, js, META-INF, styles (css) are stored in the war folder.
The JSPs are stored in the jsp folder.
The JSPs are stored in the jsp folder.
The third party jar files are stored in the lib folder.
The third party jar files are stored in the lib folder.
The java class files are stored in the WEB-INF\classes folder.
The java class files are stored in the WEB-INF\classes folder.
This project forms the Hello World Fax Application for the rest of this tutorial.
C:\work\FaxWebApplication>tree
Folder PATH listing
Volume serial number is 00740061 EC1C:ADB1
C:.
+---db
+---src
. +---faxapp
. +---dao
. +---entity
. +---util
. +---web
+---war
+---images
+---js
+---META-INF
+---styles
+---WEB-INF
+---classes
+---jsp
+---lib
Here is the build.xml required for this project. Let us consider it piece by piece.
<?xml version = "1.0"?>
<project name = "fax" basedir = "." default = "build">
<property name = "src.dir" value = "src"/>
<property name = "web.dir" value = "war"/>
<property name = "build.dir" value = "${web.dir}/WEB-INF/classes"/>
<property name = "name" value = "fax"/>
<path id = "master-classpath">
<fileset dir = "${web.dir}/WEB-INF/lib">
<include name = "*.jar"/>
</fileset>
<pathelement path = "${build.dir}"/>
</path>
<target name = "build" description = "Compile source tree java files">
<mkdir dir = "${build.dir}"/>
<javac destdir = "${build.dir}" source = "1.5" target = "1.5">
<src path = "${src.dir}"/>
<classpath refid = "master-classpath"/>
</javac>
</target>
<target name = "clean" description = "Clean output directories">
<delete>
<fileset dir = "${build.dir}">
<include name = "**/*.class"/>
</fileset>
</delete>
</target>
</project>
First, let us declare some properties for the source, web, and build folders.
<property name = "src.dir" value = "src"/>
<property name = "web.dir" value = "war"/>
<property name = "build.dir" value = "${web.dir}/WEB-INF/classes"/>
In this example β
src.dir refers to the source folder of the project where the java source files can be found.
src.dir refers to the source folder of the project where the java source files can be found.
web.dir refers to the web source folder of the project, where you can find the JSPs, web.xml, css, javascript and other web related files
web.dir refers to the web source folder of the project, where you can find the JSPs, web.xml, css, javascript and other web related files
build.dir refers to the output folder of the project compilation.
build.dir refers to the output folder of the project compilation.
Properties can refer to other properties. As shown in the above example, the build.dir property makes a reference to the web.dir property.
In this example, the src.dir refers to the source folder of the project.
The default target of our project is the compile target. But first let us look at the clean target.
The clean target, as the name suggests, deletes the files in the build folder.
<target name = "clean" description = "Clean output directories">
<delete>
<fileset dir = "${build.dir}">
<include name = "**/*.class"/>
</fileset>
</delete>
</target>
The master-classpath holds the classpath information. In this case, it includes the classes in the build folder and the jar files in the lib folder.
<path id = "master-classpath">
<fileset dir = "${web.dir}/WEB-INF/lib">
<include name = "*.jar"/>
</fileset>
<pathelement path = "${build.dir}"/>
</path>
Finally, the build target to build the files. First of all, we create the build directory, if it does not exist. Then we execute the javac command (specifying jdk1.5 as our target compilation). We supply the source folder and the classpath to the javac task and ask it to drop the class files in the build folder.
<target name = "build" description = "Compile main source tree java files">
<mkdir dir = "${build.dir}"/>
<javac destdir = "${build.dir}" source = "1.5" target = "1.5" debug = "true"
deprecation = "false" optimize = "false" failonerror = "true">
<src path = "${src.dir}"/>
<classpath refid = "master-classpath"/>
</javac>
</target>
Executing Ant on this file compiles the java source files and places the classes in the build folder.
The following outcome is the result of running the Ant file β
C:\>ant
Buildfile: C:\build.xml
BUILD SUCCESSFUL
Total time: 6.3 seconds
The files are compiled and placed in the build.dir folder.
20 Lectures
2 hours
Deepti Trivedi
19 Lectures
2.5 hours
Deepti Trivedi
139 Lectures
14 hours
Er. Himanshu Vasishta
30 Lectures
1.5 hours
Pushpendu Mondal
65 Lectures
6.5 hours
Ridhi Arora
10 Lectures
2 hours
Manish Gupta
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2363,
"s": 2097,
"text": "Now that we have learnt about the data types in Ant, it is time to put that knowledge into action. We will build a project in this chapter. The aim of this chapter is to build an Ant file that compiles the java classes and places them in the WEB-INF\\classes folder."
},
{
"code": null,
"e": 2406,
"s": 2363,
"text": "Consider the following project structure β"
},
{
"code": null,
"e": 2456,
"s": 2406,
"text": "The database scripts are stored in the db folder."
},
{
"code": null,
"e": 2506,
"s": 2456,
"text": "The database scripts are stored in the db folder."
},
{
"code": null,
"e": 2556,
"s": 2506,
"text": "The java source code is stored in the src folder."
},
{
"code": null,
"e": 2606,
"s": 2556,
"text": "The java source code is stored in the src folder."
},
{
"code": null,
"e": 2675,
"s": 2606,
"text": "The images, js, META-INF, styles (css) are stored in the war folder."
},
{
"code": null,
"e": 2744,
"s": 2675,
"text": "The images, js, META-INF, styles (css) are stored in the war folder."
},
{
"code": null,
"e": 2783,
"s": 2744,
"text": "The JSPs are stored in the jsp folder."
},
{
"code": null,
"e": 2822,
"s": 2783,
"text": "The JSPs are stored in the jsp folder."
},
{
"code": null,
"e": 2878,
"s": 2822,
"text": "The third party jar files are stored in the lib folder."
},
{
"code": null,
"e": 2934,
"s": 2878,
"text": "The third party jar files are stored in the lib folder."
},
{
"code": null,
"e": 2997,
"s": 2934,
"text": "The java class files are stored in the WEB-INF\\classes folder."
},
{
"code": null,
"e": 3060,
"s": 2997,
"text": "The java class files are stored in the WEB-INF\\classes folder."
},
{
"code": null,
"e": 3142,
"s": 3060,
"text": "This project forms the Hello World Fax Application for the rest of this tutorial."
},
{
"code": null,
"e": 3441,
"s": 3142,
"text": "C:\\work\\FaxWebApplication>tree\nFolder PATH listing\nVolume serial number is 00740061 EC1C:ADB1\nC:.\n+---db\n+---src\n. +---faxapp\n. +---dao\n. +---entity\n. +---util\n. +---web\n+---war\n +---images\n +---js\n +---META-INF\n +---styles\n +---WEB-INF\n +---classes\n +---jsp\n +---lib\n"
},
{
"code": null,
"e": 3525,
"s": 3441,
"text": "Here is the build.xml required for this project. Let us consider it piece by piece."
},
{
"code": null,
"e": 4533,
"s": 3525,
"text": "<?xml version = \"1.0\"?>\n<project name = \"fax\" basedir = \".\" default = \"build\">\n <property name = \"src.dir\" value = \"src\"/>\n <property name = \"web.dir\" value = \"war\"/>\n <property name = \"build.dir\" value = \"${web.dir}/WEB-INF/classes\"/>\n <property name = \"name\" value = \"fax\"/>\n\n <path id = \"master-classpath\">\n <fileset dir = \"${web.dir}/WEB-INF/lib\">\n <include name = \"*.jar\"/>\n </fileset>\n \n <pathelement path = \"${build.dir}\"/>\n </path>\n\n <target name = \"build\" description = \"Compile source tree java files\">\n <mkdir dir = \"${build.dir}\"/>\n \n <javac destdir = \"${build.dir}\" source = \"1.5\" target = \"1.5\">\n <src path = \"${src.dir}\"/>\n <classpath refid = \"master-classpath\"/>\n </javac>\n </target>\n \n <target name = \"clean\" description = \"Clean output directories\">\n <delete>\n <fileset dir = \"${build.dir}\">\n <include name = \"**/*.class\"/>\n </fileset>\n </delete>\n </target>\n</project>"
},
{
"code": null,
"e": 4611,
"s": 4533,
"text": "First, let us declare some properties for the source, web, and build folders."
},
{
"code": null,
"e": 4765,
"s": 4611,
"text": "<property name = \"src.dir\" value = \"src\"/>\n<property name = \"web.dir\" value = \"war\"/>\n<property name = \"build.dir\" value = \"${web.dir}/WEB-INF/classes\"/>"
},
{
"code": null,
"e": 4783,
"s": 4765,
"text": "In this example β"
},
{
"code": null,
"e": 4876,
"s": 4783,
"text": "src.dir refers to the source folder of the project where the java source files can be found."
},
{
"code": null,
"e": 4969,
"s": 4876,
"text": "src.dir refers to the source folder of the project where the java source files can be found."
},
{
"code": null,
"e": 5107,
"s": 4969,
"text": "web.dir refers to the web source folder of the project, where you can find the JSPs, web.xml, css, javascript and other web related files"
},
{
"code": null,
"e": 5245,
"s": 5107,
"text": "web.dir refers to the web source folder of the project, where you can find the JSPs, web.xml, css, javascript and other web related files"
},
{
"code": null,
"e": 5311,
"s": 5245,
"text": "build.dir refers to the output folder of the project compilation."
},
{
"code": null,
"e": 5377,
"s": 5311,
"text": "build.dir refers to the output folder of the project compilation."
},
{
"code": null,
"e": 5516,
"s": 5377,
"text": "Properties can refer to other properties. As shown in the above example, the build.dir property makes a reference to the web.dir property."
},
{
"code": null,
"e": 5589,
"s": 5516,
"text": "In this example, the src.dir refers to the source folder of the project."
},
{
"code": null,
"e": 5689,
"s": 5589,
"text": "The default target of our project is the compile target. But first let us look at the clean target."
},
{
"code": null,
"e": 5768,
"s": 5689,
"text": "The clean target, as the name suggests, deletes the files in the build folder."
},
{
"code": null,
"e": 5962,
"s": 5768,
"text": "<target name = \"clean\" description = \"Clean output directories\">\n <delete>\n <fileset dir = \"${build.dir}\">\n <include name = \"**/*.class\"/>\n </fileset>\n </delete>\n</target>"
},
{
"code": null,
"e": 6111,
"s": 5962,
"text": "The master-classpath holds the classpath information. In this case, it includes the classes in the build folder and the jar files in the lib folder."
},
{
"code": null,
"e": 6284,
"s": 6111,
"text": "<path id = \"master-classpath\">\n <fileset dir = \"${web.dir}/WEB-INF/lib\">\n <include name = \"*.jar\"/>\n </fileset>\n \n <pathelement path = \"${build.dir}\"/>\n</path>"
},
{
"code": null,
"e": 6598,
"s": 6284,
"text": "Finally, the build target to build the files. First of all, we create the build directory, if it does not exist. Then we execute the javac command (specifying jdk1.5 as our target compilation). We supply the source folder and the classpath to the javac task and ask it to drop the class files in the build folder."
},
{
"code": null,
"e": 6961,
"s": 6598,
"text": "<target name = \"build\" description = \"Compile main source tree java files\">\n <mkdir dir = \"${build.dir}\"/>\n \n <javac destdir = \"${build.dir}\" source = \"1.5\" target = \"1.5\" debug = \"true\"\n deprecation = \"false\" optimize = \"false\" failonerror = \"true\">\n <src path = \"${src.dir}\"/>\n <classpath refid = \"master-classpath\"/>\n </javac>\n</target>"
},
{
"code": null,
"e": 7063,
"s": 6961,
"text": "Executing Ant on this file compiles the java source files and places the classes in the build folder."
},
{
"code": null,
"e": 7125,
"s": 7063,
"text": "The following outcome is the result of running the Ant file β"
},
{
"code": null,
"e": 7200,
"s": 7125,
"text": "C:\\>ant\nBuildfile: C:\\build.xml\n\nBUILD SUCCESSFUL\nTotal time: 6.3 seconds\n"
},
{
"code": null,
"e": 7259,
"s": 7200,
"text": "The files are compiled and placed in the build.dir folder."
},
{
"code": null,
"e": 7292,
"s": 7259,
"text": "\n 20 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 7308,
"s": 7292,
"text": " Deepti Trivedi"
},
{
"code": null,
"e": 7343,
"s": 7308,
"text": "\n 19 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 7359,
"s": 7343,
"text": " Deepti Trivedi"
},
{
"code": null,
"e": 7394,
"s": 7359,
"text": "\n 139 Lectures \n 14 hours \n"
},
{
"code": null,
"e": 7417,
"s": 7394,
"text": " Er. Himanshu Vasishta"
},
{
"code": null,
"e": 7452,
"s": 7417,
"text": "\n 30 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 7470,
"s": 7452,
"text": " Pushpendu Mondal"
},
{
"code": null,
"e": 7505,
"s": 7470,
"text": "\n 65 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 7518,
"s": 7505,
"text": " Ridhi Arora"
},
{
"code": null,
"e": 7551,
"s": 7518,
"text": "\n 10 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 7565,
"s": 7551,
"text": " Manish Gupta"
},
{
"code": null,
"e": 7572,
"s": 7565,
"text": " Print"
},
{
"code": null,
"e": 7583,
"s": 7572,
"text": " Add Notes"
}
] |
HTML5 - time
|
A time (hour, minute, seconds, fractional seconds) encoded according to ISO 8601.
<!DOCTYPE HTML>
<html>
<body>
<form action = "/cgi-bin/html5.cgi" method = "get">
Time : <input type = "time" name = "newinput" />
<input type = "submit" value = "submit" />
</form>
</body>
</html>
19 Lectures
2 hours
Anadi Sharma
16 Lectures
1.5 hours
Anadi Sharma
18 Lectures
1.5 hours
Frahaan Hussain
57 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
54 Lectures
6 hours
DigiFisk (Programming Is Fun)
45 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2690,
"s": 2608,
"text": "A time (hour, minute, seconds, fractional seconds) encoded according to ISO 8601."
},
{
"code": null,
"e": 2927,
"s": 2690,
"text": "<!DOCTYPE HTML>\n\n<html>\n <body>\n\n <form action = \"/cgi-bin/html5.cgi\" method = \"get\">\n Time : <input type = \"time\" name = \"newinput\" />\n <input type = \"submit\" value = \"submit\" />\n </form>\n\n </body>\n</html>"
},
{
"code": null,
"e": 2960,
"s": 2927,
"text": "\n 19 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 2974,
"s": 2960,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3009,
"s": 2974,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3023,
"s": 3009,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3058,
"s": 3023,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3075,
"s": 3058,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3110,
"s": 3075,
"text": "\n 57 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3141,
"s": 3110,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3174,
"s": 3141,
"text": "\n 54 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3205,
"s": 3174,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3240,
"s": 3205,
"text": "\n 45 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3271,
"s": 3240,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3278,
"s": 3271,
"text": " Print"
},
{
"code": null,
"e": 3289,
"s": 3278,
"text": " Add Notes"
}
] |
Sentiment Analysis β Comparing 3 Common Approaches: Naive Bayes, LSTM, and VADER | by Kevin C Lee | Towards Data Science
|
Note: The code for this post can be found here
Sentiment Analysis, or Opinion Mining, is a subfield of NLP (Natural Language Processing) that aims to extract attitudes, appraisals, opinions, and emotions from text. Inspired by the rapid migration of customer interactions to digital formats e.g. emails, chat rooms, social media posts, comments, reviews, and surveys, Sentiment Analysis has become an integral part of analytics organizations must perform to understand how they are positioned in the market. To be clear, Sentiment Analysis isnβt a novel concept. In fact, it has always been an important part of CRM (Customer Relationship Management) and Market Research β companies rely on knowing their customers better to evolve and innovate. The more recent rise is driven largely by the availability/accessibility of customer interaction records and well as improved computing capabilities to process these data. This advancement has really benefited consumers in meaningful ways. More than ever, organizations are listening to their constituents to improve. There are numerous approaches for Sentiment Analysis. In this article, weβll explore three such approaches: 1) Naive Bayes, 2) Deep Learning LSTM, and 3) Pre-Trained Rule-Based VADER Models. We will focus on comparing simple out-of-the-box version of the models with the recognition that each approach can be tuned to improve performance. The intention is not to go into great details about how each methodology works but rather a conceptual study on how they compare to help determine when one should be preferred over another.
The objective of Sentiment Analysis ranges on the positive to negative spectrum. As with other NLP efforts, it is generally considered a classification problem, though it can be viewed as a regression problem when precision is important. Sentiment Analysis used to be accomplished by having a large labor force to read through and manually assess texts. This approach is costly and prone to human error. In an effort to automate this process, companies look to advanced analytical methods for solving this problem. The challenge with Sentiment Analysis is that people express and interpret sentiment polarity and intensity differently. Furthermore, words and sentences can have multiple meanings based on the context (known as polysemy). While some of these issues can be mitigated, there is almost always a trade-off between speed and performance like any analytical tasks. We review three general methodologies, each with its own strengths and drawbacks:
In addition to highlighting conceptual differences, we use the Sentiment140 data set to benchmark performances. This data set contains 1.6 million tweets and the corresponding sentiment labels (positive and negative).
We begin with an easy to apply approach using the popular VADER (Valence Aware Dictionary and sEntiment Reasoner) tool. At its core, VADER uses a comprehensive, high quality lexicon (~7500 features) and sophisticated linguistic rules to produce sentiment scores. The construction and validation (statistically) of the sentiment dictionary is carefully documented in its published paper β this huge achievement cannot be overstated.
// vader_lexicon.txt...good: 1.9happy 2.7awesome 3.1bad -2.5sad -2.1catastrophic -2.2...
As the above sample shows, the VADER lexicon is a dictionary that assigns a predetermined sentiment score between -4 (most extreme negative) and 4 (most extreme positive) to each feature, which can be a word, an acronym, or an emoticon. VADER curated a valence-based lexicon capable of detecting both the intensity and polarity aspects of sentiments. This combined with powerful modifiers such as negations, contractions, conjunctions, booster words, degree adverbs, capitalization, punctuations, and slangs, are used to calculate scores for the input text(s). These modifiers are implemented as a Rule-Based model that changes the initial valence scores. The generous developers of VADER made it open source and easy to use:
# import SentimentIntensityAnalyzer class from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer# polarity_scores method of SentimentIntensityAnalyzerSentimentIntensityAnalyzer().polarity_scores('Today is a good day.')# output: # {'neg': 0.0, 'neu': 0.58, 'pos': 0.42, 'compound': 0.4404}
VADER produces a compound score that summarizes the sentiment intensity of the input text. It is computed by summing the valence scores of each feature in the lexicon, adjusted according to the rules, and then normalized to be between -1 (most extreme negative) and +1 (most extreme positive). The documentation describes the compound score as the βnormalized, weighted composite scoreβ. Furthermore, the pos, neg, neu scores represent the ratios for proportions of text that fall in each category (ex. Rule-Based enhancements).
Rule-Based models are easily understood and quick to implement, making it an attractive option for Sentiment Analysis. They are contingent on having a powerful lexicon and comprehensive linguistic rules. The challenge with Rule-Based models is that lexicons are time-consuming to create and validate. They struggle with coverage across endless combination of lexical features that can be important, as well as suitability issues across domains when words have different meanings. Furthermore, the approach only evaluates individual words and ignores the context in which they are used. This often leads to errors, particularly for sarcasm and irony.
Using VADER β we were able to produce an accuracy score of 72% on our test data set. VADER considers emoticons and acronyms/initialisms commonly found in social media text so it can be performant in the domain, but will likely perform worse in others. Important to note that VADER does produces precise polarity scores, which we categorize as positive or negative for comparison purposes.
P.S. Other lexicons include LIWC (Linguistic Inquiry and Word Count) and ANEW (Affective Norms for English Words).
While Rule-Based solutions have proved to be performant and reliable, it is rigid and limited by a lexicon that could expire. Manually creating and validating a comprehensive sentiment lexicon is difficult. Instead, we want to move towards a Machine Learning solution that associates input texts to corresponding tags algorithmically. During the training process, pairs of texts and tags (sentiments) are fed into the Machine Learning algorithm to create a model capable of making predictions on new texts. An important caution worth mentioning is that supervised Machine Learning requires data to be labelled, which can mean that any subjectivity and bias in the data would be reflected in the model. Compared to pre-trained models, custom models give more control over the output and are suitable for applications that are specific.
The Naive Bayes classifier uses probabilities to make predictions based on prior knowledge of conditions that might be related. In other words, it uses conditional probabilities of each lexical feature occurring in either positive or negative text in the training data to arrive at the outcome.
Machine Learning for NLP requires preprocessing to extract features from the original text(s). Specifically, it requires transformation of text data to numerical representations before the algorithms can process them, i.e. vectorization. For Naive Bayes, we will construct a simple DTM (document-term matrix) for model consumption although additional features can be included such as length of text, time/location of publication, named entities, etc. DTM tends to result in a wide feature space as each unique word or phrase in the vocabulary of the entire corpus becomes a feature. We include some data cleaning steps to help with dimensionality reduction and model (classifiers) performance. More about data preprocessing for NLP can be found here. The vector representation is constructed by counting the TF (Term Frequency) and weighting them with IDF (Inverse Document Frequency). We can use N-grams (consecutive terms) to capture some context in the text such as negations. N-gram contexts are a blunt instrument and canβt always capture expressions correctly. They can also negatively impact the model by burdening it with too many features.
We apply the following transformation to generate the training/testing data:
The Naive Bayes model uses features that are reasonably easy to understand. It supports large-scale Sentiment Analysis efforts since the computation required for training is fast. However, it does have some significant drawbacks. As a probabilistic classifier, it is highly reliant on priors so the training data has to be complete and representative. The lack of good training data leads to poor inference on unseen data or out-of-vocabulary texts. It can also suffer if there is bias or imbalance in the data. Furthermore, it assumes that features are independent of one another, which means that the lexical features in the DTM contribute equally throughout all sentences, regardless of the relative position in the text. The Naive Bayes DTM model (with 300K unigram and bigram features) trained quickly (< 7 minutes). It produced a training score of 86% accuracy and testing /validation score of 79% accuracy.
For longer and wider data sets, Spark can be used to train the model quickly using the code here.
Deep Learning allows for processing data in a much more complex manner. A Long Short-Term Memory model, or LSTM, is a type of Recurrent Neural Network (RNN) used to process temporal data. Since we think that the order of features (words) in a sentence is significant, this is the neural network architecture we use.
Deep Learning is computationally expensive and do not do well (poor performance and slow convergence) with high-dimensional, sparse vectors. When we extract features from the original text for model training, we need to represent them as vectors that are dense. One such technique is to convert each text into a sequence of numbers, where each number is mapped to a word in the vocabulary. Taking it a step further, we need to map words that have similar usage/meaning to similar real number vectors (rather than an index) using Word Embeddings. Without Word Embeddings, the model will misinterpret the index number of the words as having significance. Word Embeddings put all words into a multi-dimensional vector space so their similarities can be measured by distance. Generating Word Embeddings is done using open source pre-trained models (such as Word2vec, GloVe, or fastText) or custom neural network (unsupervised learning) models. When training custom Word Embeddings, it can be done separately or jointly with the neural network model of the task at hand (as an addition layer). This is the approach we take as it tends to lead to embeddings that are targeted to the context of data as well as the objective. In contrast to a document-term matrix that is sparse (hundreds of thousands of dimension), using Word Embeddings produces vectors that have fewer (hundreds) dimensions while capturing semantic similarities. Word Embeddings is considered one of the key breakthroughs of Deep Learning for challenging NLP problems.
We apply the following transformation to generate the training/testing data:
One big advantage for the Deep Learning neural network approach is that we donβt have to try and engineer features since the neural network will learn the context and important features. However, this comes at the cost of interpretability β making it a significant limitation in some cases. Additionally, it is the most expensive approach in terms of the time to compute, particularly if Word Embeddings are jointly trained since it requires a large data set. For our data set, the Word Embedding LSTM model (with 61MM parameters) took 20 hours to train. It did produce a remarkable training score of 96% accuracy and testing/validation score of 80% accuracy.
When done correctly, Sentiment Analysis can provide tremendous value for any organization. Today, organizations use Sentiment Analysis to understand the publicβs feelings towards their products, services, and brand. This can guide marketing strategies, inspire product development, inform political campaigns, and detect potentially damaging events. Below are some proven examples:
Identify potential detractors for prioritization to improve Net Promoter Score (NPS) (Customer Care/Feedback Analytics)
Evaluate customer engagements quickly to identify and resolve negative customer experiences, which translates to improved customer service and higher rate of returning customers (Ticket Triaging)
Monitor and manage public sentiment about the brand (Brand Intelligence)
We reviewed three approaches for Sentiment Analysis, each with its own strengths and drawbacks. When is comes to choosing the appropriate approach, there are some key things to consider:
What is the tolerance for accuracy and/or speed? If speed is prioritized over accuracy, Rule-Based solutions can be the right solution.
Availability and completeness of data for training? With robust training data, a Naive Bayes model can be the right solution as it is fast to implement.
How important is model interpretability? Deep Learning can be the right solution if accuracy is prioritized over model interpretability.
It is not uncommon to run multiple models in parallel for comparison. Once deployed, the process should include a feedback loop to inform when the models need to be updated.
Iβm also working on sharing the code for how to train NLP models faster with parallel computing. If you enjoyed the article, I invite you to follow me so you can be notified for the continuation of this project.
|
[
{
"code": null,
"e": 219,
"s": 172,
"text": "Note: The code for this post can be found here"
},
{
"code": null,
"e": 1765,
"s": 219,
"text": "Sentiment Analysis, or Opinion Mining, is a subfield of NLP (Natural Language Processing) that aims to extract attitudes, appraisals, opinions, and emotions from text. Inspired by the rapid migration of customer interactions to digital formats e.g. emails, chat rooms, social media posts, comments, reviews, and surveys, Sentiment Analysis has become an integral part of analytics organizations must perform to understand how they are positioned in the market. To be clear, Sentiment Analysis isnβt a novel concept. In fact, it has always been an important part of CRM (Customer Relationship Management) and Market Research β companies rely on knowing their customers better to evolve and innovate. The more recent rise is driven largely by the availability/accessibility of customer interaction records and well as improved computing capabilities to process these data. This advancement has really benefited consumers in meaningful ways. More than ever, organizations are listening to their constituents to improve. There are numerous approaches for Sentiment Analysis. In this article, weβll explore three such approaches: 1) Naive Bayes, 2) Deep Learning LSTM, and 3) Pre-Trained Rule-Based VADER Models. We will focus on comparing simple out-of-the-box version of the models with the recognition that each approach can be tuned to improve performance. The intention is not to go into great details about how each methodology works but rather a conceptual study on how they compare to help determine when one should be preferred over another."
},
{
"code": null,
"e": 2722,
"s": 1765,
"text": "The objective of Sentiment Analysis ranges on the positive to negative spectrum. As with other NLP efforts, it is generally considered a classification problem, though it can be viewed as a regression problem when precision is important. Sentiment Analysis used to be accomplished by having a large labor force to read through and manually assess texts. This approach is costly and prone to human error. In an effort to automate this process, companies look to advanced analytical methods for solving this problem. The challenge with Sentiment Analysis is that people express and interpret sentiment polarity and intensity differently. Furthermore, words and sentences can have multiple meanings based on the context (known as polysemy). While some of these issues can be mitigated, there is almost always a trade-off between speed and performance like any analytical tasks. We review three general methodologies, each with its own strengths and drawbacks:"
},
{
"code": null,
"e": 2940,
"s": 2722,
"text": "In addition to highlighting conceptual differences, we use the Sentiment140 data set to benchmark performances. This data set contains 1.6 million tweets and the corresponding sentiment labels (positive and negative)."
},
{
"code": null,
"e": 3372,
"s": 2940,
"text": "We begin with an easy to apply approach using the popular VADER (Valence Aware Dictionary and sEntiment Reasoner) tool. At its core, VADER uses a comprehensive, high quality lexicon (~7500 features) and sophisticated linguistic rules to produce sentiment scores. The construction and validation (statistically) of the sentiment dictionary is carefully documented in its published paper β this huge achievement cannot be overstated."
},
{
"code": null,
"e": 3461,
"s": 3372,
"text": "// vader_lexicon.txt...good: 1.9happy 2.7awesome 3.1bad -2.5sad -2.1catastrophic -2.2..."
},
{
"code": null,
"e": 4187,
"s": 3461,
"text": "As the above sample shows, the VADER lexicon is a dictionary that assigns a predetermined sentiment score between -4 (most extreme negative) and 4 (most extreme positive) to each feature, which can be a word, an acronym, or an emoticon. VADER curated a valence-based lexicon capable of detecting both the intensity and polarity aspects of sentiments. This combined with powerful modifiers such as negations, contractions, conjunctions, booster words, degree adverbs, capitalization, punctuations, and slangs, are used to calculate scores for the input text(s). These modifiers are implemented as a Rule-Based model that changes the initial valence scores. The generous developers of VADER made it open source and easy to use:"
},
{
"code": null,
"e": 4490,
"s": 4187,
"text": "# import SentimentIntensityAnalyzer class from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer# polarity_scores method of SentimentIntensityAnalyzerSentimentIntensityAnalyzer().polarity_scores('Today is a good day.')# output: # {'neg': 0.0, 'neu': 0.58, 'pos': 0.42, 'compound': 0.4404}"
},
{
"code": null,
"e": 5019,
"s": 4490,
"text": "VADER produces a compound score that summarizes the sentiment intensity of the input text. It is computed by summing the valence scores of each feature in the lexicon, adjusted according to the rules, and then normalized to be between -1 (most extreme negative) and +1 (most extreme positive). The documentation describes the compound score as the βnormalized, weighted composite scoreβ. Furthermore, the pos, neg, neu scores represent the ratios for proportions of text that fall in each category (ex. Rule-Based enhancements)."
},
{
"code": null,
"e": 5669,
"s": 5019,
"text": "Rule-Based models are easily understood and quick to implement, making it an attractive option for Sentiment Analysis. They are contingent on having a powerful lexicon and comprehensive linguistic rules. The challenge with Rule-Based models is that lexicons are time-consuming to create and validate. They struggle with coverage across endless combination of lexical features that can be important, as well as suitability issues across domains when words have different meanings. Furthermore, the approach only evaluates individual words and ignores the context in which they are used. This often leads to errors, particularly for sarcasm and irony."
},
{
"code": null,
"e": 6058,
"s": 5669,
"text": "Using VADER β we were able to produce an accuracy score of 72% on our test data set. VADER considers emoticons and acronyms/initialisms commonly found in social media text so it can be performant in the domain, but will likely perform worse in others. Important to note that VADER does produces precise polarity scores, which we categorize as positive or negative for comparison purposes."
},
{
"code": null,
"e": 6173,
"s": 6058,
"text": "P.S. Other lexicons include LIWC (Linguistic Inquiry and Word Count) and ANEW (Affective Norms for English Words)."
},
{
"code": null,
"e": 7008,
"s": 6173,
"text": "While Rule-Based solutions have proved to be performant and reliable, it is rigid and limited by a lexicon that could expire. Manually creating and validating a comprehensive sentiment lexicon is difficult. Instead, we want to move towards a Machine Learning solution that associates input texts to corresponding tags algorithmically. During the training process, pairs of texts and tags (sentiments) are fed into the Machine Learning algorithm to create a model capable of making predictions on new texts. An important caution worth mentioning is that supervised Machine Learning requires data to be labelled, which can mean that any subjectivity and bias in the data would be reflected in the model. Compared to pre-trained models, custom models give more control over the output and are suitable for applications that are specific."
},
{
"code": null,
"e": 7303,
"s": 7008,
"text": "The Naive Bayes classifier uses probabilities to make predictions based on prior knowledge of conditions that might be related. In other words, it uses conditional probabilities of each lexical feature occurring in either positive or negative text in the training data to arrive at the outcome."
},
{
"code": null,
"e": 8452,
"s": 7303,
"text": "Machine Learning for NLP requires preprocessing to extract features from the original text(s). Specifically, it requires transformation of text data to numerical representations before the algorithms can process them, i.e. vectorization. For Naive Bayes, we will construct a simple DTM (document-term matrix) for model consumption although additional features can be included such as length of text, time/location of publication, named entities, etc. DTM tends to result in a wide feature space as each unique word or phrase in the vocabulary of the entire corpus becomes a feature. We include some data cleaning steps to help with dimensionality reduction and model (classifiers) performance. More about data preprocessing for NLP can be found here. The vector representation is constructed by counting the TF (Term Frequency) and weighting them with IDF (Inverse Document Frequency). We can use N-grams (consecutive terms) to capture some context in the text such as negations. N-gram contexts are a blunt instrument and canβt always capture expressions correctly. They can also negatively impact the model by burdening it with too many features."
},
{
"code": null,
"e": 8529,
"s": 8452,
"text": "We apply the following transformation to generate the training/testing data:"
},
{
"code": null,
"e": 9443,
"s": 8529,
"text": "The Naive Bayes model uses features that are reasonably easy to understand. It supports large-scale Sentiment Analysis efforts since the computation required for training is fast. However, it does have some significant drawbacks. As a probabilistic classifier, it is highly reliant on priors so the training data has to be complete and representative. The lack of good training data leads to poor inference on unseen data or out-of-vocabulary texts. It can also suffer if there is bias or imbalance in the data. Furthermore, it assumes that features are independent of one another, which means that the lexical features in the DTM contribute equally throughout all sentences, regardless of the relative position in the text. The Naive Bayes DTM model (with 300K unigram and bigram features) trained quickly (< 7 minutes). It produced a training score of 86% accuracy and testing /validation score of 79% accuracy."
},
{
"code": null,
"e": 9541,
"s": 9443,
"text": "For longer and wider data sets, Spark can be used to train the model quickly using the code here."
},
{
"code": null,
"e": 9857,
"s": 9541,
"text": "Deep Learning allows for processing data in a much more complex manner. A Long Short-Term Memory model, or LSTM, is a type of Recurrent Neural Network (RNN) used to process temporal data. Since we think that the order of features (words) in a sentence is significant, this is the neural network architecture we use."
},
{
"code": null,
"e": 11389,
"s": 9857,
"text": "Deep Learning is computationally expensive and do not do well (poor performance and slow convergence) with high-dimensional, sparse vectors. When we extract features from the original text for model training, we need to represent them as vectors that are dense. One such technique is to convert each text into a sequence of numbers, where each number is mapped to a word in the vocabulary. Taking it a step further, we need to map words that have similar usage/meaning to similar real number vectors (rather than an index) using Word Embeddings. Without Word Embeddings, the model will misinterpret the index number of the words as having significance. Word Embeddings put all words into a multi-dimensional vector space so their similarities can be measured by distance. Generating Word Embeddings is done using open source pre-trained models (such as Word2vec, GloVe, or fastText) or custom neural network (unsupervised learning) models. When training custom Word Embeddings, it can be done separately or jointly with the neural network model of the task at hand (as an addition layer). This is the approach we take as it tends to lead to embeddings that are targeted to the context of data as well as the objective. In contrast to a document-term matrix that is sparse (hundreds of thousands of dimension), using Word Embeddings produces vectors that have fewer (hundreds) dimensions while capturing semantic similarities. Word Embeddings is considered one of the key breakthroughs of Deep Learning for challenging NLP problems."
},
{
"code": null,
"e": 11466,
"s": 11389,
"text": "We apply the following transformation to generate the training/testing data:"
},
{
"code": null,
"e": 12126,
"s": 11466,
"text": "One big advantage for the Deep Learning neural network approach is that we donβt have to try and engineer features since the neural network will learn the context and important features. However, this comes at the cost of interpretability β making it a significant limitation in some cases. Additionally, it is the most expensive approach in terms of the time to compute, particularly if Word Embeddings are jointly trained since it requires a large data set. For our data set, the Word Embedding LSTM model (with 61MM parameters) took 20 hours to train. It did produce a remarkable training score of 96% accuracy and testing/validation score of 80% accuracy."
},
{
"code": null,
"e": 12508,
"s": 12126,
"text": "When done correctly, Sentiment Analysis can provide tremendous value for any organization. Today, organizations use Sentiment Analysis to understand the publicβs feelings towards their products, services, and brand. This can guide marketing strategies, inspire product development, inform political campaigns, and detect potentially damaging events. Below are some proven examples:"
},
{
"code": null,
"e": 12628,
"s": 12508,
"text": "Identify potential detractors for prioritization to improve Net Promoter Score (NPS) (Customer Care/Feedback Analytics)"
},
{
"code": null,
"e": 12824,
"s": 12628,
"text": "Evaluate customer engagements quickly to identify and resolve negative customer experiences, which translates to improved customer service and higher rate of returning customers (Ticket Triaging)"
},
{
"code": null,
"e": 12897,
"s": 12824,
"text": "Monitor and manage public sentiment about the brand (Brand Intelligence)"
},
{
"code": null,
"e": 13084,
"s": 12897,
"text": "We reviewed three approaches for Sentiment Analysis, each with its own strengths and drawbacks. When is comes to choosing the appropriate approach, there are some key things to consider:"
},
{
"code": null,
"e": 13220,
"s": 13084,
"text": "What is the tolerance for accuracy and/or speed? If speed is prioritized over accuracy, Rule-Based solutions can be the right solution."
},
{
"code": null,
"e": 13373,
"s": 13220,
"text": "Availability and completeness of data for training? With robust training data, a Naive Bayes model can be the right solution as it is fast to implement."
},
{
"code": null,
"e": 13510,
"s": 13373,
"text": "How important is model interpretability? Deep Learning can be the right solution if accuracy is prioritized over model interpretability."
},
{
"code": null,
"e": 13684,
"s": 13510,
"text": "It is not uncommon to run multiple models in parallel for comparison. Once deployed, the process should include a feedback loop to inform when the models need to be updated."
}
] |
Implement Dynamic SQL query inside a MySQL stored procedure?
|
For dynamic SQL query in a stored procedure, use the concept of PREPARE STATEMENT. Let us first create a table β
mysql> create table DemoTable2033
-> (
-> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> Name varchar(20)
-> );
Query OK, 0 rows affected (1.61 sec)
Insert some records in the table using insert command β
mysql> insert into DemoTable2033(Name) values('Chris');
Query OK, 1 row affected (0.85 sec)
mysql> insert into DemoTable2033(Name) values('Bob');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable2033(Name) values('David');
Query OK, 1 row affected (0.24 sec)
mysql> insert into DemoTable2033(Name) values('Mike');
Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement β
mysql> select *from DemoTable2033;
This will produce the following output β
+----+-------+
| Id | Name |
+----+-------+
| 1 | Chris |
| 2 | Bob |
| 3 | David |
| 4 | Mike |
+----+-------+
4 rows in set (0.00 sec)
Following is the query to create a stored procedure and implement dynamic SQL β
mysql> delimiter //
mysql> create procedure dynamic_query()
-> begin
-> set @query=concat("select *from DemoTable2033 where Id=3");
-> prepare st from @query;
-> execute st;
-> end
-> //
Query OK, 0 rows affected (0.13 sec)
mysql> delimiter ;
Call the stored procedure β
mysql> call dynamic_query();
This will produce the following output β
+----+-------+
| Id | Name |
+----+-------+
| 3 | David |
+----+-------+
1 row in set (0.04 sec)
Query OK, 0 rows affected (0.05 sec)
|
[
{
"code": null,
"e": 1175,
"s": 1062,
"text": "For dynamic SQL query in a stored procedure, use the concept of PREPARE STATEMENT. Let us first create a table β"
},
{
"code": null,
"e": 1336,
"s": 1175,
"text": "mysql> create table DemoTable2033\n -> (\n -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> Name varchar(20)\n -> );\nQuery OK, 0 rows affected (1.61 sec)"
},
{
"code": null,
"e": 1392,
"s": 1336,
"text": "Insert some records in the table using insert command β"
},
{
"code": null,
"e": 1760,
"s": 1392,
"text": "mysql> insert into DemoTable2033(Name) values('Chris');\nQuery OK, 1 row affected (0.85 sec)\n\nmysql> insert into DemoTable2033(Name) values('Bob');\nQuery OK, 1 row affected (0.19 sec)\n\nmysql> insert into DemoTable2033(Name) values('David');\nQuery OK, 1 row affected (0.24 sec)\n\nmysql> insert into DemoTable2033(Name) values('Mike');\nQuery OK, 1 row affected (0.12 sec)"
},
{
"code": null,
"e": 1820,
"s": 1760,
"text": "Display all records from the table using select statement β"
},
{
"code": null,
"e": 1855,
"s": 1820,
"text": "mysql> select *from DemoTable2033;"
},
{
"code": null,
"e": 1896,
"s": 1855,
"text": "This will produce the following output β"
},
{
"code": null,
"e": 2041,
"s": 1896,
"text": "+----+-------+\n| Id | Name |\n+----+-------+\n| 1 | Chris |\n| 2 | Bob |\n| 3 | David |\n| 4 | Mike |\n+----+-------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2121,
"s": 2041,
"text": "Following is the query to create a stored procedure and implement dynamic SQL β"
},
{
"code": null,
"e": 2383,
"s": 2121,
"text": "mysql> delimiter //\nmysql> create procedure dynamic_query()\n -> begin\n -> set @query=concat(\"select *from DemoTable2033 where Id=3\");\n -> prepare st from @query;\n -> execute st;\n -> end\n -> //\nQuery OK, 0 rows affected (0.13 sec)\n\nmysql> delimiter ;"
},
{
"code": null,
"e": 2411,
"s": 2383,
"text": "Call the stored procedure β"
},
{
"code": null,
"e": 2440,
"s": 2411,
"text": "mysql> call dynamic_query();"
},
{
"code": null,
"e": 2481,
"s": 2440,
"text": "This will produce the following output β"
},
{
"code": null,
"e": 2617,
"s": 2481,
"text": "+----+-------+\n| Id | Name |\n+----+-------+\n| 3 | David |\n+----+-------+\n1 row in set (0.04 sec)\nQuery OK, 0 rows affected (0.05 sec)"
}
] |
How to Deploy Your React Websites on GitHub? - GeeksforGeeks
|
07 Mar, 2022
Building a web application is always exciting for developers especially when you step into the programming world for the first time. You build the front end of your application after a lot of struggle and you want to showcase your skill, your creativity, and of course your hard work to the world. Some of the folks might be familiar with the free hosting website where they can host their application. Some of you might be also familiar with Github pages to deploy the static web page. If you donβt know then here is the link to check that... Using GitHub to Host a Free Static Website. Well, these resources are quite popular to make your web app live on the server, and why not if itβs quite useful and available free of cost.
Do you know that you can make a cool website using the popular javascript library React and can also be deployed on GitHub pages? Donβt you believe it...?? Install the React Developer Tool in your system and check the link Portfolio on your own. Isnβt it cool and amazing to learn and build a web application using React? Isnβt it cool and amazing to deploy your React web app on GitHub pages free of cost and showcase it to the world?
Now if you are someone who is excited to learn ReactJS then here is the link for you GeeksforGeeks ReactJS but to deploy your beautiful application on GitHub pages we need to learn few more things. So in this blog, we are going to discuss step-by-step procedures to deploy your React application on GitHub pages.
1. React: A popular JavaScript library developed by Facebook which is used to create and handle flexible components for the user interface.
2. Git: An amazing open-source version control system to handle small and large projects. It is used to collaborate with other developers and to keep track of changes in source code during software development.
3. GitHub: A code hosting platform for collaboration and version control. It is used to work and store web development projects.
4. Github Pages: It allows you to turn your GitHub repositories into an elegant website to showcase your portfolio, projects, documentation, or anything else you want to make live but remember that there is no database to set up and no server to configure.
5. NodeJS and npm: Node.js is a server runtime environment for running Javascript on the server and npm is a package manager used to download and install different packages for JavaScript projects.
1. Download Git and go through the default installation process.
2. An adequate version of NodeJS and npm should be installed. Here is the command to check the installation and version.
$ node --version
$ npm --version
3. An adequate version of create-react-app is installed. Here is the command to check the installation and version.
$ create-react-app --version
If itβs not installed then use the command below to install it globally.
$ npm install -g create-react-app
4. A GitHub account.
1. Firstly create a React application in your system using the command given below. We are giving the name βreact-deployβ to this application. This is the app you will deploy to GitHub Pages. This process will create a new folder named βreact-deployβ in your directory.
$ create-react-app react-deploy
2. Now enter your new application and run the following command to start the application. You will see your application is running on a local development server http://localhost:3000.
#change directory
$ cd react-deploy
#run application in the development environment
$ npm start
3. After checking that your application runs perfectly without any error on a local server, create a new repository on GitHub. We are giving this name βmy-appβ which is different from the application name you have created in the previous step. However, you can also choose the same name i.e. βreact-deployβ for your GitHub repository name. Itβs totally up to you.
4. Install the gh-pages package as a βdev-dependencyβ of the app.
#install gh-pages package
$ npm install --save gh-pages
5. Add some properties to the appβs package.json file. At the top level, add a homepage property. Define its value to be the string http://{username}.github.io/{repo-name}, where {username} is your GitHub username, and {repo-name} is the name of the GitHub repository (my-app) you created in step 3.
Take a look at the example given below...
"homepage": "http://anuupadhyay.github.io/my-app",
Now you need to add two more properties. In the existing scripts property, add a predeploy property and a deploy property, each having the values shown below:
"scripts": {
//...
"predeploy": "npm run build",
"deploy": "gh-pages -d build",
//...
"build": "react-scripts build && cp build/index.html build/404.html", // this will prevent page reloads to give a 404 error
}
Once the above thing is done your file package.json will look something like this...
Next, if you are using the Router from react-router-dom then you need to change the Browser router tags to
//...
BrowserRouter basename={process.env.PUBLIC_URL}
//...
6. In this step create a git repository in the appβs folder and add the GitHub repository as a βremoteβ in your local git repository. This will make it so the gh-pages package knows where you want it to deploy your app in step 7. It will also make it so git knows where you want it to push your source code (i.e. the commits on your master branch) in step 8.
#create a new git repository
$ git init
#add remote repository
$ git remote add origin https://github.com/anuupadhyay/my-app.git
7. Now here is the magic. Follow the command below and generate a production build of your app, to deploy your code on GitHub pages.
#deploy application
$ npm run deploy
Thatβs it. Your React application is published on GitHub pages and if you want to verify it just go to the settings tab of your application in your Github repository and scroll down. You will see something like below...
In our case, the app is accessible at: https://anuupadhyay.github.io/my-app/
8. At this point, if you will explore the GitHub repository you will notice that the master branch did not exist, a gh-pages branch did exist. It means the latter contained the built app code, as opposed to the appβs source code. So to create a default master branch and push your source code to it run the command given below...
#add all changed file paths to staged changes
$ git add .
#commit all staged changes
$ git commit -m "Create a React app and publish it to GitHub Pages"
#pushed local repository to remote repository on GitHub
$ git push origin master
After this last step once again explores the GitHub repository. You will notice that a master branch now existed, and it contained the appβs source code. You will see something like below in your GitHub repository.
So, the master branch held the source code, and the gh-pages branch held the built app code.
itissandeep98
GBlog
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Roadmap to Become a Web Developer in 2022
DSA Sheet by Love Babbar
GET and POST requests using Python
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Working with csv files in Python
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 24682,
"s": 24654,
"text": "\n07 Mar, 2022"
},
{
"code": null,
"e": 25413,
"s": 24682,
"text": "Building a web application is always exciting for developers especially when you step into the programming world for the first time. You build the front end of your application after a lot of struggle and you want to showcase your skill, your creativity, and of course your hard work to the world. Some of the folks might be familiar with the free hosting website where they can host their application. Some of you might be also familiar with Github pages to deploy the static web page. If you donβt know then here is the link to check that... Using GitHub to Host a Free Static Website. Well, these resources are quite popular to make your web app live on the server, and why not if itβs quite useful and available free of cost. "
},
{
"code": null,
"e": 25850,
"s": 25413,
"text": "Do you know that you can make a cool website using the popular javascript library React and can also be deployed on GitHub pages? Donβt you believe it...?? Install the React Developer Tool in your system and check the link Portfolio on your own. Isnβt it cool and amazing to learn and build a web application using React? Isnβt it cool and amazing to deploy your React web app on GitHub pages free of cost and showcase it to the world? "
},
{
"code": null,
"e": 26164,
"s": 25850,
"text": "Now if you are someone who is excited to learn ReactJS then here is the link for you GeeksforGeeks ReactJS but to deploy your beautiful application on GitHub pages we need to learn few more things. So in this blog, we are going to discuss step-by-step procedures to deploy your React application on GitHub pages. "
},
{
"code": null,
"e": 26305,
"s": 26164,
"text": "1. React: A popular JavaScript library developed by Facebook which is used to create and handle flexible components for the user interface. "
},
{
"code": null,
"e": 26517,
"s": 26305,
"text": "2. Git: An amazing open-source version control system to handle small and large projects. It is used to collaborate with other developers and to keep track of changes in source code during software development. "
},
{
"code": null,
"e": 26647,
"s": 26517,
"text": "3. GitHub: A code hosting platform for collaboration and version control. It is used to work and store web development projects. "
},
{
"code": null,
"e": 26905,
"s": 26647,
"text": "4. Github Pages: It allows you to turn your GitHub repositories into an elegant website to showcase your portfolio, projects, documentation, or anything else you want to make live but remember that there is no database to set up and no server to configure. "
},
{
"code": null,
"e": 27104,
"s": 26905,
"text": "5. NodeJS and npm: Node.js is a server runtime environment for running Javascript on the server and npm is a package manager used to download and install different packages for JavaScript projects. "
},
{
"code": null,
"e": 27170,
"s": 27104,
"text": "1. Download Git and go through the default installation process. "
},
{
"code": null,
"e": 27292,
"s": 27170,
"text": "2. An adequate version of NodeJS and npm should be installed. Here is the command to check the installation and version. "
},
{
"code": null,
"e": 27309,
"s": 27292,
"text": "$ node --version"
},
{
"code": null,
"e": 27325,
"s": 27309,
"text": "$ npm --version"
},
{
"code": null,
"e": 27442,
"s": 27325,
"text": "3. An adequate version of create-react-app is installed. Here is the command to check the installation and version. "
},
{
"code": null,
"e": 27471,
"s": 27442,
"text": "$ create-react-app --version"
},
{
"code": null,
"e": 27545,
"s": 27471,
"text": "If itβs not installed then use the command below to install it globally. "
},
{
"code": null,
"e": 27579,
"s": 27545,
"text": "$ npm install -g create-react-app"
},
{
"code": null,
"e": 27601,
"s": 27579,
"text": "4. A GitHub account. "
},
{
"code": null,
"e": 27872,
"s": 27601,
"text": "1. Firstly create a React application in your system using the command given below. We are giving the name βreact-deployβ to this application. This is the app you will deploy to GitHub Pages. This process will create a new folder named βreact-deployβ in your directory. "
},
{
"code": null,
"e": 27904,
"s": 27872,
"text": "$ create-react-app react-deploy"
},
{
"code": null,
"e": 28089,
"s": 27904,
"text": "2. Now enter your new application and run the following command to start the application. You will see your application is running on a local development server http://localhost:3000. "
},
{
"code": null,
"e": 28185,
"s": 28089,
"text": "#change directory\n$ cd react-deploy\n#run application in the development environment\n$ npm start"
},
{
"code": null,
"e": 28550,
"s": 28185,
"text": "3. After checking that your application runs perfectly without any error on a local server, create a new repository on GitHub. We are giving this name βmy-appβ which is different from the application name you have created in the previous step. However, you can also choose the same name i.e. βreact-deployβ for your GitHub repository name. Itβs totally up to you. "
},
{
"code": null,
"e": 28617,
"s": 28550,
"text": "4. Install the gh-pages package as a βdev-dependencyβ of the app. "
},
{
"code": null,
"e": 28673,
"s": 28617,
"text": "#install gh-pages package\n$ npm install --save gh-pages"
},
{
"code": null,
"e": 28973,
"s": 28673,
"text": "5. Add some properties to the appβs package.json file. At the top level, add a homepage property. Define its value to be the string http://{username}.github.io/{repo-name}, where {username} is your GitHub username, and {repo-name} is the name of the GitHub repository (my-app) you created in step 3."
},
{
"code": null,
"e": 29016,
"s": 28973,
"text": "Take a look at the example given below... "
},
{
"code": null,
"e": 29068,
"s": 29016,
"text": "\"homepage\": \"http://anuupadhyay.github.io/my-app\", "
},
{
"code": null,
"e": 29228,
"s": 29068,
"text": "Now you need to add two more properties. In the existing scripts property, add a predeploy property and a deploy property, each having the values shown below: "
},
{
"code": null,
"e": 29451,
"s": 29228,
"text": "\"scripts\": {\n //...\n \"predeploy\": \"npm run build\",\n \"deploy\": \"gh-pages -d build\",\n //...\n \"build\": \"react-scripts build && cp build/index.html build/404.html\", // this will prevent page reloads to give a 404 error\n}"
},
{
"code": null,
"e": 29537,
"s": 29451,
"text": "Once the above thing is done your file package.json will look something like this... "
},
{
"code": null,
"e": 29647,
"s": 29539,
"text": "Next, if you are using the Router from react-router-dom then you need to change the Browser router tags to "
},
{
"code": null,
"e": 29710,
"s": 29647,
"text": "//...\n BrowserRouter basename={process.env.PUBLIC_URL}\n//... "
},
{
"code": null,
"e": 30070,
"s": 29710,
"text": "6. In this step create a git repository in the appβs folder and add the GitHub repository as a βremoteβ in your local git repository. This will make it so the gh-pages package knows where you want it to deploy your app in step 7. It will also make it so git knows where you want it to push your source code (i.e. the commits on your master branch) in step 8. "
},
{
"code": null,
"e": 30199,
"s": 30070,
"text": "#create a new git repository\n$ git init\n#add remote repository\n$ git remote add origin https://github.com/anuupadhyay/my-app.git"
},
{
"code": null,
"e": 30333,
"s": 30199,
"text": "7. Now here is the magic. Follow the command below and generate a production build of your app, to deploy your code on GitHub pages. "
},
{
"code": null,
"e": 30370,
"s": 30333,
"text": "#deploy application\n$ npm run deploy"
},
{
"code": null,
"e": 30591,
"s": 30370,
"text": "Thatβs it. Your React application is published on GitHub pages and if you want to verify it just go to the settings tab of your application in your Github repository and scroll down. You will see something like below... "
},
{
"code": null,
"e": 30669,
"s": 30591,
"text": "In our case, the app is accessible at: https://anuupadhyay.github.io/my-app/ "
},
{
"code": null,
"e": 31000,
"s": 30669,
"text": "8. At this point, if you will explore the GitHub repository you will notice that the master branch did not exist, a gh-pages branch did exist. It means the latter contained the built app code, as opposed to the appβs source code. So to create a default master branch and push your source code to it run the command given below... "
},
{
"code": null,
"e": 31234,
"s": 31000,
"text": "#add all changed file paths to staged changes\n$ git add .\n#commit all staged changes\n$ git commit -m \"Create a React app and publish it to GitHub Pages\"\n#pushed local repository to remote repository on GitHub\n$ git push origin master"
},
{
"code": null,
"e": 31450,
"s": 31234,
"text": "After this last step once again explores the GitHub repository. You will notice that a master branch now existed, and it contained the appβs source code. You will see something like below in your GitHub repository. "
},
{
"code": null,
"e": 31544,
"s": 31450,
"text": "So, the master branch held the source code, and the gh-pages branch held the built app code. "
},
{
"code": null,
"e": 31558,
"s": 31544,
"text": "itissandeep98"
},
{
"code": null,
"e": 31564,
"s": 31558,
"text": "GBlog"
},
{
"code": null,
"e": 31581,
"s": 31564,
"text": "Web Technologies"
},
{
"code": null,
"e": 31679,
"s": 31581,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31721,
"s": 31679,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 31746,
"s": 31721,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 31781,
"s": 31746,
"text": "GET and POST requests using Python"
},
{
"code": null,
"e": 31843,
"s": 31781,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 31876,
"s": 31843,
"text": "Working with csv files in Python"
},
{
"code": null,
"e": 31918,
"s": 31876,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 31951,
"s": 31918,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 31994,
"s": 31951,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 32056,
"s": 31994,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
Tryit Editor v3.6 - Show React
|
import { useState } from "react";
import ReactDOM from "react-dom/client";
import Todos from "./Todos";
const App = () => {
const [count, setCount] = useState(0);
const [todos, setTodos] = useState(["todo 1", "todo 2"]);
const increment = () => {
setCount((c) => c + 1);
};
return (
<>
<Todos todos={todos} />
<hr />
<div>
Count: {count}
<button onClick={increment}>+</button>
</div>
</>
);
};
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport"
content="width=device-width, initial-scale=1" />
|
[
{
"code": null,
"e": 554,
"s": 0,
"text": "\nimport { useState } from \"react\";\nimport ReactDOM from \"react-dom/client\";\nimport Todos from \"./Todos\";\n\nconst App = () => {\n const [count, setCount] = useState(0);\n const [todos, setTodos] = useState([\"todo 1\", \"todo 2\"]);\n\n const increment = () => {\n setCount((c) => c + 1);\n };\n\n return (\n <>\n <Todos todos={todos} />\n <hr />\n <div>\n Count: {count}\n <button onClick={increment}>+</button>\n </div>\n </>\n );\n};\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(<App />);\n\n"
}
] |
Check if sum of divisors of two numbers are same in Python
|
Suppose we have two numbers p and q. We have to check whether the sum of all divisors of these tow numbers are same or not.
So, if the input is like p = 559, q = 703, then the output will be True the divisors of 559 is 1, 13, 43 and 703 is 1, 19, 37. The sum of the divisors are 57.
To solve this, we will follow these steps β
Define a function divSum() . This will take n
total := 1
i := 2
while i * i <= n, doif n divisible by i, thentotal := total + i + the floor of (n / i)i := i + 1
if n divisible by i, thentotal := total + i + the floor of (n / i)
total := total + i + the floor of (n / i)
i := i + 1
return total
From the main method return true when divSum(p) is same as divSum(q), otherwise false
Let us see the following implementation to get better understanding β
Live Demo
from math import floor
def divSum(n):
total = 1
i = 2
while i * i <= n:
if n % i == 0:
total += i + floor(n / i)
i += 1
return total
def solve(p, q):
return divSum(p) == divSum(q)
p = 559
q = 703
print(solve(p, q))
559, 703
True
|
[
{
"code": null,
"e": 1186,
"s": 1062,
"text": "Suppose we have two numbers p and q. We have to check whether the sum of all divisors of these tow numbers are same or not."
},
{
"code": null,
"e": 1345,
"s": 1186,
"text": "So, if the input is like p = 559, q = 703, then the output will be True the divisors of 559 is 1, 13, 43 and 703 is 1, 19, 37. The sum of the divisors are 57."
},
{
"code": null,
"e": 1389,
"s": 1345,
"text": "To solve this, we will follow these steps β"
},
{
"code": null,
"e": 1435,
"s": 1389,
"text": "Define a function divSum() . This will take n"
},
{
"code": null,
"e": 1446,
"s": 1435,
"text": "total := 1"
},
{
"code": null,
"e": 1453,
"s": 1446,
"text": "i := 2"
},
{
"code": null,
"e": 1550,
"s": 1453,
"text": "while i * i <= n, doif n divisible by i, thentotal := total + i + the floor of (n / i)i := i + 1"
},
{
"code": null,
"e": 1617,
"s": 1550,
"text": "if n divisible by i, thentotal := total + i + the floor of (n / i)"
},
{
"code": null,
"e": 1659,
"s": 1617,
"text": "total := total + i + the floor of (n / i)"
},
{
"code": null,
"e": 1670,
"s": 1659,
"text": "i := i + 1"
},
{
"code": null,
"e": 1683,
"s": 1670,
"text": "return total"
},
{
"code": null,
"e": 1769,
"s": 1683,
"text": "From the main method return true when divSum(p) is same as divSum(q), otherwise false"
},
{
"code": null,
"e": 1839,
"s": 1769,
"text": "Let us see the following implementation to get better understanding β"
},
{
"code": null,
"e": 1849,
"s": 1839,
"text": "Live Demo"
},
{
"code": null,
"e": 2109,
"s": 1849,
"text": "from math import floor\n \ndef divSum(n):\n total = 1\n i = 2\n while i * i <= n:\n if n % i == 0:\n total += i + floor(n / i)\n i += 1\n \n return total\n \ndef solve(p, q):\n return divSum(p) == divSum(q)\n\np = 559\nq = 703\nprint(solve(p, q))"
},
{
"code": null,
"e": 2119,
"s": 2109,
"text": "559, 703\n"
},
{
"code": null,
"e": 2124,
"s": 2119,
"text": "True"
}
] |
Creating an Asynchronous Multithreaded chat Application in Java - GeeksforGeeks
|
01 Apr, 2019
Prerequisite: Datagrams in Java
In this article, we will learn how to use Datagrams in Java to create an Asynchronous messaging application in java. Asynchronous in this context means that both the server and the client can send each other texts independently without waiting for any kind of response from the other party. We will be using the concept of multi-threading to implement Sending and receiving text messages between the processes with the help of DatagramPackets. Datagrams are bundles of information passed between applications. Once the datagram has been released to its intended target, it is independent and there is no assurance that it will arrive or even that some application will be there to receive it. Java implements datagrams on top of the UDP (User Datagram Protocol) protocol.
Below is the implementation of the above approach.
UnsyncChatServer.java
UnsyncChatClient.java
import java.net.*;import java.io.*;import java.util.*; public class UnSyncChatServer { public static void main(String args[]) throws IOException, InterruptedException { // Create DatagramSocket and get ip DatagramSocket ss = new DatagramSocket(1234); InetAddress ip = InetAddress.getLocalHost(); System.out.println("Running UnSyncChatServer.java"); System.out.println("Server is Up...."); // Create a sender thread // with a nested runnable class definition Thread ssend; ssend = new Thread(new Runnable() { @Override public void run() { try { Scanner sc = new Scanner(System.in); while (true) { synchronized (this) { byte[] sd = new byte[1000]; // scan new message to send sd = sc.nextLine().getBytes(); DatagramPacket sp = new DatagramPacket( sd, sd.length, ip, 5334); // send the new packet ss.send(sp); String msg = new String(sd); System.out.println("Server says: " + msg); // exit condition if ((msg).equals("bye")) { System.out.println("Server" + " exiting... "); break; } System.out.println("Waiting for" + " client response... "); } } } catch (Exception e) { System.out.println("Exception occured"); } } }); Thread sreceive; sreceive = new Thread(new Runnable() { @Override public void run() { try { while (true) { synchronized (this) { byte[] rd = new byte[1000]; // Receive new message DatagramPacket sp1 = new DatagramPacket( rd, rd.length); ss.receive(sp1); // Convert byte data to string String msg = (new String(rd)).trim(); System.out.println("Client (" + sp1.getPort() + "):" + " " + msg); // Exit condition if (msg.equals("bye")) { System.out.println("Client" + " connection closed."); break; } } } } catch (Exception e) { System.out.println("Exception occured"); } } }); ssend.start(); sreceive.start(); ssend.join(); sreceive.join(); }}
import java.io.*;import java.net.*;import java.util.Scanner; public class UnSyncChatClient { public static void main(String args[]) throws IOException, InterruptedException { // create DatagramSocket and get ip DatagramSocket cs = new DatagramSocket(5334); InetAddress ip = InetAddress.getLocalHost(); System.out.println("Running UnSyncChatClient.java"); System.out.println("Client is Up...."); // create a sender thread with a nested // runnable class definition Thread csend; csend = new Thread(new Runnable() { @Override public void run() { try { Scanner sc = new Scanner(System.in); while (true) { synchronized (this) { byte[] sd = new byte[1000]; // scan new message to send sd = sc.nextLine().getBytes(); // create datagram packet // for new message DatagramPacket sp = new DatagramPacket( sd, sd.length, ip, 1234); // send the new packet cs.send(sp); String msg = new String(sd); System.out.println("Client says: " + msg); // exit condition if (msg.equals("bye")) { System.out.println("client " + "exiting... "); break; } System.out.println("Waiting for " + "server response..."); } } } catch (IOException e) { System.out.println("Exception occured"); } } }); // create a receiver thread with a nested // runnable class definition Thread creceive; creceive = new Thread(new Runnable() { @Override public void run() { try { while (true) { synchronized (this) { byte[] rd = new byte[1000]; // receive new message DatagramPacket sp1 = new DatagramPacket( rd, rd.length); cs.receive(sp1); // convert byte data to string String msg = (new String(rd)).trim(); System.out.println("Server: " + msg); // exit condition if (msg.equals("bye")) { System.out.println("Server" + " Stopped...."); break; } } } } catch (IOException e) { System.out.println("Exception occured"); } } }); csend.start(); creceive.start(); csend.join(); creceive.join(); }}
Output: Window 1 (UnSyncChatServer.java)
Running UnSyncChatServer.java
Server is Up....
Client (5334): hey
hi
Server says: hi
Waiting for client response...
ssup?
Server says: ssup?
Waiting for client response...
Client (5334): good
Client (5334): u?
good as well
Server says: good as well
Waiting for client response...
Client (5334): bye
Client connection closed.
bye
Server says: bye
Server exiting...
Output: Window 2 (UnSyncChatClient.java)
Running UnSyncChatClient.java
Client is Up....
hey
Client says: hey
Waiting for server response...
Server: hi
Server: ssup?
good
Client says: good
Waiting for server response...
u?
Client says: u?
Waiting for server response...
Server: good as well
bye
Client says: bye
client exiting...
Server: bye
Server Stopped...
Note:
Use an offline IDE to run this program as an online IDE may timeout.
Run program 1 first and the program 2.
Java-Multithreading
Computer Networks
Java
Java Programs
Java
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Advanced Encryption Standard (AES)
Intrusion Detection System (IDS)
Multiple Access Protocols in Computer Network
GSM in Wireless Communication
Cryptography and its Types
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Arrays.sort() in Java with examples
Reverse a string in Java
|
[
{
"code": null,
"e": 24510,
"s": 24482,
"text": "\n01 Apr, 2019"
},
{
"code": null,
"e": 24542,
"s": 24510,
"text": "Prerequisite: Datagrams in Java"
},
{
"code": null,
"e": 25314,
"s": 24542,
"text": "In this article, we will learn how to use Datagrams in Java to create an Asynchronous messaging application in java. Asynchronous in this context means that both the server and the client can send each other texts independently without waiting for any kind of response from the other party. We will be using the concept of multi-threading to implement Sending and receiving text messages between the processes with the help of DatagramPackets. Datagrams are bundles of information passed between applications. Once the datagram has been released to its intended target, it is independent and there is no assurance that it will arrive or even that some application will be there to receive it. Java implements datagrams on top of the UDP (User Datagram Protocol) protocol."
},
{
"code": null,
"e": 25365,
"s": 25314,
"text": "Below is the implementation of the above approach."
},
{
"code": null,
"e": 25387,
"s": 25365,
"text": "UnsyncChatServer.java"
},
{
"code": null,
"e": 25409,
"s": 25387,
"text": "UnsyncChatClient.java"
},
{
"code": "import java.net.*;import java.io.*;import java.util.*; public class UnSyncChatServer { public static void main(String args[]) throws IOException, InterruptedException { // Create DatagramSocket and get ip DatagramSocket ss = new DatagramSocket(1234); InetAddress ip = InetAddress.getLocalHost(); System.out.println(\"Running UnSyncChatServer.java\"); System.out.println(\"Server is Up....\"); // Create a sender thread // with a nested runnable class definition Thread ssend; ssend = new Thread(new Runnable() { @Override public void run() { try { Scanner sc = new Scanner(System.in); while (true) { synchronized (this) { byte[] sd = new byte[1000]; // scan new message to send sd = sc.nextLine().getBytes(); DatagramPacket sp = new DatagramPacket( sd, sd.length, ip, 5334); // send the new packet ss.send(sp); String msg = new String(sd); System.out.println(\"Server says: \" + msg); // exit condition if ((msg).equals(\"bye\")) { System.out.println(\"Server\" + \" exiting... \"); break; } System.out.println(\"Waiting for\" + \" client response... \"); } } } catch (Exception e) { System.out.println(\"Exception occured\"); } } }); Thread sreceive; sreceive = new Thread(new Runnable() { @Override public void run() { try { while (true) { synchronized (this) { byte[] rd = new byte[1000]; // Receive new message DatagramPacket sp1 = new DatagramPacket( rd, rd.length); ss.receive(sp1); // Convert byte data to string String msg = (new String(rd)).trim(); System.out.println(\"Client (\" + sp1.getPort() + \"):\" + \" \" + msg); // Exit condition if (msg.equals(\"bye\")) { System.out.println(\"Client\" + \" connection closed.\"); break; } } } } catch (Exception e) { System.out.println(\"Exception occured\"); } } }); ssend.start(); sreceive.start(); ssend.join(); sreceive.join(); }}",
"e": 29210,
"s": 25409,
"text": null
},
{
"code": "import java.io.*;import java.net.*;import java.util.Scanner; public class UnSyncChatClient { public static void main(String args[]) throws IOException, InterruptedException { // create DatagramSocket and get ip DatagramSocket cs = new DatagramSocket(5334); InetAddress ip = InetAddress.getLocalHost(); System.out.println(\"Running UnSyncChatClient.java\"); System.out.println(\"Client is Up....\"); // create a sender thread with a nested // runnable class definition Thread csend; csend = new Thread(new Runnable() { @Override public void run() { try { Scanner sc = new Scanner(System.in); while (true) { synchronized (this) { byte[] sd = new byte[1000]; // scan new message to send sd = sc.nextLine().getBytes(); // create datagram packet // for new message DatagramPacket sp = new DatagramPacket( sd, sd.length, ip, 1234); // send the new packet cs.send(sp); String msg = new String(sd); System.out.println(\"Client says: \" + msg); // exit condition if (msg.equals(\"bye\")) { System.out.println(\"client \" + \"exiting... \"); break; } System.out.println(\"Waiting for \" + \"server response...\"); } } } catch (IOException e) { System.out.println(\"Exception occured\"); } } }); // create a receiver thread with a nested // runnable class definition Thread creceive; creceive = new Thread(new Runnable() { @Override public void run() { try { while (true) { synchronized (this) { byte[] rd = new byte[1000]; // receive new message DatagramPacket sp1 = new DatagramPacket( rd, rd.length); cs.receive(sp1); // convert byte data to string String msg = (new String(rd)).trim(); System.out.println(\"Server: \" + msg); // exit condition if (msg.equals(\"bye\")) { System.out.println(\"Server\" + \" Stopped....\"); break; } } } } catch (IOException e) { System.out.println(\"Exception occured\"); } } }); csend.start(); creceive.start(); csend.join(); creceive.join(); }}",
"e": 32975,
"s": 29210,
"text": null
},
{
"code": null,
"e": 33016,
"s": 32975,
"text": "Output: Window 1 (UnSyncChatServer.java)"
},
{
"code": null,
"e": 33385,
"s": 33016,
"text": "Running UnSyncChatServer.java\nServer is Up....\nClient (5334): hey\nhi\nServer says: hi\nWaiting for client response... \nssup?\nServer says: ssup?\nWaiting for client response... \nClient (5334): good\nClient (5334): u?\ngood as well\nServer says: good as well\nWaiting for client response... \nClient (5334): bye\nClient connection closed.\nbye\nServer says: bye\nServer exiting... \n"
},
{
"code": null,
"e": 33426,
"s": 33385,
"text": "Output: Window 2 (UnSyncChatClient.java)"
},
{
"code": null,
"e": 33746,
"s": 33426,
"text": "Running UnSyncChatClient.java\nClient is Up....\nhey\nClient says: hey\nWaiting for server response...\nServer: hi\nServer: ssup?\ngood\nClient says: good\nWaiting for server response...\nu?\nClient says: u?\nWaiting for server response...\nServer: good as well\nbye\nClient says: bye\nclient exiting... \nServer: bye\nServer Stopped...\n"
},
{
"code": null,
"e": 33752,
"s": 33746,
"text": "Note:"
},
{
"code": null,
"e": 33821,
"s": 33752,
"text": "Use an offline IDE to run this program as an online IDE may timeout."
},
{
"code": null,
"e": 33860,
"s": 33821,
"text": "Run program 1 first and the program 2."
},
{
"code": null,
"e": 33880,
"s": 33860,
"text": "Java-Multithreading"
},
{
"code": null,
"e": 33898,
"s": 33880,
"text": "Computer Networks"
},
{
"code": null,
"e": 33903,
"s": 33898,
"text": "Java"
},
{
"code": null,
"e": 33917,
"s": 33903,
"text": "Java Programs"
},
{
"code": null,
"e": 33922,
"s": 33917,
"text": "Java"
},
{
"code": null,
"e": 33940,
"s": 33922,
"text": "Computer Networks"
},
{
"code": null,
"e": 34038,
"s": 33940,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34073,
"s": 34038,
"text": "Advanced Encryption Standard (AES)"
},
{
"code": null,
"e": 34106,
"s": 34073,
"text": "Intrusion Detection System (IDS)"
},
{
"code": null,
"e": 34152,
"s": 34106,
"text": "Multiple Access Protocols in Computer Network"
},
{
"code": null,
"e": 34182,
"s": 34152,
"text": "GSM in Wireless Communication"
},
{
"code": null,
"e": 34209,
"s": 34182,
"text": "Cryptography and its Types"
},
{
"code": null,
"e": 34224,
"s": 34209,
"text": "Arrays in Java"
},
{
"code": null,
"e": 34268,
"s": 34224,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 34290,
"s": 34268,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 34326,
"s": 34290,
"text": "Arrays.sort() in Java with examples"
}
] |
Check if a number is a Pangram or not - GeeksforGeeks
|
14 May, 2021
Given an integer N, the task is to check whether the given number is a pangram or not. Note: A Pangram Number contains every digit [0- 9] at least once.
Examples:
Input : N = 10239876540022Output : YesExplanation: N contains all the digits from 0 to 9. Therefore, it is a pangram.
Input : N = 234567890Output : NoExplanation: N doesnβt contain the digit 1. Therefore, it is not a pangram.
Set-based Approach: The idea is to use Sets to store the count of distinct digits present in N. Follow the steps below to solve the problem:
Convert the number N to equivalent string.
Convert the string to a set.
If the size of the Set is 10, then it contains all the distinct possible digits [0 β 9]. Therefore, print βYesβ.
Otherwise, print βNoβ
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function to check if N// is a Pangram or notstring numberPangram(string N){ // Add all characters pf arrNum to set set<char> setNum; for (int i = 0; i < N.length(); i++) { setNum.insert(N[i]); } // If the length of set is 10 // The number is a Pangram if (setNum.size() == 10) return "True"; else return "False";} // Driver codeint main(){ string N = "10239876540022"; cout << (numberPangram(N));} // This code is contributed by ukasp.
// Java implementation of above approachimport java.math.BigInteger;import java.util.HashSet; class GFG{ // Function to check if N// is a Pangram or notstatic String numberPangram(BigInteger N){ // Stores equivalent string // representation of N String num = N.toString(); // Convert the string to Character array char[] arrNum = num.toCharArray(); // Add all characters pf arrNum to set HashSet<Character> setNum = new HashSet<Character>(); for(char ch : arrNum) { setNum.add(ch); } // If the length of set is 10 // The number is a Pangram if (setNum.size() == 10) return "True"; else return "False";} // Driver codepublic static void main(String[] args){ BigInteger N = new BigInteger("10239876540022"); System.out.print(numberPangram(N));}} // This code is contributed by abhinavjain194
# Python3 implementation of above approach # Function to check if N# is a Pangram or notdef numberPangram(N): # Stores equivalent string # representation of N num = str(N) # Convert the string to set setnum = set(num) # If the length of set is 10 if(len(setnum) == 10): # The number is a Pangram return True else: return False # Driver Code N = 10239876540022print(numberPangram(N))
// C# implementation of above approachusing System;using System.Globalization;using System.Numerics;using System.Collections.Generic;class GFG{ // Function to check if N// is a Pangram or notstatic String numberPangram(ulong N){ // Stores equivalent string // representation of N string num = N.ToString(); // Convert the string to Character array char[] arrNum = num.ToCharArray(); // Add all characters pf arrNum to set HashSet<char> setNum = new HashSet<char>(); foreach(char ch in arrNum) { setNum.Add(ch); } // If the length of set is 10 // The number is a Pangram if (setNum.Count == 10) return "True"; else return "False";} // Driver Code static void Main() { ulong N = 10239876540022; Console.Write(numberPangram(N)); }} // This code is contributed by SoumikMondal
<script> // Javascript implementation of above approach // Function to check if N// is a Pangram or notfunction numberPangram(N){ // Add all characters pf arrNum to set var setNum = new Set(); for (var i = 0; i < N.length; i++) { setNum.add(N[i]); } // If the length of set is 10 // The number is a Pangram if (setNum.size == 10) return "True"; else return "False";} // Driver codevar N = "10239876540022";document.write(numberPangram(N)); </script>
True
Time Complexity: O(log10N * log(log10N))Auxiliary Space: O(1)
Hashing-based Approach: Follow the steps to solve the problem:
Convert N to its equivalent string.
Calculate frequencies of all characters in this string. Counter() function can be used for this purpose in Python.
If the length of the Dictionary / HashMap storing the frequencies is 10, the number contains all possible distinct digits. Therefore, print βYesβ.
Otherwise, print βNoβ.
Below is the implementation of the above approach:
Python3
# Python implementation of above approach from collections import Counter # Function to check if# N is a Pangram or notdef numberPangram(N): # Stores equivalent string # representation of N num = str(N) # Count frequencies of # digits present in N frequency = Counter(num) # If the length of the # dictionary frequency is 10 if(len(frequency) == 10): # The number is a Pangram return True else: return False # Driver Code N =10239876540022print(numberPangram(N))
True
Time Complexity: O(log10N * log(log10N))Auxiliary Space: O(1)
abhinavjain194
SoumikMondal
ukasp
rutvik_56
cpp-map
frequency-counting
Java-HashMap
number-digits
Python dictionary-programs
Hash
Mathematical
Hash
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Quadratic Probing in Hashing
Rearrange an array such that arr[i] = i
Hashing in Java
Non-Repeating Element
What are Hash Functions and How to choose a good Hash Function?
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": 25132,
"s": 25104,
"text": "\n14 May, 2021"
},
{
"code": null,
"e": 25285,
"s": 25132,
"text": "Given an integer N, the task is to check whether the given number is a pangram or not. Note: A Pangram Number contains every digit [0- 9] at least once."
},
{
"code": null,
"e": 25295,
"s": 25285,
"text": "Examples:"
},
{
"code": null,
"e": 25413,
"s": 25295,
"text": "Input : N = 10239876540022Output : YesExplanation: N contains all the digits from 0 to 9. Therefore, it is a pangram."
},
{
"code": null,
"e": 25521,
"s": 25413,
"text": "Input : N = 234567890Output : NoExplanation: N doesnβt contain the digit 1. Therefore, it is not a pangram."
},
{
"code": null,
"e": 25662,
"s": 25521,
"text": "Set-based Approach: The idea is to use Sets to store the count of distinct digits present in N. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 25705,
"s": 25662,
"text": "Convert the number N to equivalent string."
},
{
"code": null,
"e": 25734,
"s": 25705,
"text": "Convert the string to a set."
},
{
"code": null,
"e": 25847,
"s": 25734,
"text": "If the size of the Set is 10, then it contains all the distinct possible digits [0 β 9]. Therefore, print βYesβ."
},
{
"code": null,
"e": 25869,
"s": 25847,
"text": "Otherwise, print βNoβ"
},
{
"code": null,
"e": 25920,
"s": 25869,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 25924,
"s": 25920,
"text": "C++"
},
{
"code": null,
"e": 25929,
"s": 25924,
"text": "Java"
},
{
"code": null,
"e": 25937,
"s": 25929,
"text": "Python3"
},
{
"code": null,
"e": 25940,
"s": 25937,
"text": "C#"
},
{
"code": null,
"e": 25951,
"s": 25940,
"text": "Javascript"
},
{
"code": "// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function to check if N// is a Pangram or notstring numberPangram(string N){ // Add all characters pf arrNum to set set<char> setNum; for (int i = 0; i < N.length(); i++) { setNum.insert(N[i]); } // If the length of set is 10 // The number is a Pangram if (setNum.size() == 10) return \"True\"; else return \"False\";} // Driver codeint main(){ string N = \"10239876540022\"; cout << (numberPangram(N));} // This code is contributed by ukasp.",
"e": 26528,
"s": 25951,
"text": null
},
{
"code": "// Java implementation of above approachimport java.math.BigInteger;import java.util.HashSet; class GFG{ // Function to check if N// is a Pangram or notstatic String numberPangram(BigInteger N){ // Stores equivalent string // representation of N String num = N.toString(); // Convert the string to Character array char[] arrNum = num.toCharArray(); // Add all characters pf arrNum to set HashSet<Character> setNum = new HashSet<Character>(); for(char ch : arrNum) { setNum.add(ch); } // If the length of set is 10 // The number is a Pangram if (setNum.size() == 10) return \"True\"; else return \"False\";} // Driver codepublic static void main(String[] args){ BigInteger N = new BigInteger(\"10239876540022\"); System.out.print(numberPangram(N));}} // This code is contributed by abhinavjain194",
"e": 27404,
"s": 26528,
"text": null
},
{
"code": "# Python3 implementation of above approach # Function to check if N# is a Pangram or notdef numberPangram(N): # Stores equivalent string # representation of N num = str(N) # Convert the string to set setnum = set(num) # If the length of set is 10 if(len(setnum) == 10): # The number is a Pangram return True else: return False # Driver Code N = 10239876540022print(numberPangram(N))",
"e": 27855,
"s": 27404,
"text": null
},
{
"code": "// C# implementation of above approachusing System;using System.Globalization;using System.Numerics;using System.Collections.Generic;class GFG{ // Function to check if N// is a Pangram or notstatic String numberPangram(ulong N){ // Stores equivalent string // representation of N string num = N.ToString(); // Convert the string to Character array char[] arrNum = num.ToCharArray(); // Add all characters pf arrNum to set HashSet<char> setNum = new HashSet<char>(); foreach(char ch in arrNum) { setNum.Add(ch); } // If the length of set is 10 // The number is a Pangram if (setNum.Count == 10) return \"True\"; else return \"False\";} // Driver Code static void Main() { ulong N = 10239876540022; Console.Write(numberPangram(N)); }} // This code is contributed by SoumikMondal",
"e": 28727,
"s": 27855,
"text": null
},
{
"code": "<script> // Javascript implementation of above approach // Function to check if N// is a Pangram or notfunction numberPangram(N){ // Add all characters pf arrNum to set var setNum = new Set(); for (var i = 0; i < N.length; i++) { setNum.add(N[i]); } // If the length of set is 10 // The number is a Pangram if (setNum.size == 10) return \"True\"; else return \"False\";} // Driver codevar N = \"10239876540022\";document.write(numberPangram(N)); </script>",
"e": 29225,
"s": 28727,
"text": null
},
{
"code": null,
"e": 29230,
"s": 29225,
"text": "True"
},
{
"code": null,
"e": 29294,
"s": 29232,
"text": "Time Complexity: O(log10N * log(log10N))Auxiliary Space: O(1)"
},
{
"code": null,
"e": 29357,
"s": 29294,
"text": "Hashing-based Approach: Follow the steps to solve the problem:"
},
{
"code": null,
"e": 29393,
"s": 29357,
"text": "Convert N to its equivalent string."
},
{
"code": null,
"e": 29508,
"s": 29393,
"text": "Calculate frequencies of all characters in this string. Counter() function can be used for this purpose in Python."
},
{
"code": null,
"e": 29655,
"s": 29508,
"text": "If the length of the Dictionary / HashMap storing the frequencies is 10, the number contains all possible distinct digits. Therefore, print βYesβ."
},
{
"code": null,
"e": 29678,
"s": 29655,
"text": "Otherwise, print βNoβ."
},
{
"code": null,
"e": 29729,
"s": 29678,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 29737,
"s": 29729,
"text": "Python3"
},
{
"code": "# Python implementation of above approach from collections import Counter # Function to check if# N is a Pangram or notdef numberPangram(N): # Stores equivalent string # representation of N num = str(N) # Count frequencies of # digits present in N frequency = Counter(num) # If the length of the # dictionary frequency is 10 if(len(frequency) == 10): # The number is a Pangram return True else: return False # Driver Code N =10239876540022print(numberPangram(N))",
"e": 30274,
"s": 29737,
"text": null
},
{
"code": null,
"e": 30279,
"s": 30274,
"text": "True"
},
{
"code": null,
"e": 30343,
"s": 30281,
"text": "Time Complexity: O(log10N * log(log10N))Auxiliary Space: O(1)"
},
{
"code": null,
"e": 30358,
"s": 30343,
"text": "abhinavjain194"
},
{
"code": null,
"e": 30371,
"s": 30358,
"text": "SoumikMondal"
},
{
"code": null,
"e": 30377,
"s": 30371,
"text": "ukasp"
},
{
"code": null,
"e": 30387,
"s": 30377,
"text": "rutvik_56"
},
{
"code": null,
"e": 30395,
"s": 30387,
"text": "cpp-map"
},
{
"code": null,
"e": 30414,
"s": 30395,
"text": "frequency-counting"
},
{
"code": null,
"e": 30427,
"s": 30414,
"text": "Java-HashMap"
},
{
"code": null,
"e": 30441,
"s": 30427,
"text": "number-digits"
},
{
"code": null,
"e": 30468,
"s": 30441,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 30473,
"s": 30468,
"text": "Hash"
},
{
"code": null,
"e": 30486,
"s": 30473,
"text": "Mathematical"
},
{
"code": null,
"e": 30491,
"s": 30486,
"text": "Hash"
},
{
"code": null,
"e": 30504,
"s": 30491,
"text": "Mathematical"
},
{
"code": null,
"e": 30602,
"s": 30504,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30631,
"s": 30602,
"text": "Quadratic Probing in Hashing"
},
{
"code": null,
"e": 30671,
"s": 30631,
"text": "Rearrange an array such that arr[i] = i"
},
{
"code": null,
"e": 30687,
"s": 30671,
"text": "Hashing in Java"
},
{
"code": null,
"e": 30709,
"s": 30687,
"text": "Non-Repeating Element"
},
{
"code": null,
"e": 30773,
"s": 30709,
"text": "What are Hash Functions and How to choose a good Hash Function?"
},
{
"code": null,
"e": 30803,
"s": 30773,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 30863,
"s": 30803,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 30878,
"s": 30863,
"text": "C++ Data Types"
},
{
"code": null,
"e": 30921,
"s": 30878,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
turtle.speed() function in Python - GeeksforGeeks
|
20 Jul, 2020
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
The turtle.speed() method is used to change the speed of the turtle by the value of the argument that it takes. Return or set the turtleβs speed.
Syntax :
turtle.speed(speed=None)
Note:
The turtleβs speed lies in the range 0-10.
If input is a number greater than 10 or smaller than 0.5, speed is set to 0.
Speedstrings are mapped to speedvalues in the following way:βfastestβ : 0βfastβ : 10βnormalβ : 6βslowβ : 3βslowestβ : 1
βfastestβ : 0
βfastβ : 10
βnormalβ : 6
βslowβ : 3
βslowestβ : 1
Speeds from 1 to 10 enforce increasingly faster animation of line drawing and turtle turning.
Below is the implementation of the above method with some examples :
Example 1 :
Python3
# import packageimport turtle # slowest speedturtle.speed(1) # turtle movementturtle.forward(150)
Output :
Example 2 :
Python3
# import packageimport turtle # loop for patternfor i in range(10): # set turtle speed turtle.speed(10-i) # motion for pattern turtle.forward(50+10*i) turtle.right(90)
Output :
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
|
[
{
"code": null,
"e": 25857,
"s": 25829,
"text": "\n20 Jul, 2020"
},
{
"code": null,
"e": 26074,
"s": 25857,
"text": "The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support."
},
{
"code": null,
"e": 26220,
"s": 26074,
"text": "The turtle.speed() method is used to change the speed of the turtle by the value of the argument that it takes. Return or set the turtleβs speed."
},
{
"code": null,
"e": 26229,
"s": 26220,
"text": "Syntax :"
},
{
"code": null,
"e": 26255,
"s": 26229,
"text": "turtle.speed(speed=None)\n"
},
{
"code": null,
"e": 26261,
"s": 26255,
"text": "Note:"
},
{
"code": null,
"e": 26304,
"s": 26261,
"text": "The turtleβs speed lies in the range 0-10."
},
{
"code": null,
"e": 26381,
"s": 26304,
"text": "If input is a number greater than 10 or smaller than 0.5, speed is set to 0."
},
{
"code": null,
"e": 26514,
"s": 26381,
"text": "Speedstrings are mapped to speedvalues in the following way:βfastestβ : 0βfastβ : 10βnormalβ : 6βslowβ : 3βslowestβ : 1"
},
{
"code": null,
"e": 26529,
"s": 26514,
"text": "βfastestβ : 0"
},
{
"code": null,
"e": 26545,
"s": 26529,
"text": "βfastβ : 10"
},
{
"code": null,
"e": 26560,
"s": 26545,
"text": "βnormalβ : 6"
},
{
"code": null,
"e": 26575,
"s": 26560,
"text": "βslowβ : 3"
},
{
"code": null,
"e": 26590,
"s": 26575,
"text": "βslowestβ : 1"
},
{
"code": null,
"e": 26684,
"s": 26590,
"text": "Speeds from 1 to 10 enforce increasingly faster animation of line drawing and turtle turning."
},
{
"code": null,
"e": 26753,
"s": 26684,
"text": "Below is the implementation of the above method with some examples :"
},
{
"code": null,
"e": 26765,
"s": 26753,
"text": "Example 1 :"
},
{
"code": null,
"e": 26773,
"s": 26765,
"text": "Python3"
},
{
"code": "# import packageimport turtle # slowest speedturtle.speed(1) # turtle movementturtle.forward(150)",
"e": 26873,
"s": 26773,
"text": null
},
{
"code": null,
"e": 26882,
"s": 26873,
"text": "Output :"
},
{
"code": null,
"e": 26894,
"s": 26882,
"text": "Example 2 :"
},
{
"code": null,
"e": 26902,
"s": 26894,
"text": "Python3"
},
{
"code": "# import packageimport turtle # loop for patternfor i in range(10): # set turtle speed turtle.speed(10-i) # motion for pattern turtle.forward(50+10*i) turtle.right(90)",
"e": 27085,
"s": 26902,
"text": null
},
{
"code": null,
"e": 27094,
"s": 27085,
"text": "Output :"
},
{
"code": null,
"e": 27108,
"s": 27094,
"text": "Python-turtle"
},
{
"code": null,
"e": 27115,
"s": 27108,
"text": "Python"
},
{
"code": null,
"e": 27213,
"s": 27115,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27231,
"s": 27213,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27266,
"s": 27231,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27298,
"s": 27266,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27320,
"s": 27298,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27362,
"s": 27320,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27392,
"s": 27362,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27418,
"s": 27392,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27447,
"s": 27418,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 27491,
"s": 27447,
"text": "Reading and Writing to text files in Python"
}
] |
PostgreSQL - STRING_AGG() Function - GeeksforGeeks
|
01 Jun, 2020
The STRING_AGG() function in PostgreSQL is an aggregate function that is used to concatenate a list of strings and place a separator between them.
Syntax: STRING_AGG ( expression, separator [order_by_clause] )
Letβs analyze the above syntax. The above function accepts two arguments and an optional ORDER BY clause.
expression is any valid expression that can resolve to a character string.
separator is the separator for concatenated strings.
Now letβs look into some examples.For examples we will be using the sample database (ie, dvdrental).
Example 1:We will query for a list of actorβs names for each film from the film table using the below command:
SELECT
f.title,
STRING_AGG (
a.first_name || ' ' || a.last_name,
', '
ORDER BY
a.first_name,
a.last_name
) actors
FROM
film f
INNER JOIN film_actor fa USING (film_id)
INNER JOIN actor a USING (actor_id)
GROUP BY
f.title;
Output:
Example 2:In this example we will an email list for each country from the country table. The email in each list separated by a semi-colon.To do so we use the below command:
SELECT
country,
STRING_AGG (email, ';') email_list
FROM
customer
INNER JOIN address USING (address_id)
INNER JOIN city USING (city_id)
INNER JOIN country USING (country_id)
GROUP BY
country
ORDER BY
country;
Output:
postgreSQL-aggregate-functions
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - CREATE PROCEDURE
PostgreSQL - GROUP BY clause
PostgreSQL - DROP INDEX
PostgreSQL - TIME Data Type
PostgreSQL - REPLACE Function
PostgreSQL - Copy Table
PostgreSQL - CREATE SCHEMA
PostgreSQL - Rename Table
PostgreSQL - ROW_NUMBER Function
PostgreSQL - Identity Column
|
[
{
"code": null,
"e": 25243,
"s": 25215,
"text": "\n01 Jun, 2020"
},
{
"code": null,
"e": 25390,
"s": 25243,
"text": "The STRING_AGG() function in PostgreSQL is an aggregate function that is used to concatenate a list of strings and place a separator between them."
},
{
"code": null,
"e": 25453,
"s": 25390,
"text": "Syntax: STRING_AGG ( expression, separator [order_by_clause] )"
},
{
"code": null,
"e": 25559,
"s": 25453,
"text": "Letβs analyze the above syntax. The above function accepts two arguments and an optional ORDER BY clause."
},
{
"code": null,
"e": 25634,
"s": 25559,
"text": "expression is any valid expression that can resolve to a character string."
},
{
"code": null,
"e": 25687,
"s": 25634,
"text": "separator is the separator for concatenated strings."
},
{
"code": null,
"e": 25788,
"s": 25687,
"text": "Now letβs look into some examples.For examples we will be using the sample database (ie, dvdrental)."
},
{
"code": null,
"e": 25899,
"s": 25788,
"text": "Example 1:We will query for a list of actorβs names for each film from the film table using the below command:"
},
{
"code": null,
"e": 26175,
"s": 25899,
"text": "SELECT\n f.title,\n STRING_AGG (\n a.first_name || ' ' || a.last_name,\n ', '\n ORDER BY\n a.first_name,\n a.last_name\n ) actors\nFROM\n film f\nINNER JOIN film_actor fa USING (film_id)\nINNER JOIN actor a USING (actor_id)\nGROUP BY\n f.title;"
},
{
"code": null,
"e": 26183,
"s": 26175,
"text": "Output:"
},
{
"code": null,
"e": 26356,
"s": 26183,
"text": "Example 2:In this example we will an email list for each country from the country table. The email in each list separated by a semi-colon.To do so we use the below command:"
},
{
"code": null,
"e": 26584,
"s": 26356,
"text": "SELECT\n country,\n STRING_AGG (email, ';') email_list\nFROM\n customer\nINNER JOIN address USING (address_id)\nINNER JOIN city USING (city_id)\nINNER JOIN country USING (country_id)\nGROUP BY\n country\nORDER BY\n country;"
},
{
"code": null,
"e": 26592,
"s": 26584,
"text": "Output:"
},
{
"code": null,
"e": 26623,
"s": 26592,
"text": "postgreSQL-aggregate-functions"
},
{
"code": null,
"e": 26634,
"s": 26623,
"text": "PostgreSQL"
},
{
"code": null,
"e": 26732,
"s": 26634,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26762,
"s": 26732,
"text": "PostgreSQL - CREATE PROCEDURE"
},
{
"code": null,
"e": 26791,
"s": 26762,
"text": "PostgreSQL - GROUP BY clause"
},
{
"code": null,
"e": 26815,
"s": 26791,
"text": "PostgreSQL - DROP INDEX"
},
{
"code": null,
"e": 26843,
"s": 26815,
"text": "PostgreSQL - TIME Data Type"
},
{
"code": null,
"e": 26873,
"s": 26843,
"text": "PostgreSQL - REPLACE Function"
},
{
"code": null,
"e": 26897,
"s": 26873,
"text": "PostgreSQL - Copy Table"
},
{
"code": null,
"e": 26924,
"s": 26897,
"text": "PostgreSQL - CREATE SCHEMA"
},
{
"code": null,
"e": 26950,
"s": 26924,
"text": "PostgreSQL - Rename Table"
},
{
"code": null,
"e": 26983,
"s": 26950,
"text": "PostgreSQL - ROW_NUMBER Function"
}
] |
How to divide an HTML page into four parts using frames ? - GeeksforGeeks
|
25 Mar, 2021
In this article, we will learn how to divide a page into four parts using HTML frames. This can be used to represent the header, sidebar, footer, and main content. The frames are created using the <frame> tag. We will have to use four HTML files for each of the portions.
Syntax:
<frameset>
// frame elements
</frameset>
The below example will demonstrate the approach to create the four parts of the page.
index.html
<html><frameset rows="10%,80%,10%"> <frame name="A" src="header.html"> <frameset cols="80%,20%"> <frame name="B" src="home.html"> <frame name="C" src="sidebar.html"> </frameset> <frame name="B" src="footer.html"> <frameset rows="100%"> </frameset></frameset></html>
Output: The page will now be divided like this.
We will now create the HTML pages of the four sections and the content of the main page separately.
header.html
<html><body> <h1 style="color: green; text-align: center"> GeeksforGeeks </h1></body></html>
home.html
<html><body> <h1 style="text-align: center"> Welcome to the home page </h1></body></html>
sidebar.html
<html><body> <h3>Sidebar</h3> <a href="html_content.html" target="B"> HTML </a><br> <a href="css_content.html" target="B"> CSS </a><br> <a href="js_content.html" target="B"> JS </a><br> <a href="php_content.html " target="B"> PHP </a></body></html>
footer.html
<html><body> <h4 align="center"> All Rights Reserved </h4></body></html>
html_content.html
<html><body> <p style="text-align: center"> Hyper Text Markup Language </p> </body></html>
css_content.html
<html><body> <p style="text-align: center"> Cascading Style Sheets </p> </body></html>
js_content.html
<html><body> <p style="text-align: center"> JavaScript </p> </body></html>
php_content.html
<html><body> <p style="text-align: center"> Hypertext Preprocessor </p> </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.
HTML-Attributes
HTML-Questions
HTML-Tags
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 33028,
"s": 33000,
"text": "\n25 Mar, 2021"
},
{
"code": null,
"e": 33300,
"s": 33028,
"text": "In this article, we will learn how to divide a page into four parts using HTML frames. This can be used to represent the header, sidebar, footer, and main content. The frames are created using the <frame> tag. We will have to use four HTML files for each of the portions."
},
{
"code": null,
"e": 33308,
"s": 33300,
"text": "Syntax:"
},
{
"code": null,
"e": 33353,
"s": 33308,
"text": "<frameset>\n // frame elements\n</frameset>"
},
{
"code": null,
"e": 33439,
"s": 33353,
"text": "The below example will demonstrate the approach to create the four parts of the page."
},
{
"code": null,
"e": 33450,
"s": 33439,
"text": "index.html"
},
{
"code": "<html><frameset rows=\"10%,80%,10%\"> <frame name=\"A\" src=\"header.html\"> <frameset cols=\"80%,20%\"> <frame name=\"B\" src=\"home.html\"> <frame name=\"C\" src=\"sidebar.html\"> </frameset> <frame name=\"B\" src=\"footer.html\"> <frameset rows=\"100%\"> </frameset></frameset></html>",
"e": 33748,
"s": 33450,
"text": null
},
{
"code": null,
"e": 33796,
"s": 33748,
"text": "Output: The page will now be divided like this."
},
{
"code": null,
"e": 33897,
"s": 33796,
"text": "We will now create the HTML pages of the four sections and the content of the main page separately. "
},
{
"code": null,
"e": 33909,
"s": 33897,
"text": "header.html"
},
{
"code": "<html><body> <h1 style=\"color: green; text-align: center\"> GeeksforGeeks </h1></body></html>",
"e": 34020,
"s": 33909,
"text": null
},
{
"code": null,
"e": 34030,
"s": 34020,
"text": "home.html"
},
{
"code": "<html><body> <h1 style=\"text-align: center\"> Welcome to the home page </h1></body></html>",
"e": 34125,
"s": 34030,
"text": null
},
{
"code": null,
"e": 34138,
"s": 34125,
"text": "sidebar.html"
},
{
"code": "<html><body> <h3>Sidebar</h3> <a href=\"html_content.html\" target=\"B\"> HTML </a><br> <a href=\"css_content.html\" target=\"B\"> CSS </a><br> <a href=\"js_content.html\" target=\"B\"> JS </a><br> <a href=\"php_content.html \" target=\"B\"> PHP </a></body></html>",
"e": 34408,
"s": 34138,
"text": null
},
{
"code": null,
"e": 34420,
"s": 34408,
"text": "footer.html"
},
{
"code": "<html><body> <h4 align=\"center\"> All Rights Reserved </h4></body></html>",
"e": 34498,
"s": 34420,
"text": null
},
{
"code": null,
"e": 34516,
"s": 34498,
"text": "html_content.html"
},
{
"code": "<html><body> <p style=\"text-align: center\"> Hyper Text Markup Language </p> </body></html>",
"e": 34613,
"s": 34516,
"text": null
},
{
"code": null,
"e": 34630,
"s": 34613,
"text": "css_content.html"
},
{
"code": "<html><body> <p style=\"text-align: center\"> Cascading Style Sheets </p> </body></html>",
"e": 34723,
"s": 34630,
"text": null
},
{
"code": null,
"e": 34739,
"s": 34723,
"text": "js_content.html"
},
{
"code": "<html><body> <p style=\"text-align: center\"> JavaScript </p> </body></html>",
"e": 34820,
"s": 34739,
"text": null
},
{
"code": null,
"e": 34837,
"s": 34820,
"text": "php_content.html"
},
{
"code": "<html><body> <p style=\"text-align: center\"> Hypertext Preprocessor </p> </body></html>",
"e": 34931,
"s": 34837,
"text": null
},
{
"code": null,
"e": 34939,
"s": 34931,
"text": "Output:"
},
{
"code": null,
"e": 35076,
"s": 34939,
"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": 35092,
"s": 35076,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 35107,
"s": 35092,
"text": "HTML-Questions"
},
{
"code": null,
"e": 35117,
"s": 35107,
"text": "HTML-Tags"
},
{
"code": null,
"e": 35122,
"s": 35117,
"text": "HTML"
},
{
"code": null,
"e": 35139,
"s": 35122,
"text": "Web Technologies"
},
{
"code": null,
"e": 35144,
"s": 35139,
"text": "HTML"
},
{
"code": null,
"e": 35242,
"s": 35144,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35292,
"s": 35242,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 35354,
"s": 35292,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 35402,
"s": 35354,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 35462,
"s": 35402,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 35515,
"s": 35462,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 35555,
"s": 35515,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 35588,
"s": 35555,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 35633,
"s": 35588,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 35676,
"s": 35633,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Python - Pytorch permute() method - GeeksforGeeks
|
18 Aug, 2020
PyTorch torch.permute() rearranges the original tensor according to the desired ordering and returns a new multidimensional rotated tensor. The size of the returned tensor remains the same as that of the original.
Syntax: torch.permute(*dims)
Parameters:
dims: sequence of indices in desired ordering of dimensions Of the tensor (indexing starts from zero).
Return: tensor with desired ordering of dimensions.
Letβs see this concept with the help of few examples:
Example 1: Create a two-dimensional tensor of size 2 Γ 4 and then permuted.
Python3
# import pytorch libraryimport torch # create a tensor of size 2 x 4input_var = torch.randn(2,4) # print sizeprint(input_var.size()) print(input_var) # dimensions permutedinput_var = input_var.permute(1, 0) # print sizeprint(input_var.size()) print(input_var)
Output:
torch.Size([2, 4])
tensor([[ 0.9801, 0.5296, 0.5449, -1.1481],
[-0.6762, -0.1161, 0.6360, -0.5371]])
torch.Size([4, 2])
tensor([[ 0.9801, -0.6762],
[ 0.5296, -0.1161],
[ 0.5449, 0.6360],
[-1.1481, -0.5371]])
Example 2: Create a Three-dimensional tensor of size 3 Γ 5 Γ 2 and then permuted.
Python3
# import pytorch libraryimport torch # creating a tensor with random # values of dimension 3 X 5 X 2input_var = torch.randn(3, 5, 2) # print sizeprint(input_var.size()) print(input_var) # dimensions permutedinput_var = input_var.permute(2, 0, 1) # print sizeprint(input_var.size()) print(input_var)
Output:
torch.Size([3, 5, 2])
tensor([[[ 0.2059, -0.7165],
[-1.1305, 0.5886],
[-0.1247, -0.4969],
[-0.5788, 0.0159],
[ 1.4304, 0.6014]],
[[ 2.4882, -0.3910],
[-0.5558, 0.6903],
[-0.4219, -0.5498],
[-0.5346, -0.0703],
[ 1.1497, -0.3252]],
[[-0.5075, 0.5752],
[ 1.3738, -0.3321],
[-0.3317, -0.9209],
[-1.6677, -1.1471],
[-0.9269, -0.6493]]])
torch.Size([2, 3, 5])
tensor([[[ 0.2059, -1.1305, -0.1247, -0.5788, 1.4304],
[ 2.4882, -0.5558, -0.4219, -0.5346, 1.1497],
[-0.5075, 1.3738, -0.3317, -1.6677, -0.9269]],
[[-0.7165, 0.5886, -0.4969, 0.0159, 0.6014],
[-0.3910, 0.6903, -0.5498, -0.0703, -0.3252],
[ 0.5752, -0.3321, -0.9209, -1.1471, -0.6493]]])
Python-PyTorch
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": "\n18 Aug, 2020"
},
{
"code": null,
"e": 25751,
"s": 25537,
"text": "PyTorch torch.permute() rearranges the original tensor according to the desired ordering and returns a new multidimensional rotated tensor. The size of the returned tensor remains the same as that of the original."
},
{
"code": null,
"e": 25781,
"s": 25751,
"text": "Syntax: torch.permute(*dims) "
},
{
"code": null,
"e": 25793,
"s": 25781,
"text": "Parameters:"
},
{
"code": null,
"e": 25896,
"s": 25793,
"text": "dims: sequence of indices in desired ordering of dimensions Of the tensor (indexing starts from zero)."
},
{
"code": null,
"e": 25948,
"s": 25896,
"text": "Return: tensor with desired ordering of dimensions."
},
{
"code": null,
"e": 26002,
"s": 25948,
"text": "Letβs see this concept with the help of few examples:"
},
{
"code": null,
"e": 26078,
"s": 26002,
"text": "Example 1: Create a two-dimensional tensor of size 2 Γ 4 and then permuted."
},
{
"code": null,
"e": 26086,
"s": 26078,
"text": "Python3"
},
{
"code": "# import pytorch libraryimport torch # create a tensor of size 2 x 4input_var = torch.randn(2,4) # print sizeprint(input_var.size()) print(input_var) # dimensions permutedinput_var = input_var.permute(1, 0) # print sizeprint(input_var.size()) print(input_var)",
"e": 26352,
"s": 26086,
"text": null
},
{
"code": null,
"e": 26360,
"s": 26352,
"text": "Output:"
},
{
"code": null,
"e": 26604,
"s": 26360,
"text": "torch.Size([2, 4])\ntensor([[ 0.9801, 0.5296, 0.5449, -1.1481],\n [-0.6762, -0.1161, 0.6360, -0.5371]])\ntorch.Size([4, 2])\ntensor([[ 0.9801, -0.6762],\n [ 0.5296, -0.1161],\n [ 0.5449, 0.6360],\n [-1.1481, -0.5371]])"
},
{
"code": null,
"e": 26686,
"s": 26604,
"text": "Example 2: Create a Three-dimensional tensor of size 3 Γ 5 Γ 2 and then permuted."
},
{
"code": null,
"e": 26694,
"s": 26686,
"text": "Python3"
},
{
"code": "# import pytorch libraryimport torch # creating a tensor with random # values of dimension 3 X 5 X 2input_var = torch.randn(3, 5, 2) # print sizeprint(input_var.size()) print(input_var) # dimensions permutedinput_var = input_var.permute(2, 0, 1) # print sizeprint(input_var.size()) print(input_var)",
"e": 26999,
"s": 26694,
"text": null
},
{
"code": null,
"e": 27007,
"s": 26999,
"text": "Output:"
},
{
"code": null,
"e": 27833,
"s": 27007,
"text": "torch.Size([3, 5, 2])\ntensor([[[ 0.2059, -0.7165],\n [-1.1305, 0.5886],\n [-0.1247, -0.4969],\n [-0.5788, 0.0159],\n [ 1.4304, 0.6014]],\n\n [[ 2.4882, -0.3910],\n [-0.5558, 0.6903],\n [-0.4219, -0.5498],\n [-0.5346, -0.0703],\n [ 1.1497, -0.3252]],\n\n [[-0.5075, 0.5752],\n [ 1.3738, -0.3321],\n [-0.3317, -0.9209],\n [-1.6677, -1.1471],\n [-0.9269, -0.6493]]])\ntorch.Size([2, 3, 5])\ntensor([[[ 0.2059, -1.1305, -0.1247, -0.5788, 1.4304],\n [ 2.4882, -0.5558, -0.4219, -0.5346, 1.1497],\n [-0.5075, 1.3738, -0.3317, -1.6677, -0.9269]],\n\n [[-0.7165, 0.5886, -0.4969, 0.0159, 0.6014],\n [-0.3910, 0.6903, -0.5498, -0.0703, -0.3252],\n [ 0.5752, -0.3321, -0.9209, -1.1471, -0.6493]]])\n"
},
{
"code": null,
"e": 27848,
"s": 27833,
"text": "Python-PyTorch"
},
{
"code": null,
"e": 27855,
"s": 27848,
"text": "Python"
},
{
"code": null,
"e": 27953,
"s": 27855,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27985,
"s": 27953,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28027,
"s": 27985,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28069,
"s": 28027,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28125,
"s": 28069,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28152,
"s": 28125,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28183,
"s": 28152,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28222,
"s": 28183,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28251,
"s": 28222,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 28273,
"s": 28251,
"text": "Defaultdict in Python"
}
] |
PHP | array_slice() Function - GeeksforGeeks
|
14 Nov, 2021
The array_slice() is an inbuilt function of PHP and is used to fetch a part of an array by slicing through it, according to the users choice.Syntax:
array_slice($array, $start_point, $slicing_range, preserve)
Parameters: This function can take four parameters and are described below:
$array (mandatory): This parameter refers to the original array, we want to slice.$start_point (mandatory): This parameter refers to the starting position of the array from where the slicing need to be performed. It is mandatory to supply this value. If the value supplied is negative, then the function starts slicing from the end of the array, i.e., -1 refers to the last element of the array.$slicing _range (optional): This parameter refers to the range or limit point upto which the slicing is needed to be done. A negative value will indicate the count from the end of the string. Now, this can also be left blank. On leaving blank the function will slice through all the values as mentioned in the starting point right up to the end.preserve (optional): This parameter can take only two boolean parameters, i.e., either True or False. This will tell the function whether to preserve the keys or reset it. True refers to preserve the keys and false refers to reset the keys. False being the default value.
$array (mandatory): This parameter refers to the original array, we want to slice.
$start_point (mandatory): This parameter refers to the starting position of the array from where the slicing need to be performed. It is mandatory to supply this value. If the value supplied is negative, then the function starts slicing from the end of the array, i.e., -1 refers to the last element of the array.
$slicing _range (optional): This parameter refers to the range or limit point upto which the slicing is needed to be done. A negative value will indicate the count from the end of the string. Now, this can also be left blank. On leaving blank the function will slice through all the values as mentioned in the starting point right up to the end.
preserve (optional): This parameter can take only two boolean parameters, i.e., either True or False. This will tell the function whether to preserve the keys or reset it. True refers to preserve the keys and false refers to reset the keys. False being the default value.
Return Value: As already mentioned this function will return the selected or the sliced parts of the array.Below program illustrate the array_slice() function in PHP:
In this program, we will be passing all the positive parameters along with the True value to preserve the keys.
PHP
<?php // PHP program to illustrate the// array_slice() function // Input array$array = array("ram", "krishna", "aakash", "gaurav", "raghav"); // Slice from pos 1 to pos 3 print_r(array_slice($array, 1, 3, true)); ?>
Output:
Array
(
[1] => krishna
[2] => aakash
[3] => gaurav
)
Now letβs try to observe the output by passing the same values as in above program, but with False as the value of the preserved key.
PHP
<?php // PHP program to illustrate the// array_slice() function // input array$array = array("ram", "krishna", "aakash", "gaurav", "raghav"); // Slice from pos 1 to pos 3print_r(array_slice($array, 1, 3, false)); ?>
Output:
Array
(
[0] => krishna
[1] => aakash
[2] => gaurav
)
Below program shows what happens when we dont give the range parameter:
PHP
<?php // PHP program to illustrate the// use of array_slice() // Input array$array = array("ram", "krishna", "aakash", "gaurav", "raghav"); // Slice from pos 1 to endprint_r(array_slice($array, 1)); ?>
Output:
Array
(
[0] => krishna
[1] => aakash
[2] => gaurav
[3] => raghav
)
Below program illustrate the array_slice() function when we pass the negative parameter as our starting position:
PHP
<?php // PHP program to illustrate the// use of array_slice() // Input array$array = array("ram", "krishna", "aakash", "gaurav", "raghav"); // Slice from pos 3rd position to// the end of the arrayprint_r(array_slice($array, -3)); ?>
Output:
Array
(
[0] => aakash
[1] => gaurav
[2] => raghav
)
Below program shows what happens when we try to pass the negative parameters as both the starting point and the length or range:
PHP
<?php // PHP program to illustrate the// use of array_slice() // Input Array$array = array("ram", "krishna", "aakash", "gaurav", "raghav"); // Slice from pos 1 to endprint_r(array_slice($array, -3, -2, true)); ?>
Output:
Array
(
[2] => aakash
)
Reference: http://php.net/manual/en/function.array-slice.php
kapoorsagar226
surinderdawra388
PHP-array
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
PHP | Converting string to Date and DateTime
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 ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
|
[
{
"code": null,
"e": 26145,
"s": 26117,
"text": "\n14 Nov, 2021"
},
{
"code": null,
"e": 26295,
"s": 26145,
"text": "The array_slice() is an inbuilt function of PHP and is used to fetch a part of an array by slicing through it, according to the users choice.Syntax: "
},
{
"code": null,
"e": 26355,
"s": 26295,
"text": "array_slice($array, $start_point, $slicing_range, preserve)"
},
{
"code": null,
"e": 26433,
"s": 26355,
"text": "Parameters: This function can take four parameters and are described below: "
},
{
"code": null,
"e": 27445,
"s": 26433,
"text": "$array (mandatory): This parameter refers to the original array, we want to slice.$start_point (mandatory): This parameter refers to the starting position of the array from where the slicing need to be performed. It is mandatory to supply this value. If the value supplied is negative, then the function starts slicing from the end of the array, i.e., -1 refers to the last element of the array.$slicing _range (optional): This parameter refers to the range or limit point upto which the slicing is needed to be done. A negative value will indicate the count from the end of the string. Now, this can also be left blank. On leaving blank the function will slice through all the values as mentioned in the starting point right up to the end.preserve (optional): This parameter can take only two boolean parameters, i.e., either True or False. This will tell the function whether to preserve the keys or reset it. True refers to preserve the keys and false refers to reset the keys. False being the default value."
},
{
"code": null,
"e": 27528,
"s": 27445,
"text": "$array (mandatory): This parameter refers to the original array, we want to slice."
},
{
"code": null,
"e": 27842,
"s": 27528,
"text": "$start_point (mandatory): This parameter refers to the starting position of the array from where the slicing need to be performed. It is mandatory to supply this value. If the value supplied is negative, then the function starts slicing from the end of the array, i.e., -1 refers to the last element of the array."
},
{
"code": null,
"e": 28188,
"s": 27842,
"text": "$slicing _range (optional): This parameter refers to the range or limit point upto which the slicing is needed to be done. A negative value will indicate the count from the end of the string. Now, this can also be left blank. On leaving blank the function will slice through all the values as mentioned in the starting point right up to the end."
},
{
"code": null,
"e": 28460,
"s": 28188,
"text": "preserve (optional): This parameter can take only two boolean parameters, i.e., either True or False. This will tell the function whether to preserve the keys or reset it. True refers to preserve the keys and false refers to reset the keys. False being the default value."
},
{
"code": null,
"e": 28628,
"s": 28460,
"text": "Return Value: As already mentioned this function will return the selected or the sliced parts of the array.Below program illustrate the array_slice() function in PHP: "
},
{
"code": null,
"e": 28741,
"s": 28628,
"text": "In this program, we will be passing all the positive parameters along with the True value to preserve the keys. "
},
{
"code": null,
"e": 28745,
"s": 28741,
"text": "PHP"
},
{
"code": "<?php // PHP program to illustrate the// array_slice() function // Input array$array = array(\"ram\", \"krishna\", \"aakash\", \"gaurav\", \"raghav\"); // Slice from pos 1 to pos 3 print_r(array_slice($array, 1, 3, true)); ?>",
"e": 29030,
"s": 28745,
"text": null
},
{
"code": null,
"e": 29039,
"s": 29030,
"text": "Output: "
},
{
"code": null,
"e": 29104,
"s": 29039,
"text": "Array\n(\n [1] => krishna\n [2] => aakash\n [3] => gaurav\n)"
},
{
"code": null,
"e": 29239,
"s": 29104,
"text": "Now letβs try to observe the output by passing the same values as in above program, but with False as the value of the preserved key. "
},
{
"code": null,
"e": 29243,
"s": 29239,
"text": "PHP"
},
{
"code": "<?php // PHP program to illustrate the// array_slice() function // input array$array = array(\"ram\", \"krishna\", \"aakash\", \"gaurav\", \"raghav\"); // Slice from pos 1 to pos 3print_r(array_slice($array, 1, 3, false)); ?>",
"e": 29482,
"s": 29243,
"text": null
},
{
"code": null,
"e": 29491,
"s": 29482,
"text": "Output: "
},
{
"code": null,
"e": 29556,
"s": 29491,
"text": "Array\n(\n [0] => krishna\n [1] => aakash\n [2] => gaurav\n)"
},
{
"code": null,
"e": 29629,
"s": 29556,
"text": "Below program shows what happens when we dont give the range parameter: "
},
{
"code": null,
"e": 29633,
"s": 29629,
"text": "PHP"
},
{
"code": "<?php // PHP program to illustrate the// use of array_slice() // Input array$array = array(\"ram\", \"krishna\", \"aakash\", \"gaurav\", \"raghav\"); // Slice from pos 1 to endprint_r(array_slice($array, 1)); ?>",
"e": 29858,
"s": 29633,
"text": null
},
{
"code": null,
"e": 29867,
"s": 29858,
"text": "Output: "
},
{
"code": null,
"e": 29950,
"s": 29867,
"text": "Array\n(\n [0] => krishna\n [1] => aakash\n [2] => gaurav\n [3] => raghav\n)"
},
{
"code": null,
"e": 30065,
"s": 29950,
"text": "Below program illustrate the array_slice() function when we pass the negative parameter as our starting position: "
},
{
"code": null,
"e": 30069,
"s": 30065,
"text": "PHP"
},
{
"code": "<?php // PHP program to illustrate the// use of array_slice() // Input array$array = array(\"ram\", \"krishna\", \"aakash\", \"gaurav\", \"raghav\"); // Slice from pos 3rd position to// the end of the arrayprint_r(array_slice($array, -3)); ?>",
"e": 30325,
"s": 30069,
"text": null
},
{
"code": null,
"e": 30334,
"s": 30325,
"text": "Output: "
},
{
"code": null,
"e": 30398,
"s": 30334,
"text": "Array\n(\n [0] => aakash\n [1] => gaurav\n [2] => raghav\n)"
},
{
"code": null,
"e": 30528,
"s": 30398,
"text": "Below program shows what happens when we try to pass the negative parameters as both the starting point and the length or range: "
},
{
"code": null,
"e": 30532,
"s": 30528,
"text": "PHP"
},
{
"code": "<?php // PHP program to illustrate the// use of array_slice() // Input Array$array = array(\"ram\", \"krishna\", \"aakash\", \"gaurav\", \"raghav\"); // Slice from pos 1 to endprint_r(array_slice($array, -3, -2, true)); ?>",
"e": 30768,
"s": 30532,
"text": null
},
{
"code": null,
"e": 30777,
"s": 30768,
"text": "Output: "
},
{
"code": null,
"e": 30805,
"s": 30777,
"text": "Array\n(\n [2] => aakash\n)"
},
{
"code": null,
"e": 30866,
"s": 30805,
"text": "Reference: http://php.net/manual/en/function.array-slice.php"
},
{
"code": null,
"e": 30881,
"s": 30866,
"text": "kapoorsagar226"
},
{
"code": null,
"e": 30898,
"s": 30881,
"text": "surinderdawra388"
},
{
"code": null,
"e": 30908,
"s": 30898,
"text": "PHP-array"
},
{
"code": null,
"e": 30921,
"s": 30908,
"text": "PHP-function"
},
{
"code": null,
"e": 30925,
"s": 30921,
"text": "PHP"
},
{
"code": null,
"e": 30942,
"s": 30925,
"text": "Web Technologies"
},
{
"code": null,
"e": 30946,
"s": 30942,
"text": "PHP"
},
{
"code": null,
"e": 31044,
"s": 30946,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31094,
"s": 31044,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 31134,
"s": 31094,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 31195,
"s": 31134,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 31245,
"s": 31195,
"text": "How to check whether an array is empty using PHP?"
},
{
"code": null,
"e": 31290,
"s": 31245,
"text": "PHP | Converting string to Date and DateTime"
},
{
"code": null,
"e": 31330,
"s": 31290,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 31363,
"s": 31330,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 31408,
"s": 31363,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 31451,
"s": 31408,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Optional orElseThrow() method in Java with examples - GeeksforGeeks
|
30 Jul, 2019
The orElseThrow() method of java.util.Optional class in Java is used to get the value of this Optional instance if present. If there is no value present in this Optional instance, then this method throws the exception generated from the specified supplier.
Syntax:
public <X> T
orElseThrow(Supplier<X> exceptionSupplier)
throws X extends Throwable
Parameters: This method accepts supplier as a parameter of type X to throws an exception if there is no value present in this Optional instance.
Return supplier: This method returns the value of this Optional instance, if present. If there is no value present in this Optional instance, then this method throws the exception generated from the specified supplier.
Exception: This method throws NullPointerException if there is no value present in this Optional instance.
Below programs illustrate orElseThrow() method:Program 1:
// Java program to demonstrate// Optional.orElseThrow() method import java.util.*;import java.util.function.*; public class GFG { public static void main(String[] args) { // create a Optional Optional<Integer> op = Optional.of(9455); // print supplier System.out.println("Optional: " + op); // orElseThrow supplier System.out.println( "Value by orElseThrow(" + "ArithmeticException::new) method: " + op.orElseThrow( ArithmeticException::new)); }}
Optional: Optional[9455]
Value by orElseThrow(ArithmeticException::new) method: 9455
Program 2:
// Java program to demonstrate// Optional.orElseThrow() method import java.util.*;import java.util.function.*; public class GFG { public static void main(String[] args) { // create a Optional Optional<Integer> op = Optional.empty(); // print supplier System.out.println("Optional: " + op); try { // orElseThrow supplier System.out.println( "Value by orElseThrow(" + "ArithmeticException::new) method: " + op.orElseThrow( ArithmeticException::new)); } catch (Exception e) { System.out.println(e); } }}
Optional: Optional.empty
java.lang.ArithmeticException
Reference: https://docs.oracle.com/javase/9/docs/api/java/util/Optional.html#orElseThrow-java.util.function.Supplier-
Java - util package
Java-Functions
Java-Optional
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Interfaces in Java
Stack Class in Java
Singleton Class in Java
Set in Java
Multithreading in Java
Collections in Java
Queue Interface In Java
Initializing a List in Java
LinkedList in Java
|
[
{
"code": null,
"e": 25781,
"s": 25753,
"text": "\n30 Jul, 2019"
},
{
"code": null,
"e": 26038,
"s": 25781,
"text": "The orElseThrow() method of java.util.Optional class in Java is used to get the value of this Optional instance if present. If there is no value present in this Optional instance, then this method throws the exception generated from the specified supplier."
},
{
"code": null,
"e": 26046,
"s": 26038,
"text": "Syntax:"
},
{
"code": null,
"e": 26134,
"s": 26046,
"text": "public <X> T\n orElseThrow(Supplier<X> exceptionSupplier)\n throws X extends Throwable\n"
},
{
"code": null,
"e": 26279,
"s": 26134,
"text": "Parameters: This method accepts supplier as a parameter of type X to throws an exception if there is no value present in this Optional instance."
},
{
"code": null,
"e": 26498,
"s": 26279,
"text": "Return supplier: This method returns the value of this Optional instance, if present. If there is no value present in this Optional instance, then this method throws the exception generated from the specified supplier."
},
{
"code": null,
"e": 26605,
"s": 26498,
"text": "Exception: This method throws NullPointerException if there is no value present in this Optional instance."
},
{
"code": null,
"e": 26663,
"s": 26605,
"text": "Below programs illustrate orElseThrow() method:Program 1:"
},
{
"code": "// Java program to demonstrate// Optional.orElseThrow() method import java.util.*;import java.util.function.*; public class GFG { public static void main(String[] args) { // create a Optional Optional<Integer> op = Optional.of(9455); // print supplier System.out.println(\"Optional: \" + op); // orElseThrow supplier System.out.println( \"Value by orElseThrow(\" + \"ArithmeticException::new) method: \" + op.orElseThrow( ArithmeticException::new)); }}",
"e": 27258,
"s": 26663,
"text": null
},
{
"code": null,
"e": 27344,
"s": 27258,
"text": "Optional: Optional[9455]\nValue by orElseThrow(ArithmeticException::new) method: 9455\n"
},
{
"code": null,
"e": 27355,
"s": 27344,
"text": "Program 2:"
},
{
"code": "// Java program to demonstrate// Optional.orElseThrow() method import java.util.*;import java.util.function.*; public class GFG { public static void main(String[] args) { // create a Optional Optional<Integer> op = Optional.empty(); // print supplier System.out.println(\"Optional: \" + op); try { // orElseThrow supplier System.out.println( \"Value by orElseThrow(\" + \"ArithmeticException::new) method: \" + op.orElseThrow( ArithmeticException::new)); } catch (Exception e) { System.out.println(e); } }}",
"e": 28069,
"s": 27355,
"text": null
},
{
"code": null,
"e": 28125,
"s": 28069,
"text": "Optional: Optional.empty\njava.lang.ArithmeticException\n"
},
{
"code": null,
"e": 28243,
"s": 28125,
"text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/util/Optional.html#orElseThrow-java.util.function.Supplier-"
},
{
"code": null,
"e": 28263,
"s": 28243,
"text": "Java - util package"
},
{
"code": null,
"e": 28278,
"s": 28263,
"text": "Java-Functions"
},
{
"code": null,
"e": 28292,
"s": 28278,
"text": "Java-Optional"
},
{
"code": null,
"e": 28297,
"s": 28292,
"text": "Java"
},
{
"code": null,
"e": 28302,
"s": 28297,
"text": "Java"
},
{
"code": null,
"e": 28400,
"s": 28302,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28415,
"s": 28400,
"text": "Stream In Java"
},
{
"code": null,
"e": 28434,
"s": 28415,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 28454,
"s": 28434,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 28478,
"s": 28454,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 28490,
"s": 28478,
"text": "Set in Java"
},
{
"code": null,
"e": 28513,
"s": 28490,
"text": "Multithreading in Java"
},
{
"code": null,
"e": 28533,
"s": 28513,
"text": "Collections in Java"
},
{
"code": null,
"e": 28557,
"s": 28533,
"text": "Queue Interface In Java"
},
{
"code": null,
"e": 28585,
"s": 28557,
"text": "Initializing a List in Java"
}
] |
numpy.ascontiguousarray() in Python - GeeksforGeeks
|
16 Nov, 2021
numpy.ascontiguousarray()function is used when we want to return a contiguous array in memory (C order).
Syntax : numpy.ascontiguousarray(arr, dtype=None)
Parameters :arr : [array_like] Input data, in any form that can be converted to an array. This includes scalars, lists, lists of tuples, tuples, tuples of tuples, tuples of lists, and ndarrays.dtype : [str or dtype object, optional] Data-type of returned array.
Return : ndarray Contiguous array of same shape and content as arr, with type dtype if specified.
Code #1 : List to array
# Python program explaining# numpy.ascontiguousarray() function import numpy as geekmy_list = [100, 200, 300, 400, 500] print ("Input list : ", my_list) out_arr = geek.ascontiguousarray(my_list, dtype = geek.float32)print ("output array from input list : ", out_arr)
Output :
Input list : [100, 200, 300, 400, 500]
output array from input list : [ 100. 200. 300. 400. 500.]
Code #2 : Tuple to array
# Python program explaining# numpy.ascontiguousarray() function import numpy as geek my_tuple = ([2, 6, 10], [8, 12, 16]) print ("Input tuple : ", my_tuple) out_arr = geek.ascontiguousarray(my_tuple, dtype = geek.int32) print ("output array from input tuple : ", out_arr)
Output :
Input tuple : ([2, 6, 10], [8, 12, 16])
output array from input tuple : [[ 2 6 10]
[ 8 12 16]]
Code #3 : Scalar to array
# Python program explaining# numpy.ascontiguousarray() function import numpy as geek my_scalar = 100 print ("Input scalar : ", my_scalar) out_arr = geek.ascontiguousarray(my_scalar, dtype = geek.float32) print ("output array from input scalar : ", out_arr) print(type(out_arr))
Output :
Input scalar : 100
output array from input scalar : [ 100.]
class 'numpy.ndarray'
gulshankumarar231
Python numpy-arrayCreation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Check if element exists in list in Python
|
[
{
"code": null,
"e": 26141,
"s": 26113,
"text": "\n16 Nov, 2021"
},
{
"code": null,
"e": 26246,
"s": 26141,
"text": "numpy.ascontiguousarray()function is used when we want to return a contiguous array in memory (C order)."
},
{
"code": null,
"e": 26296,
"s": 26246,
"text": "Syntax : numpy.ascontiguousarray(arr, dtype=None)"
},
{
"code": null,
"e": 26558,
"s": 26296,
"text": "Parameters :arr : [array_like] Input data, in any form that can be converted to an array. This includes scalars, lists, lists of tuples, tuples, tuples of tuples, tuples of lists, and ndarrays.dtype : [str or dtype object, optional] Data-type of returned array."
},
{
"code": null,
"e": 26656,
"s": 26558,
"text": "Return : ndarray Contiguous array of same shape and content as arr, with type dtype if specified."
},
{
"code": null,
"e": 26680,
"s": 26656,
"text": "Code #1 : List to array"
},
{
"code": "# Python program explaining# numpy.ascontiguousarray() function import numpy as geekmy_list = [100, 200, 300, 400, 500] print (\"Input list : \", my_list) out_arr = geek.ascontiguousarray(my_list, dtype = geek.float32)print (\"output array from input list : \", out_arr) ",
"e": 26957,
"s": 26680,
"text": null
},
{
"code": null,
"e": 26966,
"s": 26957,
"text": "Output :"
},
{
"code": null,
"e": 27072,
"s": 26966,
"text": "Input list : [100, 200, 300, 400, 500]\noutput array from input list : [ 100. 200. 300. 400. 500.]\n"
},
{
"code": null,
"e": 27098,
"s": 27072,
"text": " Code #2 : Tuple to array"
},
{
"code": "# Python program explaining# numpy.ascontiguousarray() function import numpy as geek my_tuple = ([2, 6, 10], [8, 12, 16]) print (\"Input tuple : \", my_tuple) out_arr = geek.ascontiguousarray(my_tuple, dtype = geek.int32) print (\"output array from input tuple : \", out_arr) ",
"e": 27379,
"s": 27098,
"text": null
},
{
"code": null,
"e": 27388,
"s": 27379,
"text": "Output :"
},
{
"code": null,
"e": 27489,
"s": 27388,
"text": "Input tuple : ([2, 6, 10], [8, 12, 16])\noutput array from input tuple : [[ 2 6 10]\n [ 8 12 16]]\n"
},
{
"code": null,
"e": 27516,
"s": 27489,
"text": " Code #3 : Scalar to array"
},
{
"code": "# Python program explaining# numpy.ascontiguousarray() function import numpy as geek my_scalar = 100 print (\"Input scalar : \", my_scalar) out_arr = geek.ascontiguousarray(my_scalar, dtype = geek.float32) print (\"output array from input scalar : \", out_arr) print(type(out_arr))",
"e": 27802,
"s": 27516,
"text": null
},
{
"code": null,
"e": 27811,
"s": 27802,
"text": "Output :"
},
{
"code": null,
"e": 27897,
"s": 27811,
"text": "Input scalar : 100\noutput array from input scalar : [ 100.]\nclass 'numpy.ndarray'\n"
},
{
"code": null,
"e": 27915,
"s": 27897,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 27942,
"s": 27915,
"text": "Python numpy-arrayCreation"
},
{
"code": null,
"e": 27955,
"s": 27942,
"text": "Python-numpy"
},
{
"code": null,
"e": 27962,
"s": 27955,
"text": "Python"
},
{
"code": null,
"e": 28060,
"s": 27962,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28078,
"s": 28060,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28113,
"s": 28078,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28145,
"s": 28113,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28167,
"s": 28145,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28209,
"s": 28167,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28239,
"s": 28209,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28268,
"s": 28239,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 28312,
"s": 28268,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 28349,
"s": 28312,
"text": "Create a Pandas DataFrame from Lists"
}
] |
How to get the height and width of an Image using ReactJS? - GeeksforGeeks
|
30 Sep, 2020
In reacting whatever we write that looks like HTML is not pure HTML actually. All the HTML looking stuff are JSX, Behind the scene, they are converted to vanilla JavaScript using babel. These all work in this way to make the developersβ life easier. Since JSX are not HTML thatβs why we do have any direct reference to the HTML elements and thatβs why we canβt direct fetch properties of any HTML element. To fetch the elementsβ property, React gives something called as βrefβ. Using ref we can create a direct reference to any HTML elements and get controlled over HTML elements properties. Here we use the βrefβ system to fetch image height and width.
Example 1: This example illustrates how to fetch the current height and width of the image.
index.js:JavascriptJavascriptimport React from 'react'import ReactDOM from 'react-dom'import App from './App' ReactDOM.render(<App />, document.querySelector('#root'))
index.js:
Javascript
import React from 'react'import ReactDOM from 'react-dom'import App from './App' ReactDOM.render(<App />, document.querySelector('#root'))
App.js:JavascriptJavascriptimport React, { Component } from 'react'class App extends Component{ constructor(props){ super(props) // Initialize count state this.state = {show : false} // Bind context of 'this' this.handleClick = this.handleClick.bind(this) // Create reference of DOM object this.imgRef = React.createRef() } renderDetails() { return this.state.show ? // Accessing image details using imgRef <div> <p><strong>Height : </strong> {this.imgRef.current.clientHeight}px</p> <p><strong>Width : </strong> {this.imgRef.current.clientWidth}px</p> </div> : null } handleClick(){ // Update state value this.setState({ show : true }) } render(){ return( <div> <h3>GeeksforGeeks</h3> {/* Assign reference to DOM element */} <img ref={this.imgRef} src='https://media.geeksforgeeks.org/wp-content/uploads/20200617121258/gfg-image2-300x177.png' alt='gfg' /> <div> <button onClick={this.handleClick}>Get image details</button> </div> {this.renderDetails()} </div> ) } }export default App
App.js:
Javascript
import React, { Component } from 'react'class App extends Component{ constructor(props){ super(props) // Initialize count state this.state = {show : false} // Bind context of 'this' this.handleClick = this.handleClick.bind(this) // Create reference of DOM object this.imgRef = React.createRef() } renderDetails() { return this.state.show ? // Accessing image details using imgRef <div> <p><strong>Height : </strong> {this.imgRef.current.clientHeight}px</p> <p><strong>Width : </strong> {this.imgRef.current.clientWidth}px</p> </div> : null } handleClick(){ // Update state value this.setState({ show : true }) } render(){ return( <div> <h3>GeeksforGeeks</h3> {/* Assign reference to DOM element */} <img ref={this.imgRef} src='https://media.geeksforgeeks.org/wp-content/uploads/20200617121258/gfg-image2-300x177.png' alt='gfg' /> <div> <button onClick={this.handleClick}>Get image details</button> </div> {this.renderDetails()} </div> ) } }export default App
Output :
Example 2:
index.js:JavascriptJavascriptimport React from 'react'import ReactDOM from 'react-dom'import App from './App' ReactDOM.render(<App />, document.querySelector('#root'))
index.js:
Javascript
import React from 'react'import ReactDOM from 'react-dom'import App from './App' ReactDOM.render(<App />, document.querySelector('#root'))
App.js:JavascriptJavascriptimport React, { Component } from 'react'class App extends Component{ constructor(props){ super(props) // Initialize count state this.state = {height:null, width:null, isIncrease:false} // Bind context of 'this' this.handleClick = this.handleClick.bind(this) // Create reference of DOM object this.imgRef = React.createRef() } handleClick(){ // Fetching current height and width const height = this.imgRef.current.clientHeight const width = this.imgRef.current.clientWidth alert(` Height : ${height} Width : ${width} `) } render(){ return( <div> <h3>GeeksforGeeks</h3> {/* Assign reference to DOM element */} <img ref={this.imgRef} src='https://media.geeksforgeeks.org/wp-content/uploads/20200819170816/colorfulbulmaheroelements-300x154.png' alt='gfg' /> <div> <button onClick={this.handleClick}> Fetch dimension </button> </div> </div> ) } }export default App
App.js:
Javascript
import React, { Component } from 'react'class App extends Component{ constructor(props){ super(props) // Initialize count state this.state = {height:null, width:null, isIncrease:false} // Bind context of 'this' this.handleClick = this.handleClick.bind(this) // Create reference of DOM object this.imgRef = React.createRef() } handleClick(){ // Fetching current height and width const height = this.imgRef.current.clientHeight const width = this.imgRef.current.clientWidth alert(` Height : ${height} Width : ${width} `) } render(){ return( <div> <h3>GeeksforGeeks</h3> {/* Assign reference to DOM element */} <img ref={this.imgRef} src='https://media.geeksforgeeks.org/wp-content/uploads/20200819170816/colorfulbulmaheroelements-300x154.png' alt='gfg' /> <div> <button onClick={this.handleClick}> Fetch dimension </button> </div> </div> ) } }export default App
Output :
react-js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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?
Difference between var, let and const keywords in JavaScript
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to create footer to stay at the bottom of a Web page?
Node.js fs.readFileSync() Method
How to calculate the number of days between two dates in javascript?
|
[
{
"code": null,
"e": 28387,
"s": 28359,
"text": "\n30 Sep, 2020"
},
{
"code": null,
"e": 29041,
"s": 28387,
"text": "In reacting whatever we write that looks like HTML is not pure HTML actually. All the HTML looking stuff are JSX, Behind the scene, they are converted to vanilla JavaScript using babel. These all work in this way to make the developersβ life easier. Since JSX are not HTML thatβs why we do have any direct reference to the HTML elements and thatβs why we canβt direct fetch properties of any HTML element. To fetch the elementsβ property, React gives something called as βrefβ. Using ref we can create a direct reference to any HTML elements and get controlled over HTML elements properties. Here we use the βrefβ system to fetch image height and width."
},
{
"code": null,
"e": 29133,
"s": 29041,
"text": "Example 1: This example illustrates how to fetch the current height and width of the image."
},
{
"code": null,
"e": 29302,
"s": 29133,
"text": "index.js:JavascriptJavascriptimport React from 'react'import ReactDOM from 'react-dom'import App from './App' ReactDOM.render(<App />, document.querySelector('#root'))"
},
{
"code": null,
"e": 29312,
"s": 29302,
"text": "index.js:"
},
{
"code": null,
"e": 29323,
"s": 29312,
"text": "Javascript"
},
{
"code": "import React from 'react'import ReactDOM from 'react-dom'import App from './App' ReactDOM.render(<App />, document.querySelector('#root'))",
"e": 29463,
"s": 29323,
"text": null
},
{
"code": null,
"e": 30642,
"s": 29463,
"text": "App.js:JavascriptJavascriptimport React, { Component } from 'react'class App extends Component{ constructor(props){ super(props) // Initialize count state this.state = {show : false} // Bind context of 'this' this.handleClick = this.handleClick.bind(this) // Create reference of DOM object this.imgRef = React.createRef() } renderDetails() { return this.state.show ? // Accessing image details using imgRef <div> <p><strong>Height : </strong> {this.imgRef.current.clientHeight}px</p> <p><strong>Width : </strong> {this.imgRef.current.clientWidth}px</p> </div> : null } handleClick(){ // Update state value this.setState({ show : true }) } render(){ return( <div> <h3>GeeksforGeeks</h3> {/* Assign reference to DOM element */} <img ref={this.imgRef} src='https://media.geeksforgeeks.org/wp-content/uploads/20200617121258/gfg-image2-300x177.png' alt='gfg' /> <div> <button onClick={this.handleClick}>Get image details</button> </div> {this.renderDetails()} </div> ) } }export default App"
},
{
"code": null,
"e": 30650,
"s": 30642,
"text": "App.js:"
},
{
"code": null,
"e": 30661,
"s": 30650,
"text": "Javascript"
},
{
"code": "import React, { Component } from 'react'class App extends Component{ constructor(props){ super(props) // Initialize count state this.state = {show : false} // Bind context of 'this' this.handleClick = this.handleClick.bind(this) // Create reference of DOM object this.imgRef = React.createRef() } renderDetails() { return this.state.show ? // Accessing image details using imgRef <div> <p><strong>Height : </strong> {this.imgRef.current.clientHeight}px</p> <p><strong>Width : </strong> {this.imgRef.current.clientWidth}px</p> </div> : null } handleClick(){ // Update state value this.setState({ show : true }) } render(){ return( <div> <h3>GeeksforGeeks</h3> {/* Assign reference to DOM element */} <img ref={this.imgRef} src='https://media.geeksforgeeks.org/wp-content/uploads/20200617121258/gfg-image2-300x177.png' alt='gfg' /> <div> <button onClick={this.handleClick}>Get image details</button> </div> {this.renderDetails()} </div> ) } }export default App",
"e": 31813,
"s": 30661,
"text": null
},
{
"code": null,
"e": 31822,
"s": 31813,
"text": "Output :"
},
{
"code": null,
"e": 31834,
"s": 31822,
"text": "Example 2: "
},
{
"code": null,
"e": 32003,
"s": 31834,
"text": "index.js:JavascriptJavascriptimport React from 'react'import ReactDOM from 'react-dom'import App from './App' ReactDOM.render(<App />, document.querySelector('#root'))"
},
{
"code": null,
"e": 32013,
"s": 32003,
"text": "index.js:"
},
{
"code": null,
"e": 32024,
"s": 32013,
"text": "Javascript"
},
{
"code": "import React from 'react'import ReactDOM from 'react-dom'import App from './App' ReactDOM.render(<App />, document.querySelector('#root'))",
"e": 32164,
"s": 32024,
"text": null
},
{
"code": null,
"e": 33211,
"s": 32164,
"text": "App.js:JavascriptJavascriptimport React, { Component } from 'react'class App extends Component{ constructor(props){ super(props) // Initialize count state this.state = {height:null, width:null, isIncrease:false} // Bind context of 'this' this.handleClick = this.handleClick.bind(this) // Create reference of DOM object this.imgRef = React.createRef() } handleClick(){ // Fetching current height and width const height = this.imgRef.current.clientHeight const width = this.imgRef.current.clientWidth alert(` Height : ${height} Width : ${width} `) } render(){ return( <div> <h3>GeeksforGeeks</h3> {/* Assign reference to DOM element */} <img ref={this.imgRef} src='https://media.geeksforgeeks.org/wp-content/uploads/20200819170816/colorfulbulmaheroelements-300x154.png' alt='gfg' /> <div> <button onClick={this.handleClick}> Fetch dimension </button> </div> </div> ) } }export default App"
},
{
"code": null,
"e": 33219,
"s": 33211,
"text": "App.js:"
},
{
"code": null,
"e": 33230,
"s": 33219,
"text": "Javascript"
},
{
"code": "import React, { Component } from 'react'class App extends Component{ constructor(props){ super(props) // Initialize count state this.state = {height:null, width:null, isIncrease:false} // Bind context of 'this' this.handleClick = this.handleClick.bind(this) // Create reference of DOM object this.imgRef = React.createRef() } handleClick(){ // Fetching current height and width const height = this.imgRef.current.clientHeight const width = this.imgRef.current.clientWidth alert(` Height : ${height} Width : ${width} `) } render(){ return( <div> <h3>GeeksforGeeks</h3> {/* Assign reference to DOM element */} <img ref={this.imgRef} src='https://media.geeksforgeeks.org/wp-content/uploads/20200819170816/colorfulbulmaheroelements-300x154.png' alt='gfg' /> <div> <button onClick={this.handleClick}> Fetch dimension </button> </div> </div> ) } }export default App",
"e": 34250,
"s": 33230,
"text": null
},
{
"code": null,
"e": 34259,
"s": 34250,
"text": "Output :"
},
{
"code": null,
"e": 34268,
"s": 34259,
"text": "react-js"
},
{
"code": null,
"e": 34285,
"s": 34268,
"text": "Web Technologies"
},
{
"code": null,
"e": 34383,
"s": 34285,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34423,
"s": 34383,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 34456,
"s": 34423,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 34501,
"s": 34456,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 34544,
"s": 34501,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 34594,
"s": 34544,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 34655,
"s": 34594,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 34717,
"s": 34655,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 34775,
"s": 34717,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 34808,
"s": 34775,
"text": "Node.js fs.readFileSync() Method"
}
] |
C# - Indexers Using String as an Index - GeeksforGeeks
|
30 Aug, 2020
Prerequisite: Properties in C#
Indexers allow instances of a class or struct to be indexed just like arrays. By using indexers class will behave like a virtual array. The indexed value can be set or retrieved without explicitly specifying a type or instance member. Indexers resemble properties except that their accessors take parameters. Indexers are almost similar to the Properties. The main difference between Indexers and Properties is that the accessors of the Indexers will take parameters.
This method will give you more information, readability. If we want to retrieve information using a string as an index.
Example:
ic["username"] = "user12";
ic["password"] = "12345";
This will give more readability than the code given below.
ic[0] = "user12";
ic[1] = "12345";
Syntax:
[access_modifier] [return_type] this [argument_list]
{
get
{
// retrieval code or code to get the value
}
set
{
// code for setting value to member
}
In the above syntax:
access_modifier: It can be public, private, protected, or internal.
return_type: It can be any valid C# type. In this case, it will be of string type.
this: It is the keyword which points to the object of the current class.
argument_list: This specifies the parameter list of the indexer.
get{ } and set { }: These are the accessors.
Example:
C#
// C# program to illustrate the Indexers // Using String as an Index using System; // class declaration class IndexerPOC { // class members private string[] val = new string[4]; // indexer array private string[] indices={"username","password","email","Book"}; // Indexer declaration // Here pubic is the modifier // string is the return type of // Indexer and "this" is the keyword // which refer to the calling object. // having parameters list public string this[string index] { // get Accessor // retrieving the values // stored in val[] array // of strings using string indexer. get { return val[Array.IndexOf(indices,index)]; } // set Accessor // setting the value at // passed i of val set { // value keyword is used // to define the value // being assigned by the // set indexer. val[ Array.IndexOf(indices,index)] = value; } } } // Driver Class class Program { // Main Method public static void Main() { // creating an object of parent class which // acts as primary address for using Indexer IndexerPOC ic = new IndexerPOC(); // Inserting values in ic[] // Here we are using the object // of class as an array ic["username"] = "user12"; ic["password"] = "12345"; ic["email"] = "user123@gmail.com"; ic["Book"]="CSHARP"; Console.Write("Printing values stored in objects used as arrays\n"); // printing values Console.WriteLine("UserName = {0}", ic["username"]); Console.WriteLine("Password = {0}", ic["password"]); Console.WriteLine("Email = {0}", ic["email"]); Console.WriteLine("Book = {0}", ic["Book"]); } }
Output:
Printing values stored in objects used as arrays
UserName = user12
Password = 12345
Email = user123@gmail.com
Book = CSHARP
CSharp-Indexers & Properties
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
C# | Inheritance
Partial Classes in C#
C# | Generics - Introduction
Top 50 C# Interview Questions & Answers
C# | How to insert an element in an Array?
Switch Statement in C#
Convert String to Character Array in C#
Linked List Implementation in C#
|
[
{
"code": null,
"e": 25573,
"s": 25545,
"text": "\n30 Aug, 2020"
},
{
"code": null,
"e": 25604,
"s": 25573,
"text": "Prerequisite: Properties in C#"
},
{
"code": null,
"e": 26072,
"s": 25604,
"text": "Indexers allow instances of a class or struct to be indexed just like arrays. By using indexers class will behave like a virtual array. The indexed value can be set or retrieved without explicitly specifying a type or instance member. Indexers resemble properties except that their accessors take parameters. Indexers are almost similar to the Properties. The main difference between Indexers and Properties is that the accessors of the Indexers will take parameters."
},
{
"code": null,
"e": 26192,
"s": 26072,
"text": "This method will give you more information, readability. If we want to retrieve information using a string as an index."
},
{
"code": null,
"e": 26201,
"s": 26192,
"text": "Example:"
},
{
"code": null,
"e": 26259,
"s": 26201,
"text": "ic[\"username\"] = \"user12\"; \nic[\"password\"] = \"12345\"; \n"
},
{
"code": null,
"e": 26318,
"s": 26259,
"text": "This will give more readability than the code given below."
},
{
"code": null,
"e": 26358,
"s": 26318,
"text": "ic[0] = \"user12\"; \nic[1] = \"12345\"; \n"
},
{
"code": null,
"e": 26366,
"s": 26358,
"text": "Syntax:"
},
{
"code": null,
"e": 26535,
"s": 26366,
"text": "[access_modifier] [return_type] this [argument_list]\n{\n get \n {\n // retrieval code or code to get the value \n }\n set \n {\n // code for setting value to member\n }\n"
},
{
"code": null,
"e": 26556,
"s": 26535,
"text": "In the above syntax:"
},
{
"code": null,
"e": 26624,
"s": 26556,
"text": "access_modifier: It can be public, private, protected, or internal."
},
{
"code": null,
"e": 26707,
"s": 26624,
"text": "return_type: It can be any valid C# type. In this case, it will be of string type."
},
{
"code": null,
"e": 26780,
"s": 26707,
"text": "this: It is the keyword which points to the object of the current class."
},
{
"code": null,
"e": 26845,
"s": 26780,
"text": "argument_list: This specifies the parameter list of the indexer."
},
{
"code": null,
"e": 26890,
"s": 26845,
"text": "get{ } and set { }: These are the accessors."
},
{
"code": null,
"e": 26899,
"s": 26890,
"text": "Example:"
},
{
"code": null,
"e": 26902,
"s": 26899,
"text": "C#"
},
{
"code": "// C# program to illustrate the Indexers // Using String as an Index using System; // class declaration class IndexerPOC { // class members private string[] val = new string[4]; // indexer array private string[] indices={\"username\",\"password\",\"email\",\"Book\"}; // Indexer declaration // Here pubic is the modifier // string is the return type of // Indexer and \"this\" is the keyword // which refer to the calling object. // having parameters list public string this[string index] { // get Accessor // retrieving the values // stored in val[] array // of strings using string indexer. get { return val[Array.IndexOf(indices,index)]; } // set Accessor // setting the value at // passed i of val set { // value keyword is used // to define the value // being assigned by the // set indexer. val[ Array.IndexOf(indices,index)] = value; } } } // Driver Class class Program { // Main Method public static void Main() { // creating an object of parent class which // acts as primary address for using Indexer IndexerPOC ic = new IndexerPOC(); // Inserting values in ic[] // Here we are using the object // of class as an array ic[\"username\"] = \"user12\"; ic[\"password\"] = \"12345\"; ic[\"email\"] = \"user123@gmail.com\"; ic[\"Book\"]=\"CSHARP\"; Console.Write(\"Printing values stored in objects used as arrays\\n\"); // printing values Console.WriteLine(\"UserName = {0}\", ic[\"username\"]); Console.WriteLine(\"Password = {0}\", ic[\"password\"]); Console.WriteLine(\"Email = {0}\", ic[\"email\"]); Console.WriteLine(\"Book = {0}\", ic[\"Book\"]); } }",
"e": 28838,
"s": 26902,
"text": null
},
{
"code": null,
"e": 28846,
"s": 28838,
"text": "Output:"
},
{
"code": null,
"e": 28970,
"s": 28846,
"text": "Printing values stored in objects used as arrays\nUserName = user12\nPassword = 12345\nEmail = user123@gmail.com\nBook = CSHARP"
},
{
"code": null,
"e": 28999,
"s": 28970,
"text": "CSharp-Indexers & Properties"
},
{
"code": null,
"e": 29002,
"s": 28999,
"text": "C#"
},
{
"code": null,
"e": 29100,
"s": 29002,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29123,
"s": 29100,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 29151,
"s": 29123,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 29168,
"s": 29151,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 29190,
"s": 29168,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 29219,
"s": 29190,
"text": "C# | Generics - Introduction"
},
{
"code": null,
"e": 29259,
"s": 29219,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 29302,
"s": 29259,
"text": "C# | How to insert an element in an Array?"
},
{
"code": null,
"e": 29325,
"s": 29302,
"text": "Switch Statement in C#"
},
{
"code": null,
"e": 29365,
"s": 29325,
"text": "Convert String to Character Array in C#"
}
] |
Minimum insertions to form a palindrome | DP-28 - GeeksforGeeks
|
25 Feb, 2022
Given string str, the task is to find the minimum number of characters to be inserted to convert it to a palindrome.
Before we go further, let us understand with a few examples:
ab: Number of insertions required is 1 i.e. bab
aa: Number of insertions required is 0 i.e. aa
abcd: Number of insertions required is 3 i.e. dcbabcd
abcda: Number of insertions required is 2 i.e. adcbcda which is the same as the number of insertions in the substring bcd(Why?).
abcde: Number of insertions required is 4 i.e. edcbabcde
Let the input string be str[l......h]. The problem can be broken down into three parts:
Find the minimum number of insertions in the substring str[l+1,.......h].Find the minimum number of insertions in the substring str[l.......h-1].Find the minimum number of insertions in the substring str[l+1......h-1].
Find the minimum number of insertions in the substring str[l+1,.......h].
Find the minimum number of insertions in the substring str[l.......h-1].
Find the minimum number of insertions in the substring str[l+1......h-1].
Recursive Approach: The minimum number of insertions in the string str[l.....h] can be given as:
minInsertions(str[l+1.....h-1]) if str[l] is equal to str[h]
min(minInsertions(str[l.....h-1]), minInsertions(str[l+1.....h])) + 1 otherwise
Below is the implementation of the above approach:
C++
C
Java
Python 3
C#
Javascript
// A Naive recursive program to find minimum// number insertions needed to make a string// palindrome#include<bits/stdc++.h>using namespace std; // Recursive function to find // minimum number of insertionsint findMinInsertions(char str[], int l, int h){ // Base Cases if (l > h) return INT_MAX; if (l == h) return 0; if (l == h - 1) return (str[l] == str[h])? 0 : 1; // Check if the first and last characters are // same. On the basis of the comparison result, // decide which subproblem(s) to call return (str[l] == str[h])? findMinInsertions(str, l + 1, h - 1): (min(findMinInsertions(str, l, h - 1), findMinInsertions(str, l + 1, h)) + 1);} // Driver codeint main(){ char str[] = "geeks"; cout << findMinInsertions(str, 0, strlen(str) - 1); return 0;} // This code is contributed by// Akanksha Rai
// A Naive recursive program to find minimum// number insertions needed to make a string// palindrome#include <stdio.h>#include <limits.h>#include <string.h> // A utility function to find minimum of two numbersint min(int a, int b){ return a < b ? a : b; } // Recursive function to find minimum number of// insertionsint findMinInsertions(char str[], int l, int h){ // Base Cases if (l > h) return INT_MAX; if (l == h) return 0; if (l == h - 1) return (str[l] == str[h])? 0 : 1; // Check if the first and last characters are // same. On the basis of the comparison result, // decide which subproblem(s) to call return (str[l] == str[h])? findMinInsertions(str, l + 1, h - 1): (min(findMinInsertions(str, l, h - 1), findMinInsertions(str, l + 1, h)) + 1);} // Driver program to test above functionsint main(){ char str[] = "geeks"; printf("%d", findMinInsertions(str, 0, strlen(str)-1)); return 0;}
// A Naive recursive Java program to find minimum// number insertions needed to make a string// palindromeclass GFG { // Recursive function to find minimum number // of insertions static int findMinInsertions(char str[], int l, int h) { // Base Cases if (l > h) return Integer.MAX_VALUE; if (l == h) return 0; if (l == h - 1) return (str[l] == str[h])? 0 : 1; // Check if the first and last characters // are same. On the basis of the comparison // result, decide which subproblem(s) to call return (str[l] == str[h])? findMinInsertions(str, l + 1, h - 1): (Integer.min(findMinInsertions(str, l, h - 1), findMinInsertions(str, l + 1, h)) + 1); } // Driver program to test above functions public static void main(String args[]) { String str= "geeks"; System.out.println(findMinInsertions(str.toCharArray(), 0, str.length()-1)); }}// This code is contributed by Sumit Ghosh
# A Naive recursive program to find minimum# number insertions needed to make a string# palindromeimport sys # Recursive function to find minimum# number of insertionsdef findMinInsertions(str, l, h): # Base Cases if (l > h): return sys.maxsize if (l == h): return 0 if (l == h - 1): return 0 if(str[l] == str[h]) else 1 # Check if the first and last characters are # same. On the basis of the comparison result, # decide which subproblem(s) to call if(str[l] == str[h]): return findMinInsertions(str, l + 1, h - 1) else: return (min(findMinInsertions(str, l, h - 1), findMinInsertions(str, l + 1, h)) + 1) # Driver Codeif __name__ == "__main__": str = "geeks" print(findMinInsertions(str, 0, len(str) - 1)) # This code is contributed by ita_c
// A Naive recursive C# program// to find minimum number// insertions needed to make// a string palindromeusing System; class GFG{ // Recursive function to // find minimum number of // insertions static int findMinInsertions(char []str, int l, int h) { // Base Cases if (l > h) return int.MaxValue; if (l == h) return 0; if (l == h - 1) return (str[l] == str[h])? 0 : 1; // Check if the first and // last characters are same. // On the basis of the // comparison result, decide // which subproblem(s) to call return (str[l] == str[h])? findMinInsertions(str, l + 1, h - 1): (Math.Min(findMinInsertions(str, l, h - 1), findMinInsertions(str, l + 1, h)) + 1); } // Driver Code public static void Main() { string str= "geeks"; Console.WriteLine(findMinInsertions(str.ToCharArray(), 0, str.Length - 1)); }} // This code is contributed by Sam007
<script> // A Naive recursive JavaScript program to find minimum// number insertions needed to make a string// palindrome // Recursive function to find minimum number // of insertions function findMinInsertions(str,l,h) { // Base Cases if (l > h) return Number.MAX_VALUE; if (l == h) return 0; if (l == h - 1) return (str[l] == str[h])? 0 : 1; // Check if the first and last characters // are same. On the basis of the comparison // result, decide which subproblem(s) to call return (str[l] == str[h]) ? findMinInsertions(str, l + 1, h - 1) : (Math.min(findMinInsertions(str, l, h - 1), findMinInsertions(str, l + 1, h)) + 1) } // Driver program to test above functions let str= "geeks"; document.write(findMinInsertions(str,0, str.length-1)); // This code is contributed by rag2127 </script>
Output:
3
Dynamic Programming based Solution If we observe the above approach carefully, we can find that it exhibits overlapping subproblems. Suppose we want to find the minimum number of insertions in string βabcdeβ:
abcde
/ | \
/ | \
bcde abcd bcd <- case 3 is discarded as str[l] != str[h]
/ | \ / | \
/ | \ / | \
cde bcd cd bcd abc bc
/ | \ / | \ /|\ / | \
de cd d cd bc c......................
The substrings in bold show that the recursion is to be terminated and the recursion tree cannot originate from there. Substring in the same color indicates overlapping subproblems.
How to re-use solutions of subproblems? The memorization technique is used to avoid similar subproblem recalls. We can create a table to store the results of subproblems so that they can be used directly if the same subproblem is encountered again.The below table represents the stored values for the string abcde.
a b c d e
----------
0 1 2 3 4
0 0 1 2 3
0 0 0 1 2
0 0 0 0 1
0 0 0 0 0
How to fill the table? The table should be filled in a diagonal fashion. For the string abcde, 0....4, the following should be ordered in which the table is filled:
Gap = 1: (0, 1) (1, 2) (2, 3) (3, 4)
Gap = 2: (0, 2) (1, 3) (2, 4)
Gap = 3: (0, 3) (1, 4)
Gap = 4: (0, 4)
Below is the implementation of the above approach:
C++
C
Java
Python3
C#
Javascript
// A Dynamic Programming based program to find// minimum number insertions needed to make a// string palindrome#include <bits/stdc++.h>using namespace std; // A DP function to find minimum// number of insertionsint findMinInsertionsDP(char str[], int n){ // Create a table of size n*n. table[i][j] // will store minimum number of insertions // needed to convert str[i..j] to a palindrome. int table[n][n], l, h, gap; // Initialize all table entries as 0 memset(table, 0, sizeof(table)); // Fill the table for (gap = 1; gap < n; ++gap) for (l = 0, h = gap; h < n; ++l, ++h) table[l][h] = (str[l] == str[h])? table[l + 1][h - 1] : (min(table[l][h - 1], table[l + 1][h]) + 1); // Return minimum number of insertions // for str[0..n-1] return table[0][n - 1];} // Driver Codeint main(){ char str[] = "geeks"; cout << findMinInsertionsDP(str, strlen(str)); return 0;} // This is code is contributed by rathbhupendra
// A Dynamic Programming based program to find// minimum number insertions needed to make a// string palindrome#include <stdio.h>#include <string.h> // A utility function to find minimum of two integersint min(int a, int b){ return a < b ? a : b; } // A DP function to find minimum number of insertionsint findMinInsertionsDP(char str[], int n){ // Create a table of size n*n. table[i][j] // will store minimum number of insertions // needed to convert str[i..j] to a palindrome. int table[n][n], l, h, gap; // Initialize all table entries as 0 memset(table, 0, sizeof(table)); // Fill the table for (gap = 1; gap < n; ++gap) for (l = 0, h = gap; h < n; ++l, ++h) table[l][h] = (str[l] == str[h])? table[l+1][h-1] : (min(table[l][h-1], table[l+1][h]) + 1); // Return minimum number of insertions for // str[0..n-1] return table[0][n-1];} // Driver program to test above function.int main(){ char str[] = "geeks"; printf("%d", findMinInsertionsDP(str, strlen(str))); return 0;}
// A Java solution for Dynamic Programming// based program to find minimum number// insertions needed to make a string// palindromeimport java.util.Arrays; class GFG{ // A DP function to find minimum number // of insertions static int findMinInsertionsDP(char str[], int n) { // Create a table of size n*n. table[i][j] // will store minimum number of insertions // needed to convert str[i..j] to a palindrome. int table[][] = new int[n][n]; int l, h, gap; // Fill the table for (gap = 1; gap < n; ++gap) for (l = 0, h = gap; h < n; ++l, ++h) table[l][h] = (str[l] == str[h])? table[l+1][h-1] : (Integer.min(table[l][h-1], table[l+1][h]) + 1); // Return minimum number of insertions // for str[0..n-1] return table[0][n-1]; } // Driver program to test above function. public static void main(String args[]) { String str = "geeks"; System.out.println( findMinInsertionsDP(str.toCharArray(), str.length())); }}// This code is contributed by Sumit Ghosh
# A Dynamic Programming based program to# find minimum number insertions needed# to make a string palindrome # A utility function to find minimum# of two integersdef Min(a, b): return min(a, b) # A DP function to find minimum number# of insertionsdef findMinInsertionsDP(str1, n): # Create a table of size n*n. table[i][j] # will store minimum number of insertions # needed to convert str1[i..j] to a palindrome. table = [[0 for i in range(n)] for i in range(n)] l, h, gap = 0, 0, 0 # Fill the table for gap in range(1, n): l = 0 for h in range(gap, n): if str1[l] == str1[h]: table[l][h] = table[l + 1][h - 1] else: table[l][h] = (Min(table[l][h - 1], table[l + 1][h]) + 1) l += 1 # Return minimum number of insertions # for str1[0..n-1] return table[0][n - 1]; # Driver Codestr1 = "geeks"print(findMinInsertionsDP(str1, len(str1))) # This code is contributed by# Mohit kumar 29
// A C# solution for Dynamic Programming// based program to find minimum number// insertions needed to make a string// palindromeusing System; class GFG{ // A DP function to find minimum number // of insertions static int findMinInsertionsDP(char []str, int n) { // Create a table of size n*n. table[i][j] // will store minimum number of insertions // needed to convert str[i..j] to a palindrome. int [,]table = new int[n, n]; int l, h, gap; // Fill the table for (gap = 1; gap < n; ++gap) for (l = 0, h = gap; h < n; ++l, ++h) table[l, h] = (str[l] == str[h])? table[l+1, h-1] : (Math.Min(table[l, h-1], table[l+1, h]) + 1); // Return minimum number of insertions // for str[0..n-1] return table[0, n-1]; } // Driver code public static void Main() { String str = "geeks"; Console.Write( findMinInsertionsDP(str.ToCharArray(), str.Length)); }} // This code is contributed by Rajput-Ji
<script> // A Javascript solution for Dynamic Programming// based program to find minimum number// insertions needed to make a string// palindrome // A DP function to find minimum number // of insertions function findMinInsertionsDP(str,n) { // Create a table of size n*n. table[i][j] // will store minimum number of insertions // needed to convert str[i..j] to a palindrome. let table=new Array(n); for(let i=0;i<n;i++) { table[i]=new Array(n); } for(let i=0;i<n;i++) { for(let j=0;j<n;j++) { table[i][j]=0; } } let l=0, h=0, gap=0; // Fill the table for (gap = 1; gap < n; gap++) { for (l = 0, h = gap; h < n; l++, h++) { table[l][h] = (str[l] == str[h]) ? table[l+1][h-1] : (Math.min(table[l][h-1],table[l+1][h]) + 1); } } // Return minimum number of insertions // for str[0..n-1] return table[0][n - 1]; } // Driver program to test above function. let str = "geeks"; document.write(findMinInsertionsDP(str, str.length)); // This code is contributed by avanitrachhadiya2155 </script>
Output:
3
Time complexity: O(N^2) Auxiliary Space: O(N^2)
Another Dynamic Programming Solution (Variation of Longest Common Subsequence Problem) The problem of finding minimum insertions can also be solved using Longest Common Subsequence (LCS) Problem. If we find out the LCS of string and its reverse, we know how many maximum characters can form a palindrome. We need to insert the remaining characters. Following are the steps.
Find the length of LCS of the input string and its reverse. Let the length be βlβ.The minimum number of insertions needed is the length of the input string minus βlβ.
Find the length of LCS of the input string and its reverse. Let the length be βlβ.
The minimum number of insertions needed is the length of the input string minus βlβ.
Below is the implementation of the above approach:
C++
C
Java
Python3
C#
Javascript
// An LCS based program to find minimum number// insertions needed to make a string palindrome#include <bits/stdc++.h>using namespace std; // Returns length of LCS for X[0..m-1], Y[0..n-1].int lcs( string X, string Y, int m, int n ){ int L[m+1][n+1]; int i, j; /* Following steps build L[m+1][n+1] in bottom up fashion. Note that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] */ for (i = 0; i <= m; i++) { for (j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i][j] = 0; else if (X[i - 1] == Y[j - 1]) L[i][j] = L[i - 1][j - 1] + 1; else L[i][j] = max(L[i - 1][j], L[i][j - 1]); } } /* L[m][n] contains length of LCS for X[0..n-1] and Y[0..m-1] */ return L[m][n];} void reverseStr(string& str){ int n = str.length(); // Swap character starting from two // corners for (int i = 0; i < n / 2; i++) swap(str[i], str[n - i - 1]);} // LCS based function to find minimum number of// insertionsint findMinInsertionsLCS(string str, int n){ // Creata another string to store reverse of 'str' string rev = ""; rev = str; reverseStr(rev); // The output is length of string minus length of lcs of // str and it reverse return (n - lcs(str, rev, n, n));} // Driver codeint main(){ string str = "geeks"; cout << findMinInsertionsLCS(str, str.length()); return 0;} // This code is contributed by rathbhupendra
// An LCS based program to find minimum number// insertions needed to make a string palindrome#include<stdio.h>#include <string.h> /* Utility function to get max of 2 integers */int max(int a, int b){ return (a > b)? a : b; } /* Returns length of LCS for X[0..m-1], Y[0..n-1]. See http://goo.gl/bHQVP for details of this function */int lcs( char *X, char *Y, int m, int n ){ int L[m+1][n+1]; int i, j; /* Following steps build L[m+1][n+1] in bottom up fashion. Note that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] */ for (i=0; i<=m; i++) { for (j=0; j<=n; j++) { if (i == 0 || j == 0) L[i][j] = 0; else if (X[i-1] == Y[j-1]) L[i][j] = L[i-1][j-1] + 1; else L[i][j] = max(L[i-1][j], L[i][j-1]); } } /* L[m][n] contains length of LCS for X[0..n-1] and Y[0..m-1] */ return L[m][n];} // LCS based function to find minimum number of// insertionsint findMinInsertionsLCS(char str[], int n){ // Creata another string to store reverse of 'str' char rev[n+1]; strcpy(rev, str); strrev(rev); // The output is length of string minus length of lcs of // str and it reverse return (n - lcs(str, rev, n, n));} // Driver program to test above functionsint main(){ char str[] = "geeks"; printf("%d", findMinInsertionsLCS(str, strlen(str))); return 0;}
// An LCS based Java program to find minimum// number insertions needed to make a string// palindromeclass GFG{ /* Returns length of LCS for X[0..m-1], Y[0..n-1]. See http://goo.gl/bHQVP for details of this function */ static int lcs( String X, String Y, int m, int n ) { int L[][] = new int[m+1][n+1]; int i, j; /* Following steps build L[m+1][n+1] in bottom up fashion. Note that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] */ for (i=0; i<=m; i++) { for (j=0; j<=n; j++) { if (i == 0 || j == 0) L[i][j] = 0; else if (X.charAt(i-1) == Y.charAt(j-1)) L[i][j] = L[i-1][j-1] + 1; else L[i][j] = Integer.max(L[i-1][j], L[i][j-1]); } } /* L[m][n] contains length of LCS for X[0..n-1] and Y[0..m-1] */ return L[m][n]; } // LCS based function to find minimum number // of insertions static int findMinInsertionsLCS(String str, int n) { // Using StringBuffer to reverse a String StringBuffer sb = new StringBuffer(str); sb.reverse(); String revString = sb.toString(); // The output is length of string minus // length of lcs of str and it reverse return (n - lcs(str, revString , n, n)); } // Driver program to test above functions public static void main(String args[]) { String str = "geeks"; System.out.println( findMinInsertionsLCS(str, str.length())); }}// This code is contributed by Sumit Ghosh
# An LCS based Python3 program to find minimum# number insertions needed to make a string# palindrome """ Returns length of LCS for X[0..m-1],Y[0..n-1]. See http://goo.gl/bHQVP fordetails of this function """def lcs(X, Y, m, n) : L = [[0 for i in range(n + 1)] for j in range(m + 1)] """ Following steps build L[m + 1, n + 1] in bottom up fashion. Note that L[i, j] contains length of LCS of X[0..i - 1] and Y[0..j - 1] """ for i in range(m + 1) : for j in range(n + 1) : if (i == 0 or j == 0) : L[i][j] = 0 elif (X[i - 1] == Y[j - 1]) : L[i][j] = L[i - 1][j - 1] + 1 else : L[i][j] = max(L[i - 1][j], L[i][j - 1]) """ L[m,n] contains length of LCS for X[0..n-1] and Y[0..m-1] """ return L[m][n] # LCS based function to find minimum number# of insertionsdef findMinInsertionsLCS(Str, n) : # Using charArray to reverse a String charArray = list(Str) charArray.reverse() revString = "".join(charArray) # The output is length of string minus # length of lcs of str and it reverse return (n - lcs(Str, revString , n, n)) # Driver code Str = "geeks"print(findMinInsertionsLCS(Str,len(Str))) # This code is contributed by divyehrabadiya07
// An LCS based C# program to find minimum// number insertions needed to make a string// palindromeusing System; class GFG{ /* Returns length of LCS for X[0..m-1], Y[0..n-1]. See http://goo.gl/bHQVP for details of this function */ static int lcs( string X, string Y, int m, int n ) { int[,] L = new int[m + 1, n + 1]; int i, j; /* Following steps build L[m+1,n+1] in bottom up fashion. Note that L[i,j] contains length of LCS of X[0..i-1] and Y[0..j-1] */ for (i = 0; i <= m; i++) { for (j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i, j] = 0; else if (X[i - 1] == Y[j - 1]) L[i, j] = L[i - 1, j - 1] + 1; else L[i, j] = Math.Max(L[i - 1, j], L[i, j - 1]); } } /* L[m,n] contains length of LCS for X[0..n-1] and Y[0..m-1] */ return L[m,n]; } // LCS based function to find minimum number // of insertions static int findMinInsertionsLCS(string str, int n) { // Using charArray to reverse a String char[] charArray = str.ToCharArray(); Array.Reverse(charArray); string revString = new string(charArray); // The output is length of string minus // length of lcs of str and it reverse return (n - lcs(str, revString , n, n)); } // Driver code static void Main() { string str = "geeks"; Console.WriteLine(findMinInsertionsLCS(str,str.Length)); }} // This code is contributed by mits
<script>// An LCS based Javascript program to find minimum// number insertions needed to make a string// palindrome /* Returns length of LCS for X[0..m-1], Y[0..n-1]. See http://goo.gl/bHQVP for details of this function */ function lcs(X, Y, m, n) { let L = new Array(m+1); for(let i = 0; i < m + 1; i++) { L[i] = new Array(n+1); for(let j = 0; j < n + 1; j++) { L[i][j] = 0; } } let i, j; /* Following steps build L[m+1][n+1] in bottom up fashion. Note that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] */ for (i = 0; i <= m; i++) { for (j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i][j] = 0; else if (X[i - 1] == Y[j - 1]) L[i][j] = L[i - 1][j - 1] + 1; else L[i][j] = Math.max(L[i - 1][j], L[i][j - 1]); } } /* L[m][n] contains length of LCS for X[0..n-1] and Y[0..m-1] */ return L[m][n]; } // LCS based function to find minimum number // of insertions function findMinInsertionsLCS(str, n) { let revString = str.split('').reverse().join(''); // The output is length of string minus // length of lcs of str and it reverse return (n - lcs(str, revString , n, n)); } // Driver program to test above functions let str = "geeks"; document.write(findMinInsertionsLCS(str, str.length)); // This code is contributed by unknown2108</script>
Output:
3
Time complexity: O(N^2) Auxiliary Space: O(N^2)
Related Article : Minimum number of Appends needed to make a string palindromeThis article is compiled by Aashish Barnwal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Sam007
ukasp
mohit kumar 29
Rajput-Ji
Akanksha_Rai
rathbhupendra
Mithun Kumar
nandishwar001
divyeshrabadiya07
rag2127
avanitrachhadiya2155
unknown2108
simmytarika5
surindertarika1234
kumaripunam984122
Amazon
Google
palindrome
Dynamic Programming
Strings
Amazon
Google
Strings
Dynamic Programming
palindrome
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Floyd Warshall Algorithm | DP-16
Matrix Chain Multiplication | DP-8
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Edit Distance | DP-5
Overlapping Subproblems Property in Dynamic Programming | DP-1
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Check for Balanced Brackets in an expression (well-formedness) using Stack
|
[
{
"code": null,
"e": 26255,
"s": 26227,
"text": "\n25 Feb, 2022"
},
{
"code": null,
"e": 26372,
"s": 26255,
"text": "Given string str, the task is to find the minimum number of characters to be inserted to convert it to a palindrome."
},
{
"code": null,
"e": 26434,
"s": 26372,
"text": "Before we go further, let us understand with a few examples: "
},
{
"code": null,
"e": 26482,
"s": 26434,
"text": "ab: Number of insertions required is 1 i.e. bab"
},
{
"code": null,
"e": 26529,
"s": 26482,
"text": "aa: Number of insertions required is 0 i.e. aa"
},
{
"code": null,
"e": 26583,
"s": 26529,
"text": "abcd: Number of insertions required is 3 i.e. dcbabcd"
},
{
"code": null,
"e": 26712,
"s": 26583,
"text": "abcda: Number of insertions required is 2 i.e. adcbcda which is the same as the number of insertions in the substring bcd(Why?)."
},
{
"code": null,
"e": 26769,
"s": 26712,
"text": "abcde: Number of insertions required is 4 i.e. edcbabcde"
},
{
"code": null,
"e": 26859,
"s": 26769,
"text": "Let the input string be str[l......h]. The problem can be broken down into three parts: "
},
{
"code": null,
"e": 27078,
"s": 26859,
"text": "Find the minimum number of insertions in the substring str[l+1,.......h].Find the minimum number of insertions in the substring str[l.......h-1].Find the minimum number of insertions in the substring str[l+1......h-1]."
},
{
"code": null,
"e": 27152,
"s": 27078,
"text": "Find the minimum number of insertions in the substring str[l+1,.......h]."
},
{
"code": null,
"e": 27225,
"s": 27152,
"text": "Find the minimum number of insertions in the substring str[l.......h-1]."
},
{
"code": null,
"e": 27299,
"s": 27225,
"text": "Find the minimum number of insertions in the substring str[l+1......h-1]."
},
{
"code": null,
"e": 27398,
"s": 27299,
"text": "Recursive Approach: The minimum number of insertions in the string str[l.....h] can be given as: "
},
{
"code": null,
"e": 27459,
"s": 27398,
"text": "minInsertions(str[l+1.....h-1]) if str[l] is equal to str[h]"
},
{
"code": null,
"e": 27539,
"s": 27459,
"text": "min(minInsertions(str[l.....h-1]), minInsertions(str[l+1.....h])) + 1 otherwise"
},
{
"code": null,
"e": 27592,
"s": 27539,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27596,
"s": 27592,
"text": "C++"
},
{
"code": null,
"e": 27598,
"s": 27596,
"text": "C"
},
{
"code": null,
"e": 27603,
"s": 27598,
"text": "Java"
},
{
"code": null,
"e": 27612,
"s": 27603,
"text": "Python 3"
},
{
"code": null,
"e": 27615,
"s": 27612,
"text": "C#"
},
{
"code": null,
"e": 27626,
"s": 27615,
"text": "Javascript"
},
{
"code": "// A Naive recursive program to find minimum// number insertions needed to make a string// palindrome#include<bits/stdc++.h>using namespace std; // Recursive function to find // minimum number of insertionsint findMinInsertions(char str[], int l, int h){ // Base Cases if (l > h) return INT_MAX; if (l == h) return 0; if (l == h - 1) return (str[l] == str[h])? 0 : 1; // Check if the first and last characters are // same. On the basis of the comparison result, // decide which subproblem(s) to call return (str[l] == str[h])? findMinInsertions(str, l + 1, h - 1): (min(findMinInsertions(str, l, h - 1), findMinInsertions(str, l + 1, h)) + 1);} // Driver codeint main(){ char str[] = \"geeks\"; cout << findMinInsertions(str, 0, strlen(str) - 1); return 0;} // This code is contributed by// Akanksha Rai",
"e": 28520,
"s": 27626,
"text": null
},
{
"code": "// A Naive recursive program to find minimum// number insertions needed to make a string// palindrome#include <stdio.h>#include <limits.h>#include <string.h> // A utility function to find minimum of two numbersint min(int a, int b){ return a < b ? a : b; } // Recursive function to find minimum number of// insertionsint findMinInsertions(char str[], int l, int h){ // Base Cases if (l > h) return INT_MAX; if (l == h) return 0; if (l == h - 1) return (str[l] == str[h])? 0 : 1; // Check if the first and last characters are // same. On the basis of the comparison result, // decide which subproblem(s) to call return (str[l] == str[h])? findMinInsertions(str, l + 1, h - 1): (min(findMinInsertions(str, l, h - 1), findMinInsertions(str, l + 1, h)) + 1);} // Driver program to test above functionsint main(){ char str[] = \"geeks\"; printf(\"%d\", findMinInsertions(str, 0, strlen(str)-1)); return 0;}",
"e": 29513,
"s": 28520,
"text": null
},
{
"code": "// A Naive recursive Java program to find minimum// number insertions needed to make a string// palindromeclass GFG { // Recursive function to find minimum number // of insertions static int findMinInsertions(char str[], int l, int h) { // Base Cases if (l > h) return Integer.MAX_VALUE; if (l == h) return 0; if (l == h - 1) return (str[l] == str[h])? 0 : 1; // Check if the first and last characters // are same. On the basis of the comparison // result, decide which subproblem(s) to call return (str[l] == str[h])? findMinInsertions(str, l + 1, h - 1): (Integer.min(findMinInsertions(str, l, h - 1), findMinInsertions(str, l + 1, h)) + 1); } // Driver program to test above functions public static void main(String args[]) { String str= \"geeks\"; System.out.println(findMinInsertions(str.toCharArray(), 0, str.length()-1)); }}// This code is contributed by Sumit Ghosh",
"e": 30604,
"s": 29513,
"text": null
},
{
"code": "# A Naive recursive program to find minimum# number insertions needed to make a string# palindromeimport sys # Recursive function to find minimum# number of insertionsdef findMinInsertions(str, l, h): # Base Cases if (l > h): return sys.maxsize if (l == h): return 0 if (l == h - 1): return 0 if(str[l] == str[h]) else 1 # Check if the first and last characters are # same. On the basis of the comparison result, # decide which subproblem(s) to call if(str[l] == str[h]): return findMinInsertions(str, l + 1, h - 1) else: return (min(findMinInsertions(str, l, h - 1), findMinInsertions(str, l + 1, h)) + 1) # Driver Codeif __name__ == \"__main__\": str = \"geeks\" print(findMinInsertions(str, 0, len(str) - 1)) # This code is contributed by ita_c",
"e": 31447,
"s": 30604,
"text": null
},
{
"code": "// A Naive recursive C# program// to find minimum number// insertions needed to make// a string palindromeusing System; class GFG{ // Recursive function to // find minimum number of // insertions static int findMinInsertions(char []str, int l, int h) { // Base Cases if (l > h) return int.MaxValue; if (l == h) return 0; if (l == h - 1) return (str[l] == str[h])? 0 : 1; // Check if the first and // last characters are same. // On the basis of the // comparison result, decide // which subproblem(s) to call return (str[l] == str[h])? findMinInsertions(str, l + 1, h - 1): (Math.Min(findMinInsertions(str, l, h - 1), findMinInsertions(str, l + 1, h)) + 1); } // Driver Code public static void Main() { string str= \"geeks\"; Console.WriteLine(findMinInsertions(str.ToCharArray(), 0, str.Length - 1)); }} // This code is contributed by Sam007",
"e": 32664,
"s": 31447,
"text": null
},
{
"code": "<script> // A Naive recursive JavaScript program to find minimum// number insertions needed to make a string// palindrome // Recursive function to find minimum number // of insertions function findMinInsertions(str,l,h) { // Base Cases if (l > h) return Number.MAX_VALUE; if (l == h) return 0; if (l == h - 1) return (str[l] == str[h])? 0 : 1; // Check if the first and last characters // are same. On the basis of the comparison // result, decide which subproblem(s) to call return (str[l] == str[h]) ? findMinInsertions(str, l + 1, h - 1) : (Math.min(findMinInsertions(str, l, h - 1), findMinInsertions(str, l + 1, h)) + 1) } // Driver program to test above functions let str= \"geeks\"; document.write(findMinInsertions(str,0, str.length-1)); // This code is contributed by rag2127 </script>",
"e": 33649,
"s": 32664,
"text": null
},
{
"code": null,
"e": 33658,
"s": 33649,
"text": "Output: "
},
{
"code": null,
"e": 33660,
"s": 33658,
"text": "3"
},
{
"code": null,
"e": 33871,
"s": 33660,
"text": "Dynamic Programming based Solution If we observe the above approach carefully, we can find that it exhibits overlapping subproblems. Suppose we want to find the minimum number of insertions in string βabcdeβ: "
},
{
"code": null,
"e": 34205,
"s": 33871,
"text": " abcde\n / | \\\n / | \\\n bcde abcd bcd <- case 3 is discarded as str[l] != str[h]\n / | \\ / | \\\n / | \\ / | \\\n cde bcd cd bcd abc bc\n / | \\ / | \\ /|\\ / | \\\nde cd d cd bc c......................"
},
{
"code": null,
"e": 34387,
"s": 34205,
"text": "The substrings in bold show that the recursion is to be terminated and the recursion tree cannot originate from there. Substring in the same color indicates overlapping subproblems."
},
{
"code": null,
"e": 34703,
"s": 34387,
"text": "How to re-use solutions of subproblems? The memorization technique is used to avoid similar subproblem recalls. We can create a table to store the results of subproblems so that they can be used directly if the same subproblem is encountered again.The below table represents the stored values for the string abcde. "
},
{
"code": null,
"e": 34777,
"s": 34703,
"text": "a b c d e\n----------\n0 1 2 3 4\n0 0 1 2 3 \n0 0 0 1 2 \n0 0 0 0 1 \n0 0 0 0 0"
},
{
"code": null,
"e": 34942,
"s": 34777,
"text": "How to fill the table? The table should be filled in a diagonal fashion. For the string abcde, 0....4, the following should be ordered in which the table is filled:"
},
{
"code": null,
"e": 35051,
"s": 34942,
"text": "Gap = 1: (0, 1) (1, 2) (2, 3) (3, 4)\n\nGap = 2: (0, 2) (1, 3) (2, 4)\n\nGap = 3: (0, 3) (1, 4)\n\nGap = 4: (0, 4)"
},
{
"code": null,
"e": 35103,
"s": 35051,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 35107,
"s": 35103,
"text": "C++"
},
{
"code": null,
"e": 35109,
"s": 35107,
"text": "C"
},
{
"code": null,
"e": 35114,
"s": 35109,
"text": "Java"
},
{
"code": null,
"e": 35122,
"s": 35114,
"text": "Python3"
},
{
"code": null,
"e": 35125,
"s": 35122,
"text": "C#"
},
{
"code": null,
"e": 35136,
"s": 35125,
"text": "Javascript"
},
{
"code": "// A Dynamic Programming based program to find// minimum number insertions needed to make a// string palindrome#include <bits/stdc++.h>using namespace std; // A DP function to find minimum// number of insertionsint findMinInsertionsDP(char str[], int n){ // Create a table of size n*n. table[i][j] // will store minimum number of insertions // needed to convert str[i..j] to a palindrome. int table[n][n], l, h, gap; // Initialize all table entries as 0 memset(table, 0, sizeof(table)); // Fill the table for (gap = 1; gap < n; ++gap) for (l = 0, h = gap; h < n; ++l, ++h) table[l][h] = (str[l] == str[h])? table[l + 1][h - 1] : (min(table[l][h - 1], table[l + 1][h]) + 1); // Return minimum number of insertions // for str[0..n-1] return table[0][n - 1];} // Driver Codeint main(){ char str[] = \"geeks\"; cout << findMinInsertionsDP(str, strlen(str)); return 0;} // This is code is contributed by rathbhupendra",
"e": 36185,
"s": 35136,
"text": null
},
{
"code": "// A Dynamic Programming based program to find// minimum number insertions needed to make a// string palindrome#include <stdio.h>#include <string.h> // A utility function to find minimum of two integersint min(int a, int b){ return a < b ? a : b; } // A DP function to find minimum number of insertionsint findMinInsertionsDP(char str[], int n){ // Create a table of size n*n. table[i][j] // will store minimum number of insertions // needed to convert str[i..j] to a palindrome. int table[n][n], l, h, gap; // Initialize all table entries as 0 memset(table, 0, sizeof(table)); // Fill the table for (gap = 1; gap < n; ++gap) for (l = 0, h = gap; h < n; ++l, ++h) table[l][h] = (str[l] == str[h])? table[l+1][h-1] : (min(table[l][h-1], table[l+1][h]) + 1); // Return minimum number of insertions for // str[0..n-1] return table[0][n-1];} // Driver program to test above function.int main(){ char str[] = \"geeks\"; printf(\"%d\", findMinInsertionsDP(str, strlen(str))); return 0;}",
"e": 37304,
"s": 36185,
"text": null
},
{
"code": "// A Java solution for Dynamic Programming// based program to find minimum number// insertions needed to make a string// palindromeimport java.util.Arrays; class GFG{ // A DP function to find minimum number // of insertions static int findMinInsertionsDP(char str[], int n) { // Create a table of size n*n. table[i][j] // will store minimum number of insertions // needed to convert str[i..j] to a palindrome. int table[][] = new int[n][n]; int l, h, gap; // Fill the table for (gap = 1; gap < n; ++gap) for (l = 0, h = gap; h < n; ++l, ++h) table[l][h] = (str[l] == str[h])? table[l+1][h-1] : (Integer.min(table[l][h-1], table[l+1][h]) + 1); // Return minimum number of insertions // for str[0..n-1] return table[0][n-1]; } // Driver program to test above function. public static void main(String args[]) { String str = \"geeks\"; System.out.println( findMinInsertionsDP(str.toCharArray(), str.length())); }}// This code is contributed by Sumit Ghosh",
"e": 38476,
"s": 37304,
"text": null
},
{
"code": "# A Dynamic Programming based program to# find minimum number insertions needed# to make a string palindrome # A utility function to find minimum# of two integersdef Min(a, b): return min(a, b) # A DP function to find minimum number# of insertionsdef findMinInsertionsDP(str1, n): # Create a table of size n*n. table[i][j] # will store minimum number of insertions # needed to convert str1[i..j] to a palindrome. table = [[0 for i in range(n)] for i in range(n)] l, h, gap = 0, 0, 0 # Fill the table for gap in range(1, n): l = 0 for h in range(gap, n): if str1[l] == str1[h]: table[l][h] = table[l + 1][h - 1] else: table[l][h] = (Min(table[l][h - 1], table[l + 1][h]) + 1) l += 1 # Return minimum number of insertions # for str1[0..n-1] return table[0][n - 1]; # Driver Codestr1 = \"geeks\"print(findMinInsertionsDP(str1, len(str1))) # This code is contributed by# Mohit kumar 29",
"e": 39518,
"s": 38476,
"text": null
},
{
"code": "// A C# solution for Dynamic Programming// based program to find minimum number// insertions needed to make a string// palindromeusing System; class GFG{ // A DP function to find minimum number // of insertions static int findMinInsertionsDP(char []str, int n) { // Create a table of size n*n. table[i][j] // will store minimum number of insertions // needed to convert str[i..j] to a palindrome. int [,]table = new int[n, n]; int l, h, gap; // Fill the table for (gap = 1; gap < n; ++gap) for (l = 0, h = gap; h < n; ++l, ++h) table[l, h] = (str[l] == str[h])? table[l+1, h-1] : (Math.Min(table[l, h-1], table[l+1, h]) + 1); // Return minimum number of insertions // for str[0..n-1] return table[0, n-1]; } // Driver code public static void Main() { String str = \"geeks\"; Console.Write( findMinInsertionsDP(str.ToCharArray(), str.Length)); }} // This code is contributed by Rajput-Ji",
"e": 40619,
"s": 39518,
"text": null
},
{
"code": "<script> // A Javascript solution for Dynamic Programming// based program to find minimum number// insertions needed to make a string// palindrome // A DP function to find minimum number // of insertions function findMinInsertionsDP(str,n) { // Create a table of size n*n. table[i][j] // will store minimum number of insertions // needed to convert str[i..j] to a palindrome. let table=new Array(n); for(let i=0;i<n;i++) { table[i]=new Array(n); } for(let i=0;i<n;i++) { for(let j=0;j<n;j++) { table[i][j]=0; } } let l=0, h=0, gap=0; // Fill the table for (gap = 1; gap < n; gap++) { for (l = 0, h = gap; h < n; l++, h++) { table[l][h] = (str[l] == str[h]) ? table[l+1][h-1] : (Math.min(table[l][h-1],table[l+1][h]) + 1); } } // Return minimum number of insertions // for str[0..n-1] return table[0][n - 1]; } // Driver program to test above function. let str = \"geeks\"; document.write(findMinInsertionsDP(str, str.length)); // This code is contributed by avanitrachhadiya2155 </script>",
"e": 41978,
"s": 40619,
"text": null
},
{
"code": null,
"e": 41987,
"s": 41978,
"text": "Output: "
},
{
"code": null,
"e": 41989,
"s": 41987,
"text": "3"
},
{
"code": null,
"e": 42037,
"s": 41989,
"text": "Time complexity: O(N^2) Auxiliary Space: O(N^2)"
},
{
"code": null,
"e": 42412,
"s": 42037,
"text": "Another Dynamic Programming Solution (Variation of Longest Common Subsequence Problem) The problem of finding minimum insertions can also be solved using Longest Common Subsequence (LCS) Problem. If we find out the LCS of string and its reverse, we know how many maximum characters can form a palindrome. We need to insert the remaining characters. Following are the steps. "
},
{
"code": null,
"e": 42579,
"s": 42412,
"text": "Find the length of LCS of the input string and its reverse. Let the length be βlβ.The minimum number of insertions needed is the length of the input string minus βlβ."
},
{
"code": null,
"e": 42662,
"s": 42579,
"text": "Find the length of LCS of the input string and its reverse. Let the length be βlβ."
},
{
"code": null,
"e": 42747,
"s": 42662,
"text": "The minimum number of insertions needed is the length of the input string minus βlβ."
},
{
"code": null,
"e": 42800,
"s": 42747,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 42804,
"s": 42800,
"text": "C++"
},
{
"code": null,
"e": 42806,
"s": 42804,
"text": "C"
},
{
"code": null,
"e": 42811,
"s": 42806,
"text": "Java"
},
{
"code": null,
"e": 42819,
"s": 42811,
"text": "Python3"
},
{
"code": null,
"e": 42822,
"s": 42819,
"text": "C#"
},
{
"code": null,
"e": 42833,
"s": 42822,
"text": "Javascript"
},
{
"code": "// An LCS based program to find minimum number// insertions needed to make a string palindrome#include <bits/stdc++.h>using namespace std; // Returns length of LCS for X[0..m-1], Y[0..n-1].int lcs( string X, string Y, int m, int n ){ int L[m+1][n+1]; int i, j; /* Following steps build L[m+1][n+1] in bottom up fashion. Note that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] */ for (i = 0; i <= m; i++) { for (j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i][j] = 0; else if (X[i - 1] == Y[j - 1]) L[i][j] = L[i - 1][j - 1] + 1; else L[i][j] = max(L[i - 1][j], L[i][j - 1]); } } /* L[m][n] contains length of LCS for X[0..n-1] and Y[0..m-1] */ return L[m][n];} void reverseStr(string& str){ int n = str.length(); // Swap character starting from two // corners for (int i = 0; i < n / 2; i++) swap(str[i], str[n - i - 1]);} // LCS based function to find minimum number of// insertionsint findMinInsertionsLCS(string str, int n){ // Creata another string to store reverse of 'str' string rev = \"\"; rev = str; reverseStr(rev); // The output is length of string minus length of lcs of // str and it reverse return (n - lcs(str, rev, n, n));} // Driver codeint main(){ string str = \"geeks\"; cout << findMinInsertionsLCS(str, str.length()); return 0;} // This code is contributed by rathbhupendra",
"e": 44334,
"s": 42833,
"text": null
},
{
"code": "// An LCS based program to find minimum number// insertions needed to make a string palindrome#include<stdio.h>#include <string.h> /* Utility function to get max of 2 integers */int max(int a, int b){ return (a > b)? a : b; } /* Returns length of LCS for X[0..m-1], Y[0..n-1]. See http://goo.gl/bHQVP for details of this function */int lcs( char *X, char *Y, int m, int n ){ int L[m+1][n+1]; int i, j; /* Following steps build L[m+1][n+1] in bottom up fashion. Note that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] */ for (i=0; i<=m; i++) { for (j=0; j<=n; j++) { if (i == 0 || j == 0) L[i][j] = 0; else if (X[i-1] == Y[j-1]) L[i][j] = L[i-1][j-1] + 1; else L[i][j] = max(L[i-1][j], L[i][j-1]); } } /* L[m][n] contains length of LCS for X[0..n-1] and Y[0..m-1] */ return L[m][n];} // LCS based function to find minimum number of// insertionsint findMinInsertionsLCS(char str[], int n){ // Creata another string to store reverse of 'str' char rev[n+1]; strcpy(rev, str); strrev(rev); // The output is length of string minus length of lcs of // str and it reverse return (n - lcs(str, rev, n, n));} // Driver program to test above functionsint main(){ char str[] = \"geeks\"; printf(\"%d\", findMinInsertionsLCS(str, strlen(str))); return 0;}",
"e": 45703,
"s": 44334,
"text": null
},
{
"code": "// An LCS based Java program to find minimum// number insertions needed to make a string// palindromeclass GFG{ /* Returns length of LCS for X[0..m-1], Y[0..n-1]. See http://goo.gl/bHQVP for details of this function */ static int lcs( String X, String Y, int m, int n ) { int L[][] = new int[m+1][n+1]; int i, j; /* Following steps build L[m+1][n+1] in bottom up fashion. Note that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] */ for (i=0; i<=m; i++) { for (j=0; j<=n; j++) { if (i == 0 || j == 0) L[i][j] = 0; else if (X.charAt(i-1) == Y.charAt(j-1)) L[i][j] = L[i-1][j-1] + 1; else L[i][j] = Integer.max(L[i-1][j], L[i][j-1]); } } /* L[m][n] contains length of LCS for X[0..n-1] and Y[0..m-1] */ return L[m][n]; } // LCS based function to find minimum number // of insertions static int findMinInsertionsLCS(String str, int n) { // Using StringBuffer to reverse a String StringBuffer sb = new StringBuffer(str); sb.reverse(); String revString = sb.toString(); // The output is length of string minus // length of lcs of str and it reverse return (n - lcs(str, revString , n, n)); } // Driver program to test above functions public static void main(String args[]) { String str = \"geeks\"; System.out.println( findMinInsertionsLCS(str, str.length())); }}// This code is contributed by Sumit Ghosh",
"e": 47371,
"s": 45703,
"text": null
},
{
"code": "# An LCS based Python3 program to find minimum# number insertions needed to make a string# palindrome \"\"\" Returns length of LCS for X[0..m-1],Y[0..n-1]. See http://goo.gl/bHQVP fordetails of this function \"\"\"def lcs(X, Y, m, n) : L = [[0 for i in range(n + 1)] for j in range(m + 1)] \"\"\" Following steps build L[m + 1, n + 1] in bottom up fashion. Note that L[i, j] contains length of LCS of X[0..i - 1] and Y[0..j - 1] \"\"\" for i in range(m + 1) : for j in range(n + 1) : if (i == 0 or j == 0) : L[i][j] = 0 elif (X[i - 1] == Y[j - 1]) : L[i][j] = L[i - 1][j - 1] + 1 else : L[i][j] = max(L[i - 1][j], L[i][j - 1]) \"\"\" L[m,n] contains length of LCS for X[0..n-1] and Y[0..m-1] \"\"\" return L[m][n] # LCS based function to find minimum number# of insertionsdef findMinInsertionsLCS(Str, n) : # Using charArray to reverse a String charArray = list(Str) charArray.reverse() revString = \"\".join(charArray) # The output is length of string minus # length of lcs of str and it reverse return (n - lcs(Str, revString , n, n)) # Driver code Str = \"geeks\"print(findMinInsertionsLCS(Str,len(Str))) # This code is contributed by divyehrabadiya07",
"e": 48661,
"s": 47371,
"text": null
},
{
"code": "// An LCS based C# program to find minimum// number insertions needed to make a string// palindromeusing System; class GFG{ /* Returns length of LCS for X[0..m-1], Y[0..n-1]. See http://goo.gl/bHQVP for details of this function */ static int lcs( string X, string Y, int m, int n ) { int[,] L = new int[m + 1, n + 1]; int i, j; /* Following steps build L[m+1,n+1] in bottom up fashion. Note that L[i,j] contains length of LCS of X[0..i-1] and Y[0..j-1] */ for (i = 0; i <= m; i++) { for (j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i, j] = 0; else if (X[i - 1] == Y[j - 1]) L[i, j] = L[i - 1, j - 1] + 1; else L[i, j] = Math.Max(L[i - 1, j], L[i, j - 1]); } } /* L[m,n] contains length of LCS for X[0..n-1] and Y[0..m-1] */ return L[m,n]; } // LCS based function to find minimum number // of insertions static int findMinInsertionsLCS(string str, int n) { // Using charArray to reverse a String char[] charArray = str.ToCharArray(); Array.Reverse(charArray); string revString = new string(charArray); // The output is length of string minus // length of lcs of str and it reverse return (n - lcs(str, revString , n, n)); } // Driver code static void Main() { string str = \"geeks\"; Console.WriteLine(findMinInsertionsLCS(str,str.Length)); }} // This code is contributed by mits",
"e": 50274,
"s": 48661,
"text": null
},
{
"code": "<script>// An LCS based Javascript program to find minimum// number insertions needed to make a string// palindrome /* Returns length of LCS for X[0..m-1], Y[0..n-1]. See http://goo.gl/bHQVP for details of this function */ function lcs(X, Y, m, n) { let L = new Array(m+1); for(let i = 0; i < m + 1; i++) { L[i] = new Array(n+1); for(let j = 0; j < n + 1; j++) { L[i][j] = 0; } } let i, j; /* Following steps build L[m+1][n+1] in bottom up fashion. Note that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] */ for (i = 0; i <= m; i++) { for (j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i][j] = 0; else if (X[i - 1] == Y[j - 1]) L[i][j] = L[i - 1][j - 1] + 1; else L[i][j] = Math.max(L[i - 1][j], L[i][j - 1]); } } /* L[m][n] contains length of LCS for X[0..n-1] and Y[0..m-1] */ return L[m][n]; } // LCS based function to find minimum number // of insertions function findMinInsertionsLCS(str, n) { let revString = str.split('').reverse().join(''); // The output is length of string minus // length of lcs of str and it reverse return (n - lcs(str, revString , n, n)); } // Driver program to test above functions let str = \"geeks\"; document.write(findMinInsertionsLCS(str, str.length)); // This code is contributed by unknown2108</script>",
"e": 51970,
"s": 50274,
"text": null
},
{
"code": null,
"e": 51979,
"s": 51970,
"text": "Output: "
},
{
"code": null,
"e": 51981,
"s": 51979,
"text": "3"
},
{
"code": null,
"e": 52030,
"s": 51981,
"text": "Time complexity: O(N^2) Auxiliary Space: O(N^2) "
},
{
"code": null,
"e": 52278,
"s": 52030,
"text": "Related Article : Minimum number of Appends needed to make a string palindromeThis article is compiled by Aashish Barnwal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 52285,
"s": 52278,
"text": "Sam007"
},
{
"code": null,
"e": 52291,
"s": 52285,
"text": "ukasp"
},
{
"code": null,
"e": 52306,
"s": 52291,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 52316,
"s": 52306,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 52329,
"s": 52316,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 52343,
"s": 52329,
"text": "rathbhupendra"
},
{
"code": null,
"e": 52356,
"s": 52343,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 52370,
"s": 52356,
"text": "nandishwar001"
},
{
"code": null,
"e": 52388,
"s": 52370,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 52396,
"s": 52388,
"text": "rag2127"
},
{
"code": null,
"e": 52417,
"s": 52396,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 52429,
"s": 52417,
"text": "unknown2108"
},
{
"code": null,
"e": 52442,
"s": 52429,
"text": "simmytarika5"
},
{
"code": null,
"e": 52461,
"s": 52442,
"text": "surindertarika1234"
},
{
"code": null,
"e": 52479,
"s": 52461,
"text": "kumaripunam984122"
},
{
"code": null,
"e": 52486,
"s": 52479,
"text": "Amazon"
},
{
"code": null,
"e": 52493,
"s": 52486,
"text": "Google"
},
{
"code": null,
"e": 52504,
"s": 52493,
"text": "palindrome"
},
{
"code": null,
"e": 52524,
"s": 52504,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 52532,
"s": 52524,
"text": "Strings"
},
{
"code": null,
"e": 52539,
"s": 52532,
"text": "Amazon"
},
{
"code": null,
"e": 52546,
"s": 52539,
"text": "Google"
},
{
"code": null,
"e": 52554,
"s": 52546,
"text": "Strings"
},
{
"code": null,
"e": 52574,
"s": 52554,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 52585,
"s": 52574,
"text": "palindrome"
},
{
"code": null,
"e": 52683,
"s": 52585,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 52716,
"s": 52683,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 52751,
"s": 52716,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 52819,
"s": 52751,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 52840,
"s": 52819,
"text": "Edit Distance | DP-5"
},
{
"code": null,
"e": 52903,
"s": 52840,
"text": "Overlapping Subproblems Property in Dynamic Programming | DP-1"
},
{
"code": null,
"e": 52949,
"s": 52903,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 52974,
"s": 52949,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 53034,
"s": 52974,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 53049,
"s": 53034,
"text": "C++ Data Types"
}
] |
Count number of strings (made of R, G and B) using given combination - GeeksforGeeks
|
08 Jun, 2021
We need to make a string of size n. Each character of the string is either βRβ, βBβ or βGβ. In the final string there needs to be at least r number of βRβ, at least b number of βBβ and at least g number of βGβ (such that r + g + b <= n). We need to find number of such strings possible.Examples:
Input : n = 4, r = 1,
b = 1, g = 1.
Output: 36
No. of 'R' >= 1,
No. of βGβ >= 1,
No. of βBβ >= 1 and
(No. of βRβ) + (No. of βBβ) + (No. of βGβ) = n
then following cases are possible:
1. RBGR and its 12 permutation
2. RBGB and its 12 permutation
3. RBGG and its 12 permutation
Hence answer is 36.
Asked in : Directi
As R, B and G have to be included atleast for given no. of times. Remaining values = n -(r + b + g).Make all combinations for the remaining values.Consider each element one by one for the remaining values and sum up all the permutations.Return total no. of permutations of all the combinations.
As R, B and G have to be included atleast for given no. of times. Remaining values = n -(r + b + g).
Make all combinations for the remaining values.
Consider each element one by one for the remaining values and sum up all the permutations.
Return total no. of permutations of all the combinations.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to count number of possible strings// with n characters.#include<bits/stdc++.h>using namespace std; // Function to calculate number of stringsint possibleStrings( int n, int r, int b, int g){ // Store factorial of numbers up to n // for further computation int fact[n+1]; fact[0] = 1; for (int i = 1; i <= n; i++) fact[i] = fact[i-1] * i; // Find the remaining values to be added int left = n - (r+g+b); int sum = 0; // Make all possible combinations // of R, B and G for the remaining value for (int i = 0; i <= left; i++) { for (int j = 0; j<= left-i; j++) { int k = left - (i+j); // Compute permutation of each combination // one by one and add them. sum = sum + fact[n] / (fact[i+r]*fact[j+b]*fact[k+g]); } } // Return total no. of strings/permutation return sum;} // Drivers codeint main(){ int n = 4, r = 2; int b = 0, g = 1; cout << possibleStrings(n, r, b, g); return 0;}
// Java program to count number of possible// strings with n characters. class GFG{ //Function to calculate number of strings static int possibleStrings( int n, int r, int b, int g) { // Store factorial of numbers up to n // for further computation int fact[] = new int[n+1]; fact[0] = 1; for (int i = 1; i <= n; i++) fact[i] = fact[i-1] * i; // Find the remaining values to be added int left = n - (r+g+b); int sum = 0; // Make all possible combinations // of R, B and G for the remaining value for (int i = 0; i <= left; i++) { for (int j = 0; j<= left-i; j++) { int k = left - (i+j); // Compute permutation of each combination // one by one and add them. sum = sum + fact[n] / (fact[i+r]*fact[j+b]*fact[k+g]); } } // Return total no. of strings/permutation return sum; } //Drivers code public static void main(String []args) { int n = 4, r = 2; int b = 0, g = 1; System.out.println(possibleStrings(n, r, b, g)); }}
# Python 3 program to count number of# possible strings with n characters. # Function to calculate number of stringsdef possibleStrings(n, r, b, g): # Store factorial of numbers up to n # for further computation fact = [0 for i in range(n + 1)] fact[0] = 1 for i in range(1, n + 1, 1): fact[i] = fact[i - 1] * i # Find the remaining values to be added left = n - (r + g + b) sum = 0 # Make all possible combinations of # R, B and G for the remaining value for i in range(0, left + 1, 1): for j in range(0, left - i + 1, 1): k = left - (i + j) # Compute permutation of each # combination one by one and add them. sum = (sum + fact[n] / (fact[i + r] * fact[j + b] * fact[k + g])) # Return total no. of # strings/permutation return sum # Driver codeif __name__ == '__main__': n = 4 r = 2 b = 0 g = 1 print(int(possibleStrings(n, r, b, g))) # This code is contributed by# Sanjit_Prasad
// C# program to count number of possible// strings with n characters.using System; class GFG{ //Function to calculate number of strings static int possibleStrings( int n, int r, int b, int g) { // Store factorial of numbers up to n // for further computation int[] fact = new int[n + 1]; fact[0] = 1; for (int i = 1; i <= n; i++) fact[i] = fact[i - 1] * i; // Find the remaining values to be added int left = n - (r + g + b); int sum = 0; // Make all possible combinations // of R, B and G for the remaining value for (int i = 0; i <= left; i++) { for (int j = 0; j <= left - i; j++) { int k = left - (i + j); // Compute permutation of each combination // one by one and add them. sum = sum + fact[n] / (fact[i + r] * fact[j + b] * fact[k + g]); } } // Return total no. of strings/permutation return sum; } //Drivers code public static void Main() { int n = 4, r = 2; int b = 0, g = 1; Console.WriteLine(possibleStrings(n, r, b, g)); }} // This Code is contributed by Code_Mech.
<?php// PHP program to count number// of possible strings with// n characters. // Function to calculate// number of stringsfunction possibleStrings( $n, $r, $b, $g){ // Store factorial of // numbers up to n for // further computation $fact[0] = 1; for ($i = 1; $i <= $n; $i++) $fact[$i] = $fact[$i - 1] * $i; // Find the remaining // values to be added $left = $n - ($r + $g + $b); $sum = 0; // Make all possible combinations // of R, B and G for the remaining value for ($i = 0; $i <= $left; $i++) { for ($j = 0; $j <= $left - $i; $j++) { $k = $left - ($i+$j); // Compute permutation of // each combination one // by one and add them. $sum = $sum + $fact[$n] / ($fact[$i + $r] * $fact[$j + $b] * $fact[$k + $g]); } } // Return total no. of // strings/permutation return $sum;} // Driver Code $n = 4; $r = 2; $b = 0; $g = 1; echo possibleStrings($n, $r, $b, $g); // This code is contributed by jit_t.?>
<script>// Javascript program to count number of possible// strings with n characters. // Function to calculate number of strings function possibleStrings(n,r,b,g) { // Store factorial of numbers up to n // for further computation let fact = new Array(n+1); fact[0] = 1; for (let i = 1; i <= n; i++) fact[i] = fact[i-1] * i; // Find the remaining values to be added let left = n - (r+g+b); let sum = 0; // Make all possible combinations // of R, B and G for the remaining value for (let i = 0; i <= left; i++) { for (let j = 0; j<= left-i; j++) { let k = left - (i+j); // Compute permutation of each combination // one by one and add them. sum = sum + fact[n] / (fact[i+r]*fact[j+b]*fact[k+g]); } } // Return total no. of strings/permutation return sum; } // Drivers code let n = 4, r = 2; let b = 0, g = 1; document.write(possibleStrings(n, r, b, g)); // This code is contributed by avanitrachhadiya2155 </script>
Output:
22
To handle n with large numbers, we can use the concept of Large Factorial.This article is contributed by Sahil Chhabra. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.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.
jit_t
ukasp
Sanjit_Prasad
Code_Mech
avanitrachhadiya2155
ruhelaa48
Directi
permutation
Combinatorial
Strings
Directi
Strings
permutation
Combinatorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Combinational Sum
Count ways to reach the nth stair using step 1, 2 or 3
Print all possible strings of length k that can be formed from a set of n characters
Count of subsets with sum equal to X
Python program to get all subsets of given size of a set
Reverse a string in Java
C++ Data Types
Check for Balanced Brackets in an expression (well-formedness) using Stack
Python program to check if a string is palindrome or not
KMP Algorithm for Pattern Searching
|
[
{
"code": null,
"e": 26803,
"s": 26775,
"text": "\n08 Jun, 2021"
},
{
"code": null,
"e": 27101,
"s": 26803,
"text": "We need to make a string of size n. Each character of the string is either βRβ, βBβ or βGβ. In the final string there needs to be at least r number of βRβ, at least b number of βBβ and at least g number of βGβ (such that r + g + b <= n). We need to find number of such strings possible.Examples: "
},
{
"code": null,
"e": 27410,
"s": 27101,
"text": "Input : n = 4, r = 1, \n b = 1, g = 1.\nOutput: 36 \nNo. of 'R' >= 1, \nNo. of βGβ >= 1, \nNo. of βBβ >= 1 and \n(No. of βRβ) + (No. of βBβ) + (No. of βGβ) = n\nthen following cases are possible:\n1. RBGR and its 12 permutation\n2. RBGB and its 12 permutation\n3. RBGG and its 12 permutation\nHence answer is 36."
},
{
"code": null,
"e": 27430,
"s": 27410,
"text": "Asked in : Directi "
},
{
"code": null,
"e": 27727,
"s": 27432,
"text": "As R, B and G have to be included atleast for given no. of times. Remaining values = n -(r + b + g).Make all combinations for the remaining values.Consider each element one by one for the remaining values and sum up all the permutations.Return total no. of permutations of all the combinations."
},
{
"code": null,
"e": 27828,
"s": 27727,
"text": "As R, B and G have to be included atleast for given no. of times. Remaining values = n -(r + b + g)."
},
{
"code": null,
"e": 27876,
"s": 27828,
"text": "Make all combinations for the remaining values."
},
{
"code": null,
"e": 27967,
"s": 27876,
"text": "Consider each element one by one for the remaining values and sum up all the permutations."
},
{
"code": null,
"e": 28025,
"s": 27967,
"text": "Return total no. of permutations of all the combinations."
},
{
"code": null,
"e": 28031,
"s": 28027,
"text": "C++"
},
{
"code": null,
"e": 28036,
"s": 28031,
"text": "Java"
},
{
"code": null,
"e": 28044,
"s": 28036,
"text": "Python3"
},
{
"code": null,
"e": 28047,
"s": 28044,
"text": "C#"
},
{
"code": null,
"e": 28051,
"s": 28047,
"text": "PHP"
},
{
"code": null,
"e": 28062,
"s": 28051,
"text": "Javascript"
},
{
"code": "// C++ program to count number of possible strings// with n characters.#include<bits/stdc++.h>using namespace std; // Function to calculate number of stringsint possibleStrings( int n, int r, int b, int g){ // Store factorial of numbers up to n // for further computation int fact[n+1]; fact[0] = 1; for (int i = 1; i <= n; i++) fact[i] = fact[i-1] * i; // Find the remaining values to be added int left = n - (r+g+b); int sum = 0; // Make all possible combinations // of R, B and G for the remaining value for (int i = 0; i <= left; i++) { for (int j = 0; j<= left-i; j++) { int k = left - (i+j); // Compute permutation of each combination // one by one and add them. sum = sum + fact[n] / (fact[i+r]*fact[j+b]*fact[k+g]); } } // Return total no. of strings/permutation return sum;} // Drivers codeint main(){ int n = 4, r = 2; int b = 0, g = 1; cout << possibleStrings(n, r, b, g); return 0;}",
"e": 29112,
"s": 28062,
"text": null
},
{
"code": "// Java program to count number of possible// strings with n characters. class GFG{ //Function to calculate number of strings static int possibleStrings( int n, int r, int b, int g) { // Store factorial of numbers up to n // for further computation int fact[] = new int[n+1]; fact[0] = 1; for (int i = 1; i <= n; i++) fact[i] = fact[i-1] * i; // Find the remaining values to be added int left = n - (r+g+b); int sum = 0; // Make all possible combinations // of R, B and G for the remaining value for (int i = 0; i <= left; i++) { for (int j = 0; j<= left-i; j++) { int k = left - (i+j); // Compute permutation of each combination // one by one and add them. sum = sum + fact[n] / (fact[i+r]*fact[j+b]*fact[k+g]); } } // Return total no. of strings/permutation return sum; } //Drivers code public static void main(String []args) { int n = 4, r = 2; int b = 0, g = 1; System.out.println(possibleStrings(n, r, b, g)); }}",
"e": 30250,
"s": 29112,
"text": null
},
{
"code": "# Python 3 program to count number of# possible strings with n characters. # Function to calculate number of stringsdef possibleStrings(n, r, b, g): # Store factorial of numbers up to n # for further computation fact = [0 for i in range(n + 1)] fact[0] = 1 for i in range(1, n + 1, 1): fact[i] = fact[i - 1] * i # Find the remaining values to be added left = n - (r + g + b) sum = 0 # Make all possible combinations of # R, B and G for the remaining value for i in range(0, left + 1, 1): for j in range(0, left - i + 1, 1): k = left - (i + j) # Compute permutation of each # combination one by one and add them. sum = (sum + fact[n] / (fact[i + r] * fact[j + b] * fact[k + g])) # Return total no. of # strings/permutation return sum # Driver codeif __name__ == '__main__': n = 4 r = 2 b = 0 g = 1 print(int(possibleStrings(n, r, b, g))) # This code is contributed by# Sanjit_Prasad",
"e": 31288,
"s": 30250,
"text": null
},
{
"code": "// C# program to count number of possible// strings with n characters.using System; class GFG{ //Function to calculate number of strings static int possibleStrings( int n, int r, int b, int g) { // Store factorial of numbers up to n // for further computation int[] fact = new int[n + 1]; fact[0] = 1; for (int i = 1; i <= n; i++) fact[i] = fact[i - 1] * i; // Find the remaining values to be added int left = n - (r + g + b); int sum = 0; // Make all possible combinations // of R, B and G for the remaining value for (int i = 0; i <= left; i++) { for (int j = 0; j <= left - i; j++) { int k = left - (i + j); // Compute permutation of each combination // one by one and add them. sum = sum + fact[n] / (fact[i + r] * fact[j + b] * fact[k + g]); } } // Return total no. of strings/permutation return sum; } //Drivers code public static void Main() { int n = 4, r = 2; int b = 0, g = 1; Console.WriteLine(possibleStrings(n, r, b, g)); }} // This Code is contributed by Code_Mech.",
"e": 32587,
"s": 31288,
"text": null
},
{
"code": "<?php// PHP program to count number// of possible strings with// n characters. // Function to calculate// number of stringsfunction possibleStrings( $n, $r, $b, $g){ // Store factorial of // numbers up to n for // further computation $fact[0] = 1; for ($i = 1; $i <= $n; $i++) $fact[$i] = $fact[$i - 1] * $i; // Find the remaining // values to be added $left = $n - ($r + $g + $b); $sum = 0; // Make all possible combinations // of R, B and G for the remaining value for ($i = 0; $i <= $left; $i++) { for ($j = 0; $j <= $left - $i; $j++) { $k = $left - ($i+$j); // Compute permutation of // each combination one // by one and add them. $sum = $sum + $fact[$n] / ($fact[$i + $r] * $fact[$j + $b] * $fact[$k + $g]); } } // Return total no. of // strings/permutation return $sum;} // Driver Code $n = 4; $r = 2; $b = 0; $g = 1; echo possibleStrings($n, $r, $b, $g); // This code is contributed by jit_t.?>",
"e": 33705,
"s": 32587,
"text": null
},
{
"code": "<script>// Javascript program to count number of possible// strings with n characters. // Function to calculate number of strings function possibleStrings(n,r,b,g) { // Store factorial of numbers up to n // for further computation let fact = new Array(n+1); fact[0] = 1; for (let i = 1; i <= n; i++) fact[i] = fact[i-1] * i; // Find the remaining values to be added let left = n - (r+g+b); let sum = 0; // Make all possible combinations // of R, B and G for the remaining value for (let i = 0; i <= left; i++) { for (let j = 0; j<= left-i; j++) { let k = left - (i+j); // Compute permutation of each combination // one by one and add them. sum = sum + fact[n] / (fact[i+r]*fact[j+b]*fact[k+g]); } } // Return total no. of strings/permutation return sum; } // Drivers code let n = 4, r = 2; let b = 0, g = 1; document.write(possibleStrings(n, r, b, g)); // This code is contributed by avanitrachhadiya2155 </script>",
"e": 34844,
"s": 33705,
"text": null
},
{
"code": null,
"e": 34854,
"s": 34844,
"text": "Output: "
},
{
"code": null,
"e": 34857,
"s": 34854,
"text": "22"
},
{
"code": null,
"e": 35358,
"s": 34857,
"text": "To handle n with large numbers, we can use the concept of Large Factorial.This article is contributed by Sahil Chhabra. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.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": 35364,
"s": 35358,
"text": "jit_t"
},
{
"code": null,
"e": 35370,
"s": 35364,
"text": "ukasp"
},
{
"code": null,
"e": 35384,
"s": 35370,
"text": "Sanjit_Prasad"
},
{
"code": null,
"e": 35394,
"s": 35384,
"text": "Code_Mech"
},
{
"code": null,
"e": 35415,
"s": 35394,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 35425,
"s": 35415,
"text": "ruhelaa48"
},
{
"code": null,
"e": 35433,
"s": 35425,
"text": "Directi"
},
{
"code": null,
"e": 35445,
"s": 35433,
"text": "permutation"
},
{
"code": null,
"e": 35459,
"s": 35445,
"text": "Combinatorial"
},
{
"code": null,
"e": 35467,
"s": 35459,
"text": "Strings"
},
{
"code": null,
"e": 35475,
"s": 35467,
"text": "Directi"
},
{
"code": null,
"e": 35483,
"s": 35475,
"text": "Strings"
},
{
"code": null,
"e": 35495,
"s": 35483,
"text": "permutation"
},
{
"code": null,
"e": 35509,
"s": 35495,
"text": "Combinatorial"
},
{
"code": null,
"e": 35607,
"s": 35509,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35625,
"s": 35607,
"text": "Combinational Sum"
},
{
"code": null,
"e": 35680,
"s": 35625,
"text": "Count ways to reach the nth stair using step 1, 2 or 3"
},
{
"code": null,
"e": 35765,
"s": 35680,
"text": "Print all possible strings of length k that can be formed from a set of n characters"
},
{
"code": null,
"e": 35802,
"s": 35765,
"text": "Count of subsets with sum equal to X"
},
{
"code": null,
"e": 35859,
"s": 35802,
"text": "Python program to get all subsets of given size of a set"
},
{
"code": null,
"e": 35884,
"s": 35859,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 35899,
"s": 35884,
"text": "C++ Data Types"
},
{
"code": null,
"e": 35974,
"s": 35899,
"text": "Check for Balanced Brackets in an expression (well-formedness) using Stack"
},
{
"code": null,
"e": 36031,
"s": 35974,
"text": "Python program to check if a string is palindrome or not"
}
] |
How to Create a Socket at a Specific Port in Java? - GeeksforGeeks
|
15 Sep, 2021
A socket is one end-point of a two-way communication link between two programs running on the network. Socket classes are used to represent the connection between a client program and a server program. Socket Programming, us basically client-server programming where a socket is used as a link between them. We need to import the βjava.net package in our program which provides two classes namely Socket class and ServerSocket class. Socket Class implements the client-side of the connection and ServerSocket class implements the server-side of the connection.
Procedure:
In order to create a socket, the βjava.netβ package needs to be imported thereafter using the Socket and ServerSocket class, we create the object of that class.
The Server opens a ServerSocket on a well-known port and waits for input.Meanwhile, the Client opens a (client) Socket with the serverβs hostname and this well-known port address.It sends a request message to the server to initialize a communication session.
The Server opens a ServerSocket on a well-known port and waits for input.
Meanwhile, the Client opens a (client) Socket with the serverβs hostname and this well-known port address.
It sends a request message to the server to initialize a communication session.
At Server Side
import java.net.Socket;
ServerSocket mySsocket= new ServerSocket(portnumber);
Note: The ServerSocket class takes a single parameter: Port number.
Here, the ServerSocket is created by passing it a specific port number to listen on.
At Client Side
import java.net.Socket;
Socket myCsocket= new Socket( address, portnumber);
Note: The Socket class takes the two parameters namely Address and the Port number.
This ask the server side for the IP address, and then it opens a socket to that server on that specified port.
Example 1: Server-side
Java
// Java program for creating socket on Server-side// Server program depicting creation of a socket// at a specific port // Importing majorly Socket and ServerSocket class// from java.net packageimport java.net.*; // Classpublic class GFG { // Main driver method public static void main(String[] args) throws Exception { // Try block to check for exceptions try { // Creating an object of ServerSocket class // with the custom port number - 80 ServerSocket mySsocket = new ServerSocket(80); // Display commands for better readability System.out.println("Server started"); System.out.println("Waiting for a client ..."); // Here it will wait for any client which wants // to get connected to this server // Establishing a connection // using accept() method() Socket socket = mySsocket.accept(); // Display message System.out.println( "Client accepted through the port number: " + mySsocket.getLocalPort()); // getLocalPort() function returning the port // number which is being used } // Catch block to handle for exceptions catch (Exception e) { // Simply return/exit return; } }}
Output:
Server started
Waiting for a client ...
Client accepted through the port number: 80
Example 2: Client-side
Java
// Java program for creating socket on Client-side// Client program depicting creation of a socket// at a specific port // Importing majorly Socket and ServerSocket class// from java.net packageimport java.net.*; // Classpublic class GFG { // Main driver method public static void main(String[] args) throws Exception { // Try block to check for exceptions try { // Creating an object of Socket class where // port number same as server side program Socket myCsocket = new Socket("localhost", 80); // creating client with local ip address // port number as '80' // Display message for better readability System.out.println("Connected to Server"); } // Catch block to handle exceptions catch (Exception e) { // Simply return and exit the program return; } }}
Output:
Connected to Server
simranarora5sos
Java-Networking
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": 25225,
"s": 25197,
"text": "\n15 Sep, 2021"
},
{
"code": null,
"e": 25786,
"s": 25225,
"text": "A socket is one end-point of a two-way communication link between two programs running on the network. Socket classes are used to represent the connection between a client program and a server program. Socket Programming, us basically client-server programming where a socket is used as a link between them. We need to import the βjava.net package in our program which provides two classes namely Socket class and ServerSocket class. Socket Class implements the client-side of the connection and ServerSocket class implements the server-side of the connection."
},
{
"code": null,
"e": 25798,
"s": 25786,
"text": "Procedure: "
},
{
"code": null,
"e": 25959,
"s": 25798,
"text": "In order to create a socket, the βjava.netβ package needs to be imported thereafter using the Socket and ServerSocket class, we create the object of that class."
},
{
"code": null,
"e": 26218,
"s": 25959,
"text": "The Server opens a ServerSocket on a well-known port and waits for input.Meanwhile, the Client opens a (client) Socket with the serverβs hostname and this well-known port address.It sends a request message to the server to initialize a communication session."
},
{
"code": null,
"e": 26292,
"s": 26218,
"text": "The Server opens a ServerSocket on a well-known port and waits for input."
},
{
"code": null,
"e": 26399,
"s": 26292,
"text": "Meanwhile, the Client opens a (client) Socket with the serverβs hostname and this well-known port address."
},
{
"code": null,
"e": 26479,
"s": 26399,
"text": "It sends a request message to the server to initialize a communication session."
},
{
"code": null,
"e": 26494,
"s": 26479,
"text": "At Server Side"
},
{
"code": null,
"e": 26572,
"s": 26494,
"text": "import java.net.Socket;\nServerSocket mySsocket= new ServerSocket(portnumber);"
},
{
"code": null,
"e": 26642,
"s": 26572,
"text": "Note: The ServerSocket class takes a single parameter: Port number. "
},
{
"code": null,
"e": 26727,
"s": 26642,
"text": "Here, the ServerSocket is created by passing it a specific port number to listen on."
},
{
"code": null,
"e": 26742,
"s": 26727,
"text": "At Client Side"
},
{
"code": null,
"e": 26818,
"s": 26742,
"text": "import java.net.Socket;\nSocket myCsocket= new Socket( address, portnumber);"
},
{
"code": null,
"e": 26903,
"s": 26818,
"text": "Note: The Socket class takes the two parameters namely Address and the Port number. "
},
{
"code": null,
"e": 27014,
"s": 26903,
"text": "This ask the server side for the IP address, and then it opens a socket to that server on that specified port."
},
{
"code": null,
"e": 27038,
"s": 27014,
"text": "Example 1: Server-side "
},
{
"code": null,
"e": 27043,
"s": 27038,
"text": "Java"
},
{
"code": "// Java program for creating socket on Server-side// Server program depicting creation of a socket// at a specific port // Importing majorly Socket and ServerSocket class// from java.net packageimport java.net.*; // Classpublic class GFG { // Main driver method public static void main(String[] args) throws Exception { // Try block to check for exceptions try { // Creating an object of ServerSocket class // with the custom port number - 80 ServerSocket mySsocket = new ServerSocket(80); // Display commands for better readability System.out.println(\"Server started\"); System.out.println(\"Waiting for a client ...\"); // Here it will wait for any client which wants // to get connected to this server // Establishing a connection // using accept() method() Socket socket = mySsocket.accept(); // Display message System.out.println( \"Client accepted through the port number: \" + mySsocket.getLocalPort()); // getLocalPort() function returning the port // number which is being used } // Catch block to handle for exceptions catch (Exception e) { // Simply return/exit return; } }}",
"e": 28405,
"s": 27043,
"text": null
},
{
"code": null,
"e": 28414,
"s": 28405,
"text": " Output:"
},
{
"code": null,
"e": 28498,
"s": 28414,
"text": "Server started\nWaiting for a client ...\nClient accepted through the port number: 80"
},
{
"code": null,
"e": 28521,
"s": 28498,
"text": "Example 2: Client-side"
},
{
"code": null,
"e": 28526,
"s": 28521,
"text": "Java"
},
{
"code": "// Java program for creating socket on Client-side// Client program depicting creation of a socket// at a specific port // Importing majorly Socket and ServerSocket class// from java.net packageimport java.net.*; // Classpublic class GFG { // Main driver method public static void main(String[] args) throws Exception { // Try block to check for exceptions try { // Creating an object of Socket class where // port number same as server side program Socket myCsocket = new Socket(\"localhost\", 80); // creating client with local ip address // port number as '80' // Display message for better readability System.out.println(\"Connected to Server\"); } // Catch block to handle exceptions catch (Exception e) { // Simply return and exit the program return; } }}",
"e": 29444,
"s": 28526,
"text": null
},
{
"code": null,
"e": 29452,
"s": 29444,
"text": "Output:"
},
{
"code": null,
"e": 29472,
"s": 29452,
"text": "Connected to Server"
},
{
"code": null,
"e": 29490,
"s": 29474,
"text": "simranarora5sos"
},
{
"code": null,
"e": 29506,
"s": 29490,
"text": "Java-Networking"
},
{
"code": null,
"e": 29513,
"s": 29506,
"text": "Picked"
},
{
"code": null,
"e": 29518,
"s": 29513,
"text": "Java"
},
{
"code": null,
"e": 29523,
"s": 29518,
"text": "Java"
},
{
"code": null,
"e": 29621,
"s": 29523,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29636,
"s": 29621,
"text": "Stream In Java"
},
{
"code": null,
"e": 29657,
"s": 29636,
"text": "Constructors in Java"
},
{
"code": null,
"e": 29676,
"s": 29657,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 29706,
"s": 29676,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 29752,
"s": 29706,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 29769,
"s": 29752,
"text": "Generics in Java"
},
{
"code": null,
"e": 29790,
"s": 29769,
"text": "Introduction to Java"
},
{
"code": null,
"e": 29833,
"s": 29790,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 29869,
"s": 29833,
"text": "Internal Working of HashMap in Java"
}
] |
Print all prime factors and their powers - GeeksforGeeks
|
04 Mar, 2022
Given a number N, print all its unique prime factors and their powers in N. Examples:
Input: N = 100
Output: Factor Power
2 2
5 2
Input: N = 35
Output: Factor Power
5 1
7 1
A Simple Solution is to first find prime factors of N. Then for every prime factor, find the highest power of it that divides N and print it.An Efficient Solution is to use Sieve of Eratosthenes.
1) First compute an array s[N+1] using Sieve of Eratosthenes.
s[i] = Smallest prime factor of "i" that
divides "i".
For example let N = 10
s[2] = s[4] = s[6] = s[8] = s[10] = 2;
s[3] = s[9] = 3;
s[5] = 5;
s[7] = 7;
2) Using the above computed array s[],
we can find all powers in O(Log N) time.
curr = s[N]; // Current prime factor of N
cnt = 1; // Power of current prime factor
// Printing prime factors and their powers
while (N > 1)
{
N /= s[N];
// N is now N/s[N]. If new N also has its
// smallest prime factor as curr, increment
// power and continue
if (curr == s[N])
{
cnt++;
continue;
}
// Print prime factor and its power
print(curr, cnt);
// Update current prime factor as s[N] and
// initializing count as 1.
curr = s[N];
cnt = 1;
}
Below is the implementation of above steps.
C++
Java
Python3
C#
PHP
Javascript
// C++ Program to print prime factors and their// powers using Sieve Of Eratosthenes#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 generate prime factors and its powervoid generatePrimeFactors(int N){ // s[i] is going to store smallest prime factor // of i. int s[N+1]; // Filling values in s[] using sieve sieveOfEratosthenes(N, s); printf("Factor Power\n"); int curr = s[N]; // Current prime factor of N int cnt = 1; // Power of current prime factor // Printing prime factors and their powers while (N > 1) { N /= s[N]; // N is now N/s[N]. If new N als has smallest // prime factor as curr, increment power if (curr == s[N]) { cnt++; continue; } printf("%d\t%d\n", curr, cnt); // Update current prime factor as s[N] and // initializing count as 1. curr = s[N]; cnt = 1; }} //Driver Programint main(){ int N = 360; generatePrimeFactors(N); return 0;}
// Java Program to print prime// factors and their powers using// Sieve Of Eratosthenesclass 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. boolean[] prime = new boolean[N + 1]; // 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 generate prime// factors and its powerstatic void generatePrimeFactors(int N){ // s[i] is going to store // smallest prime factor of i. int[] s = new int[N + 1]; // Filling values in s[] using sieve sieveOfEratosthenes(N, s); System.out.println("Factor Power"); int curr = s[N]; // Current prime factor of N int cnt = 1; // Power of current prime factor // Printing prime factors // and their powers while (N > 1) { N /= s[N]; // N is now N/s[N]. If new N // also has smallest prime // factor as curr, increment power if (curr == s[N]) { cnt++; continue; } System.out.println(curr + "\t" + cnt); // Update current prime factor // as s[N] and initializing // count as 1. curr = s[N]; cnt = 1; }} // Driver Codepublic static void main(String[] args){ int N = 360; generatePrimeFactors(N);}} // This code is contributed by mits
# Python3 program to print prime# factors and their powers# using Sieve Of Eratosthenes # 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 array # "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, int(N / i) + 1, 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 generate prime# factors and its powerdef generatePrimeFactors(N): # s[i] is going to store # smallest prime factor # of i. s = [0] * (N+1) # Filling values in s[] # using sieve sieveOfEratosthenes(N, s) print("Factor Power") # Current prime factor of N curr = s[N] # Power of current prime factor cnt = 1 # Printing prime factors and #their powers while (N > 1): N //= s[N] # N is now N/s[N]. If new N # also has smallest prime # factor as curr, increment # power if (curr == s[N]): cnt += 1 continue print(str(curr) + "\t" + str(cnt)) # Update current prime factor # as s[N] and initializing # count as 1. curr = s[N] cnt = 1 #Driver ProgramN = 360generatePrimeFactors(N) # This code is contributed by Ansu Kumari
// C# Program to print prime// factors and their powers using// Sieve Of Eratosthenesclass 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]; // 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 generate prime// factors and its powerstatic void generatePrimeFactors(int N){ // s[i] is going to store // smallest prime factor of i. int[] s = new int[N + 1]; // Filling values in s[] using sieve sieveOfEratosthenes(N, s); System.Console.WriteLine("Factor Power"); int curr = s[N]; // Current prime factor of N int cnt = 1; // Power of current prime factor // Printing prime factors // and their powers while (N > 1) { N /= s[N]; // N is now N/s[N]. If new N // also has smallest prime // factor as curr, increment power if (curr == s[N]) { cnt++; continue; } System.Console.WriteLine(curr + "\t" + cnt); // Update current prime factor // as s[N] and initializing // count as 1. curr = s[N]; cnt = 1; }} // Driver Codestatic void Main(){ int N = 360; generatePrimeFactors(N);}} // This code is contributed by mits
<?php// PHP Program to print prime factors and// their powers using Sieve Of Eratosthenes // 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 generate prime factors// and its powerfunction generatePrimeFactors($N){ // s[i] is going to store smallest // prime factor of i. $s = array_fill(0, $N + 1, 0); // Filling values in s[] using sieve sieveOfEratosthenes($N, $s); print("Factor Power\n"); $curr = $s[$N]; // Current prime factor of N $cnt = 1; // Power of current prime factor // Printing prime factors and their powers while ($N > 1) { if($s[$N]) $N = (int)($N / $s[$N]); // N is now N/s[N]. If new N als has smallest // prime factor as curr, increment power if ($curr == $s[$N]) { $cnt++; continue; } print($curr . "\t" . $cnt . "\n"); // Update current prime factor as s[N] // and initializing count as 1. $curr = $s[$N]; $cnt = 1; }} // Driver Code$N = 360;generatePrimeFactors($N); // This code is contributed by mits?>
<script> // javascript Program to print prime// factors and their powers using// Sieve Of Eratosthenes // 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.from({length: N+1}, (_, i) => 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 generate prime// factors and its powerfunction generatePrimeFactors(N){ // s[i] is going to store // smallest prime factor of i. var s = Array.from({length: N+1}, (_, i) => 0); // Filling values in s using sieve sieveOfEratosthenes(N, s); document.write("Factor Power"); var curr = s[N]; // Current prime factor of N var cnt = 1; // Power of current prime factor // Printing prime factors // and their powers while (N > 1) { N /= s[N]; // N is now N/s[N]. If new N // also has smallest prime // factor as curr, increment power if (curr == s[N]) { cnt++; continue; } document.write("<br>"+curr + "\t" + cnt); // Update current prime factor // as s[N] and initializing // count as 1. curr = s[N]; cnt = 1; }} // Driver Codevar N = 360;generatePrimeFactors(N); // This code contributed by Princi Singh</script>
Output:
Factor Power
2 3
3 2
5 1
The above algorithm finds all powers in O(Log N) time after we have filled s[]. This can be very useful in competitive environment where we have an upper limit and we need to compute prime factors and their powers for many test cases. In this scenario, the array needs to be s[] filled only once.This article is contributed by Rahul Agrawal. 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.
Mithun Kumar
nidhi_biet
princi singh
ankita_saini
simmytarika5
Prime Number
prime-factor
sieve
Mathematical
Technical Scripter
Mathematical
Prime Number
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
Print all possible combinations of r elements in a given array of size n
Operators in C / C++
Program for factorial of a number
The Knight's tour problem | Backtracking-1
Find minimum number of coins that make a given value
Program for Decimal to Binary Conversion
Program to find sum of elements in a given array
|
[
{
"code": null,
"e": 26343,
"s": 26315,
"text": "\n04 Mar, 2022"
},
{
"code": null,
"e": 26431,
"s": 26343,
"text": "Given a number N, print all its unique prime factors and their powers in N. Examples: "
},
{
"code": null,
"e": 26580,
"s": 26431,
"text": "Input: N = 100\nOutput: Factor Power\n 2 2\n 5 2\n\nInput: N = 35\nOutput: Factor Power\n 5 1\n 7 1"
},
{
"code": null,
"e": 26778,
"s": 26580,
"text": "A Simple Solution is to first find prime factors of N. Then for every prime factor, find the highest power of it that divides N and print it.An Efficient Solution is to use Sieve of Eratosthenes. "
},
{
"code": null,
"e": 27709,
"s": 26778,
"text": "1) First compute an array s[N+1] using Sieve of Eratosthenes.\n\ns[i] = Smallest prime factor of \"i\" that\n divides \"i\".\n\nFor example let N = 10\n s[2] = s[4] = s[6] = s[8] = s[10] = 2;\n s[3] = s[9] = 3;\n s[5] = 5;\n s[7] = 7;\n\n\n2) Using the above computed array s[],\n we can find all powers in O(Log N) time.\n\n curr = s[N]; // Current prime factor of N\n cnt = 1; // Power of current prime factor\n\n // Printing prime factors and their powers\n while (N > 1)\n {\n N /= s[N];\n\n // N is now N/s[N]. If new N also has its \n // smallest prime factor as curr, increment \n // power and continue\n if (curr == s[N])\n {\n cnt++;\n continue;\n }\n\n // Print prime factor and its power\n print(curr, cnt);\n\n // Update current prime factor as s[N] and\n // initializing count as 1.\n curr = s[N];\n cnt = 1;\n }"
},
{
"code": null,
"e": 27754,
"s": 27709,
"text": "Below is the implementation of above steps. "
},
{
"code": null,
"e": 27758,
"s": 27754,
"text": "C++"
},
{
"code": null,
"e": 27763,
"s": 27758,
"text": "Java"
},
{
"code": null,
"e": 27771,
"s": 27763,
"text": "Python3"
},
{
"code": null,
"e": 27774,
"s": 27771,
"text": "C#"
},
{
"code": null,
"e": 27778,
"s": 27774,
"text": "PHP"
},
{
"code": null,
"e": 27789,
"s": 27778,
"text": "Javascript"
},
{
"code": "// C++ Program to print prime factors and their// powers using Sieve Of Eratosthenes#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 generate prime factors and its powervoid generatePrimeFactors(int N){ // s[i] is going to store smallest prime factor // of i. int s[N+1]; // Filling values in s[] using sieve sieveOfEratosthenes(N, s); printf(\"Factor Power\\n\"); int curr = s[N]; // Current prime factor of N int cnt = 1; // Power of current prime factor // Printing prime factors and their powers while (N > 1) { N /= s[N]; // N is now N/s[N]. If new N als has smallest // prime factor as curr, increment power if (curr == s[N]) { cnt++; continue; } printf(\"%d\\t%d\\n\", curr, cnt); // Update current prime factor as s[N] and // initializing count as 1. curr = s[N]; cnt = 1; }} //Driver Programint main(){ int N = 360; generatePrimeFactors(N); return 0;}",
"e": 29846,
"s": 27789,
"text": null
},
{
"code": "// Java Program to print prime// factors and their powers using// Sieve Of Eratosthenesclass 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. boolean[] prime = new boolean[N + 1]; // 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 generate prime// factors and its powerstatic void generatePrimeFactors(int N){ // s[i] is going to store // smallest prime factor of i. int[] s = new int[N + 1]; // Filling values in s[] using sieve sieveOfEratosthenes(N, s); System.out.println(\"Factor Power\"); int curr = s[N]; // Current prime factor of N int cnt = 1; // Power of current prime factor // Printing prime factors // and their powers while (N > 1) { N /= s[N]; // N is now N/s[N]. If new N // also has smallest prime // factor as curr, increment power if (curr == s[N]) { cnt++; continue; } System.out.println(curr + \"\\t\" + cnt); // Update current prime factor // as s[N] and initializing // count as 1. curr = s[N]; cnt = 1; }} // Driver Codepublic static void main(String[] args){ int N = 360; generatePrimeFactors(N);}} // This code is contributed by mits",
"e": 32104,
"s": 29846,
"text": null
},
{
"code": "# Python3 program to print prime# factors and their powers# using Sieve Of Eratosthenes # 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 array # \"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, int(N / i) + 1, 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 generate prime# factors and its powerdef generatePrimeFactors(N): # s[i] is going to store # smallest prime factor # of i. s = [0] * (N+1) # Filling values in s[] # using sieve sieveOfEratosthenes(N, s) print(\"Factor Power\") # Current prime factor of N curr = s[N] # Power of current prime factor cnt = 1 # Printing prime factors and #their powers while (N > 1): N //= s[N] # N is now N/s[N]. If new N # also has smallest prime # factor as curr, increment # power if (curr == s[N]): cnt += 1 continue print(str(curr) + \"\\t\" + str(cnt)) # Update current prime factor # as s[N] and initializing # count as 1. curr = s[N] cnt = 1 #Driver ProgramN = 360generatePrimeFactors(N) # This code is contributed by Ansu Kumari",
"e": 34092,
"s": 32104,
"text": null
},
{
"code": "// C# Program to print prime// factors and their powers using// Sieve Of Eratosthenesclass 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]; // 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 generate prime// factors and its powerstatic void generatePrimeFactors(int N){ // s[i] is going to store // smallest prime factor of i. int[] s = new int[N + 1]; // Filling values in s[] using sieve sieveOfEratosthenes(N, s); System.Console.WriteLine(\"Factor Power\"); int curr = s[N]; // Current prime factor of N int cnt = 1; // Power of current prime factor // Printing prime factors // and their powers while (N > 1) { N /= s[N]; // N is now N/s[N]. If new N // also has smallest prime // factor as curr, increment power if (curr == s[N]) { cnt++; continue; } System.Console.WriteLine(curr + \"\\t\" + cnt); // Update current prime factor // as s[N] and initializing // count as 1. curr = s[N]; cnt = 1; }} // Driver Codestatic void Main(){ int N = 360; generatePrimeFactors(N);}} // This code is contributed by mits",
"e": 36302,
"s": 34092,
"text": null
},
{
"code": "<?php// PHP Program to print prime factors and// their powers using Sieve Of Eratosthenes // 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 generate prime factors// and its powerfunction generatePrimeFactors($N){ // s[i] is going to store smallest // prime factor of i. $s = array_fill(0, $N + 1, 0); // Filling values in s[] using sieve sieveOfEratosthenes($N, $s); print(\"Factor Power\\n\"); $curr = $s[$N]; // Current prime factor of N $cnt = 1; // Power of current prime factor // Printing prime factors and their powers while ($N > 1) { if($s[$N]) $N = (int)($N / $s[$N]); // N is now N/s[N]. If new N als has smallest // prime factor as curr, increment power if ($curr == $s[$N]) { $cnt++; continue; } print($curr . \"\\t\" . $cnt . \"\\n\"); // Update current prime factor as s[N] // and initializing count as 1. $curr = $s[$N]; $cnt = 1; }} // Driver Code$N = 360;generatePrimeFactors($N); // This code is contributed by mits?>",
"e": 38458,
"s": 36302,
"text": null
},
{
"code": "<script> // javascript Program to print prime// factors and their powers using// Sieve Of Eratosthenes // 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.from({length: N+1}, (_, i) => 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 generate prime// factors and its powerfunction generatePrimeFactors(N){ // s[i] is going to store // smallest prime factor of i. var s = Array.from({length: N+1}, (_, i) => 0); // Filling values in s using sieve sieveOfEratosthenes(N, s); document.write(\"Factor Power\"); var curr = s[N]; // Current prime factor of N var cnt = 1; // Power of current prime factor // Printing prime factors // and their powers while (N > 1) { N /= s[N]; // N is now N/s[N]. If new N // also has smallest prime // factor as curr, increment power if (curr == s[N]) { cnt++; continue; } document.write(\"<br>\"+curr + \"\\t\" + cnt); // Update current prime factor // as s[N] and initializing // count as 1. curr = s[N]; cnt = 1; }} // Driver Codevar N = 360;generatePrimeFactors(N); // This code contributed by Princi Singh</script>",
"e": 40659,
"s": 38458,
"text": null
},
{
"code": null,
"e": 40669,
"s": 40659,
"text": "Output: "
},
{
"code": null,
"e": 40716,
"s": 40669,
"text": "Factor Power\n 2 3\n 3 2\n 5 1"
},
{
"code": null,
"e": 41434,
"s": 40716,
"text": "The above algorithm finds all powers in O(Log N) time after we have filled s[]. This can be very useful in competitive environment where we have an upper limit and we need to compute prime factors and their powers for many test cases. In this scenario, the array needs to be s[] filled only once.This article is contributed by Rahul Agrawal. 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": 41447,
"s": 41434,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 41458,
"s": 41447,
"text": "nidhi_biet"
},
{
"code": null,
"e": 41471,
"s": 41458,
"text": "princi singh"
},
{
"code": null,
"e": 41484,
"s": 41471,
"text": "ankita_saini"
},
{
"code": null,
"e": 41497,
"s": 41484,
"text": "simmytarika5"
},
{
"code": null,
"e": 41510,
"s": 41497,
"text": "Prime Number"
},
{
"code": null,
"e": 41523,
"s": 41510,
"text": "prime-factor"
},
{
"code": null,
"e": 41529,
"s": 41523,
"text": "sieve"
},
{
"code": null,
"e": 41542,
"s": 41529,
"text": "Mathematical"
},
{
"code": null,
"e": 41561,
"s": 41542,
"text": "Technical Scripter"
},
{
"code": null,
"e": 41574,
"s": 41561,
"text": "Mathematical"
},
{
"code": null,
"e": 41587,
"s": 41574,
"text": "Prime Number"
},
{
"code": null,
"e": 41593,
"s": 41587,
"text": "sieve"
},
{
"code": null,
"e": 41691,
"s": 41593,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 41715,
"s": 41691,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 41758,
"s": 41715,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 41772,
"s": 41758,
"text": "Prime Numbers"
},
{
"code": null,
"e": 41845,
"s": 41772,
"text": "Print all possible combinations of r elements in a given array of size n"
},
{
"code": null,
"e": 41866,
"s": 41845,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 41900,
"s": 41866,
"text": "Program for factorial of a number"
},
{
"code": null,
"e": 41943,
"s": 41900,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 41996,
"s": 41943,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 42037,
"s": 41996,
"text": "Program for Decimal to Binary Conversion"
}
] |
Seating arrangement of N boys sitting around a round table such that two particular boys sit together - GeeksforGeeks
|
31 Mar, 2021
There are N boys which are to be seated around a round table. The task is to find the number of ways in which N boys can sit around a round table such that two particular boys sit together.Examples:
Input: N = 5 Output: 48 2 boy can be arranged in 2! ways and other boys can be arranged in (5 β 1)! (1 is subtracted because the previously selected two boys will be considered as a single boy now) So, total ways are 2! * 4! = 48.Input: N = 9 Output: 80640
Approach:
First, 2 boys can be arranged in 2! ways.
No. of ways to arrange remaining boys and the previous two boy pair is (n β 1)!.
So, Total ways = 2! * (n β 1)!.
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; // Function to return the total count of waysint Total_Ways(int n){ // Find (n - 1) factorial int fac = 1; for (int i = 2; i <= n - 1; i++) { fac = fac * i; } // Return (n - 1)! * 2! return (fac * 2);} // Driver codeint main(){ int n = 5; cout << Total_Ways(n); return 0;}
// Java implementation of the approachimport java.io.*; class GFG{ // Function to return the total count of waysstatic int Total_Ways(int n){ // Find (n - 1) factorial int fac = 1; for (int i = 2; i <= n - 1; i++) { fac = fac * i; } // Return (n - 1)! * 2! return (fac * 2);} // Driver codepublic static void main (String[] args){ int n = 5; System.out.println (Total_Ways(n));}} // This code is contributed by Tushil.
# Python3 implementation of the approach # Function to return the total count of waysdef Total_Ways(n) : # Find (n - 1) factorial fac = 1; for i in range(2, n) : fac = fac * i; # Return (n - 1)! * 2! return (fac * 2); # Driver codeif __name__ == "__main__" : n = 5; print(Total_Ways(n)); # This code is contributed by AnkitRai01
// C# implementation of the approachusing System; class GFG{ // Function to return the total count of waysstatic int Total_Ways(int n){ // Find (n - 1) factorial int fac = 1; for (int i = 2; i <= n - 1; i++) { fac = fac * i; } // Return (n - 1)! * 2! return (fac * 2);} // Driver codestatic public void Main (){ int n = 5; Console.Write(Total_Ways(n));}} // This code is contributed by ajit..
<script>// javascript implementation of the approach // Function to return the total count of ways function Total_Ways(n) { // Find (n - 1) factorial var fac = 1; for (i = 2; i <= n - 1; i++) { fac = fac * i; } // Return (n - 1)! * 2! return (fac * 2); } // Driver code var n = 5; document.write(Total_Ways(n)); // This code is contributed by aashish1995</script>
48
ankthon
jit_t
aashish1995
Permutation and Combination
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Prime Numbers
Program to find GCD or HCF of two numbers
Sieve of Eratosthenes
Print all possible combinations of r elements in a given array of size n
Operators in C / C++
The Knight's tour problem | Backtracking-1
Program for factorial of a number
Program for Decimal to Binary Conversion
|
[
{
"code": null,
"e": 26383,
"s": 26355,
"text": "\n31 Mar, 2021"
},
{
"code": null,
"e": 26584,
"s": 26383,
"text": "There are N boys which are to be seated around a round table. The task is to find the number of ways in which N boys can sit around a round table such that two particular boys sit together.Examples: "
},
{
"code": null,
"e": 26843,
"s": 26584,
"text": "Input: N = 5 Output: 48 2 boy can be arranged in 2! ways and other boys can be arranged in (5 β 1)! (1 is subtracted because the previously selected two boys will be considered as a single boy now) So, total ways are 2! * 4! = 48.Input: N = 9 Output: 80640 "
},
{
"code": null,
"e": 26857,
"s": 26845,
"text": "Approach: "
},
{
"code": null,
"e": 26899,
"s": 26857,
"text": "First, 2 boys can be arranged in 2! ways."
},
{
"code": null,
"e": 26980,
"s": 26899,
"text": "No. of ways to arrange remaining boys and the previous two boy pair is (n β 1)!."
},
{
"code": null,
"e": 27012,
"s": 26980,
"text": "So, Total ways = 2! * (n β 1)!."
},
{
"code": null,
"e": 27065,
"s": 27012,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27069,
"s": 27065,
"text": "C++"
},
{
"code": null,
"e": 27074,
"s": 27069,
"text": "Java"
},
{
"code": null,
"e": 27082,
"s": 27074,
"text": "Python3"
},
{
"code": null,
"e": 27085,
"s": 27082,
"text": "C#"
},
{
"code": null,
"e": 27096,
"s": 27085,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the total count of waysint Total_Ways(int n){ // Find (n - 1) factorial int fac = 1; for (int i = 2; i <= n - 1; i++) { fac = fac * i; } // Return (n - 1)! * 2! return (fac * 2);} // Driver codeint main(){ int n = 5; cout << Total_Ways(n); return 0;}",
"e": 27489,
"s": 27096,
"text": null
},
{
"code": "// Java implementation of the approachimport java.io.*; class GFG{ // Function to return the total count of waysstatic int Total_Ways(int n){ // Find (n - 1) factorial int fac = 1; for (int i = 2; i <= n - 1; i++) { fac = fac * i; } // Return (n - 1)! * 2! return (fac * 2);} // Driver codepublic static void main (String[] args){ int n = 5; System.out.println (Total_Ways(n));}} // This code is contributed by Tushil.",
"e": 27950,
"s": 27489,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function to return the total count of waysdef Total_Ways(n) : # Find (n - 1) factorial fac = 1; for i in range(2, n) : fac = fac * i; # Return (n - 1)! * 2! return (fac * 2); # Driver codeif __name__ == \"__main__\" : n = 5; print(Total_Ways(n)); # This code is contributed by AnkitRai01",
"e": 28320,
"s": 27950,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Function to return the total count of waysstatic int Total_Ways(int n){ // Find (n - 1) factorial int fac = 1; for (int i = 2; i <= n - 1; i++) { fac = fac * i; } // Return (n - 1)! * 2! return (fac * 2);} // Driver codestatic public void Main (){ int n = 5; Console.Write(Total_Ways(n));}} // This code is contributed by ajit..",
"e": 28750,
"s": 28320,
"text": null
},
{
"code": "<script>// javascript implementation of the approach // Function to return the total count of ways function Total_Ways(n) { // Find (n - 1) factorial var fac = 1; for (i = 2; i <= n - 1; i++) { fac = fac * i; } // Return (n - 1)! * 2! return (fac * 2); } // Driver code var n = 5; document.write(Total_Ways(n)); // This code is contributed by aashish1995</script>",
"e": 29207,
"s": 28750,
"text": null
},
{
"code": null,
"e": 29210,
"s": 29207,
"text": "48"
},
{
"code": null,
"e": 29220,
"s": 29212,
"text": "ankthon"
},
{
"code": null,
"e": 29226,
"s": 29220,
"text": "jit_t"
},
{
"code": null,
"e": 29238,
"s": 29226,
"text": "aashish1995"
},
{
"code": null,
"e": 29266,
"s": 29238,
"text": "Permutation and Combination"
},
{
"code": null,
"e": 29279,
"s": 29266,
"text": "Mathematical"
},
{
"code": null,
"e": 29292,
"s": 29279,
"text": "Mathematical"
},
{
"code": null,
"e": 29390,
"s": 29292,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29414,
"s": 29390,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 29457,
"s": 29414,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 29471,
"s": 29457,
"text": "Prime Numbers"
},
{
"code": null,
"e": 29513,
"s": 29471,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 29535,
"s": 29513,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 29608,
"s": 29535,
"text": "Print all possible combinations of r elements in a given array of size n"
},
{
"code": null,
"e": 29629,
"s": 29608,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 29672,
"s": 29629,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 29706,
"s": 29672,
"text": "Program for factorial of a number"
}
] |
Difference between innerText and innerHTML - GeeksforGeeks
|
19 Jun, 2019
innerText and innerHTML are both properties of JavaScript. However, there are differences in which the text is handled. Let us check the syntax of the two and then take an example to look at the differences.
Syntax:Let us assume that we have a JavaScript variable called x.
var x = document.getElementById('test');
Hereβs how we can use innerText and innerHTML on this variable.
innerTextx.innerText
x.innerText
innerHTMLx.innerHTML
x.innerHTML
Example:
<!DOCTYPE html><html> <head> <title> Difference between InnerHTML and InnerText </title></head> <body style="text-align:center;"> <h1 style="color:green">GeeksforGeeks</h1> <div id="test"> The following element contains some <codes>code</codes> and <italic>some text</italic>. </div> <p></p> <button onClick="innerTextFn()"> innerHTML </button> <button onClick="innerHTMLFn()"> innerText </button> <p id="op"></p> <script> function innerTextFn() { var x = document.getElementById('test'); alert(x.innerText); } function innerHTMLFn() { var x = document.getElementById('test'); alert(x.innerHTML); } </script></body> </html>
OutputBefore click:
After click innerHTML:
After click innerText:
Differences:As we can see from the example above the innerText property sets or returns the text content as plain text of the specified node, and all its descendants whereas the innerHTML property gets and sets the plain text or HTML contents in the elements. Unlike innerText, inner HTML lets you work with HTML rich text and doesnβt automatically encode and decode text.
Picked
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
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
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 ?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 26053,
"s": 26025,
"text": "\n19 Jun, 2019"
},
{
"code": null,
"e": 26261,
"s": 26053,
"text": "innerText and innerHTML are both properties of JavaScript. However, there are differences in which the text is handled. Let us check the syntax of the two and then take an example to look at the differences."
},
{
"code": null,
"e": 26327,
"s": 26261,
"text": "Syntax:Let us assume that we have a JavaScript variable called x."
},
{
"code": null,
"e": 26368,
"s": 26327,
"text": "var x = document.getElementById('test');"
},
{
"code": null,
"e": 26432,
"s": 26368,
"text": "Hereβs how we can use innerText and innerHTML on this variable."
},
{
"code": null,
"e": 26453,
"s": 26432,
"text": "innerTextx.innerText"
},
{
"code": null,
"e": 26465,
"s": 26453,
"text": "x.innerText"
},
{
"code": null,
"e": 26486,
"s": 26465,
"text": "innerHTMLx.innerHTML"
},
{
"code": null,
"e": 26498,
"s": 26486,
"text": "x.innerHTML"
},
{
"code": null,
"e": 26507,
"s": 26498,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> Difference between InnerHTML and InnerText </title></head> <body style=\"text-align:center;\"> <h1 style=\"color:green\">GeeksforGeeks</h1> <div id=\"test\"> The following element contains some <codes>code</codes> and <italic>some text</italic>. </div> <p></p> <button onClick=\"innerTextFn()\"> innerHTML </button> <button onClick=\"innerHTMLFn()\"> innerText </button> <p id=\"op\"></p> <script> function innerTextFn() { var x = document.getElementById('test'); alert(x.innerText); } function innerHTMLFn() { var x = document.getElementById('test'); alert(x.innerHTML); } </script></body> </html>",
"e": 27301,
"s": 26507,
"text": null
},
{
"code": null,
"e": 27321,
"s": 27301,
"text": "OutputBefore click:"
},
{
"code": null,
"e": 27344,
"s": 27321,
"text": "After click innerHTML:"
},
{
"code": null,
"e": 27367,
"s": 27344,
"text": "After click innerText:"
},
{
"code": null,
"e": 27740,
"s": 27367,
"text": "Differences:As we can see from the example above the innerText property sets or returns the text content as plain text of the specified node, and all its descendants whereas the innerHTML property gets and sets the plain text or HTML contents in the elements. Unlike innerText, inner HTML lets you work with HTML rich text and doesnβt automatically encode and decode text."
},
{
"code": null,
"e": 27747,
"s": 27740,
"text": "Picked"
},
{
"code": null,
"e": 27758,
"s": 27747,
"text": "JavaScript"
},
{
"code": null,
"e": 27775,
"s": 27758,
"text": "Web Technologies"
},
{
"code": null,
"e": 27873,
"s": 27775,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27913,
"s": 27873,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 27958,
"s": 27913,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28019,
"s": 27958,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28091,
"s": 28019,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 28143,
"s": 28091,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 28183,
"s": 28143,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28216,
"s": 28183,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28261,
"s": 28216,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28304,
"s": 28261,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
How to Install Dart on MacOS? - GeeksforGeeks
|
06 Dec, 2021
The dart is an SDK (Software Development Kit) and SDK as you may observe from its name it is mainly a collection of software development tools that facilitate the creation of different applications, some of the tools include compilers debuggers libraries, and perhaps the software framework aiding towards the development process of creating.
As of November 2021, the following versions are supported:
macOS 10.15 (Catalina)
macOS 11 (Big Sur)
macOS 12 (Monterey)
Step 1: Install Homebrew, If you donβt know how to install it, check out this article.
Step 2: Now open the terminal and run the following commands
$ brew tap dart-lang/dart
Output:
Step 3: Now run this command on the terminal to install Dart
$ brew install dart
Output:
Now Dart is on your system.
Upgrade to the new version:
To upgrade when there is a new release of Dart is available:
$ brew upgrade dart
Switch to a specific version:
If you want to switch between locally installed Dart releases or want to go to the previous version then, use brew switch dart <version>. Example:
$ brew switch dart 2.12.4
Note: The brew switch command was removed after the 2.6 release of Homebrew. To continue using brew switch, downgrade Homebrew to a 2.6 version:
$ cd /usr/local/Homebrew && git checkout 2.6.2
you can check which versions of Dart youβve installed by running the following commands :
$ brew dart --version
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 Install FFmpeg on Windows?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Set Git Username and Password in GitBash?
How to create a nested RecyclerView in Android
How to Install Jupyter Notebook on MacOS?
Installation of Node.js on Linux
How to Install FFmpeg on Windows?
How to Install Pygame on Windows ?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Install Jupyter Notebook on MacOS?
|
[
{
"code": null,
"e": 26222,
"s": 26194,
"text": "\n06 Dec, 2021"
},
{
"code": null,
"e": 26565,
"s": 26222,
"text": "The dart is an SDK (Software Development Kit) and SDK as you may observe from its name it is mainly a collection of software development tools that facilitate the creation of different applications, some of the tools include compilers debuggers libraries, and perhaps the software framework aiding towards the development process of creating."
},
{
"code": null,
"e": 26624,
"s": 26565,
"text": "As of November 2021, the following versions are supported:"
},
{
"code": null,
"e": 26647,
"s": 26624,
"text": "macOS 10.15 (Catalina)"
},
{
"code": null,
"e": 26666,
"s": 26647,
"text": "macOS 11 (Big Sur)"
},
{
"code": null,
"e": 26686,
"s": 26666,
"text": "macOS 12 (Monterey)"
},
{
"code": null,
"e": 26774,
"s": 26686,
"text": "Step 1: Install Homebrew, If you donβt know how to install it, check out this article. "
},
{
"code": null,
"e": 26835,
"s": 26774,
"text": "Step 2: Now open the terminal and run the following commands"
},
{
"code": null,
"e": 26862,
"s": 26835,
"text": " $ brew tap dart-lang/dart"
},
{
"code": null,
"e": 26870,
"s": 26862,
"text": "Output:"
},
{
"code": null,
"e": 26931,
"s": 26870,
"text": "Step 3: Now run this command on the terminal to install Dart"
},
{
"code": null,
"e": 26951,
"s": 26931,
"text": "$ brew install dart"
},
{
"code": null,
"e": 26959,
"s": 26951,
"text": "Output:"
},
{
"code": null,
"e": 26987,
"s": 26959,
"text": "Now Dart is on your system."
},
{
"code": null,
"e": 27015,
"s": 26987,
"text": "Upgrade to the new version:"
},
{
"code": null,
"e": 27076,
"s": 27015,
"text": "To upgrade when there is a new release of Dart is available:"
},
{
"code": null,
"e": 27096,
"s": 27076,
"text": "$ brew upgrade dart"
},
{
"code": null,
"e": 27126,
"s": 27096,
"text": "Switch to a specific version:"
},
{
"code": null,
"e": 27273,
"s": 27126,
"text": "If you want to switch between locally installed Dart releases or want to go to the previous version then, use brew switch dart <version>. Example:"
},
{
"code": null,
"e": 27299,
"s": 27273,
"text": "$ brew switch dart 2.12.4"
},
{
"code": null,
"e": 27444,
"s": 27299,
"text": "Note: The brew switch command was removed after the 2.6 release of Homebrew. To continue using brew switch, downgrade Homebrew to a 2.6 version:"
},
{
"code": null,
"e": 27491,
"s": 27444,
"text": "$ cd /usr/local/Homebrew && git checkout 2.6.2"
},
{
"code": null,
"e": 27581,
"s": 27491,
"text": "you can check which versions of Dart youβve installed by running the following commands :"
},
{
"code": null,
"e": 27603,
"s": 27581,
"text": "$ brew dart --version"
},
{
"code": null,
"e": 27618,
"s": 27603,
"text": "how-to-install"
},
{
"code": null,
"e": 27625,
"s": 27618,
"text": "Picked"
},
{
"code": null,
"e": 27632,
"s": 27625,
"text": "How To"
},
{
"code": null,
"e": 27651,
"s": 27632,
"text": "Installation Guide"
},
{
"code": null,
"e": 27749,
"s": 27651,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27783,
"s": 27749,
"text": "How to Install FFmpeg on Windows?"
},
{
"code": null,
"e": 27841,
"s": 27783,
"text": "How to Add External JAR File to an IntelliJ IDEA Project?"
},
{
"code": null,
"e": 27890,
"s": 27841,
"text": "How to Set Git Username and Password in GitBash?"
},
{
"code": null,
"e": 27937,
"s": 27890,
"text": "How to create a nested RecyclerView in Android"
},
{
"code": null,
"e": 27979,
"s": 27937,
"text": "How to Install Jupyter Notebook on MacOS?"
},
{
"code": null,
"e": 28012,
"s": 27979,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28046,
"s": 28012,
"text": "How to Install FFmpeg on Windows?"
},
{
"code": null,
"e": 28081,
"s": 28046,
"text": "How to Install Pygame on Windows ?"
},
{
"code": null,
"e": 28139,
"s": 28081,
"text": "How to Add External JAR File to an IntelliJ IDEA Project?"
}
] |
Node.js Bot.onText() API for Telegram Bot - GeeksforGeeks
|
30 Sep, 2020
The Bot.onText() method is used in the Node.js Telegram Bot API. This Node.js module to interact with the official Telegram Bot API. This method is used to reply when the users interact with the Telegram BOT.
Syntax:
TelegramBot.onText(regexp, callback)
Parameters: This Method accepts two parameters as mentioned above and described below:
regexp: Itβs the regular expression, the message must contains /echo.
callback: It is the callback function which is passed as parameter and called when the function call is executed.
Return Type: The return type of the function is void.
Installing Module: Install the module using the following command:
npm i telegram-bot-api
Steps to get the keys:
First get the GET BOT_TOKEN from BOTFATHER in telegram. Just search for BOTFATHER in Telegram and select the verified one as shown below:Type /start and then click on /newbot as shown below:Now type the name of the bot and that must be unique.Now just copy the token From the BotFather. And for deleting the token simply search /delete token in BotFather.
First get the GET BOT_TOKEN from BOTFATHER in telegram. Just search for BOTFATHER in Telegram and select the verified one as shown below:
Type /start and then click on /newbot as shown below:
Now type the name of the bot and that must be unique.
Now just copy the token From the BotFather. And for deleting the token simply search /delete token in BotFather.
Project structure:
Filename: bot.js
var token = 'Enter the token'; const TelegramBot = require('node-telegram-bot-api'); const bot = new TelegramBot(token, {polling: true}); // Matches "/echo [whatever]"bot.onText(/\/echo(.+)/, (msg, match) => { // The 'msg' is the received Message from Telegram // and 'match' is the result of executing the regexp // above on the text content of the message const chatId = msg.chat.id; // The captured "whatever" const resp = match[1]; // send back the matched "whatever" to the chat bot.sendMessage(chatId,resp); });
Run bot.js file using the following command:
node bot.js
Output:
Node.js-Methods
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js fs.writeFile() Method
Node.js fs.readFile() Method
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
How to use an ES6 import in Node.js?
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 26289,
"s": 26261,
"text": "\n30 Sep, 2020"
},
{
"code": null,
"e": 26498,
"s": 26289,
"text": "The Bot.onText() method is used in the Node.js Telegram Bot API. This Node.js module to interact with the official Telegram Bot API. This method is used to reply when the users interact with the Telegram BOT."
},
{
"code": null,
"e": 26506,
"s": 26498,
"text": "Syntax:"
},
{
"code": null,
"e": 26543,
"s": 26506,
"text": "TelegramBot.onText(regexp, callback)"
},
{
"code": null,
"e": 26630,
"s": 26543,
"text": "Parameters: This Method accepts two parameters as mentioned above and described below:"
},
{
"code": null,
"e": 26700,
"s": 26630,
"text": "regexp: Itβs the regular expression, the message must contains /echo."
},
{
"code": null,
"e": 26814,
"s": 26700,
"text": "callback: It is the callback function which is passed as parameter and called when the function call is executed."
},
{
"code": null,
"e": 26868,
"s": 26814,
"text": "Return Type: The return type of the function is void."
},
{
"code": null,
"e": 26935,
"s": 26868,
"text": "Installing Module: Install the module using the following command:"
},
{
"code": null,
"e": 26958,
"s": 26935,
"text": "npm i telegram-bot-api"
},
{
"code": null,
"e": 26981,
"s": 26958,
"text": "Steps to get the keys:"
},
{
"code": null,
"e": 27337,
"s": 26981,
"text": "First get the GET BOT_TOKEN from BOTFATHER in telegram. Just search for BOTFATHER in Telegram and select the verified one as shown below:Type /start and then click on /newbot as shown below:Now type the name of the bot and that must be unique.Now just copy the token From the BotFather. And for deleting the token simply search /delete token in BotFather."
},
{
"code": null,
"e": 27475,
"s": 27337,
"text": "First get the GET BOT_TOKEN from BOTFATHER in telegram. Just search for BOTFATHER in Telegram and select the verified one as shown below:"
},
{
"code": null,
"e": 27529,
"s": 27475,
"text": "Type /start and then click on /newbot as shown below:"
},
{
"code": null,
"e": 27583,
"s": 27529,
"text": "Now type the name of the bot and that must be unique."
},
{
"code": null,
"e": 27696,
"s": 27583,
"text": "Now just copy the token From the BotFather. And for deleting the token simply search /delete token in BotFather."
},
{
"code": null,
"e": 27715,
"s": 27696,
"text": "Project structure:"
},
{
"code": null,
"e": 27732,
"s": 27715,
"text": "Filename: bot.js"
},
{
"code": "var token = 'Enter the token'; const TelegramBot = require('node-telegram-bot-api'); const bot = new TelegramBot(token, {polling: true}); // Matches \"/echo [whatever]\"bot.onText(/\\/echo(.+)/, (msg, match) => { // The 'msg' is the received Message from Telegram // and 'match' is the result of executing the regexp // above on the text content of the message const chatId = msg.chat.id; // The captured \"whatever\" const resp = match[1]; // send back the matched \"whatever\" to the chat bot.sendMessage(chatId,resp); });",
"e": 28264,
"s": 27732,
"text": null
},
{
"code": null,
"e": 28309,
"s": 28264,
"text": "Run bot.js file using the following command:"
},
{
"code": null,
"e": 28321,
"s": 28309,
"text": "node bot.js"
},
{
"code": null,
"e": 28329,
"s": 28321,
"text": "Output:"
},
{
"code": null,
"e": 28345,
"s": 28329,
"text": "Node.js-Methods"
},
{
"code": null,
"e": 28353,
"s": 28345,
"text": "Node.js"
},
{
"code": null,
"e": 28370,
"s": 28353,
"text": "Web Technologies"
},
{
"code": null,
"e": 28468,
"s": 28370,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28498,
"s": 28468,
"text": "Node.js fs.writeFile() Method"
},
{
"code": null,
"e": 28527,
"s": 28498,
"text": "Node.js fs.readFile() Method"
},
{
"code": null,
"e": 28584,
"s": 28527,
"text": "How to install the previous version of node.js and npm ?"
},
{
"code": null,
"e": 28638,
"s": 28584,
"text": "Difference between promise and async await in Node.js"
},
{
"code": null,
"e": 28675,
"s": 28638,
"text": "How to use an ES6 import in Node.js?"
},
{
"code": null,
"e": 28715,
"s": 28675,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28760,
"s": 28715,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28803,
"s": 28760,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28865,
"s": 28803,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
How to Get Size, Minimum, and Maximum Value of Data Types in Java? - GeeksforGeeks
|
28 Mar, 2021
The size of a data type is given by (name of datatype).SIZE. The maximum value that it can store is given by (Name of data type).MAX_VALUE. The minimum value that it can store is given by (Name of data type).MIN_VALUE.
Always write first word of data type in capital.
Example:
1. If you want to print the size of float data type, use Float.SIZE
2. If you want to print the size and value of the Byte use the following code
Java
// Print size, minimum value and maximum// value of Byte data types in javaimport java.io.*; class ValuesOfByte { public static void main(String[] args) { System.out.println("Byte\t" + Byte.SIZE + "\t" + Byte.MIN_VALUE + "\t" + Byte.MAX_VALUE); }}
Byte 8 -128 127
3. To print the size, the maximum and minimum value of all primitive data type use the following code
Java
// Print size, minimum value and // maximum value of data types in javapublic class RangeOfDataTypes { public static void main(String args[]) { System.out.println( "S.No.\t Data Type\t Size\t Min. Value\t\t Max. Value\t"); System.out.println("1\t Byte\t\t" + Byte.SIZE + "\t" + Byte.MIN_VALUE + "\t\t\t" + Byte.MAX_VALUE); System.out.println("2\t Short\t\t" + Short.SIZE + "\t" + Short.MIN_VALUE + "\t\t\t" + Short.MAX_VALUE); System.out.println("3\t Integer\t" + Integer.SIZE + "\t" + Integer.MIN_VALUE + "\t\t" + Integer.MAX_VALUE); System.out.println("4\t Float\t\t" + Float.SIZE + "\t" + Float.MIN_VALUE + "\t\t\t" + Float.MAX_VALUE); System.out.println("5\t Long\t\t" + Long.SIZE + "\t" + Long.MIN_VALUE + "\t" + Long.MAX_VALUE); System.out.println("6\t Double\t" + Double.SIZE + "\t" + Double.MIN_VALUE + "\t\t" + Short.MAX_VALUE); System.out.println("7\t Character\t" + Character.SIZE); }}
Output:
S.No. Data Type Size Min. Value Max. Value
1 Byte 8 -128 127
2 Short 16 -32768 32767
3 Integer 32 -2147483648 2147483647
4 Float 32 1.4E-45 3.4028235E38
5 Long 64 -9223372036854775808 9223372036854775807
6 Double 64 4.9E-324 1.7976931348623157E308
7 Character 16
Java-Data Types
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
Program to print ASCII Value of a character
|
[
{
"code": null,
"e": 25251,
"s": 25223,
"text": "\n28 Mar, 2021"
},
{
"code": null,
"e": 25470,
"s": 25251,
"text": "The size of a data type is given by (name of datatype).SIZE. The maximum value that it can store is given by (Name of data type).MAX_VALUE. The minimum value that it can store is given by (Name of data type).MIN_VALUE."
},
{
"code": null,
"e": 25519,
"s": 25470,
"text": "Always write first word of data type in capital."
},
{
"code": null,
"e": 25528,
"s": 25519,
"text": "Example:"
},
{
"code": null,
"e": 25596,
"s": 25528,
"text": "1. If you want to print the size of float data type, use Float.SIZE"
},
{
"code": null,
"e": 25674,
"s": 25596,
"text": "2. If you want to print the size and value of the Byte use the following code"
},
{
"code": null,
"e": 25679,
"s": 25674,
"text": "Java"
},
{
"code": "// Print size, minimum value and maximum// value of Byte data types in javaimport java.io.*; class ValuesOfByte { public static void main(String[] args) { System.out.println(\"Byte\\t\" + Byte.SIZE + \"\\t\" + Byte.MIN_VALUE + \"\\t\" + Byte.MAX_VALUE); }}",
"e": 25996,
"s": 25679,
"text": null
},
{
"code": null,
"e": 26021,
"s": 25996,
"text": "Byte 8 -128 127"
},
{
"code": null,
"e": 26123,
"s": 26021,
"text": "3. To print the size, the maximum and minimum value of all primitive data type use the following code"
},
{
"code": null,
"e": 26128,
"s": 26123,
"text": "Java"
},
{
"code": "// Print size, minimum value and // maximum value of data types in javapublic class RangeOfDataTypes { public static void main(String args[]) { System.out.println( \"S.No.\\t Data Type\\t Size\\t Min. Value\\t\\t Max. Value\\t\"); System.out.println(\"1\\t Byte\\t\\t\" + Byte.SIZE + \"\\t\" + Byte.MIN_VALUE + \"\\t\\t\\t\" + Byte.MAX_VALUE); System.out.println(\"2\\t Short\\t\\t\" + Short.SIZE + \"\\t\" + Short.MIN_VALUE + \"\\t\\t\\t\" + Short.MAX_VALUE); System.out.println(\"3\\t Integer\\t\" + Integer.SIZE + \"\\t\" + Integer.MIN_VALUE + \"\\t\\t\" + Integer.MAX_VALUE); System.out.println(\"4\\t Float\\t\\t\" + Float.SIZE + \"\\t\" + Float.MIN_VALUE + \"\\t\\t\\t\" + Float.MAX_VALUE); System.out.println(\"5\\t Long\\t\\t\" + Long.SIZE + \"\\t\" + Long.MIN_VALUE + \"\\t\" + Long.MAX_VALUE); System.out.println(\"6\\t Double\\t\" + Double.SIZE + \"\\t\" + Double.MIN_VALUE + \"\\t\\t\" + Short.MAX_VALUE); System.out.println(\"7\\t Character\\t\" + Character.SIZE); }}",
"e": 27450,
"s": 26128,
"text": null
},
{
"code": null,
"e": 27458,
"s": 27450,
"text": "Output:"
},
{
"code": null,
"e": 28050,
"s": 27458,
"text": "S.No. Data Type Size Min. Value Max. Value\n1 Byte 8 -128 127\n2 Short 16 -32768 32767\n3 Integer 32 -2147483648 2147483647\n4 Float 32 1.4E-45 3.4028235E38\n5 Long 64 -9223372036854775808 9223372036854775807\n6 Double 64 4.9E-324 1.7976931348623157E308\n7 Character 16\n"
},
{
"code": null,
"e": 28066,
"s": 28050,
"text": "Java-Data Types"
},
{
"code": null,
"e": 28071,
"s": 28066,
"text": "Java"
},
{
"code": null,
"e": 28085,
"s": 28071,
"text": "Java Programs"
},
{
"code": null,
"e": 28090,
"s": 28085,
"text": "Java"
},
{
"code": null,
"e": 28188,
"s": 28090,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28203,
"s": 28188,
"text": "Stream In Java"
},
{
"code": null,
"e": 28224,
"s": 28203,
"text": "Constructors in Java"
},
{
"code": null,
"e": 28243,
"s": 28224,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 28273,
"s": 28243,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 28319,
"s": 28273,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 28345,
"s": 28319,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 28379,
"s": 28345,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 28426,
"s": 28379,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 28458,
"s": 28426,
"text": "How to Iterate HashMap in Java?"
}
] |
Minimum edges to be removed from given undirected graph to remove any existing path between nodes A and B
|
14 Dec, 2021
Given two integers N and M denoting the number of vertices and edges in the graph and array edges[][] of size M, denoting an edge between edges[i][0] and edges[i][1], the task is to find the minimum edges directly connected with node B that must be removed such that there exist no path between vertex A and B.
Examples:
Input: N = 4, A = 3, B = 2, edges[][] = {{3, 1}, {3, 4}, {1, 2}, {4, 2}}Output: 2Explanation: The edges at index 2 and 3 i.e., {1, 2} and {4, 2} must be removed as they both are in the path from vertex A to vertex B.
Input: N = 6, A = 1, B = 6, edges[][] = {{1, 2}, {1, 6}, {2, 6}, {1, 4}, {4, 6}, {4, 3}, {2, 4}}Output: 3
Approach: The given problem can be solved using a Depth-first search algorithm. It can be observed that all the edges associated with the ending vertex B and exist in any path from starting node A and ending at node B must be removed. Hence, perform a dfs starting from node A and maintain all the visited vertices from it. Follow the steps below to solve the problem:
Create an adjacency matrix g[][] which stores the edges between two nodes.
Initialize an array v[], to mark the node which can be reached from node A.
Create a variable cnt, which stores the count of nodes needed to be removed. Initially, cnt = 0.
Iterate through all the nodes and if it is reachable from A and is directly connected with B, increment the value of cnt.
The value stored in cnt is the required answer.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function for Depth first Searchvoid dfs(int s, vector<vector<int> > g, vector<int>& v){ for (auto i : g[s]) { // If current vertex is // not visited yet if (!v[i]) { v[i] = 1; // Recursive call for // dfs function dfs(i, g, v); } }} // Function to find the out the minimum// number of edges that must be removedint deleteEdges(int n, int m, int a, int b, vector<vector<int> > edges){ // Creating Adjacency Matrix vector<vector<int> > g(n, vector<int>()); for (int i = 0; i < m; i++) { g[edges[i][0] - 1].push_back(edges[i][1] - 1); g[edges[i][1] - 1].push_back(edges[i][0] - 1); } // Vector for marking visited vector<int> v(n, 0); v[a - 1] = 1; // Calling dfs function dfs(a - 1, g, v); // Stores the final count int cnt = 0; for (int i = 0; i < n; i++) { // If current node can not // be visited from node A if (v[i] == 0) continue; for (int j = 0; j < g[i].size(); j++) { // If a node between current // node and node b exist if (g[i][j] == b - 1) { cnt++; } } } // Return Answer return cnt;} // Driver Codeint main(){ int N = 6; int M = 7; int A = 1; int B = 6; vector<vector<int> > edges{ { 1, 2 }, { 5, 2 }, { 2, 4 }, { 2, 3 }, { 3, 6 }, { 4, 6 }, { 5, 6 } }; cout << deleteEdges(N, M, A, B, edges); return 0;}
// Java program for the above approachimport java.util.*; class GFG{ // Function for Depth first Searchstatic void dfs(int s, Vector<Integer> [] g, int[] v){ for (int i : g[s]) { // If current vertex is // not visited yet if (v[i] == 0) { v[i] = 1; // Recursive call for // dfs function dfs(i, g, v); } }} // Function to find the out the minimum// number of edges that must be removedstatic int deleteEdges(int n, int m, int a, int b, int[][] edges){ // Creating Adjacency Matrix Vector<Integer> []g = new Vector[n]; for (int i = 0; i < g.length; i++) g[i] = new Vector<Integer>(); for (int i = 0; i < m; i++) { g[edges[i][0] - 1].add(edges[i][1] - 1); g[edges[i][1] - 1].add(edges[i][0] - 1); } // Vector for marking visited int []v = new int[n]; v[a - 1] = 1; // Calling dfs function dfs(a - 1, g, v); // Stores the final count int cnt = 0; for (int i = 0; i < n; i++) { // If current node can not // be visited from node A if (v[i] == 0) continue; for (int j = 0; j < g[i].size(); j++) { // If a node between current // node and node b exist if (g[i].get(j) == b - 1) { cnt++; } } } // Return Answer return cnt;} // Driver Codepublic static void main(String[] args){ int N = 6; int M = 7; int A = 1; int B = 6; int[][] edges ={ { 1, 2 }, { 5, 2 }, { 2, 4 }, { 2, 3 }, { 3, 6 }, { 4, 6 }, { 5, 6 } }; System.out.print(deleteEdges(N, M, A, B, edges)); }} // This code is contributed by 29AjayKumar
# Python program for the above approach # Function for Depth first Searchdef dfs(s, g, v): for i in g[s]: # If current vertex is # not visited yet if not v[i]: v[i] = 1 # Recursive call for # dfs function dfs(i, g, v) # Function to find the out the minimum# number of edges that must be removeddef deleteEdges(n, m, a, b, edges): # Creating Adjacency Matrix g = [0] * m for i in range(len(g)): g[i] = [] for i in range(m): g[edges[i][0] - 1].append(edges[i][1] - 1) g[edges[i][1] - 1].append(edges[i][0] - 1) # Vector for marking visited v = [0] * n v[a - 1] = 1 # Calling dfs function dfs(a - 1, g, v) # Stores the final count cnt = 0 for i in range(n): # If current node can not # be visited from node A if (v[i] == 0): continue for j in range(len(g[i])): # If a node between current # node and node b exist if (g[i][j] == b - 1): cnt += 1 # Return Answer return cnt # Driver CodeN = 6M = 7A = 1B = 6edges = [[1, 2], [5, 2], [2, 4], [2, 3], [3, 6], [4, 6], [5, 6]] print(deleteEdges(N, M, A, B, edges)) # This code is contributed by gfgking
// C# program for the above approachusing System;using System.Collections.Generic; public class GFG{ // Function for Depth first Searchstatic void dfs(int s, List<int> [] g, int[] v){ foreach (int i in g[s]) { // If current vertex is // not visited yet if (v[i] == 0) { v[i] = 1; // Recursive call for // dfs function dfs(i, g, v); } }} // Function to find the out the minimum// number of edges that must be removedstatic int deleteEdges(int n, int m, int a, int b, int[,] edges){ // Creating Adjacency Matrix List<int> []g = new List<int>[n]; for (int i = 0; i < g.Length; i++) g[i] = new List<int>(); for (int i = 0; i < m; i++) { g[edges[i,0] - 1].Add(edges[i,1] - 1); g[edges[i,1] - 1].Add(edges[i,0] - 1); } // List for marking visited int []v = new int[n]; v[a - 1] = 1; // Calling dfs function dfs(a - 1, g, v); // Stores the readonly count int cnt = 0; for (int i = 0; i < n; i++) { // If current node can not // be visited from node A if (v[i] == 0) continue; for (int j = 0; j < g[i].Count; j++) { // If a node between current // node and node b exist if (g[i][j] == b - 1) { cnt++; } } } // Return Answer return cnt;} // Driver Codepublic static void Main(String[] args){ int N = 6; int M = 7; int A = 1; int B = 6; int[,] edges ={ { 1, 2 }, { 5, 2 }, { 2, 4 }, { 2, 3 }, { 3, 6 }, { 4, 6 }, { 5, 6 } }; Console.Write(deleteEdges(N, M, A, B, edges));}} // This code is contributed by shikhasingrajput
<script> // JavaScript program for the above approach // Function for Depth first Searchfunction dfs(s, g, v){ for(let i of g[s]) { // If current vertex is // not visited yet if (!v[i]) { v[i] = 1; // Recursive call for // dfs function dfs(i, g, v); } }} // Function to find the out the minimum// number of edges that must be removedfunction deleteEdges(n, m, a, b, edges){ // Creating Adjacency Matrix let g = new Array(m); for(let i = 0; i < g.length; i++) { g[i] = []; } for(let i = 0; i < m; i++) { g[edges[i][0] - 1].push(edges[i][1] - 1); g[edges[i][1] - 1].push(edges[i][0] - 1); } // Vector for marking visited let v = new Array(n).fill(0) v[a - 1] = 1; // Calling dfs function dfs(a - 1, g, v); // Stores the final count let cnt = 0; for(let i = 0; i < n; i++) { // If current node can not // be visited from node A if (v[i] == 0) continue; for(let j = 0; j < g[i].length; j++) { // If a node between current // node and node b exist if (g[i][j] == b - 1) { cnt++; } } } // Return Answer return cnt;} // Driver Codelet N = 6;let M = 7;let A = 1;let B = 6;let edges = [ [ 1, 2 ], [ 5, 2 ], [ 2, 4 ], [ 2, 3 ], [ 3, 6 ], [ 4, 6 ], [ 5, 6 ] ]; document.write(deleteEdges(N, M, A, B, edges)); // This code is contributed by Potta Lokesh </script>
3
Time Complexity: O(N)Auxiliary Space: O(N)
lokeshpotta20
gfgking
29AjayKumar
shikhasingrajput
DFS
Graph
Recursion
Recursion
DFS
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n14 Dec, 2021"
},
{
"code": null,
"e": 363,
"s": 52,
"text": "Given two integers N and M denoting the number of vertices and edges in the graph and array edges[][] of size M, denoting an edge between edges[i][0] and edges[i][1], the task is to find the minimum edges directly connected with node B that must be removed such that there exist no path between vertex A and B."
},
{
"code": null,
"e": 373,
"s": 363,
"text": "Examples:"
},
{
"code": null,
"e": 590,
"s": 373,
"text": "Input: N = 4, A = 3, B = 2, edges[][] = {{3, 1}, {3, 4}, {1, 2}, {4, 2}}Output: 2Explanation: The edges at index 2 and 3 i.e., {1, 2} and {4, 2} must be removed as they both are in the path from vertex A to vertex B."
},
{
"code": null,
"e": 696,
"s": 590,
"text": "Input: N = 6, A = 1, B = 6, edges[][] = {{1, 2}, {1, 6}, {2, 6}, {1, 4}, {4, 6}, {4, 3}, {2, 4}}Output: 3"
},
{
"code": null,
"e": 1065,
"s": 696,
"text": "Approach: The given problem can be solved using a Depth-first search algorithm. It can be observed that all the edges associated with the ending vertex B and exist in any path from starting node A and ending at node B must be removed. Hence, perform a dfs starting from node A and maintain all the visited vertices from it. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 1140,
"s": 1065,
"text": "Create an adjacency matrix g[][] which stores the edges between two nodes."
},
{
"code": null,
"e": 1216,
"s": 1140,
"text": "Initialize an array v[], to mark the node which can be reached from node A."
},
{
"code": null,
"e": 1313,
"s": 1216,
"text": "Create a variable cnt, which stores the count of nodes needed to be removed. Initially, cnt = 0."
},
{
"code": null,
"e": 1435,
"s": 1313,
"text": "Iterate through all the nodes and if it is reachable from A and is directly connected with B, increment the value of cnt."
},
{
"code": null,
"e": 1483,
"s": 1435,
"text": "The value stored in cnt is the required answer."
},
{
"code": null,
"e": 1534,
"s": 1483,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1538,
"s": 1534,
"text": "C++"
},
{
"code": null,
"e": 1543,
"s": 1538,
"text": "Java"
},
{
"code": null,
"e": 1551,
"s": 1543,
"text": "Python3"
},
{
"code": null,
"e": 1554,
"s": 1551,
"text": "C#"
},
{
"code": null,
"e": 1565,
"s": 1554,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function for Depth first Searchvoid dfs(int s, vector<vector<int> > g, vector<int>& v){ for (auto i : g[s]) { // If current vertex is // not visited yet if (!v[i]) { v[i] = 1; // Recursive call for // dfs function dfs(i, g, v); } }} // Function to find the out the minimum// number of edges that must be removedint deleteEdges(int n, int m, int a, int b, vector<vector<int> > edges){ // Creating Adjacency Matrix vector<vector<int> > g(n, vector<int>()); for (int i = 0; i < m; i++) { g[edges[i][0] - 1].push_back(edges[i][1] - 1); g[edges[i][1] - 1].push_back(edges[i][0] - 1); } // Vector for marking visited vector<int> v(n, 0); v[a - 1] = 1; // Calling dfs function dfs(a - 1, g, v); // Stores the final count int cnt = 0; for (int i = 0; i < n; i++) { // If current node can not // be visited from node A if (v[i] == 0) continue; for (int j = 0; j < g[i].size(); j++) { // If a node between current // node and node b exist if (g[i][j] == b - 1) { cnt++; } } } // Return Answer return cnt;} // Driver Codeint main(){ int N = 6; int M = 7; int A = 1; int B = 6; vector<vector<int> > edges{ { 1, 2 }, { 5, 2 }, { 2, 4 }, { 2, 3 }, { 3, 6 }, { 4, 6 }, { 5, 6 } }; cout << deleteEdges(N, M, A, B, edges); return 0;}",
"e": 3181,
"s": 1565,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*; class GFG{ // Function for Depth first Searchstatic void dfs(int s, Vector<Integer> [] g, int[] v){ for (int i : g[s]) { // If current vertex is // not visited yet if (v[i] == 0) { v[i] = 1; // Recursive call for // dfs function dfs(i, g, v); } }} // Function to find the out the minimum// number of edges that must be removedstatic int deleteEdges(int n, int m, int a, int b, int[][] edges){ // Creating Adjacency Matrix Vector<Integer> []g = new Vector[n]; for (int i = 0; i < g.length; i++) g[i] = new Vector<Integer>(); for (int i = 0; i < m; i++) { g[edges[i][0] - 1].add(edges[i][1] - 1); g[edges[i][1] - 1].add(edges[i][0] - 1); } // Vector for marking visited int []v = new int[n]; v[a - 1] = 1; // Calling dfs function dfs(a - 1, g, v); // Stores the final count int cnt = 0; for (int i = 0; i < n; i++) { // If current node can not // be visited from node A if (v[i] == 0) continue; for (int j = 0; j < g[i].size(); j++) { // If a node between current // node and node b exist if (g[i].get(j) == b - 1) { cnt++; } } } // Return Answer return cnt;} // Driver Codepublic static void main(String[] args){ int N = 6; int M = 7; int A = 1; int B = 6; int[][] edges ={ { 1, 2 }, { 5, 2 }, { 2, 4 }, { 2, 3 }, { 3, 6 }, { 4, 6 }, { 5, 6 } }; System.out.print(deleteEdges(N, M, A, B, edges)); }} // This code is contributed by 29AjayKumar",
"e": 4903,
"s": 3181,
"text": null
},
{
"code": "# Python program for the above approach # Function for Depth first Searchdef dfs(s, g, v): for i in g[s]: # If current vertex is # not visited yet if not v[i]: v[i] = 1 # Recursive call for # dfs function dfs(i, g, v) # Function to find the out the minimum# number of edges that must be removeddef deleteEdges(n, m, a, b, edges): # Creating Adjacency Matrix g = [0] * m for i in range(len(g)): g[i] = [] for i in range(m): g[edges[i][0] - 1].append(edges[i][1] - 1) g[edges[i][1] - 1].append(edges[i][0] - 1) # Vector for marking visited v = [0] * n v[a - 1] = 1 # Calling dfs function dfs(a - 1, g, v) # Stores the final count cnt = 0 for i in range(n): # If current node can not # be visited from node A if (v[i] == 0): continue for j in range(len(g[i])): # If a node between current # node and node b exist if (g[i][j] == b - 1): cnt += 1 # Return Answer return cnt # Driver CodeN = 6M = 7A = 1B = 6edges = [[1, 2], [5, 2], [2, 4], [2, 3], [3, 6], [4, 6], [5, 6]] print(deleteEdges(N, M, A, B, edges)) # This code is contributed by gfgking",
"e": 6192,
"s": 4903,
"text": null
},
{
"code": "// C# program for the above approachusing System;using System.Collections.Generic; public class GFG{ // Function for Depth first Searchstatic void dfs(int s, List<int> [] g, int[] v){ foreach (int i in g[s]) { // If current vertex is // not visited yet if (v[i] == 0) { v[i] = 1; // Recursive call for // dfs function dfs(i, g, v); } }} // Function to find the out the minimum// number of edges that must be removedstatic int deleteEdges(int n, int m, int a, int b, int[,] edges){ // Creating Adjacency Matrix List<int> []g = new List<int>[n]; for (int i = 0; i < g.Length; i++) g[i] = new List<int>(); for (int i = 0; i < m; i++) { g[edges[i,0] - 1].Add(edges[i,1] - 1); g[edges[i,1] - 1].Add(edges[i,0] - 1); } // List for marking visited int []v = new int[n]; v[a - 1] = 1; // Calling dfs function dfs(a - 1, g, v); // Stores the readonly count int cnt = 0; for (int i = 0; i < n; i++) { // If current node can not // be visited from node A if (v[i] == 0) continue; for (int j = 0; j < g[i].Count; j++) { // If a node between current // node and node b exist if (g[i][j] == b - 1) { cnt++; } } } // Return Answer return cnt;} // Driver Codepublic static void Main(String[] args){ int N = 6; int M = 7; int A = 1; int B = 6; int[,] edges ={ { 1, 2 }, { 5, 2 }, { 2, 4 }, { 2, 3 }, { 3, 6 }, { 4, 6 }, { 5, 6 } }; Console.Write(deleteEdges(N, M, A, B, edges));}} // This code is contributed by shikhasingrajput",
"e": 7927,
"s": 6192,
"text": null
},
{
"code": "<script> // JavaScript program for the above approach // Function for Depth first Searchfunction dfs(s, g, v){ for(let i of g[s]) { // If current vertex is // not visited yet if (!v[i]) { v[i] = 1; // Recursive call for // dfs function dfs(i, g, v); } }} // Function to find the out the minimum// number of edges that must be removedfunction deleteEdges(n, m, a, b, edges){ // Creating Adjacency Matrix let g = new Array(m); for(let i = 0; i < g.length; i++) { g[i] = []; } for(let i = 0; i < m; i++) { g[edges[i][0] - 1].push(edges[i][1] - 1); g[edges[i][1] - 1].push(edges[i][0] - 1); } // Vector for marking visited let v = new Array(n).fill(0) v[a - 1] = 1; // Calling dfs function dfs(a - 1, g, v); // Stores the final count let cnt = 0; for(let i = 0; i < n; i++) { // If current node can not // be visited from node A if (v[i] == 0) continue; for(let j = 0; j < g[i].length; j++) { // If a node between current // node and node b exist if (g[i][j] == b - 1) { cnt++; } } } // Return Answer return cnt;} // Driver Codelet N = 6;let M = 7;let A = 1;let B = 6;let edges = [ [ 1, 2 ], [ 5, 2 ], [ 2, 4 ], [ 2, 3 ], [ 3, 6 ], [ 4, 6 ], [ 5, 6 ] ]; document.write(deleteEdges(N, M, A, B, edges)); // This code is contributed by Potta Lokesh </script>",
"e": 9557,
"s": 7927,
"text": null
},
{
"code": null,
"e": 9559,
"s": 9557,
"text": "3"
},
{
"code": null,
"e": 9602,
"s": 9559,
"text": "Time Complexity: O(N)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 9616,
"s": 9602,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 9624,
"s": 9616,
"text": "gfgking"
},
{
"code": null,
"e": 9636,
"s": 9624,
"text": "29AjayKumar"
},
{
"code": null,
"e": 9653,
"s": 9636,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 9657,
"s": 9653,
"text": "DFS"
},
{
"code": null,
"e": 9663,
"s": 9657,
"text": "Graph"
},
{
"code": null,
"e": 9673,
"s": 9663,
"text": "Recursion"
},
{
"code": null,
"e": 9683,
"s": 9673,
"text": "Recursion"
},
{
"code": null,
"e": 9687,
"s": 9683,
"text": "DFS"
},
{
"code": null,
"e": 9693,
"s": 9687,
"text": "Graph"
}
] |
Thread isAlive() Method in Java With Examples
|
09 May, 2022
Thread class in java provides numerous methods that are very essential in order to understand the working of threads as the thread stages are triggered by them. Java multi-threading provides two ways to find with the help of isAlive() and join() method.One thread gets to know when another thread has ended. Let us do depict stages of the lifecycle of the thread via the below image which helps us to connect dots to understand these methodsβ workings.
Now let us do discuss isAlive() method of Thread class to a deeper depth. Basically, this method works internally very closely in parallel to the lifecycle stages of a thread. It tests if this thread is alive. A thread is alive if it has been started and has not yet died. There is a transitional period from when a thread is running to when a thread is not running. After the run() method returns, there is a short period of time before the thread stops. If we want to know if the start method of the thread class has been called or if the thread has been terminated, we must use the isAlive() method. This method is used to find out if a thread has actually been started and has yet not terminated.
Syntax:
final boolean isAlive()
Return Value: Boolean value returns
Note: While returning this function returns true if the thread upon which it is called is still running. It returns false otherwise.
Example
Java
// Java program to Illustrate isAlive() Method// of Thread class // Main class extending Thread classpublic class oneThread extends Thread { // Method 1 // run() method for thread public void run() { // Print statement System.out.println("geeks "); // Try block to check for exceptions try { // making thread to sleep for 300 nano-seconds // using sleep() method Thread.sleep(300); } // Catch block to handle InterruptedException catch (InterruptedException ie) { } // Display message when exception occurred System.out.println("forgeeks "); } // Method 2 // Main driver method public static void main(String[] args) { // Creating threads using above class as // it is extending Thread class oneThread c1 = new oneThread(); oneThread c2 = new oneThread(); // Starting threads c1.start(); c2.start(); // Checking whether thread is alive or not // Returning boolean true if alive else false System.out.println(c1.isAlive()); System.out.println(c2.isAlive()); }}
Output:
geeks
true
true
geeks
forgeeks
forgeeks
This article is contributed by Shivani Ghughtyal. 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.
solankimayank
saurabh1990aror
simmytarika5
surinderdawra388
Java-Multithreading
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Strings in Java
Java Programming Examples
Abstraction in Java
HashSet in Java
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n09 May, 2022"
},
{
"code": null,
"e": 506,
"s": 53,
"text": "Thread class in java provides numerous methods that are very essential in order to understand the working of threads as the thread stages are triggered by them. Java multi-threading provides two ways to find with the help of isAlive() and join() method.One thread gets to know when another thread has ended. Let us do depict stages of the lifecycle of the thread via the below image which helps us to connect dots to understand these methodsβ workings."
},
{
"code": null,
"e": 1208,
"s": 506,
"text": "Now let us do discuss isAlive() method of Thread class to a deeper depth. Basically, this method works internally very closely in parallel to the lifecycle stages of a thread. It tests if this thread is alive. A thread is alive if it has been started and has not yet died. There is a transitional period from when a thread is running to when a thread is not running. After the run() method returns, there is a short period of time before the thread stops. If we want to know if the start method of the thread class has been called or if the thread has been terminated, we must use the isAlive() method. This method is used to find out if a thread has actually been started and has yet not terminated. "
},
{
"code": null,
"e": 1217,
"s": 1208,
"text": "Syntax: "
},
{
"code": null,
"e": 1241,
"s": 1217,
"text": "final boolean isAlive()"
},
{
"code": null,
"e": 1279,
"s": 1241,
"text": "Return Value: Boolean value returns "
},
{
"code": null,
"e": 1412,
"s": 1279,
"text": "Note: While returning this function returns true if the thread upon which it is called is still running. It returns false otherwise."
},
{
"code": null,
"e": 1420,
"s": 1412,
"text": "Example"
},
{
"code": null,
"e": 1425,
"s": 1420,
"text": "Java"
},
{
"code": "// Java program to Illustrate isAlive() Method// of Thread class // Main class extending Thread classpublic class oneThread extends Thread { // Method 1 // run() method for thread public void run() { // Print statement System.out.println(\"geeks \"); // Try block to check for exceptions try { // making thread to sleep for 300 nano-seconds // using sleep() method Thread.sleep(300); } // Catch block to handle InterruptedException catch (InterruptedException ie) { } // Display message when exception occurred System.out.println(\"forgeeks \"); } // Method 2 // Main driver method public static void main(String[] args) { // Creating threads using above class as // it is extending Thread class oneThread c1 = new oneThread(); oneThread c2 = new oneThread(); // Starting threads c1.start(); c2.start(); // Checking whether thread is alive or not // Returning boolean true if alive else false System.out.println(c1.isAlive()); System.out.println(c2.isAlive()); }}",
"e": 2613,
"s": 1425,
"text": null
},
{
"code": null,
"e": 2622,
"s": 2613,
"text": "Output: "
},
{
"code": null,
"e": 2665,
"s": 2622,
"text": "geeks \ntrue\ntrue\ngeeks \nforgeeks \nforgeeks"
},
{
"code": null,
"e": 3091,
"s": 2665,
"text": "This article is contributed by Shivani Ghughtyal. 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": 3105,
"s": 3091,
"text": "solankimayank"
},
{
"code": null,
"e": 3121,
"s": 3105,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 3134,
"s": 3121,
"text": "simmytarika5"
},
{
"code": null,
"e": 3151,
"s": 3134,
"text": "surinderdawra388"
},
{
"code": null,
"e": 3171,
"s": 3151,
"text": "Java-Multithreading"
},
{
"code": null,
"e": 3176,
"s": 3171,
"text": "Java"
},
{
"code": null,
"e": 3181,
"s": 3176,
"text": "Java"
},
{
"code": null,
"e": 3279,
"s": 3181,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3294,
"s": 3279,
"text": "Stream In Java"
},
{
"code": null,
"e": 3315,
"s": 3294,
"text": "Introduction to Java"
},
{
"code": null,
"e": 3336,
"s": 3315,
"text": "Constructors in Java"
},
{
"code": null,
"e": 3355,
"s": 3336,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 3372,
"s": 3355,
"text": "Generics in Java"
},
{
"code": null,
"e": 3402,
"s": 3372,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 3418,
"s": 3402,
"text": "Strings in Java"
},
{
"code": null,
"e": 3444,
"s": 3418,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 3464,
"s": 3444,
"text": "Abstraction in Java"
}
] |
Longest Common Prefix using Trie
|
12 Jul, 2019
Given a set of strings, find the longest common prefix.
Input : {βgeeksforgeeksβ, βgeeksβ, βgeekβ, βgeezerβ}
Output : "gee"
Input : {"apple", "ape", "april"}
Output : "ap"
Previous Approaches : Word by Word Matching , Character by Character Matching, Divide and Conquer , Binary Search.
In this article, an approach using Trie date structure is discussed.Steps:
Insert all the words one by one in the trie. After inserting we perform a walk on the trie.
In this walk, go deeper until we find a node having more than 1 children(branching occurs) or 0 children (one of the string gets exhausted).This is because the characters (nodes in trie) which are present in the longest common prefix must be the single child of its parent, i.e- there should not be branching in any of these nodes.
This is because the characters (nodes in trie) which are present in the longest common prefix must be the single child of its parent, i.e- there should not be branching in any of these nodes.
Algorithm Illustration considering strings as β βgeeksforgeeksβ, βgeeksβ, βgeekβ, βgeezerβ
C++
Java
Python3
C#
// A Program to find the longest common// prefix of the given words #include<bits/stdc++.h>using namespace std; // Alphabet size (# of symbols)#define ALPHABET_SIZE (26) // Converts key current character into index// use only 'a' through 'z' and lower case#define CHAR_TO_INDEX(c) ((int)c - (int)'a') // Trie nodestruct TrieNode{ struct TrieNode *children[ALPHABET_SIZE]; // isLeaf is true if the node represents // end of a word bool isLeaf;}; // Returns new trie node (initialized to NULLs)struct TrieNode *getNode(void){ struct TrieNode *pNode = new TrieNode; if (pNode) { int i; pNode->isLeaf = false; for (i = 0; i < ALPHABET_SIZE; i++) pNode->children[i] = NULL; } return pNode;} // If not present, inserts the key into the trie// If the key is a prefix of trie node, just marks leaf nodevoid insert(struct TrieNode *root, string key){ int length = key.length(); int index; struct TrieNode *pCrawl = root; for (int level = 0; level < length; level++) { index = CHAR_TO_INDEX(key[level]); if (!pCrawl->children[index]) pCrawl->children[index] = getNode(); pCrawl = pCrawl->children[index]; } // mark last node as leaf pCrawl->isLeaf = true;} // Counts and returns the number of children of the// current nodeint countChildren(struct TrieNode *node, int *index){ int count = 0; for (int i=0; i<ALPHABET_SIZE; i++) { if (node->children[i] != NULL) { count++; *index = i; } } return (count);} // Perform a walk on the trie and return the// longest common prefix stringstring walkTrie(struct TrieNode *root){ struct TrieNode *pCrawl = root; int index; string prefix; while (countChildren(pCrawl, &index) == 1 && pCrawl->isLeaf == false) { pCrawl = pCrawl->children[index]; prefix.push_back('a'+index); } return (prefix);} // A Function to construct trievoid constructTrie(string arr[], int n, struct TrieNode *root){ for (int i = 0; i < n; i++) insert (root, arr[i]); return;} // A Function that returns the longest common prefix// from the array of stringsstring commonPrefix(string arr[], int n){ struct TrieNode *root = getNode(); constructTrie(arr, n, root); // Perform a walk on the trie return walkTrie(root);} // Driver program to test above functionint main(){ string arr[] = {"geeksforgeeks", "geeks", "geek", "geezer"}; int n = sizeof (arr) / sizeof (arr[0]); string ans = commonPrefix(arr, n); if (ans.length()) cout << "The longest common prefix is " << ans; else cout << "There is no common prefix"; return (0);}
// Java Program to find the longest common// prefix of the given wordspublic class Longest_common_prefix { // Alphabet size (# of symbols) static final int ALPHABET_SIZE = 26; // Trie node static class TrieNode { TrieNode[] children = new TrieNode[ALPHABET_SIZE]; // isLeaf is true if the node represents // end of a word boolean isLeaf; // constructor public TrieNode() { isLeaf = false; for (int i = 0; i < ALPHABET_SIZE; i++) children[i] = null; } }; static TrieNode root; static int indexs; // If not present, inserts the key into the trie // If the key is a prefix of trie node, just marks // leaf node static void insert(String key) { int length = key.length(); int index; TrieNode pCrawl = root; for (int level = 0; level < length; level++) { index = key.charAt(level) - 'a'; if (pCrawl.children[index] == null) pCrawl.children[index] = new TrieNode(); pCrawl = pCrawl.children[index]; } // mark last node as leaf pCrawl.isLeaf = true; } // Counts and returns the number of children of the // current node static int countChildren(TrieNode node) { int count = 0; for (int i=0; i<ALPHABET_SIZE; i++) { if (node.children[i] != null) { count++; indexs = i; } } return (count); } // Perform a walk on the trie and return the // longest common prefix string static String walkTrie() { TrieNode pCrawl = root; indexs = 0; String prefix = ""; while (countChildren(pCrawl) == 1 && pCrawl.isLeaf == false) { pCrawl = pCrawl.children[indexs]; prefix += (char)('a' + indexs); } return prefix; } // A Function to construct trie static void constructTrie(String arr[], int n) { for (int i = 0; i < n; i++) insert (arr[i]); return; } // A Function that returns the longest common prefix // from the array of strings static String commonPrefix(String arr[], int n) { root = new TrieNode(); constructTrie(arr, n); // Perform a walk on the trie return walkTrie(); } // Driver program to test above function public static void main(String args[]) { String arr[] = {"geeksforgeeks", "geeks", "geek", "geezer"}; int n = arr.length; String ans = commonPrefix(arr, n); if (ans.length() != 0) System.out.println("The longest common prefix is "+ans); else System.out.println("There is no common prefix"); }}// This code is contributed by Sumit Ghosh
# Python 3 program to find the longest common prefixALPHABET_SIZE = 26indexs = 0class TrieNode: # constructor def __init__(self): self.isLeaf = False self.children = [None]*ALPHABET_SIZE # Function to facilitate insertion in Trie# If not present, insert the node in the Triedef insert(key, root): pCrawl = root for level in range(len(key)): index = ord(key[level]) - ord('a') if pCrawl.children[index] == None: pCrawl.children[index] = TrieNode() pCrawl = pCrawl.children[index] pCrawl.isLeaf = True # Function to construct Triedef constructTrie(arr, n, root): for i in range(n): insert(arr[i], root) # Counts and returns number of children of the nodedef countChildren(node): count = 0 for i in range(ALPHABET_SIZE): if node.children[i] != None: count +=1 # Keeping track of diversion in the trie global indexs indexs = i return count # Perform walk on trie and return longest common prefix def walkTrie(root): pCrawl = root prefix = "" while(countChildren(pCrawl) == 1 and pCrawl.isLeaf == False): pCrawl = pCrawl.children[indexs] prefix += chr(97 + indexs) return prefix or -1 # Function that returns longest common prefix def commonPrefix(arr, n, root): constructTrie(arr, n, root) return walkTrie(root) # Driver code to test the coden = 4arr = ["geeksforgeeks", "geeks", "geek", "geezer"]root = TrieNode()print(commonPrefix(arr,n, root)) # This code is Contributed by Akshay Jain (DA-IICT)
// C# Program to find the longest common// prefix of the given wordsusing System; public class Longest_common_prefix { // Alphabet size (# of symbols) static readonly int ALPHABET_SIZE = 26; // Trie node public class TrieNode { public TrieNode[] children = new TrieNode[ALPHABET_SIZE]; // isLeaf is true if the node represents // end of a word public bool isLeaf; // constructor public TrieNode() { isLeaf = false; for (int i = 0; i < ALPHABET_SIZE; i++) children[i] = null; } }; static TrieNode root; static int indexs; // If not present, inserts the key into the trie // If the key is a prefix of trie node, just marks // leaf node static void insert(String key) { int length = key.Length; int index; TrieNode pCrawl = root; for (int level = 0; level < length; level++) { index = key[level] - 'a'; if (pCrawl.children[index] == null) pCrawl.children[index] = new TrieNode(); pCrawl = pCrawl.children[index]; } // mark last node as leaf pCrawl.isLeaf = true; } // Counts and returns the number of children of the // current node static int countChildren(TrieNode node) { int count = 0; for (int i = 0; i < ALPHABET_SIZE; i++) { if (node.children[i] != null) { count++; indexs = i; } } return (count); } // Perform a walk on the trie and return the // longest common prefix string static String walkTrie() { TrieNode pCrawl = root; indexs = 0; String prefix = ""; while (countChildren(pCrawl) == 1 && pCrawl.isLeaf == false) { pCrawl = pCrawl.children[indexs]; prefix += (char)('a' + indexs); } return prefix; } // A Function to construct trie static void constructTrie(String []arr, int n) { for (int i = 0; i < n; i++) insert (arr[i]); return; } // A Function that returns the longest common prefix // from the array of strings static String commonPrefix(String []arr, int n) { root = new TrieNode(); constructTrie(arr, n); // Perform a walk on the trie return walkTrie(); } // Driver program to test above function public static void Main(String []args) { String []arr = {"geeksforgeeks", "geeks", "geek", "geezer"}; int n = arr.Length; String ans = commonPrefix(arr, n); if (ans.Length != 0) Console.WriteLine("The longest common prefix is "+ans); else Console.WriteLine("There is no common prefix"); }} // This code contributed by Rajput-Ji
The longest common prefix is gee
Time Complexity : Inserting all the words in the trie takes O(MN) time and performing a walk on the trie takes O(M) time, where-
N = Number of strings
M = Length of the largest string
Auxiliary Space: To store all the strings we need to allocate O(26*M*N) ~ O(MN) space for the Trie.
This article is contributed by Rachit Belwariar. 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
addiegupta
Rajput-Ji
lucasyuso
Longest Common Prefix
Trie
VMWare
Advanced Data Structure
Arrays
Strings
VMWare
Arrays
Strings
Trie
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n12 Jul, 2019"
},
{
"code": null,
"e": 110,
"s": 54,
"text": "Given a set of strings, find the longest common prefix."
},
{
"code": null,
"e": 230,
"s": 110,
"text": "Input : {βgeeksforgeeksβ, βgeeksβ, βgeekβ, βgeezerβ}\nOutput : \"gee\"\n\nInput : {\"apple\", \"ape\", \"april\"}\nOutput : \"ap\"\n"
},
{
"code": null,
"e": 345,
"s": 230,
"text": "Previous Approaches : Word by Word Matching , Character by Character Matching, Divide and Conquer , Binary Search."
},
{
"code": null,
"e": 420,
"s": 345,
"text": "In this article, an approach using Trie date structure is discussed.Steps:"
},
{
"code": null,
"e": 512,
"s": 420,
"text": "Insert all the words one by one in the trie. After inserting we perform a walk on the trie."
},
{
"code": null,
"e": 844,
"s": 512,
"text": "In this walk, go deeper until we find a node having more than 1 children(branching occurs) or 0 children (one of the string gets exhausted).This is because the characters (nodes in trie) which are present in the longest common prefix must be the single child of its parent, i.e- there should not be branching in any of these nodes."
},
{
"code": null,
"e": 1036,
"s": 844,
"text": "This is because the characters (nodes in trie) which are present in the longest common prefix must be the single child of its parent, i.e- there should not be branching in any of these nodes."
},
{
"code": null,
"e": 1127,
"s": 1036,
"text": "Algorithm Illustration considering strings as β βgeeksforgeeksβ, βgeeksβ, βgeekβ, βgeezerβ"
},
{
"code": null,
"e": 1131,
"s": 1127,
"text": "C++"
},
{
"code": null,
"e": 1136,
"s": 1131,
"text": "Java"
},
{
"code": null,
"e": 1144,
"s": 1136,
"text": "Python3"
},
{
"code": null,
"e": 1147,
"s": 1144,
"text": "C#"
},
{
"code": "// A Program to find the longest common// prefix of the given words #include<bits/stdc++.h>using namespace std; // Alphabet size (# of symbols)#define ALPHABET_SIZE (26) // Converts key current character into index// use only 'a' through 'z' and lower case#define CHAR_TO_INDEX(c) ((int)c - (int)'a') // Trie nodestruct TrieNode{ struct TrieNode *children[ALPHABET_SIZE]; // isLeaf is true if the node represents // end of a word bool isLeaf;}; // Returns new trie node (initialized to NULLs)struct TrieNode *getNode(void){ struct TrieNode *pNode = new TrieNode; if (pNode) { int i; pNode->isLeaf = false; for (i = 0; i < ALPHABET_SIZE; i++) pNode->children[i] = NULL; } return pNode;} // If not present, inserts the key into the trie// If the key is a prefix of trie node, just marks leaf nodevoid insert(struct TrieNode *root, string key){ int length = key.length(); int index; struct TrieNode *pCrawl = root; for (int level = 0; level < length; level++) { index = CHAR_TO_INDEX(key[level]); if (!pCrawl->children[index]) pCrawl->children[index] = getNode(); pCrawl = pCrawl->children[index]; } // mark last node as leaf pCrawl->isLeaf = true;} // Counts and returns the number of children of the// current nodeint countChildren(struct TrieNode *node, int *index){ int count = 0; for (int i=0; i<ALPHABET_SIZE; i++) { if (node->children[i] != NULL) { count++; *index = i; } } return (count);} // Perform a walk on the trie and return the// longest common prefix stringstring walkTrie(struct TrieNode *root){ struct TrieNode *pCrawl = root; int index; string prefix; while (countChildren(pCrawl, &index) == 1 && pCrawl->isLeaf == false) { pCrawl = pCrawl->children[index]; prefix.push_back('a'+index); } return (prefix);} // A Function to construct trievoid constructTrie(string arr[], int n, struct TrieNode *root){ for (int i = 0; i < n; i++) insert (root, arr[i]); return;} // A Function that returns the longest common prefix// from the array of stringsstring commonPrefix(string arr[], int n){ struct TrieNode *root = getNode(); constructTrie(arr, n, root); // Perform a walk on the trie return walkTrie(root);} // Driver program to test above functionint main(){ string arr[] = {\"geeksforgeeks\", \"geeks\", \"geek\", \"geezer\"}; int n = sizeof (arr) / sizeof (arr[0]); string ans = commonPrefix(arr, n); if (ans.length()) cout << \"The longest common prefix is \" << ans; else cout << \"There is no common prefix\"; return (0);}",
"e": 3918,
"s": 1147,
"text": null
},
{
"code": "// Java Program to find the longest common// prefix of the given wordspublic class Longest_common_prefix { // Alphabet size (# of symbols) static final int ALPHABET_SIZE = 26; // Trie node static class TrieNode { TrieNode[] children = new TrieNode[ALPHABET_SIZE]; // isLeaf is true if the node represents // end of a word boolean isLeaf; // constructor public TrieNode() { isLeaf = false; for (int i = 0; i < ALPHABET_SIZE; i++) children[i] = null; } }; static TrieNode root; static int indexs; // If not present, inserts the key into the trie // If the key is a prefix of trie node, just marks // leaf node static void insert(String key) { int length = key.length(); int index; TrieNode pCrawl = root; for (int level = 0; level < length; level++) { index = key.charAt(level) - 'a'; if (pCrawl.children[index] == null) pCrawl.children[index] = new TrieNode(); pCrawl = pCrawl.children[index]; } // mark last node as leaf pCrawl.isLeaf = true; } // Counts and returns the number of children of the // current node static int countChildren(TrieNode node) { int count = 0; for (int i=0; i<ALPHABET_SIZE; i++) { if (node.children[i] != null) { count++; indexs = i; } } return (count); } // Perform a walk on the trie and return the // longest common prefix string static String walkTrie() { TrieNode pCrawl = root; indexs = 0; String prefix = \"\"; while (countChildren(pCrawl) == 1 && pCrawl.isLeaf == false) { pCrawl = pCrawl.children[indexs]; prefix += (char)('a' + indexs); } return prefix; } // A Function to construct trie static void constructTrie(String arr[], int n) { for (int i = 0; i < n; i++) insert (arr[i]); return; } // A Function that returns the longest common prefix // from the array of strings static String commonPrefix(String arr[], int n) { root = new TrieNode(); constructTrie(arr, n); // Perform a walk on the trie return walkTrie(); } // Driver program to test above function public static void main(String args[]) { String arr[] = {\"geeksforgeeks\", \"geeks\", \"geek\", \"geezer\"}; int n = arr.length; String ans = commonPrefix(arr, n); if (ans.length() != 0) System.out.println(\"The longest common prefix is \"+ans); else System.out.println(\"There is no common prefix\"); }}// This code is contributed by Sumit Ghosh",
"e": 6904,
"s": 3918,
"text": null
},
{
"code": "# Python 3 program to find the longest common prefixALPHABET_SIZE = 26indexs = 0class TrieNode: # constructor def __init__(self): self.isLeaf = False self.children = [None]*ALPHABET_SIZE # Function to facilitate insertion in Trie# If not present, insert the node in the Triedef insert(key, root): pCrawl = root for level in range(len(key)): index = ord(key[level]) - ord('a') if pCrawl.children[index] == None: pCrawl.children[index] = TrieNode() pCrawl = pCrawl.children[index] pCrawl.isLeaf = True # Function to construct Triedef constructTrie(arr, n, root): for i in range(n): insert(arr[i], root) # Counts and returns number of children of the nodedef countChildren(node): count = 0 for i in range(ALPHABET_SIZE): if node.children[i] != None: count +=1 # Keeping track of diversion in the trie global indexs indexs = i return count # Perform walk on trie and return longest common prefix def walkTrie(root): pCrawl = root prefix = \"\" while(countChildren(pCrawl) == 1 and pCrawl.isLeaf == False): pCrawl = pCrawl.children[indexs] prefix += chr(97 + indexs) return prefix or -1 # Function that returns longest common prefix def commonPrefix(arr, n, root): constructTrie(arr, n, root) return walkTrie(root) # Driver code to test the coden = 4arr = [\"geeksforgeeks\", \"geeks\", \"geek\", \"geezer\"]root = TrieNode()print(commonPrefix(arr,n, root)) # This code is Contributed by Akshay Jain (DA-IICT)",
"e": 8473,
"s": 6904,
"text": null
},
{
"code": "// C# Program to find the longest common// prefix of the given wordsusing System; public class Longest_common_prefix { // Alphabet size (# of symbols) static readonly int ALPHABET_SIZE = 26; // Trie node public class TrieNode { public TrieNode[] children = new TrieNode[ALPHABET_SIZE]; // isLeaf is true if the node represents // end of a word public bool isLeaf; // constructor public TrieNode() { isLeaf = false; for (int i = 0; i < ALPHABET_SIZE; i++) children[i] = null; } }; static TrieNode root; static int indexs; // If not present, inserts the key into the trie // If the key is a prefix of trie node, just marks // leaf node static void insert(String key) { int length = key.Length; int index; TrieNode pCrawl = root; for (int level = 0; level < length; level++) { index = key[level] - 'a'; if (pCrawl.children[index] == null) pCrawl.children[index] = new TrieNode(); pCrawl = pCrawl.children[index]; } // mark last node as leaf pCrawl.isLeaf = true; } // Counts and returns the number of children of the // current node static int countChildren(TrieNode node) { int count = 0; for (int i = 0; i < ALPHABET_SIZE; i++) { if (node.children[i] != null) { count++; indexs = i; } } return (count); } // Perform a walk on the trie and return the // longest common prefix string static String walkTrie() { TrieNode pCrawl = root; indexs = 0; String prefix = \"\"; while (countChildren(pCrawl) == 1 && pCrawl.isLeaf == false) { pCrawl = pCrawl.children[indexs]; prefix += (char)('a' + indexs); } return prefix; } // A Function to construct trie static void constructTrie(String []arr, int n) { for (int i = 0; i < n; i++) insert (arr[i]); return; } // A Function that returns the longest common prefix // from the array of strings static String commonPrefix(String []arr, int n) { root = new TrieNode(); constructTrie(arr, n); // Perform a walk on the trie return walkTrie(); } // Driver program to test above function public static void Main(String []args) { String []arr = {\"geeksforgeeks\", \"geeks\", \"geek\", \"geezer\"}; int n = arr.Length; String ans = commonPrefix(arr, n); if (ans.Length != 0) Console.WriteLine(\"The longest common prefix is \"+ans); else Console.WriteLine(\"There is no common prefix\"); }} // This code contributed by Rajput-Ji",
"e": 11469,
"s": 8473,
"text": null
},
{
"code": null,
"e": 11502,
"s": 11469,
"text": "The longest common prefix is gee"
},
{
"code": null,
"e": 11631,
"s": 11502,
"text": "Time Complexity : Inserting all the words in the trie takes O(MN) time and performing a walk on the trie takes O(M) time, where-"
},
{
"code": null,
"e": 11687,
"s": 11631,
"text": "N = Number of strings\nM = Length of the largest string\n"
},
{
"code": null,
"e": 11787,
"s": 11687,
"text": "Auxiliary Space: To store all the strings we need to allocate O(26*M*N) ~ O(MN) space for the Trie."
},
{
"code": null,
"e": 12092,
"s": 11787,
"text": " This article is contributed by Rachit Belwariar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 12216,
"s": 12092,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 12227,
"s": 12216,
"text": "addiegupta"
},
{
"code": null,
"e": 12237,
"s": 12227,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 12247,
"s": 12237,
"text": "lucasyuso"
},
{
"code": null,
"e": 12269,
"s": 12247,
"text": "Longest Common Prefix"
},
{
"code": null,
"e": 12274,
"s": 12269,
"text": "Trie"
},
{
"code": null,
"e": 12281,
"s": 12274,
"text": "VMWare"
},
{
"code": null,
"e": 12305,
"s": 12281,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 12312,
"s": 12305,
"text": "Arrays"
},
{
"code": null,
"e": 12320,
"s": 12312,
"text": "Strings"
},
{
"code": null,
"e": 12327,
"s": 12320,
"text": "VMWare"
},
{
"code": null,
"e": 12334,
"s": 12327,
"text": "Arrays"
},
{
"code": null,
"e": 12342,
"s": 12334,
"text": "Strings"
},
{
"code": null,
"e": 12347,
"s": 12342,
"text": "Trie"
}
] |
Display the red, green and blue color planes of a color image in MATLAB
|
28 Mar, 2019
Prerequisite β RGB image representationA colored image can be represented as a 3 order matrix. The first order is for the rows, the second order is for the columns and the third order is for specifying the color of the corresponding pixel. Here we use the RGB color format, so the third order will take 3 values of Red, Green ans Blue respectively. The values of the rows and columns depends on the size of the image.
Approach:
Load the image into a variable J by using imread().
Store the number of rows and columns of the image in variables, r and c.
Create 3 zero matrices R, G and B (one for each of the 3 colors) of size rXc.
Store the corresponding color plane of the image in the corresponding zero matrix.1: Red
2: Green
3: Blue
1: Red
2: Green
3: Blue
Display the images by using imshow(), but typecast them into uint8 first.
Implementation:
% MATLAB code to display the red, green and blue% color planes of a color image % read the imageI = imread('lenna.png'); % rows and columns in the imager = size(I, 1);c = size(I, 2); % creating zero matricesR = zeros(r, c, 3);G = zeros(r, c, 3);B = zeros(r, c, 3); % storing the corresponding color plane % red planeR(:, :, 1) = I(:, :, 1); % green planeG(:, :, 2) = I(:, :, 2); % blue planeB(:, :, 3) = I(:, :, 3); % displaying the imagesfigure, imshow(uint8(R));figure, imshow(uint8(G));figure, imshow(uint8(B));
Input :Output :
Image-Processing
MATLAB
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n28 Mar, 2019"
},
{
"code": null,
"e": 472,
"s": 54,
"text": "Prerequisite β RGB image representationA colored image can be represented as a 3 order matrix. The first order is for the rows, the second order is for the columns and the third order is for specifying the color of the corresponding pixel. Here we use the RGB color format, so the third order will take 3 values of Red, Green ans Blue respectively. The values of the rows and columns depends on the size of the image."
},
{
"code": null,
"e": 482,
"s": 472,
"text": "Approach:"
},
{
"code": null,
"e": 534,
"s": 482,
"text": "Load the image into a variable J by using imread()."
},
{
"code": null,
"e": 607,
"s": 534,
"text": "Store the number of rows and columns of the image in variables, r and c."
},
{
"code": null,
"e": 685,
"s": 607,
"text": "Create 3 zero matrices R, G and B (one for each of the 3 colors) of size rXc."
},
{
"code": null,
"e": 792,
"s": 685,
"text": "Store the corresponding color plane of the image in the corresponding zero matrix.1: Red\n2: Green\n3: Blue "
},
{
"code": null,
"e": 817,
"s": 792,
"text": "1: Red\n2: Green\n3: Blue "
},
{
"code": null,
"e": 891,
"s": 817,
"text": "Display the images by using imshow(), but typecast them into uint8 first."
},
{
"code": null,
"e": 907,
"s": 891,
"text": "Implementation:"
},
{
"code": "% MATLAB code to display the red, green and blue% color planes of a color image % read the imageI = imread('lenna.png'); % rows and columns in the imager = size(I, 1);c = size(I, 2); % creating zero matricesR = zeros(r, c, 3);G = zeros(r, c, 3);B = zeros(r, c, 3); % storing the corresponding color plane % red planeR(:, :, 1) = I(:, :, 1); % green planeG(:, :, 2) = I(:, :, 2); % blue planeB(:, :, 3) = I(:, :, 3); % displaying the imagesfigure, imshow(uint8(R));figure, imshow(uint8(G));figure, imshow(uint8(B));",
"e": 1430,
"s": 907,
"text": null
},
{
"code": null,
"e": 1446,
"s": 1430,
"text": "Input :Output :"
},
{
"code": null,
"e": 1463,
"s": 1446,
"text": "Image-Processing"
},
{
"code": null,
"e": 1470,
"s": 1463,
"text": "MATLAB"
},
{
"code": null,
"e": 1496,
"s": 1470,
"text": "Advanced Computer Subject"
}
] |
Set Database From Single User Mode to Multi User in SQL
|
16 Dec, 2021
A single-user mode specifies that only one user at a time can access the database. If you set the database to single-user mode then all other connections will be closed without warning. If you get disconnected after setting the database into single-user mode, a different user can connect to database, but only one user.
Where as in multiple-user mode more than one user can connect to the same database at the same time. This mode is generally used in organizations so that multiple users can access it simultaneously. Areas where Multi-user database is used are Banks, supermarket, insurance agencies sector.
Here we will see, how to set database from single user mode to multi user mode.
There are two ways to perform the given activity:
Using ALTER command
Using Object explorer in SQL Server Management Studio.
For demonstration, follow the steps given below:
Step 1: Create database
Use the following command to create database.
Query:
CREATE TABLE geeks;
Step 2: Set database into single user mode
ALTER command followed by SET keyword is used to set the user mode of database. Before changing the access mode all the open connections must be closed. Use the ROLLBACK IMMEDIATE termination clause after ALTER command along with βWITHβ keyword to close open connection.
Syntax:
ALTER DATABASE database_name SET
SINGLE_USER WITH ROLLBACK IMMEDIATE
Query:
ALTER DATABASE geeks SET SINGLE_USER
WITH ROLLBACK IMMEDIATE;
Output:
Here, we can see that βsingle userβ is displayed alongside the geeks database name.
We can use ALTER command in same way as we used to set the single user access mode. This commands need not connection closure.
Syntax:
ALTER DATABASE database_name
SET MULTI_USER;
Query:
ALTER DATABASE geeks
SET MULTI_USER;
Output:
Here , βsingle userβ keyword that was displayed earlier alongside geeks database is removed now.
Steps to change access mode:
Select View from menu bar.
Select Object explorer option. Object explorer will be appeared on left side of the screen.
Select Database folder and select your database (geeks we have used here).
Right click on the database and select properties option.
A dialog box will open, select βoptionβ option from left hand side of dialog box screen.
Scroll down to get βSTATEβ field.
Select Restrict access option from STATE field.
Select MULTI_USER from dropdown menu.
Click βOKβ.
Step 1: Open Object explorer
Step 2: Select properties
Step 3: Select option keyword from dialog box
Step 4: Select MULTI_USER from dropdown list in Restrict Access field
Step 5: Click on Ok, A dialog box will appear. Now click on Yes button.
Step 6: Again open object explorer
We can see that the βsingle userβ keyword is no longer present with the database name.
Picked
SQL-Query
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Dec, 2021"
},
{
"code": null,
"e": 349,
"s": 28,
"text": "A single-user mode specifies that only one user at a time can access the database. If you set the database to single-user mode then all other connections will be closed without warning. If you get disconnected after setting the database into single-user mode, a different user can connect to database, but only one user."
},
{
"code": null,
"e": 639,
"s": 349,
"text": "Where as in multiple-user mode more than one user can connect to the same database at the same time. This mode is generally used in organizations so that multiple users can access it simultaneously. Areas where Multi-user database is used are Banks, supermarket, insurance agencies sector."
},
{
"code": null,
"e": 720,
"s": 639,
"text": "Here we will see, how to set database from single user mode to multi user mode. "
},
{
"code": null,
"e": 770,
"s": 720,
"text": "There are two ways to perform the given activity:"
},
{
"code": null,
"e": 790,
"s": 770,
"text": "Using ALTER command"
},
{
"code": null,
"e": 845,
"s": 790,
"text": "Using Object explorer in SQL Server Management Studio."
},
{
"code": null,
"e": 894,
"s": 845,
"text": "For demonstration, follow the steps given below:"
},
{
"code": null,
"e": 918,
"s": 894,
"text": "Step 1: Create database"
},
{
"code": null,
"e": 964,
"s": 918,
"text": "Use the following command to create database."
},
{
"code": null,
"e": 971,
"s": 964,
"text": "Query:"
},
{
"code": null,
"e": 991,
"s": 971,
"text": "CREATE TABLE geeks;"
},
{
"code": null,
"e": 1034,
"s": 991,
"text": "Step 2: Set database into single user mode"
},
{
"code": null,
"e": 1305,
"s": 1034,
"text": "ALTER command followed by SET keyword is used to set the user mode of database. Before changing the access mode all the open connections must be closed. Use the ROLLBACK IMMEDIATE termination clause after ALTER command along with βWITHβ keyword to close open connection."
},
{
"code": null,
"e": 1313,
"s": 1305,
"text": "Syntax:"
},
{
"code": null,
"e": 1383,
"s": 1313,
"text": "ALTER DATABASE database_name SET \nSINGLE_USER WITH ROLLBACK IMMEDIATE"
},
{
"code": null,
"e": 1390,
"s": 1383,
"text": "Query:"
},
{
"code": null,
"e": 1452,
"s": 1390,
"text": "ALTER DATABASE geeks SET SINGLE_USER\nWITH ROLLBACK IMMEDIATE;"
},
{
"code": null,
"e": 1460,
"s": 1452,
"text": "Output:"
},
{
"code": null,
"e": 1545,
"s": 1460,
"text": "Here, we can see that βsingle userβ is displayed alongside the geeks database name. "
},
{
"code": null,
"e": 1672,
"s": 1545,
"text": "We can use ALTER command in same way as we used to set the single user access mode. This commands need not connection closure."
},
{
"code": null,
"e": 1680,
"s": 1672,
"text": "Syntax:"
},
{
"code": null,
"e": 1726,
"s": 1680,
"text": "ALTER DATABASE database_name \nSET MULTI_USER;"
},
{
"code": null,
"e": 1733,
"s": 1726,
"text": "Query:"
},
{
"code": null,
"e": 1770,
"s": 1733,
"text": "ALTER DATABASE geeks\nSET MULTI_USER;"
},
{
"code": null,
"e": 1778,
"s": 1770,
"text": "Output:"
},
{
"code": null,
"e": 1875,
"s": 1778,
"text": "Here , βsingle userβ keyword that was displayed earlier alongside geeks database is removed now."
},
{
"code": null,
"e": 1904,
"s": 1875,
"text": "Steps to change access mode:"
},
{
"code": null,
"e": 1931,
"s": 1904,
"text": "Select View from menu bar."
},
{
"code": null,
"e": 2023,
"s": 1931,
"text": "Select Object explorer option. Object explorer will be appeared on left side of the screen."
},
{
"code": null,
"e": 2098,
"s": 2023,
"text": "Select Database folder and select your database (geeks we have used here)."
},
{
"code": null,
"e": 2156,
"s": 2098,
"text": "Right click on the database and select properties option."
},
{
"code": null,
"e": 2245,
"s": 2156,
"text": "A dialog box will open, select βoptionβ option from left hand side of dialog box screen."
},
{
"code": null,
"e": 2279,
"s": 2245,
"text": "Scroll down to get βSTATEβ field."
},
{
"code": null,
"e": 2327,
"s": 2279,
"text": "Select Restrict access option from STATE field."
},
{
"code": null,
"e": 2365,
"s": 2327,
"text": "Select MULTI_USER from dropdown menu."
},
{
"code": null,
"e": 2377,
"s": 2365,
"text": "Click βOKβ."
},
{
"code": null,
"e": 2406,
"s": 2377,
"text": "Step 1: Open Object explorer"
},
{
"code": null,
"e": 2432,
"s": 2406,
"text": "Step 2: Select properties"
},
{
"code": null,
"e": 2478,
"s": 2432,
"text": "Step 3: Select option keyword from dialog box"
},
{
"code": null,
"e": 2548,
"s": 2478,
"text": "Step 4: Select MULTI_USER from dropdown list in Restrict Access field"
},
{
"code": null,
"e": 2620,
"s": 2548,
"text": "Step 5: Click on Ok, A dialog box will appear. Now click on Yes button."
},
{
"code": null,
"e": 2655,
"s": 2620,
"text": "Step 6: Again open object explorer"
},
{
"code": null,
"e": 2742,
"s": 2655,
"text": "We can see that the βsingle userβ keyword is no longer present with the database name."
},
{
"code": null,
"e": 2749,
"s": 2742,
"text": "Picked"
},
{
"code": null,
"e": 2759,
"s": 2749,
"text": "SQL-Query"
},
{
"code": null,
"e": 2770,
"s": 2759,
"text": "SQL-Server"
},
{
"code": null,
"e": 2774,
"s": 2770,
"text": "SQL"
},
{
"code": null,
"e": 2778,
"s": 2774,
"text": "SQL"
}
] |
How to make sure that Apache service keeps running in Ubuntu
|
03 Jan, 2019
Majority of worldβs websites are hosted on are hosted on Apache Web Servers and the majority of those servers run Apache in Linux. Letβs see how to install Apache in Ubuntu:
Type the following commands in terminal application on your computer:
$ sudo apt-get update
$ sudo apt-get install apache2
Now type localhost on your browser. It will pop up a message βIT WORKSβ.
There is also another way to check whether Apache Services running in the browser or not. To check, first find the IP Address using the below command:
$ifconfig
Now, put that IP address on the browser. The same message is being displayed βIT WORKSβ. This ensures that Apache service keeps running in Ubuntu.
To find out the active ports then type:
$ netstat -a|more
Here we get all of the ports, our active connections, our virtual ports essentially that our computer is listening. If you need to get the port numbers then type:
$ netstat -an|more
It shows port80, the port for the web server, port for HTTP, it listens to every address available. Our web server is listening.
Characteristics:
To stop the web server then type:$ sudo /etc/init.d/apache2 stopTo check it Type:$ netstat -an|moreNow our web server is no more listening.
$ sudo /etc/init.d/apache2 stop
To check it Type:
$ netstat -an|more
Now our web server is no more listening.
To start our web server, type:$ sudo /etc/init.d/apache2 start
$ sudo /etc/init.d/apache2 start
To Restart our web server, type:$ sudo /etc/init.d/apache2 restartTo check, Type:$ netstat -an|moreNow our server is running.
$ sudo /etc/init.d/apache2 restart
To check, Type:
$ netstat -an|more
Now our server is running.
Now We have to create and edit our Webpage. So type the following command:
$ cd /var/www
Press ENTER to continue.
:/var/www$ ls
Press ENTER to continue.
index.html
This βindex.htmlβ is the default Webpage in the Apache. To edit the Webpage, type the Command:
:/var/www$ sudo nano index.html
<html><head><title>Dans Homepage</title></head><body><h1>Welcome to my webpage!</h1><p>This website is under construction.</p></body></html>
Press CTRL+X to save and exit.
Type localhost or Your IP address on the address bar of a web browser. βindex.htmlβ page will be displayed.
Apache
linux-command
Picked
Technical Scripter 2018
Technical Scripter
TechTips
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Find the Wi-Fi Password Using CMD in Windows?
Docker - COPY Instruction
Setting up the environment in Java
How to Run a Python Script using Docker?
Running Python script on GPU.
Top Programming Languages for Android App Development
How to setup cron jobs in Ubuntu
'dd' command in Linux
How to Add External JAR File to an IntelliJ IDEA Project?
How to Delete Temporary Files in Windows 10?
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n03 Jan, 2019"
},
{
"code": null,
"e": 228,
"s": 54,
"text": "Majority of worldβs websites are hosted on are hosted on Apache Web Servers and the majority of those servers run Apache in Linux. Letβs see how to install Apache in Ubuntu:"
},
{
"code": null,
"e": 298,
"s": 228,
"text": "Type the following commands in terminal application on your computer:"
},
{
"code": null,
"e": 352,
"s": 298,
"text": "$ sudo apt-get update\n$ sudo apt-get install apache2\n"
},
{
"code": null,
"e": 425,
"s": 352,
"text": "Now type localhost on your browser. It will pop up a message βIT WORKSβ."
},
{
"code": null,
"e": 576,
"s": 425,
"text": "There is also another way to check whether Apache Services running in the browser or not. To check, first find the IP Address using the below command:"
},
{
"code": null,
"e": 586,
"s": 576,
"text": "$ifconfig"
},
{
"code": null,
"e": 733,
"s": 586,
"text": "Now, put that IP address on the browser. The same message is being displayed βIT WORKSβ. This ensures that Apache service keeps running in Ubuntu."
},
{
"code": null,
"e": 773,
"s": 733,
"text": "To find out the active ports then type:"
},
{
"code": null,
"e": 791,
"s": 773,
"text": "$ netstat -a|more"
},
{
"code": null,
"e": 954,
"s": 791,
"text": "Here we get all of the ports, our active connections, our virtual ports essentially that our computer is listening. If you need to get the port numbers then type:"
},
{
"code": null,
"e": 973,
"s": 954,
"text": "$ netstat -an|more"
},
{
"code": null,
"e": 1102,
"s": 973,
"text": "It shows port80, the port for the web server, port for HTTP, it listens to every address available. Our web server is listening."
},
{
"code": null,
"e": 1119,
"s": 1102,
"text": "Characteristics:"
},
{
"code": null,
"e": 1259,
"s": 1119,
"text": "To stop the web server then type:$ sudo /etc/init.d/apache2 stopTo check it Type:$ netstat -an|moreNow our web server is no more listening."
},
{
"code": null,
"e": 1291,
"s": 1259,
"text": "$ sudo /etc/init.d/apache2 stop"
},
{
"code": null,
"e": 1309,
"s": 1291,
"text": "To check it Type:"
},
{
"code": null,
"e": 1328,
"s": 1309,
"text": "$ netstat -an|more"
},
{
"code": null,
"e": 1369,
"s": 1328,
"text": "Now our web server is no more listening."
},
{
"code": null,
"e": 1432,
"s": 1369,
"text": "To start our web server, type:$ sudo /etc/init.d/apache2 start"
},
{
"code": null,
"e": 1465,
"s": 1432,
"text": "$ sudo /etc/init.d/apache2 start"
},
{
"code": null,
"e": 1591,
"s": 1465,
"text": "To Restart our web server, type:$ sudo /etc/init.d/apache2 restartTo check, Type:$ netstat -an|moreNow our server is running."
},
{
"code": null,
"e": 1626,
"s": 1591,
"text": "$ sudo /etc/init.d/apache2 restart"
},
{
"code": null,
"e": 1642,
"s": 1626,
"text": "To check, Type:"
},
{
"code": null,
"e": 1661,
"s": 1642,
"text": "$ netstat -an|more"
},
{
"code": null,
"e": 1688,
"s": 1661,
"text": "Now our server is running."
},
{
"code": null,
"e": 1763,
"s": 1688,
"text": "Now We have to create and edit our Webpage. So type the following command:"
},
{
"code": null,
"e": 1777,
"s": 1763,
"text": "$ cd /var/www"
},
{
"code": null,
"e": 1802,
"s": 1777,
"text": "Press ENTER to continue."
},
{
"code": null,
"e": 1816,
"s": 1802,
"text": ":/var/www$ ls"
},
{
"code": null,
"e": 1841,
"s": 1816,
"text": "Press ENTER to continue."
},
{
"code": null,
"e": 1852,
"s": 1841,
"text": "index.html"
},
{
"code": null,
"e": 1947,
"s": 1852,
"text": "This βindex.htmlβ is the default Webpage in the Apache. To edit the Webpage, type the Command:"
},
{
"code": null,
"e": 1979,
"s": 1947,
"text": ":/var/www$ sudo nano index.html"
},
{
"code": "<html><head><title>Dans Homepage</title></head><body><h1>Welcome to my webpage!</h1><p>This website is under construction.</p></body></html>",
"e": 2120,
"s": 1979,
"text": null
},
{
"code": null,
"e": 2151,
"s": 2120,
"text": "Press CTRL+X to save and exit."
},
{
"code": null,
"e": 2259,
"s": 2151,
"text": "Type localhost or Your IP address on the address bar of a web browser. βindex.htmlβ page will be displayed."
},
{
"code": null,
"e": 2266,
"s": 2259,
"text": "Apache"
},
{
"code": null,
"e": 2280,
"s": 2266,
"text": "linux-command"
},
{
"code": null,
"e": 2287,
"s": 2280,
"text": "Picked"
},
{
"code": null,
"e": 2311,
"s": 2287,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 2330,
"s": 2311,
"text": "Technical Scripter"
},
{
"code": null,
"e": 2339,
"s": 2330,
"text": "TechTips"
},
{
"code": null,
"e": 2437,
"s": 2339,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2490,
"s": 2437,
"text": "How to Find the Wi-Fi Password Using CMD in Windows?"
},
{
"code": null,
"e": 2516,
"s": 2490,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 2551,
"s": 2516,
"text": "Setting up the environment in Java"
},
{
"code": null,
"e": 2592,
"s": 2551,
"text": "How to Run a Python Script using Docker?"
},
{
"code": null,
"e": 2622,
"s": 2592,
"text": "Running Python script on GPU."
},
{
"code": null,
"e": 2676,
"s": 2622,
"text": "Top Programming Languages for Android App Development"
},
{
"code": null,
"e": 2709,
"s": 2676,
"text": "How to setup cron jobs in Ubuntu"
},
{
"code": null,
"e": 2731,
"s": 2709,
"text": "'dd' command in Linux"
},
{
"code": null,
"e": 2789,
"s": 2731,
"text": "How to Add External JAR File to an IntelliJ IDEA Project?"
}
] |
PHP | Inserting into MySQL database
|
21 Mar, 2018
Prerequisites : MySQL introduction, Creating MySQL databaseINSERT INTO statement is used to insert new rows in a database table. Letβs see the syntax how to insert into table, considering database already exists.
SYNTAX :
INSERT INTO TABLE_NAME (column1, column2, column3, ... columnN)
VALUES (value1, value2, value3, ...valueN);
Here, column1, column2, column3, ...columnN are the names of the columns in the table into which you want to insert the data.You may not need to specify the column(s) name in the SQL query if you are adding values for all the columns of the table. But make sure the order of the values is in the same order as the columns in the table.
So to create a SQL query using the INSERT INTO statement with appropriate values, hereβs an example, which will insert a new row to the newDB table by specifying values for the first_name, last_name and email fields.
Creating table using MySQLi Object-oriented Procedure :<?php $mysqli = new mysqli("localhost", "root", "", "newdb"); if ($mysqli == = false) { die("ERROR: Could not connect. ".$mysqli->connect_error);} $sql = "INSERT INTO mytable (first_name, last_name, age) VALUES('ram', 'singh', '25') "; if ($mysqli->query($sql) == = true){ echo "Records inserted successfully.";}else{ echo "ERROR: Could not able to execute $sql. " .$mysqli->error;} // Close connection$mysqli->close();? >Output :Creating table using MySQLi Procedural Procedure :<?php $link = mysqli_connect("localhost", "root", "", "newdb"); if ($link == = false) { die("ERROR: Could not connect. ".mysqli_connect_error());} $sql = "INSERT INTO mytable (first_name, last_name, age) VALUES('ram', 'singh', '25') "; if (mysqli_query($link, $sql)){ echo "Records inserted successfully.";}else{ echo "ERROR: Could not able to execute $sql. " .mysqli_error($link);} mysqli_close($link);? >Output :Creating table using MySQLi PDO Procedure :<?phptry { $pdo = new PDO("mysql:host=localhost;dbname=newdb", "root", ""); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);}catch (PDOException $e) { die("ERROR: Could not connect. ".$e->getMessage());} try { $sql = "INSERT INTO mytable (first_name, last_name, age) VALUES('ram', 'singh', '25') "; $pdo->exec($sql); echo "Records inserted successfully.";}catch (PDOException $e) { die("ERROR: Could not able to execute $sql. " .$e->getMessage());} // Close connectionunset($pdo);? >Output :
Creating table using MySQLi Object-oriented Procedure :<?php $mysqli = new mysqli("localhost", "root", "", "newdb"); if ($mysqli == = false) { die("ERROR: Could not connect. ".$mysqli->connect_error);} $sql = "INSERT INTO mytable (first_name, last_name, age) VALUES('ram', 'singh', '25') "; if ($mysqli->query($sql) == = true){ echo "Records inserted successfully.";}else{ echo "ERROR: Could not able to execute $sql. " .$mysqli->error;} // Close connection$mysqli->close();? >Output :
<?php $mysqli = new mysqli("localhost", "root", "", "newdb"); if ($mysqli == = false) { die("ERROR: Could not connect. ".$mysqli->connect_error);} $sql = "INSERT INTO mytable (first_name, last_name, age) VALUES('ram', 'singh', '25') "; if ($mysqli->query($sql) == = true){ echo "Records inserted successfully.";}else{ echo "ERROR: Could not able to execute $sql. " .$mysqli->error;} // Close connection$mysqli->close();? >
Output :
Creating table using MySQLi Procedural Procedure :<?php $link = mysqli_connect("localhost", "root", "", "newdb"); if ($link == = false) { die("ERROR: Could not connect. ".mysqli_connect_error());} $sql = "INSERT INTO mytable (first_name, last_name, age) VALUES('ram', 'singh', '25') "; if (mysqli_query($link, $sql)){ echo "Records inserted successfully.";}else{ echo "ERROR: Could not able to execute $sql. " .mysqli_error($link);} mysqli_close($link);? >Output :
<?php $link = mysqli_connect("localhost", "root", "", "newdb"); if ($link == = false) { die("ERROR: Could not connect. ".mysqli_connect_error());} $sql = "INSERT INTO mytable (first_name, last_name, age) VALUES('ram', 'singh', '25') "; if (mysqli_query($link, $sql)){ echo "Records inserted successfully.";}else{ echo "ERROR: Could not able to execute $sql. " .mysqli_error($link);} mysqli_close($link);? >
Output :
Creating table using MySQLi PDO Procedure :<?phptry { $pdo = new PDO("mysql:host=localhost;dbname=newdb", "root", ""); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);}catch (PDOException $e) { die("ERROR: Could not connect. ".$e->getMessage());} try { $sql = "INSERT INTO mytable (first_name, last_name, age) VALUES('ram', 'singh', '25') "; $pdo->exec($sql); echo "Records inserted successfully.";}catch (PDOException $e) { die("ERROR: Could not able to execute $sql. " .$e->getMessage());} // Close connectionunset($pdo);? >Output :
<?phptry { $pdo = new PDO("mysql:host=localhost;dbname=newdb", "root", ""); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);}catch (PDOException $e) { die("ERROR: Could not connect. ".$e->getMessage());} try { $sql = "INSERT INTO mytable (first_name, last_name, age) VALUES('ram', 'singh', '25') "; $pdo->exec($sql); echo "Records inserted successfully.";}catch (PDOException $e) { die("ERROR: Could not able to execute $sql. " .$e->getMessage());} // Close connectionunset($pdo);? >
Output :
The values of the table can be viewed in MySql database as β
One can also insert multiple rows into a table with a single insert query at once. To do this, include multiple lists of column values within the INSERT INTO statement, where column values for each row must be enclosed within parentheses and separated by a comma.
Creating table using MySQLi Object-oriented Procedure :<?php $mysqli = new mysqli("localhost", "root", "", "newdb"); if ($mysqli == = false) { die("ERROR: Could not connect. ".$mysqli->connect_error);} $sql = "INSERT INTO mytable (first_name, last_name, age) VALUES('raj', 'sharma', '15'), ('kapil', 'verma', '42'), ('monty', 'singh', '29'), ('arjun', 'patel', '32') "; if ($mysqli->query($sql) == = true){ echo "Records inserted successfully.";}else{ echo "ERROR: Could not able to execute $sql. " .$mysqli->error;} $mysqli->close();? >Output :Creating table using MySQLi Procedural Procedure :<?php $link = mysqli_connect("localhost", "root", "", "newdb"); if ($link == = false) { die("ERROR: Could not connect. ".mysqli_connect_error());} $sql = "INSERT INTO mytable (first_name, last_name, age) VALUES('raj', 'sharma', '15'), ('kapil', 'verma', '42'), ('monty', 'singh', '29'), ('arjun', 'patel', '32') "; if (mysqli_query($link, $sql)){ echo "Records added successfully.";}else{ echo "ERROR: Could not able to execute $sql. " .mysqli_error($link);} // Close connectionmysqli_close($link);? >Output :Creating table using MySQLi PDO Procedure :<?php try { $pdo = new PDO("mysql:host=localhost;dbname="newdb", "root", ""); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);}catch (PDOException $e) { die("ERROR: Could not connect. ".$e->getMessage());} try { $sql = "INSERT INTO mytable (first_name, last_name, age) VALUES('raj', 'sharma', '15'), ('kapil', 'verma', '42'), ('monty', 'singh', '29'), ('arjun', 'patel', '32') "; $pdo->exec($sql); echo "Records inserted successfully.";}catch (PDOException $e) { die("ERROR: Could not able to execute $sql. " .$e->getMessage());}unset($pdo);? >
Creating table using MySQLi Object-oriented Procedure :<?php $mysqli = new mysqli("localhost", "root", "", "newdb"); if ($mysqli == = false) { die("ERROR: Could not connect. ".$mysqli->connect_error);} $sql = "INSERT INTO mytable (first_name, last_name, age) VALUES('raj', 'sharma', '15'), ('kapil', 'verma', '42'), ('monty', 'singh', '29'), ('arjun', 'patel', '32') "; if ($mysqli->query($sql) == = true){ echo "Records inserted successfully.";}else{ echo "ERROR: Could not able to execute $sql. " .$mysqli->error;} $mysqli->close();? >Output :
<?php $mysqli = new mysqli("localhost", "root", "", "newdb"); if ($mysqli == = false) { die("ERROR: Could not connect. ".$mysqli->connect_error);} $sql = "INSERT INTO mytable (first_name, last_name, age) VALUES('raj', 'sharma', '15'), ('kapil', 'verma', '42'), ('monty', 'singh', '29'), ('arjun', 'patel', '32') "; if ($mysqli->query($sql) == = true){ echo "Records inserted successfully.";}else{ echo "ERROR: Could not able to execute $sql. " .$mysqli->error;} $mysqli->close();? >
Output :
Creating table using MySQLi Procedural Procedure :<?php $link = mysqli_connect("localhost", "root", "", "newdb"); if ($link == = false) { die("ERROR: Could not connect. ".mysqli_connect_error());} $sql = "INSERT INTO mytable (first_name, last_name, age) VALUES('raj', 'sharma', '15'), ('kapil', 'verma', '42'), ('monty', 'singh', '29'), ('arjun', 'patel', '32') "; if (mysqli_query($link, $sql)){ echo "Records added successfully.";}else{ echo "ERROR: Could not able to execute $sql. " .mysqli_error($link);} // Close connectionmysqli_close($link);? >Output :
<?php $link = mysqli_connect("localhost", "root", "", "newdb"); if ($link == = false) { die("ERROR: Could not connect. ".mysqli_connect_error());} $sql = "INSERT INTO mytable (first_name, last_name, age) VALUES('raj', 'sharma', '15'), ('kapil', 'verma', '42'), ('monty', 'singh', '29'), ('arjun', 'patel', '32') "; if (mysqli_query($link, $sql)){ echo "Records added successfully.";}else{ echo "ERROR: Could not able to execute $sql. " .mysqli_error($link);} // Close connectionmysqli_close($link);? >
Output :
Creating table using MySQLi PDO Procedure :<?php try { $pdo = new PDO("mysql:host=localhost;dbname="newdb", "root", ""); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);}catch (PDOException $e) { die("ERROR: Could not connect. ".$e->getMessage());} try { $sql = "INSERT INTO mytable (first_name, last_name, age) VALUES('raj', 'sharma', '15'), ('kapil', 'verma', '42'), ('monty', 'singh', '29'), ('arjun', 'patel', '32') "; $pdo->exec($sql); echo "Records inserted successfully.";}catch (PDOException $e) { die("ERROR: Could not able to execute $sql. " .$e->getMessage());}unset($pdo);? >
<?php try { $pdo = new PDO("mysql:host=localhost;dbname="newdb", "root", ""); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);}catch (PDOException $e) { die("ERROR: Could not connect. ".$e->getMessage());} try { $sql = "INSERT INTO mytable (first_name, last_name, age) VALUES('raj', 'sharma', '15'), ('kapil', 'verma', '42'), ('monty', 'singh', '29'), ('arjun', 'patel', '32') "; $pdo->exec($sql); echo "Records inserted successfully.";}catch (PDOException $e) { die("ERROR: Could not able to execute $sql. " .$e->getMessage());}unset($pdo);? >
Output :
The values of the table can be viewed in MySql database as β
mysql
PHP
SQL
Web Technologies
SQL
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
PHP | Converting string to Date and DateTime
SQL | DDL, DQL, DML, DCL and TCL Commands
SQL | WITH clause
How to find Nth highest salary from a table
CTE in SQL
SQL | ALTER (RENAME)
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n21 Mar, 2018"
},
{
"code": null,
"e": 265,
"s": 52,
"text": "Prerequisites : MySQL introduction, Creating MySQL databaseINSERT INTO statement is used to insert new rows in a database table. Letβs see the syntax how to insert into table, considering database already exists."
},
{
"code": null,
"e": 274,
"s": 265,
"text": "SYNTAX :"
},
{
"code": null,
"e": 383,
"s": 274,
"text": "INSERT INTO TABLE_NAME (column1, column2, column3, ... columnN) \nVALUES (value1, value2, value3, ...valueN);"
},
{
"code": null,
"e": 719,
"s": 383,
"text": "Here, column1, column2, column3, ...columnN are the names of the columns in the table into which you want to insert the data.You may not need to specify the column(s) name in the SQL query if you are adding values for all the columns of the table. But make sure the order of the values is in the same order as the columns in the table."
},
{
"code": null,
"e": 936,
"s": 719,
"text": "So to create a SQL query using the INSERT INTO statement with appropriate values, hereβs an example, which will insert a new row to the newDB table by specifying values for the first_name, last_name and email fields."
},
{
"code": null,
"e": 2601,
"s": 936,
"text": "Creating table using MySQLi Object-oriented Procedure :<?php $mysqli = new mysqli(\"localhost\", \"root\", \"\", \"newdb\"); if ($mysqli == = false) { die(\"ERROR: Could not connect. \".$mysqli->connect_error);} $sql = \"INSERT INTO mytable (first_name, last_name, age) VALUES('ram', 'singh', '25') \"; if ($mysqli->query($sql) == = true){ echo \"Records inserted successfully.\";}else{ echo \"ERROR: Could not able to execute $sql. \" .$mysqli->error;} // Close connection$mysqli->close();? >Output :Creating table using MySQLi Procedural Procedure :<?php $link = mysqli_connect(\"localhost\", \"root\", \"\", \"newdb\"); if ($link == = false) { die(\"ERROR: Could not connect. \".mysqli_connect_error());} $sql = \"INSERT INTO mytable (first_name, last_name, age) VALUES('ram', 'singh', '25') \"; if (mysqli_query($link, $sql)){ echo \"Records inserted successfully.\";}else{ echo \"ERROR: Could not able to execute $sql. \" .mysqli_error($link);} mysqli_close($link);? >Output :Creating table using MySQLi PDO Procedure :<?phptry { $pdo = new PDO(\"mysql:host=localhost;dbname=newdb\", \"root\", \"\"); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);}catch (PDOException $e) { die(\"ERROR: Could not connect. \".$e->getMessage());} try { $sql = \"INSERT INTO mytable (first_name, last_name, age) VALUES('ram', 'singh', '25') \"; $pdo->exec($sql); echo \"Records inserted successfully.\";}catch (PDOException $e) { die(\"ERROR: Could not able to execute $sql. \" .$e->getMessage());} // Close connectionunset($pdo);? >Output :"
},
{
"code": null,
"e": 3125,
"s": 2601,
"text": "Creating table using MySQLi Object-oriented Procedure :<?php $mysqli = new mysqli(\"localhost\", \"root\", \"\", \"newdb\"); if ($mysqli == = false) { die(\"ERROR: Could not connect. \".$mysqli->connect_error);} $sql = \"INSERT INTO mytable (first_name, last_name, age) VALUES('ram', 'singh', '25') \"; if ($mysqli->query($sql) == = true){ echo \"Records inserted successfully.\";}else{ echo \"ERROR: Could not able to execute $sql. \" .$mysqli->error;} // Close connection$mysqli->close();? >Output :"
},
{
"code": "<?php $mysqli = new mysqli(\"localhost\", \"root\", \"\", \"newdb\"); if ($mysqli == = false) { die(\"ERROR: Could not connect. \".$mysqli->connect_error);} $sql = \"INSERT INTO mytable (first_name, last_name, age) VALUES('ram', 'singh', '25') \"; if ($mysqli->query($sql) == = true){ echo \"Records inserted successfully.\";}else{ echo \"ERROR: Could not able to execute $sql. \" .$mysqli->error;} // Close connection$mysqli->close();? >",
"e": 3586,
"s": 3125,
"text": null
},
{
"code": null,
"e": 3595,
"s": 3586,
"text": "Output :"
},
{
"code": null,
"e": 4092,
"s": 3595,
"text": "Creating table using MySQLi Procedural Procedure :<?php $link = mysqli_connect(\"localhost\", \"root\", \"\", \"newdb\"); if ($link == = false) { die(\"ERROR: Could not connect. \".mysqli_connect_error());} $sql = \"INSERT INTO mytable (first_name, last_name, age) VALUES('ram', 'singh', '25') \"; if (mysqli_query($link, $sql)){ echo \"Records inserted successfully.\";}else{ echo \"ERROR: Could not able to execute $sql. \" .mysqli_error($link);} mysqli_close($link);? >Output :"
},
{
"code": "<?php $link = mysqli_connect(\"localhost\", \"root\", \"\", \"newdb\"); if ($link == = false) { die(\"ERROR: Could not connect. \".mysqli_connect_error());} $sql = \"INSERT INTO mytable (first_name, last_name, age) VALUES('ram', 'singh', '25') \"; if (mysqli_query($link, $sql)){ echo \"Records inserted successfully.\";}else{ echo \"ERROR: Could not able to execute $sql. \" .mysqli_error($link);} mysqli_close($link);? >",
"e": 4531,
"s": 4092,
"text": null
},
{
"code": null,
"e": 4540,
"s": 4531,
"text": "Output :"
},
{
"code": null,
"e": 5186,
"s": 4540,
"text": "Creating table using MySQLi PDO Procedure :<?phptry { $pdo = new PDO(\"mysql:host=localhost;dbname=newdb\", \"root\", \"\"); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);}catch (PDOException $e) { die(\"ERROR: Could not connect. \".$e->getMessage());} try { $sql = \"INSERT INTO mytable (first_name, last_name, age) VALUES('ram', 'singh', '25') \"; $pdo->exec($sql); echo \"Records inserted successfully.\";}catch (PDOException $e) { die(\"ERROR: Could not able to execute $sql. \" .$e->getMessage());} // Close connectionunset($pdo);? >Output :"
},
{
"code": "<?phptry { $pdo = new PDO(\"mysql:host=localhost;dbname=newdb\", \"root\", \"\"); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);}catch (PDOException $e) { die(\"ERROR: Could not connect. \".$e->getMessage());} try { $sql = \"INSERT INTO mytable (first_name, last_name, age) VALUES('ram', 'singh', '25') \"; $pdo->exec($sql); echo \"Records inserted successfully.\";}catch (PDOException $e) { die(\"ERROR: Could not able to execute $sql. \" .$e->getMessage());} // Close connectionunset($pdo);? >",
"e": 5781,
"s": 5186,
"text": null
},
{
"code": null,
"e": 5790,
"s": 5781,
"text": "Output :"
},
{
"code": null,
"e": 5851,
"s": 5790,
"text": "The values of the table can be viewed in MySql database as β"
},
{
"code": null,
"e": 6115,
"s": 5851,
"text": "One can also insert multiple rows into a table with a single insert query at once. To do this, include multiple lists of column values within the INSERT INTO statement, where column values for each row must be enclosed within parentheses and separated by a comma."
},
{
"code": null,
"e": 8039,
"s": 6115,
"text": "Creating table using MySQLi Object-oriented Procedure :<?php $mysqli = new mysqli(\"localhost\", \"root\", \"\", \"newdb\"); if ($mysqli == = false) { die(\"ERROR: Could not connect. \".$mysqli->connect_error);} $sql = \"INSERT INTO mytable (first_name, last_name, age) VALUES('raj', 'sharma', '15'), ('kapil', 'verma', '42'), ('monty', 'singh', '29'), ('arjun', 'patel', '32') \"; if ($mysqli->query($sql) == = true){ echo \"Records inserted successfully.\";}else{ echo \"ERROR: Could not able to execute $sql. \" .$mysqli->error;} $mysqli->close();? >Output :Creating table using MySQLi Procedural Procedure :<?php $link = mysqli_connect(\"localhost\", \"root\", \"\", \"newdb\"); if ($link == = false) { die(\"ERROR: Could not connect. \".mysqli_connect_error());} $sql = \"INSERT INTO mytable (first_name, last_name, age) VALUES('raj', 'sharma', '15'), ('kapil', 'verma', '42'), ('monty', 'singh', '29'), ('arjun', 'patel', '32') \"; if (mysqli_query($link, $sql)){ echo \"Records added successfully.\";}else{ echo \"ERROR: Could not able to execute $sql. \" .mysqli_error($link);} // Close connectionmysqli_close($link);? >Output :Creating table using MySQLi PDO Procedure :<?php try { $pdo = new PDO(\"mysql:host=localhost;dbname=\"newdb\", \"root\", \"\"); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);}catch (PDOException $e) { die(\"ERROR: Could not connect. \".$e->getMessage());} try { $sql = \"INSERT INTO mytable (first_name, last_name, age) VALUES('raj', 'sharma', '15'), ('kapil', 'verma', '42'), ('monty', 'singh', '29'), ('arjun', 'patel', '32') \"; $pdo->exec($sql); echo \"Records inserted successfully.\";}catch (PDOException $e) { die(\"ERROR: Could not able to execute $sql. \" .$e->getMessage());}unset($pdo);? >"
},
{
"code": null,
"e": 8627,
"s": 8039,
"text": "Creating table using MySQLi Object-oriented Procedure :<?php $mysqli = new mysqli(\"localhost\", \"root\", \"\", \"newdb\"); if ($mysqli == = false) { die(\"ERROR: Could not connect. \".$mysqli->connect_error);} $sql = \"INSERT INTO mytable (first_name, last_name, age) VALUES('raj', 'sharma', '15'), ('kapil', 'verma', '42'), ('monty', 'singh', '29'), ('arjun', 'patel', '32') \"; if ($mysqli->query($sql) == = true){ echo \"Records inserted successfully.\";}else{ echo \"ERROR: Could not able to execute $sql. \" .$mysqli->error;} $mysqli->close();? >Output :"
},
{
"code": "<?php $mysqli = new mysqli(\"localhost\", \"root\", \"\", \"newdb\"); if ($mysqli == = false) { die(\"ERROR: Could not connect. \".$mysqli->connect_error);} $sql = \"INSERT INTO mytable (first_name, last_name, age) VALUES('raj', 'sharma', '15'), ('kapil', 'verma', '42'), ('monty', 'singh', '29'), ('arjun', 'patel', '32') \"; if ($mysqli->query($sql) == = true){ echo \"Records inserted successfully.\";}else{ echo \"ERROR: Could not able to execute $sql. \" .$mysqli->error;} $mysqli->close();? >",
"e": 9152,
"s": 8627,
"text": null
},
{
"code": null,
"e": 9161,
"s": 9152,
"text": "Output :"
},
{
"code": null,
"e": 9762,
"s": 9161,
"text": "Creating table using MySQLi Procedural Procedure :<?php $link = mysqli_connect(\"localhost\", \"root\", \"\", \"newdb\"); if ($link == = false) { die(\"ERROR: Could not connect. \".mysqli_connect_error());} $sql = \"INSERT INTO mytable (first_name, last_name, age) VALUES('raj', 'sharma', '15'), ('kapil', 'verma', '42'), ('monty', 'singh', '29'), ('arjun', 'patel', '32') \"; if (mysqli_query($link, $sql)){ echo \"Records added successfully.\";}else{ echo \"ERROR: Could not able to execute $sql. \" .mysqli_error($link);} // Close connectionmysqli_close($link);? >Output :"
},
{
"code": "<?php $link = mysqli_connect(\"localhost\", \"root\", \"\", \"newdb\"); if ($link == = false) { die(\"ERROR: Could not connect. \".mysqli_connect_error());} $sql = \"INSERT INTO mytable (first_name, last_name, age) VALUES('raj', 'sharma', '15'), ('kapil', 'verma', '42'), ('monty', 'singh', '29'), ('arjun', 'patel', '32') \"; if (mysqli_query($link, $sql)){ echo \"Records added successfully.\";}else{ echo \"ERROR: Could not able to execute $sql. \" .mysqli_error($link);} // Close connectionmysqli_close($link);? >",
"e": 10305,
"s": 9762,
"text": null
},
{
"code": null,
"e": 10314,
"s": 10305,
"text": "Output :"
},
{
"code": null,
"e": 11051,
"s": 10314,
"text": "Creating table using MySQLi PDO Procedure :<?php try { $pdo = new PDO(\"mysql:host=localhost;dbname=\"newdb\", \"root\", \"\"); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);}catch (PDOException $e) { die(\"ERROR: Could not connect. \".$e->getMessage());} try { $sql = \"INSERT INTO mytable (first_name, last_name, age) VALUES('raj', 'sharma', '15'), ('kapil', 'verma', '42'), ('monty', 'singh', '29'), ('arjun', 'patel', '32') \"; $pdo->exec($sql); echo \"Records inserted successfully.\";}catch (PDOException $e) { die(\"ERROR: Could not able to execute $sql. \" .$e->getMessage());}unset($pdo);? >"
},
{
"code": "<?php try { $pdo = new PDO(\"mysql:host=localhost;dbname=\"newdb\", \"root\", \"\"); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);}catch (PDOException $e) { die(\"ERROR: Could not connect. \".$e->getMessage());} try { $sql = \"INSERT INTO mytable (first_name, last_name, age) VALUES('raj', 'sharma', '15'), ('kapil', 'verma', '42'), ('monty', 'singh', '29'), ('arjun', 'patel', '32') \"; $pdo->exec($sql); echo \"Records inserted successfully.\";}catch (PDOException $e) { die(\"ERROR: Could not able to execute $sql. \" .$e->getMessage());}unset($pdo);? >",
"e": 11745,
"s": 11051,
"text": null
},
{
"code": null,
"e": 11754,
"s": 11745,
"text": "Output :"
},
{
"code": null,
"e": 11815,
"s": 11754,
"text": "The values of the table can be viewed in MySql database as β"
},
{
"code": null,
"e": 11821,
"s": 11815,
"text": "mysql"
},
{
"code": null,
"e": 11825,
"s": 11821,
"text": "PHP"
},
{
"code": null,
"e": 11829,
"s": 11825,
"text": "SQL"
},
{
"code": null,
"e": 11846,
"s": 11829,
"text": "Web Technologies"
},
{
"code": null,
"e": 11850,
"s": 11846,
"text": "SQL"
},
{
"code": null,
"e": 11854,
"s": 11850,
"text": "PHP"
},
{
"code": null,
"e": 11952,
"s": 11854,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 12002,
"s": 11952,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 12042,
"s": 12002,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 12103,
"s": 12042,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 12153,
"s": 12103,
"text": "How to check whether an array is empty using PHP?"
},
{
"code": null,
"e": 12198,
"s": 12153,
"text": "PHP | Converting string to Date and DateTime"
},
{
"code": null,
"e": 12240,
"s": 12198,
"text": "SQL | DDL, DQL, DML, DCL and TCL Commands"
},
{
"code": null,
"e": 12258,
"s": 12240,
"text": "SQL | WITH clause"
},
{
"code": null,
"e": 12302,
"s": 12258,
"text": "How to find Nth highest salary from a table"
},
{
"code": null,
"e": 12313,
"s": 12302,
"text": "CTE in SQL"
}
] |
Creating a Receipt Calculator using Python
|
17 May, 2022
A receipt calculator is generally a slip in which the total invoice along with their names is mentioned. We will use the class PrettyTable inside the prettytable library for making our receipt calculator.
It is a class present inside prettytable library which help us to make relational tables in Python.
Installation of library:
pip install prettytable
Generating PrettyTable :
Initialisation :
<table name> = PrettyTable(['<column1>','<column2>',....])
To add a row :
add_row(['<row1>','<row2>',....])
Approach :
There will be two columns: Item Name & Item Price.
We will keep taking item name and item price (in new line) Until the user enters βqβ and store the price in another variable name βtotalβ initialized as 0. When userEnters βqβ, program will stop taking inputs and return the table along with the total amount specified at the end.
Below is the Implementation:
Python3
from prettytable import PrettyTable print('--------------WELCOME TO XYZ Shop--------------\n')table = PrettyTable(['Item Name', 'Item Price'])total = 0 while(1): name = input('Enter Item name:') # 'q' to exit and print the table if(name != 'q'): price = int(input('Enter the Price:')) # store all the prices in 'total' total += price table.add_row([name, price]) continue elif(name == 'q'): break table.add_row(['TOTAL', total])print(table)print('\nThanks for shopping with us :)')print('Your total bill amount is ', total, '/-')
Output:
Note: You can run this program on any python version except for python2 you just need to change the syntax of print().
Python-projects
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n17 May, 2022"
},
{
"code": null,
"e": 257,
"s": 52,
"text": "A receipt calculator is generally a slip in which the total invoice along with their names is mentioned. We will use the class PrettyTable inside the prettytable library for making our receipt calculator."
},
{
"code": null,
"e": 359,
"s": 257,
"text": "It is a class present inside prettytable library which help us to make relational tables in Python. "
},
{
"code": null,
"e": 384,
"s": 359,
"text": "Installation of library:"
},
{
"code": null,
"e": 408,
"s": 384,
"text": "pip install prettytable"
},
{
"code": null,
"e": 433,
"s": 408,
"text": "Generating PrettyTable :"
},
{
"code": null,
"e": 559,
"s": 433,
"text": "Initialisation :\n<table name> = PrettyTable(['<column1>','<column2>',....])\n\nTo add a row :\nadd_row(['<row1>','<row2>',....])"
},
{
"code": null,
"e": 570,
"s": 559,
"text": "Approach :"
},
{
"code": null,
"e": 622,
"s": 570,
"text": "There will be two columns: Item Name & Item Price. "
},
{
"code": null,
"e": 902,
"s": 622,
"text": "We will keep taking item name and item price (in new line) Until the user enters βqβ and store the price in another variable name βtotalβ initialized as 0. When userEnters βqβ, program will stop taking inputs and return the table along with the total amount specified at the end."
},
{
"code": null,
"e": 931,
"s": 902,
"text": "Below is the Implementation:"
},
{
"code": null,
"e": 939,
"s": 931,
"text": "Python3"
},
{
"code": "from prettytable import PrettyTable print('--------------WELCOME TO XYZ Shop--------------\\n')table = PrettyTable(['Item Name', 'Item Price'])total = 0 while(1): name = input('Enter Item name:') # 'q' to exit and print the table if(name != 'q'): price = int(input('Enter the Price:')) # store all the prices in 'total' total += price table.add_row([name, price]) continue elif(name == 'q'): break table.add_row(['TOTAL', total])print(table)print('\\nThanks for shopping with us :)')print('Your total bill amount is ', total, '/-')",
"e": 1558,
"s": 939,
"text": null
},
{
"code": null,
"e": 1566,
"s": 1558,
"text": "Output:"
},
{
"code": null,
"e": 1685,
"s": 1566,
"text": "Note: You can run this program on any python version except for python2 you just need to change the syntax of print()."
},
{
"code": null,
"e": 1701,
"s": 1685,
"text": "Python-projects"
},
{
"code": null,
"e": 1716,
"s": 1701,
"text": "python-utility"
},
{
"code": null,
"e": 1723,
"s": 1716,
"text": "Python"
}
] |
C++ Program to find Median of Elements where Elements are stored in 2 different arrays
|
We shall consider a C++ program to find the median of elements where elements are stored in 2 different arrays.
Begin
Function Median() has Two arrays a1[], a2[] and n = numbers of elements of the array as arguments:
Initialize i and j by 0, and n1 and n2 by -1
for c in range 0 to n, do
if i = n, then
n1 := n2
n2 := a2[0]
break the loop
else if j = n, then
n1 := n2
n2 := a1[0]
break the loop
if a1[i] < a2[j], then
n1 := n2
n2 := a1[i]
increase i by 1
else
n1 := n2
n2 := a2[i]
increase j by 1
done
return the average of n1 and n2.
End.
#include<iostream>
#include <bits/stdc++.h>
using namespace std;
int Median(int a1[],int a2[], int n) {
int i = 0;
int j = 0;
int c;
int n1 = -1, n2 = -1;
for (c = 0; c <= n; c++) {
if (i == n) {
n1 = n2;
n2 = a2[0];
break;
}
else if (j == n) {
n1 = n2;
n2 = a1[0];
break;
}
if (a1[i] < a2[j]) {
n1 = n2;
n2 = a1[i];
i++;
} else {
n1 = n2;
n2 = a2[j];
j++;
}
}
return (n1 + n2)/2;
}
int main() {
int n1,n2, i;
cout<<"\nEnter the number of elements for 1st array: ";
cin>>n1;
int a1[n1];
for(i = 0; i < n1; i++) {
cout<<"Enter element for 1st array"<<i+1<<": ";
cin>>a1[i];
}
cout<<"\nEnter the number of elements for 2nd array: ";
cin>>n2;
int a2[n2];
for(i = 0; i < n2; i++) {
cout<<"Enter element for 2nd array "<<i+1<<": ";
cin>>a1[i];
}
if (n1 == n2)
cout << "Median is "
<< Median(a1, a2, n1) ;
else
cout << "Doesn't work for arrays"
<< " of unequal size";
return 0;
}
Enter the number of elements for 1st array: 5
Enter element for 1st array1: 2
Enter element for 1st array2: 4
Enter element for 1st array3: 6
Enter element for 1st array4: 7
Enter element for 1st array5: 9
Enter the number of elements for 2nd array: 5
Enter element for 2nd array 1: 20
Enter element for 2nd array 2: 40
Enter element for 2nd array 3: 60
Enter element for 2nd array 4: 70
Enter element for 2nd array 5: 90
Median is 20
|
[
{
"code": null,
"e": 1299,
"s": 1187,
"text": "We shall consider a C++ program to find the median of elements where elements are stored in 2 different arrays."
},
{
"code": null,
"e": 1874,
"s": 1299,
"text": "Begin\n Function Median() has Two arrays a1[], a2[] and n = numbers of elements of the array as arguments:\n Initialize i and j by 0, and n1 and n2 by -1\n for c in range 0 to n, do\n if i = n, then\n n1 := n2\n n2 := a2[0]\n break the loop\n else if j = n, then\n n1 := n2\n n2 := a1[0]\n break the loop\n if a1[i] < a2[j], then\n n1 := n2\n n2 := a1[i]\n increase i by 1\n else\n n1 := n2\n n2 := a2[i]\n increase j by 1\n done\n return the average of n1 and n2.\nEnd."
},
{
"code": null,
"e": 3009,
"s": 1874,
"text": "#include<iostream>\n#include <bits/stdc++.h>\nusing namespace std;\nint Median(int a1[],int a2[], int n) {\n int i = 0;\n int j = 0;\n int c;\n int n1 = -1, n2 = -1;\n for (c = 0; c <= n; c++) {\n if (i == n) {\n n1 = n2;\n n2 = a2[0];\n break;\n }\n else if (j == n) {\n n1 = n2;\n n2 = a1[0];\n break;\n }\n if (a1[i] < a2[j]) {\n n1 = n2;\n n2 = a1[i];\n i++;\n } else {\n n1 = n2;\n n2 = a2[j];\n j++;\n }\n }\n return (n1 + n2)/2;\n}\nint main() {\n int n1,n2, i;\n cout<<\"\\nEnter the number of elements for 1st array: \";\n cin>>n1;\n int a1[n1];\n for(i = 0; i < n1; i++) {\n cout<<\"Enter element for 1st array\"<<i+1<<\": \";\n cin>>a1[i];\n }\n cout<<\"\\nEnter the number of elements for 2nd array: \";\n cin>>n2;\n int a2[n2];\n for(i = 0; i < n2; i++) {\n cout<<\"Enter element for 2nd array \"<<i+1<<\": \";\n cin>>a1[i];\n }\n if (n1 == n2)\n cout << \"Median is \"\n << Median(a1, a2, n1) ;\n else\n cout << \"Doesn't work for arrays\"\n << \" of unequal size\";\n return 0;\n}"
},
{
"code": null,
"e": 3444,
"s": 3009,
"text": "Enter the number of elements for 1st array: 5\nEnter element for 1st array1: 2\nEnter element for 1st array2: 4\nEnter element for 1st array3: 6\nEnter element for 1st array4: 7\nEnter element for 1st array5: 9\nEnter the number of elements for 2nd array: 5\nEnter element for 2nd array 1: 20\nEnter element for 2nd array 2: 40\nEnter element for 2nd array 3: 60\nEnter element for 2nd array 4: 70\nEnter element for 2nd array 5: 90\nMedian is 20"
}
] |
How To Highlight a Time Range in Time Series Plot in Python with Matplotlib?
|
22 Sep, 2021
A time series plot is a plot which contains data which is being measured over a period of time, for example, a gross domestic product of a country, the population of the world and many other data.
Sometimes we want to highlight a specific period of the timeline so that it is easier for the observer to read specific data. We can highlight a time range in time series plot using the pyplot.axvspan() in matplotlib module.
Syntax:
matplotlib.pyplot.axvspan(xmin, xmax, ymin=0, ymax=1, **kwargs)
Parameters:
xmin: Number indicating the starting position of the vertical rectangle on X-axis.
xmin: Number indicating the ending position of the vertical rectangle on X-axis.
ymin: Vertical rectangle starting position on y axis, it will take values between 0 and 1, 0 being bottom of the axis, 1 being top of the axis
ymax: Vertical rectangle ending position on y axis, it will take values between 0 and 1, 0 being bottom of the axis, 1 being top of the axis.
**kwargs: Other optional parameters to change the properties of the rectangle, like changing color etc.
Below are some examples which depict how to highlight a time range in time series plot:
Example 1:
let us assume that we have a country, and we want to draw a plot of its gross domestic product over a span of many years. Firstly we have to prepare our data so that we can plot a graph. On the Y-axis we will be taking GDP which will be random integers from 5 to 10. On the X-axis we will be taking time period from 1900 to 2020.
We will take GDP of a country and highlight it for a certain period of time.
Python3
# import required modulesimport randomimport matplotlib.pyplot as plt # create datasetyear = [i for i in range(1900,2021)]GDP = []for i in range(121): GDP.append(random.randint(5,10)) # display dataset print("Length of year list is: " + str(len(year)))print("Length of GDP list is: " + str(len(GDP)))print("First 10 elements of respective list are: ")print(year[:10])print(GDP[:10])
Output:
Now we will plot a graph of the GDP vs year. We have scaled the Y-axis accordingly.
Python3
# depict time seriesfig, ax = plt.subplots(figsize=(5,5))ymin, ymax = plt. ylim()ax.plot(year,GDP)plt.ylim(ymin * 50, ymax * 50) # adjust labelax.set_ylabel("GDP") # assign titleax.set_title("GDP of country over years" ,size=15)plt.show()
Output:
graph of GDP vs year
The subplot keyword returns the figure i.e. the plot and the array of Axes (stored in ax) which we will use to highlight the graph.
We will use axvspan() method which adds a vertical span (rectangle) across the axes in a given range, and we can then change the color of the rectangle and then reduce its opacity so that it seems that we have highlighted it.
NOTE: Remember to reduce the opacity otherwise it will appear as a solid color rectangle on the graph.The alpha argument used using **kwargs is used to reduce the opacity.
Python3
# depict illustrationfig, ax = plt.subplots(figsize=(5, 5))ymin, ymax = plt. ylim()ax.plot(year, GDP)plt.ylim(ymin * 50, ymax * 50) # adjust labelsax.set_ylabel("GDP") # assign titleax.set_title("GDP of country over years", size=15) # highlight a time rangeax.axvspan(1990, 2010, color="blue", alpha=0.3)plt.show()
highlighted graph of GDP vs year
Example 2:
Here is another program where we will highlight the x-axis for a scatter plot.
Python3
# importing librariesimport matplotlib.pyplot as pltimport random # creating the datasetdate = [i for i in range(2000, 2021)]value = []for i in range(21): value.append(random.randint(5, 15)) # Create a figure and a set of subplotsfig, ax = plt.subplots(figsize=(10, 6)) # Creating the scatter plotax.scatter(date, value) # Highlighting for a certain period of timeax.axvspan(2002, 2005, alpha=0.3, color="green")plt.show()
highlighting over a scatter plot
Example 3 :
Below is another example where we highlight a time range from 2005 to 2010
Python3
# import required modulesimport randomimport matplotlib.pyplot as plt # create datasetx = [int(i) for i in range(2000,2020)]y = [i for i in range(20)] # depict illustrationfig, ax = plt.subplots(figsize=(10, 10))ymin, ymax = plt. ylim()ax.plot(x, y) # highlight a time rangeax.axvspan(2005, 2010, color="green", alpha=0.6)plt.show()
Output:
anikakapoor
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 ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
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
Create a directory in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Sep, 2021"
},
{
"code": null,
"e": 225,
"s": 28,
"text": "A time series plot is a plot which contains data which is being measured over a period of time, for example, a gross domestic product of a country, the population of the world and many other data."
},
{
"code": null,
"e": 450,
"s": 225,
"text": "Sometimes we want to highlight a specific period of the timeline so that it is easier for the observer to read specific data. We can highlight a time range in time series plot using the pyplot.axvspan() in matplotlib module."
},
{
"code": null,
"e": 458,
"s": 450,
"text": "Syntax:"
},
{
"code": null,
"e": 522,
"s": 458,
"text": "matplotlib.pyplot.axvspan(xmin, xmax, ymin=0, ymax=1, **kwargs)"
},
{
"code": null,
"e": 535,
"s": 522,
"text": "Parameters: "
},
{
"code": null,
"e": 618,
"s": 535,
"text": "xmin: Number indicating the starting position of the vertical rectangle on X-axis."
},
{
"code": null,
"e": 699,
"s": 618,
"text": "xmin: Number indicating the ending position of the vertical rectangle on X-axis."
},
{
"code": null,
"e": 842,
"s": 699,
"text": "ymin: Vertical rectangle starting position on y axis, it will take values between 0 and 1, 0 being bottom of the axis, 1 being top of the axis"
},
{
"code": null,
"e": 984,
"s": 842,
"text": "ymax: Vertical rectangle ending position on y axis, it will take values between 0 and 1, 0 being bottom of the axis, 1 being top of the axis."
},
{
"code": null,
"e": 1088,
"s": 984,
"text": "**kwargs: Other optional parameters to change the properties of the rectangle, like changing color etc."
},
{
"code": null,
"e": 1176,
"s": 1088,
"text": "Below are some examples which depict how to highlight a time range in time series plot:"
},
{
"code": null,
"e": 1187,
"s": 1176,
"text": "Example 1:"
},
{
"code": null,
"e": 1517,
"s": 1187,
"text": "let us assume that we have a country, and we want to draw a plot of its gross domestic product over a span of many years. Firstly we have to prepare our data so that we can plot a graph. On the Y-axis we will be taking GDP which will be random integers from 5 to 10. On the X-axis we will be taking time period from 1900 to 2020."
},
{
"code": null,
"e": 1594,
"s": 1517,
"text": "We will take GDP of a country and highlight it for a certain period of time."
},
{
"code": null,
"e": 1602,
"s": 1594,
"text": "Python3"
},
{
"code": "# import required modulesimport randomimport matplotlib.pyplot as plt # create datasetyear = [i for i in range(1900,2021)]GDP = []for i in range(121): GDP.append(random.randint(5,10)) # display dataset print(\"Length of year list is: \" + str(len(year)))print(\"Length of GDP list is: \" + str(len(GDP)))print(\"First 10 elements of respective list are: \")print(year[:10])print(GDP[:10])",
"e": 1994,
"s": 1602,
"text": null
},
{
"code": null,
"e": 2002,
"s": 1994,
"text": "Output:"
},
{
"code": null,
"e": 2086,
"s": 2002,
"text": "Now we will plot a graph of the GDP vs year. We have scaled the Y-axis accordingly."
},
{
"code": null,
"e": 2094,
"s": 2086,
"text": "Python3"
},
{
"code": "# depict time seriesfig, ax = plt.subplots(figsize=(5,5))ymin, ymax = plt. ylim()ax.plot(year,GDP)plt.ylim(ymin * 50, ymax * 50) # adjust labelax.set_ylabel(\"GDP\") # assign titleax.set_title(\"GDP of country over years\" ,size=15)plt.show()",
"e": 2333,
"s": 2094,
"text": null
},
{
"code": null,
"e": 2345,
"s": 2337,
"text": "Output:"
},
{
"code": null,
"e": 2368,
"s": 2347,
"text": "graph of GDP vs year"
},
{
"code": null,
"e": 2502,
"s": 2370,
"text": "The subplot keyword returns the figure i.e. the plot and the array of Axes (stored in ax) which we will use to highlight the graph."
},
{
"code": null,
"e": 2730,
"s": 2504,
"text": "We will use axvspan() method which adds a vertical span (rectangle) across the axes in a given range, and we can then change the color of the rectangle and then reduce its opacity so that it seems that we have highlighted it."
},
{
"code": null,
"e": 2905,
"s": 2732,
"text": "NOTE: Remember to reduce the opacity otherwise it will appear as a solid color rectangle on the graph.The alpha argument used using **kwargs is used to reduce the opacity."
},
{
"code": null,
"e": 2915,
"s": 2907,
"text": "Python3"
},
{
"code": "# depict illustrationfig, ax = plt.subplots(figsize=(5, 5))ymin, ymax = plt. ylim()ax.plot(year, GDP)plt.ylim(ymin * 50, ymax * 50) # adjust labelsax.set_ylabel(\"GDP\") # assign titleax.set_title(\"GDP of country over years\", size=15) # highlight a time rangeax.axvspan(1990, 2010, color=\"blue\", alpha=0.3)plt.show()",
"e": 3230,
"s": 2915,
"text": null
},
{
"code": null,
"e": 3263,
"s": 3230,
"text": "highlighted graph of GDP vs year"
},
{
"code": null,
"e": 3274,
"s": 3263,
"text": "Example 2:"
},
{
"code": null,
"e": 3353,
"s": 3274,
"text": "Here is another program where we will highlight the x-axis for a scatter plot."
},
{
"code": null,
"e": 3361,
"s": 3353,
"text": "Python3"
},
{
"code": "# importing librariesimport matplotlib.pyplot as pltimport random # creating the datasetdate = [i for i in range(2000, 2021)]value = []for i in range(21): value.append(random.randint(5, 15)) # Create a figure and a set of subplotsfig, ax = plt.subplots(figsize=(10, 6)) # Creating the scatter plotax.scatter(date, value) # Highlighting for a certain period of timeax.axvspan(2002, 2005, alpha=0.3, color=\"green\")plt.show()",
"e": 3787,
"s": 3361,
"text": null
},
{
"code": null,
"e": 3821,
"s": 3787,
"text": "highlighting over a scatter plot"
},
{
"code": null,
"e": 3834,
"s": 3821,
"text": "Example 3 : "
},
{
"code": null,
"e": 3909,
"s": 3834,
"text": "Below is another example where we highlight a time range from 2005 to 2010"
},
{
"code": null,
"e": 3917,
"s": 3909,
"text": "Python3"
},
{
"code": "# import required modulesimport randomimport matplotlib.pyplot as plt # create datasetx = [int(i) for i in range(2000,2020)]y = [i for i in range(20)] # depict illustrationfig, ax = plt.subplots(figsize=(10, 10))ymin, ymax = plt. ylim()ax.plot(x, y) # highlight a time rangeax.axvspan(2005, 2010, color=\"green\", alpha=0.6)plt.show()",
"e": 4250,
"s": 3917,
"text": null
},
{
"code": null,
"e": 4258,
"s": 4250,
"text": "Output:"
},
{
"code": null,
"e": 4270,
"s": 4258,
"text": "anikakapoor"
},
{
"code": null,
"e": 4277,
"s": 4270,
"text": "Picked"
},
{
"code": null,
"e": 4295,
"s": 4277,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 4302,
"s": 4295,
"text": "Python"
},
{
"code": null,
"e": 4400,
"s": 4302,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4432,
"s": 4400,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 4459,
"s": 4432,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 4490,
"s": 4459,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 4513,
"s": 4490,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 4534,
"s": 4513,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 4590,
"s": 4534,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 4632,
"s": 4590,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 4674,
"s": 4632,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 4713,
"s": 4674,
"text": "Python | Get unique values from a list"
}
] |
Flip and Invert Matrix in Python
|
Suppose we have a binary matrix mat. We have to select each row in matrix, then reverse the
row. After that, flip each bit (0 to 1 and 1 to 0).
So, if the input is like
then the output will be
To solve this, we will follow these steps β
track:= 0
for each row in mat, doreverse the rowtracker := 0for each val in row, doif val is 1, thenmat[track, tracker] := 0otherwise,mat[track, tracker] := 1tracker := tracker + 1track := track + 1
reverse the row
tracker := 0
for each val in row, doif val is 1, thenmat[track, tracker] := 0otherwise,mat[track, tracker] := 1tracker := tracker + 1
if val is 1, thenmat[track, tracker] := 0
mat[track, tracker] := 0
otherwise,mat[track, tracker] := 1
mat[track, tracker] := 1
tracker := tracker + 1
track := track + 1
return mat
Let us see the following implementation to get better understanding β
Live Demo
class Solution:
def solve(self, mat):
track=0
for row in mat:
row.reverse()
tracker = 0
for val in row:
if val == 1:
mat[track][tracker] = 0
else:
mat[track][tracker] = 1
tracker += 1
track += 1
return mat
ob = Solution()
mat = [[1,1,0],[0,1,0],[0,0,1]]
print(ob.solve(mat))
[[1,1,0],[0,1,0],[0,0,1]]
[[1, 0, 0], [1, 0, 1], [0, 1, 1]]
|
[
{
"code": null,
"e": 1331,
"s": 1187,
"text": "Suppose we have a binary matrix mat. We have to select each row in matrix, then reverse the\nrow. After that, flip each bit (0 to 1 and 1 to 0)."
},
{
"code": null,
"e": 1356,
"s": 1331,
"text": "So, if the input is like"
},
{
"code": null,
"e": 1380,
"s": 1356,
"text": "then the output will be"
},
{
"code": null,
"e": 1424,
"s": 1380,
"text": "To solve this, we will follow these steps β"
},
{
"code": null,
"e": 1434,
"s": 1424,
"text": "track:= 0"
},
{
"code": null,
"e": 1623,
"s": 1434,
"text": "for each row in mat, doreverse the rowtracker := 0for each val in row, doif val is 1, thenmat[track, tracker] := 0otherwise,mat[track, tracker] := 1tracker := tracker + 1track := track + 1"
},
{
"code": null,
"e": 1639,
"s": 1623,
"text": "reverse the row"
},
{
"code": null,
"e": 1652,
"s": 1639,
"text": "tracker := 0"
},
{
"code": null,
"e": 1773,
"s": 1652,
"text": "for each val in row, doif val is 1, thenmat[track, tracker] := 0otherwise,mat[track, tracker] := 1tracker := tracker + 1"
},
{
"code": null,
"e": 1815,
"s": 1773,
"text": "if val is 1, thenmat[track, tracker] := 0"
},
{
"code": null,
"e": 1840,
"s": 1815,
"text": "mat[track, tracker] := 0"
},
{
"code": null,
"e": 1875,
"s": 1840,
"text": "otherwise,mat[track, tracker] := 1"
},
{
"code": null,
"e": 1900,
"s": 1875,
"text": "mat[track, tracker] := 1"
},
{
"code": null,
"e": 1923,
"s": 1900,
"text": "tracker := tracker + 1"
},
{
"code": null,
"e": 1942,
"s": 1923,
"text": "track := track + 1"
},
{
"code": null,
"e": 1953,
"s": 1942,
"text": "return mat"
},
{
"code": null,
"e": 2023,
"s": 1953,
"text": "Let us see the following implementation to get better understanding β"
},
{
"code": null,
"e": 2034,
"s": 2023,
"text": " Live Demo"
},
{
"code": null,
"e": 2432,
"s": 2034,
"text": "class Solution:\n def solve(self, mat):\n track=0\n for row in mat:\n row.reverse()\n tracker = 0\n for val in row:\n if val == 1:\n mat[track][tracker] = 0\n else:\n mat[track][tracker] = 1\n tracker += 1\n track += 1\n return mat\nob = Solution()\nmat = [[1,1,0],[0,1,0],[0,0,1]]\nprint(ob.solve(mat))"
},
{
"code": null,
"e": 2458,
"s": 2432,
"text": "[[1,1,0],[0,1,0],[0,0,1]]"
},
{
"code": null,
"e": 2492,
"s": 2458,
"text": "[[1, 0, 0], [1, 0, 1], [0, 1, 1]]"
}
] |
C# | Func delegate
|
13 Oct, 2019
When we create a custom delegate we have to follow the following steps:
Step 1: Declare a custom delegate with the format which is exactly equal to the method.
Step 2: Create the object of custom delegate.
Step 3: Invoke the method.
By using these steps, we create a custom delegate as shown in the below program. But the problem is that for creating a delegate we need to follow the above procedure. To overcome this situation C# provides a built-in delegate that is Func. Using Func delegate you need not follow the following procedure to create a delegate.
Example:
// C# program to illustrate how to // create custom delegatesusing System; class GFG { // Declaring the delegate public delegate int my_delegate(int s, int d, int f, int g); // Method public static int mymethod(int s, int d, int f, int g) { return s * d * f * g; } // Main method static public void Main() { // Creating object of my_delegate my_delegate obj = mymethod; Console.WriteLine(obj(12, 34, 35, 34)); }}
Output:
485520
A Func is a built-in generic type delegate. This delegate saves you from defining a custom delegate like as shown in the above example and make your program more readable and optimized. As we know that, Func is a generic delegate so it is defined under System namespace. It can contain minimum 0 and maximum of 16 input parameters in it and contain only one out parameter. The last parameter of the Func delegate is the out parameter which is considered as return type and used for the result. Func is generally used for those methods which are going to return a value, or in other words, Func delegate is used for value returning methods. It can also contain parameters of the same type or of different types.
Syntax:
// Zero normal parameters and one result parameterpublic delegate TResult Func<out PResult>();
// One normal parameter and one result parameterpublic delegate TResult Func<in P, out PResult>(P arg);
// Two normal parameters and one result parameterpublic delegate TResult Func<in P1, in P2, out PResult>(P1 arg1, P2 arg2);
// Sixteen normal parameters and one result parameterpublic delegate TResult Func<in P1, in P2, in P3, in P4, in P05, in P6, in P7, in P8, in P9, in P10, in P11, in P12, in P13, in P14, in P15, in P16, out PResult>(P1 arg1, P2 arg2, P3 arg3, P4 arg4, P5 arg5, P6 arg6, P7 arg7, P8 arg8, P9 arg9, P10 arg10, P11 arg11, P12 arg12, P13 arg13, P14 arg14, P15 arg15, P16 arg16);
Here, P1, P2....P16 are the type of input parameters, PResult is the type of output parameter, and arg1....arg16 are the parameter of the method that the Func delegate encapsulates.
Example 1: Here, we use a Func delegate to create a delegate only in a single line without using the above procedure. This Func delegate contains four input parameters and one output parameter.
// C# program to illustrate Func delegateusing System; class GFG { // Method public static int mymethod(int s, int d, int f, int g) { return s * d * f * g; } // Main method static public void Main() { // Using Func delegate // Here, Func delegate contains // the four parameters of int type // one result parameter of int type Func<int, int, int, int, int> val = mymethod; Console.WriteLine(val(10, 100, 1000, 1)); }}
Output:
1000000
Example 2:
// C# program to illustrate Func delegateusing System; class GFG { // Method public static int method(int num) { return num + num; } // Main method static public void Main() { // Using Func delegate // Here, Func delegate contains // the one parameters of int type // one result parameter of int type Func<int, int> myfun = method; Console.WriteLine(myfun(10)); }}
Output:
20
Important Points:
The last parameter in Func Delegate is always an out parameter which is considered as a return type. It is generally used for the result.
You can also use a Func delegate with an anonymous method. As shown in the below example:Example:Func<int, int, int> val = delegate(int x, int y, int z){ return x + y + z;};
Example:
Func<int, int, int> val = delegate(int x, int y, int z){ return x + y + z;};
You can also use a Func delegate with the lambda expressions. As shown in the below example:Example:Func<int, int, int, int> val = (int x, int y, int z) = > x + y + z;
Example:
Func<int, int, int, int> val = (int x, int y, int z) = > x + y + z;
HIMANSHUGARG8
CSharp-Delegates
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to .NET Framework
C# | Multiple inheritance using interfaces
Differences Between .NET Core and .NET Framework
C# | Constructors
C# | String.IndexOf( ) Method | Set - 1
C# | Class and Object
Difference between Ref and Out keywords in C#
C# | Arrays
C# | Encapsulation
C# | Replace() Method
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n13 Oct, 2019"
},
{
"code": null,
"e": 124,
"s": 52,
"text": "When we create a custom delegate we have to follow the following steps:"
},
{
"code": null,
"e": 212,
"s": 124,
"text": "Step 1: Declare a custom delegate with the format which is exactly equal to the method."
},
{
"code": null,
"e": 258,
"s": 212,
"text": "Step 2: Create the object of custom delegate."
},
{
"code": null,
"e": 285,
"s": 258,
"text": "Step 3: Invoke the method."
},
{
"code": null,
"e": 612,
"s": 285,
"text": "By using these steps, we create a custom delegate as shown in the below program. But the problem is that for creating a delegate we need to follow the above procedure. To overcome this situation C# provides a built-in delegate that is Func. Using Func delegate you need not follow the following procedure to create a delegate."
},
{
"code": null,
"e": 621,
"s": 612,
"text": "Example:"
},
{
"code": "// C# program to illustrate how to // create custom delegatesusing System; class GFG { // Declaring the delegate public delegate int my_delegate(int s, int d, int f, int g); // Method public static int mymethod(int s, int d, int f, int g) { return s * d * f * g; } // Main method static public void Main() { // Creating object of my_delegate my_delegate obj = mymethod; Console.WriteLine(obj(12, 34, 35, 34)); }}",
"e": 1164,
"s": 621,
"text": null
},
{
"code": null,
"e": 1172,
"s": 1164,
"text": "Output:"
},
{
"code": null,
"e": 1179,
"s": 1172,
"text": "485520"
},
{
"code": null,
"e": 1890,
"s": 1179,
"text": "A Func is a built-in generic type delegate. This delegate saves you from defining a custom delegate like as shown in the above example and make your program more readable and optimized. As we know that, Func is a generic delegate so it is defined under System namespace. It can contain minimum 0 and maximum of 16 input parameters in it and contain only one out parameter. The last parameter of the Func delegate is the out parameter which is considered as return type and used for the result. Func is generally used for those methods which are going to return a value, or in other words, Func delegate is used for value returning methods. It can also contain parameters of the same type or of different types."
},
{
"code": null,
"e": 1898,
"s": 1890,
"text": "Syntax:"
},
{
"code": null,
"e": 1993,
"s": 1898,
"text": "// Zero normal parameters and one result parameterpublic delegate TResult Func<out PResult>();"
},
{
"code": null,
"e": 2097,
"s": 1993,
"text": "// One normal parameter and one result parameterpublic delegate TResult Func<in P, out PResult>(P arg);"
},
{
"code": null,
"e": 2221,
"s": 2097,
"text": "// Two normal parameters and one result parameterpublic delegate TResult Func<in P1, in P2, out PResult>(P1 arg1, P2 arg2);"
},
{
"code": null,
"e": 2595,
"s": 2221,
"text": "// Sixteen normal parameters and one result parameterpublic delegate TResult Func<in P1, in P2, in P3, in P4, in P05, in P6, in P7, in P8, in P9, in P10, in P11, in P12, in P13, in P14, in P15, in P16, out PResult>(P1 arg1, P2 arg2, P3 arg3, P4 arg4, P5 arg5, P6 arg6, P7 arg7, P8 arg8, P9 arg9, P10 arg10, P11 arg11, P12 arg12, P13 arg13, P14 arg14, P15 arg15, P16 arg16);"
},
{
"code": null,
"e": 2777,
"s": 2595,
"text": "Here, P1, P2....P16 are the type of input parameters, PResult is the type of output parameter, and arg1....arg16 are the parameter of the method that the Func delegate encapsulates."
},
{
"code": null,
"e": 2971,
"s": 2777,
"text": "Example 1: Here, we use a Func delegate to create a delegate only in a single line without using the above procedure. This Func delegate contains four input parameters and one output parameter."
},
{
"code": "// C# program to illustrate Func delegateusing System; class GFG { // Method public static int mymethod(int s, int d, int f, int g) { return s * d * f * g; } // Main method static public void Main() { // Using Func delegate // Here, Func delegate contains // the four parameters of int type // one result parameter of int type Func<int, int, int, int, int> val = mymethod; Console.WriteLine(val(10, 100, 1000, 1)); }}",
"e": 3469,
"s": 2971,
"text": null
},
{
"code": null,
"e": 3477,
"s": 3469,
"text": "Output:"
},
{
"code": null,
"e": 3485,
"s": 3477,
"text": "1000000"
},
{
"code": null,
"e": 3496,
"s": 3485,
"text": "Example 2:"
},
{
"code": "// C# program to illustrate Func delegateusing System; class GFG { // Method public static int method(int num) { return num + num; } // Main method static public void Main() { // Using Func delegate // Here, Func delegate contains // the one parameters of int type // one result parameter of int type Func<int, int> myfun = method; Console.WriteLine(myfun(10)); }}",
"e": 3942,
"s": 3496,
"text": null
},
{
"code": null,
"e": 3950,
"s": 3942,
"text": "Output:"
},
{
"code": null,
"e": 3953,
"s": 3950,
"text": "20"
},
{
"code": null,
"e": 3971,
"s": 3953,
"text": "Important Points:"
},
{
"code": null,
"e": 4109,
"s": 3971,
"text": "The last parameter in Func Delegate is always an out parameter which is considered as a return type. It is generally used for the result."
},
{
"code": null,
"e": 4286,
"s": 4109,
"text": "You can also use a Func delegate with an anonymous method. As shown in the below example:Example:Func<int, int, int> val = delegate(int x, int y, int z){ return x + y + z;};"
},
{
"code": null,
"e": 4295,
"s": 4286,
"text": "Example:"
},
{
"code": "Func<int, int, int> val = delegate(int x, int y, int z){ return x + y + z;};",
"e": 4375,
"s": 4295,
"text": null
},
{
"code": null,
"e": 4543,
"s": 4375,
"text": "You can also use a Func delegate with the lambda expressions. As shown in the below example:Example:Func<int, int, int, int> val = (int x, int y, int z) = > x + y + z;"
},
{
"code": null,
"e": 4552,
"s": 4543,
"text": "Example:"
},
{
"code": "Func<int, int, int, int> val = (int x, int y, int z) = > x + y + z;",
"e": 4620,
"s": 4552,
"text": null
},
{
"code": null,
"e": 4634,
"s": 4620,
"text": "HIMANSHUGARG8"
},
{
"code": null,
"e": 4651,
"s": 4634,
"text": "CSharp-Delegates"
},
{
"code": null,
"e": 4654,
"s": 4651,
"text": "C#"
},
{
"code": null,
"e": 4752,
"s": 4654,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4783,
"s": 4752,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 4826,
"s": 4783,
"text": "C# | Multiple inheritance using interfaces"
},
{
"code": null,
"e": 4875,
"s": 4826,
"text": "Differences Between .NET Core and .NET Framework"
},
{
"code": null,
"e": 4893,
"s": 4875,
"text": "C# | Constructors"
},
{
"code": null,
"e": 4933,
"s": 4893,
"text": "C# | String.IndexOf( ) Method | Set - 1"
},
{
"code": null,
"e": 4955,
"s": 4933,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 5001,
"s": 4955,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 5013,
"s": 5001,
"text": "C# | Arrays"
},
{
"code": null,
"e": 5032,
"s": 5013,
"text": "C# | Encapsulation"
}
] |
Java Program for Counting Sort
|
13 Jun, 2022
Counting sort is a sorting technique based on keys between a specific range. It works by counting the number of objects having distinct key values (kind of hashing). Then doing some arithmetic to calculate the position of each object in the output sequence.
Java
// Java implementation of Counting Sortclass CountingSort { void sort(char arr[]) { int n = arr.length; // The output character array that will have sorted arr char output[] = new char[n]; // Create a count array to store count of individual // characters and initialize count array as 0 int count[] = new int[256]; for (int i = 0; i < 256; ++i) count[i] = 0; // store count of each character for (int i = 0; i < n; ++i) ++count[arr[i]]; // Change count[i] so that count[i] now contains actual // position of this character in output array for (int i = 1; i <= 255; ++i) count[i] += count[i - 1]; // Build the output character array for (int i = 0; i < n; ++i) { output[count[arr[i]] - 1] = arr[i]; --count[arr[i]]; } // Copy the output array to arr, so that arr now // contains sorted characters for (int i = 0; i < n; ++i) arr[i] = output[i]; } // Driver method public static void main(String args[]) { CountingSort ob = new CountingSort(); char arr[] = {'g', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's' }; ob.sort(arr); System.out.print("Sorted character array is "); for (int i = 0; i < arr.length; ++i) System.out.print(arr[i]); }}/*This code is contributed by Rajat Mishra */
Sorted character array is eeeefggkkorss
Time Complexity: O(n+k) where n is the number of elements in the input array and k is the range of input. Auxiliary Space: O(n+k)
Please refer complete article on Counting Sort for more details!
surindertarika1234
amankr0211
counting-sort
Java Programs
Sorting
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n13 Jun, 2022"
},
{
"code": null,
"e": 310,
"s": 52,
"text": "Counting sort is a sorting technique based on keys between a specific range. It works by counting the number of objects having distinct key values (kind of hashing). Then doing some arithmetic to calculate the position of each object in the output sequence."
},
{
"code": null,
"e": 315,
"s": 310,
"text": "Java"
},
{
"code": "// Java implementation of Counting Sortclass CountingSort { void sort(char arr[]) { int n = arr.length; // The output character array that will have sorted arr char output[] = new char[n]; // Create a count array to store count of individual // characters and initialize count array as 0 int count[] = new int[256]; for (int i = 0; i < 256; ++i) count[i] = 0; // store count of each character for (int i = 0; i < n; ++i) ++count[arr[i]]; // Change count[i] so that count[i] now contains actual // position of this character in output array for (int i = 1; i <= 255; ++i) count[i] += count[i - 1]; // Build the output character array for (int i = 0; i < n; ++i) { output[count[arr[i]] - 1] = arr[i]; --count[arr[i]]; } // Copy the output array to arr, so that arr now // contains sorted characters for (int i = 0; i < n; ++i) arr[i] = output[i]; } // Driver method public static void main(String args[]) { CountingSort ob = new CountingSort(); char arr[] = {'g', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's' }; ob.sort(arr); System.out.print(\"Sorted character array is \"); for (int i = 0; i < arr.length; ++i) System.out.print(arr[i]); }}/*This code is contributed by Rajat Mishra */",
"e": 1801,
"s": 315,
"text": null
},
{
"code": null,
"e": 1841,
"s": 1801,
"text": "Sorted character array is eeeefggkkorss"
},
{
"code": null,
"e": 1973,
"s": 1843,
"text": "Time Complexity: O(n+k) where n is the number of elements in the input array and k is the range of input. Auxiliary Space: O(n+k)"
},
{
"code": null,
"e": 2039,
"s": 1973,
"text": "Please refer complete article on Counting Sort for more details! "
},
{
"code": null,
"e": 2058,
"s": 2039,
"text": "surindertarika1234"
},
{
"code": null,
"e": 2069,
"s": 2058,
"text": "amankr0211"
},
{
"code": null,
"e": 2083,
"s": 2069,
"text": "counting-sort"
},
{
"code": null,
"e": 2097,
"s": 2083,
"text": "Java Programs"
},
{
"code": null,
"e": 2105,
"s": 2097,
"text": "Sorting"
},
{
"code": null,
"e": 2113,
"s": 2105,
"text": "Sorting"
}
] |
How to Hide/Show BottomNavigationView on Scroll in Android?
|
23 Dec, 2020
BottomNavigationView is the best option for navigation in android. It makes life easier for a user to switch between multiple activities and fragments. Itβs really a pain in the butt to use an android app without having proper navigation. At GFG, we have already shared an article with you on BottomNavigationView. If you are new or donβt know that what is BottomNavigationView or want to implement it in your app then please refer to this BottomNavigationView in Android.
We all are using android apps in our daily life. If you will observe carefully, you will found that an application with a better user-interface gets a heart from the user. He will love using that application and will come again and again. For creating better and professional user interfaces you have to take care of these small things. When a BottomNavigationView will show and hide on scrolling it will look much more professional and practical. You have also seen in LinkedIn, that how itβs BottomNavigationView shows and hide on scrolling. Do you also not want to implement it in BottomNavigationView of your own app. In this article, we are going to discuss how to implement this type of behavior in our android app. After going through this article, and understanding the logic you will be able to use it everywhere.
A sample GIF is given below to get an idea about what we are going to do in this article. This is a language-independent tutorial, the steps will be the same for Java and Kotlin.
Step 1: Open an existing project which has BottomNavigationView and you want to work on it. If you havenβt created it yet then you can always refer to this BottomNavigationView in Android and create it. You may also clone this GitHub project for implementation. And we have used this project as an example in this article.
Note: Please refer to this article to clone Android Project from GitHub in Android Studio.
Step 2: Then navigate to the Layout resource File on which you have used the BottomNavigationView. For Example, we have used it in the activity_home.xml file with RecyclerView.
Step 3: Now make sure that the parent layout for that layout resource file is CordinatorLayout because this behavior will not work in any other type of layout. It will only work in CordinatorLayout.
Note: CordinatorLayout is an advanced layout in android, It has much more interesting functionalities. While you will be dealing with the complex UIβs in android, then you can do it more efficiently in CordinatorLayout. You can read more about the CordinatorLayout from here.
Step 4: Now, In BottomNavigationView add an attribute like this.
XML
app:layout_behavior="@string/hide_bottom_view_on_scroll_behavior"/>.
Step 5: Try running your application on an emulator or a physical device. In this sample project, we have used a RecyclerView with BottomNavigationView. You can do the same with ScrollView or any other object in android.
android
Android
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n23 Dec, 2020"
},
{
"code": null,
"e": 527,
"s": 54,
"text": "BottomNavigationView is the best option for navigation in android. It makes life easier for a user to switch between multiple activities and fragments. Itβs really a pain in the butt to use an android app without having proper navigation. At GFG, we have already shared an article with you on BottomNavigationView. If you are new or donβt know that what is BottomNavigationView or want to implement it in your app then please refer to this BottomNavigationView in Android."
},
{
"code": null,
"e": 1350,
"s": 527,
"text": "We all are using android apps in our daily life. If you will observe carefully, you will found that an application with a better user-interface gets a heart from the user. He will love using that application and will come again and again. For creating better and professional user interfaces you have to take care of these small things. When a BottomNavigationView will show and hide on scrolling it will look much more professional and practical. You have also seen in LinkedIn, that how itβs BottomNavigationView shows and hide on scrolling. Do you also not want to implement it in BottomNavigationView of your own app. In this article, we are going to discuss how to implement this type of behavior in our android app. After going through this article, and understanding the logic you will be able to use it everywhere."
},
{
"code": null,
"e": 1530,
"s": 1350,
"text": "A sample GIF is given below to get an idea about what we are going to do in this article. This is a language-independent tutorial, the steps will be the same for Java and Kotlin. "
},
{
"code": null,
"e": 1853,
"s": 1530,
"text": "Step 1: Open an existing project which has BottomNavigationView and you want to work on it. If you havenβt created it yet then you can always refer to this BottomNavigationView in Android and create it. You may also clone this GitHub project for implementation. And we have used this project as an example in this article."
},
{
"code": null,
"e": 1944,
"s": 1853,
"text": "Note: Please refer to this article to clone Android Project from GitHub in Android Studio."
},
{
"code": null,
"e": 2121,
"s": 1944,
"text": "Step 2: Then navigate to the Layout resource File on which you have used the BottomNavigationView. For Example, we have used it in the activity_home.xml file with RecyclerView."
},
{
"code": null,
"e": 2320,
"s": 2121,
"text": "Step 3: Now make sure that the parent layout for that layout resource file is CordinatorLayout because this behavior will not work in any other type of layout. It will only work in CordinatorLayout."
},
{
"code": null,
"e": 2596,
"s": 2320,
"text": "Note: CordinatorLayout is an advanced layout in android, It has much more interesting functionalities. While you will be dealing with the complex UIβs in android, then you can do it more efficiently in CordinatorLayout. You can read more about the CordinatorLayout from here."
},
{
"code": null,
"e": 2662,
"s": 2596,
"text": "Step 4: Now, In BottomNavigationView add an attribute like this. "
},
{
"code": null,
"e": 2666,
"s": 2662,
"text": "XML"
},
{
"code": "app:layout_behavior=\"@string/hide_bottom_view_on_scroll_behavior\"/>.",
"e": 2735,
"s": 2666,
"text": null
},
{
"code": null,
"e": 2956,
"s": 2735,
"text": "Step 5: Try running your application on an emulator or a physical device. In this sample project, we have used a RecyclerView with BottomNavigationView. You can do the same with ScrollView or any other object in android."
},
{
"code": null,
"e": 2964,
"s": 2956,
"text": "android"
},
{
"code": null,
"e": 2972,
"s": 2964,
"text": "Android"
},
{
"code": null,
"e": 2980,
"s": 2972,
"text": "Android"
}
] |
Print all subsets of given size of a set
|
24 Nov, 2021
Generate all possible subsets of size r of the given array with distinct elements.
Examples:
Input : arr[] = {1, 2, 3, 4}
r = 2
Output : 1 2
1 3
1 4
2 3
2 4
3 4
Input : arr[] = {10, 20, 30, 40, 50}
r = 3
Output : 10 20 30
10 20 40
10 20 50
10 30 40
10 30 50
10 40 50
20 30 40
20 30 50
20 40 50
30 40 50
This problem is the same Print all possible combinations of r elements in a given array of size n.The idea here is similar to Subset Sum Problem. We, one by one, consider every element of the input array, and recur for two cases:1) The element is included in the current combination (We put the element in data[] and increase the next available index in data[]) 2) The element is excluded in the current combination (We do not put the element in and do not change the index)When the number of elements in data[] becomes equal to r (size of a combination), we print it.This method is mainly based on Pascalβs Identity, i.e. ncr = n-1cr + n-1cr-1
C++
C
Java
Python3
C#
PHP
Javascript
// C++ Program to print all combination of size r in// an array of size n#include <iostream>using namespace std; void combinationUtil(int arr[], int n, int r, int index, int data[], int i); // The main function that prints all combinations of// size r in arr[] of size n. This function mainly// uses combinationUtil()void printCombination(int arr[], int n, int r){ // A temporary array to store all combination // one by one int data[r]; // Print all combination using temporary array 'data[]' combinationUtil(arr, n, r, 0, data, 0);} /* arr[] ---> Input Array n ---> Size of input array r ---> Size of a combination to be printed index ---> Current index in data[] data[] ---> Temporary array to store current combination i ---> index of current element in arr[] */void combinationUtil(int arr[], int n, int r, int index, int data[], int i){ // Current combination is ready, print it if (index == r) { for (int j = 0; j < r; j++) cout <<" "<< data[j]; cout <<"\n"; return; } // When no more elements are there to put in data[] if (i >= n) return; // current is included, put next at next location data[index] = arr[i]; combinationUtil(arr, n, r, index + 1, data, i + 1); // current is excluded, replace it with next // (Note that i+1 is passed, but index is not // changed) combinationUtil(arr, n, r, index, data, i + 1);} // Driver program to test above functionsint main(){ int arr[] = { 10, 20, 30, 40, 50 }; int r = 3; int n = sizeof(arr) / sizeof(arr[0]); printCombination(arr, n, r); return 0;} // This code is contributed by shivanisinghss2110
// C++ Program to print all combination of size r in// an array of size n#include <stdio.h>void combinationUtil(int arr[], int n, int r, int index, int data[], int i); // The main function that prints all combinations of// size r in arr[] of size n. This function mainly// uses combinationUtil()void printCombination(int arr[], int n, int r){ // A temporary array to store all combination // one by one int data[r]; // Print all combination using temporary array 'data[]' combinationUtil(arr, n, r, 0, data, 0);} /* arr[] ---> Input Array n ---> Size of input array r ---> Size of a combination to be printed index ---> Current index in data[] data[] ---> Temporary array to store current combination i ---> index of current element in arr[] */void combinationUtil(int arr[], int n, int r, int index, int data[], int i){ // Current combination is ready, print it if (index == r) { for (int j = 0; j < r; j++) printf("%d ", data[j]); printf("\n"); return; } // When no more elements are there to put in data[] if (i >= n) return; // current is included, put next at next location data[index] = arr[i]; combinationUtil(arr, n, r, index + 1, data, i + 1); // current is excluded, replace it with next // (Note that i+1 is passed, but index is not // changed) combinationUtil(arr, n, r, index, data, i + 1);} // Driver program to test above functionsint main(){ int arr[] = { 10, 20, 30, 40, 50 }; int r = 3; int n = sizeof(arr) / sizeof(arr[0]); printCombination(arr, n, r); return 0;}
// Java program to print all combination of size// r in an array of size nimport java.io.*; class Permutation { /* arr[] ---> Input Array data[] ---> Temporary array to store current combination start & end ---> Starting and Ending indexes in arr[] index ---> Current index in data[] r ---> Size of a combination to be printed */ static void combinationUtil(int arr[], int n, int r, int index, int data[], int i) { // Current combination is ready to be printed, // print it if (index == r) { for (int j = 0; j < r; j++) System.out.print(data[j] + " "); System.out.println(""); return; } // When no more elements are there to put in data[] if (i >= n) return; // current is included, put next at next // location data[index] = arr[i]; combinationUtil(arr, n, r, index + 1, data, i + 1); // current is excluded, replace it with // next (Note that i+1 is passed, but // index is not changed) combinationUtil(arr, n, r, index, data, i + 1); } // The main function that prints all combinations // of size r in arr[] of size n. This function // mainly uses combinationUtil() static void printCombination(int arr[], int n, int r) { // A temporary array to store all combination // one by one int data[] = new int[r]; // Print all combination using temporary // array 'data[]' combinationUtil(arr, n, r, 0, data, 0); } /* Driver function to check for above function */ public static void main(String[] args) { int arr[] = { 10, 20, 30, 40, 50 }; int r = 3; int n = arr.length; printCombination(arr, n, r); }}/* This code is contributed by Devesh Agrawal */
# Python3 program to print all# subset combination of n# element in given set of r element . # arr[] ---> Input Array# data[] ---> Temporary array to# store current combination# start & end ---> Starting and Ending# indexes in arr[]# index ---> Current index in data[]# r ---> Size of a combination# to be printeddef combinationUtil(arr, n, r, index, data, i): # Current combination is # ready to be printed, # print it if(index == r): for j in range(r): print(data[j], end = " ") print(" ") return # When no more elements # are there to put in data[] if(i >= n): return # current is included, # put next at next # location data[index] = arr[i] combinationUtil(arr, n, r, index + 1, data, i + 1) # current is excluded, # replace it with # next (Note that i+1 # is passed, but index # is not changed) combinationUtil(arr, n, r, index, data, i + 1) # The main function that# prints all combinations# of size r in arr[] of# size n. This function# mainly uses combinationUtil()def printcombination(arr, n, r): # A temporary array to # store all combination # one by one data = list(range(r)) # Print all combination # using temporary # array 'data[]' combinationUtil(arr, n, r, 0, data, 0) # Driver Codearr = [10, 20, 30, 40, 50] r = 3n = len(arr)printcombination(arr, n, r) # This code is contributed# by Ambuj sahu
// C# program to print all combination// of size r in an array of size nusing System; class GFG { /* arr[] ---> Input Array data[] ---> Temporary array to store current combination start & end ---> Starting and Ending indexes in arr[] index ---> Current index in data[] r ---> Size of a combination to be printed */ static void combinationUtil(int []arr, int n, int r, int index, int []data, int i) { // Current combination is ready to // be printed, print it if (index == r) { for (int j = 0; j < r; j++) Console.Write(data[j] + " "); Console.WriteLine(""); return; } // When no more elements are there // to put in data[] if (i >= n) return; // current is included, put next // at next location data[index] = arr[i]; combinationUtil(arr, n, r, index + 1, data, i + 1); // current is excluded, replace // it with next (Note that i+1 // is passed, but index is not // changed) combinationUtil(arr, n, r, index, data, i + 1); } // The main function that prints all // combinations of size r in arr[] of // size n. This function mainly uses // combinationUtil() static void printCombination(int []arr, int n, int r) { // A temporary array to store all // combination one by one int []data = new int[r]; // Print all combination using // temporary array 'data[]' combinationUtil(arr, n, r, 0, data, 0); } /* Driver function to check for above function */ public static void Main() { int []arr = { 10, 20, 30, 40, 50 }; int r = 3; int n = arr.Length; printCombination(arr, n, r); }} // This code is contributed by vt_m.
<?php// Program to print all combination of// size r in an array of size n // The main function that prints all// combinations of size r in arr[] of// size n. This function mainly uses// combinationUtil()function printCombination( $arr, $n, $r){ // A temporary array to store all // combination one by one $data = array(); // Print all combination using // temporary array 'data[]' combinationUtil($arr, $n, $r, 0, $data, 0);} /* arr[] ---> Input Arrayn ---> Size of input arrayr ---> Size of a combination to be printedindex ---> Current index in data[]data[] ---> Temporary array to storecurrent combinationi ---> index of current element in arr[] */function combinationUtil( $arr, $n, $r, $index, $data, $i){ // Current combination is ready, print it if ($index == $r) { for ( $j = 0; $j < $r; $j++) echo $data[$j]," "; echo "\n"; return; } // When no more elements are there to // put in data[] if ($i >= $n) return; // current is included, put next at // next location $data[$index] = $arr[$i]; combinationUtil($arr, $n, $r, $index + 1, $data, $i + 1); // current is excluded, replace it with // next (Note that i+1 is passed, but // index is not changed) combinationUtil($arr, $n, $r, $index, $data, $i + 1);} // Driver program to test above functions $arr = array( 10, 20, 30, 40, 50 ); $r = 3; $n = count($arr); printCombination($arr, $n, $r); // This code is contributed by anuj_67.?>
<script> // Javascript program to print all combination // of size r in an array of size n /* arr[] ---> Input Array data[] ---> Temporary array to store current combination start & end ---> Starting and Ending indexes in arr[] index ---> Current index in data[] r ---> Size of a combination to be printed */ function combinationUtil(arr, n, r, index, data, i) { // Current combination is ready to // be printed, print it if (index == r) { for (let j = 0; j < r; j++) document.write(data[j] + " "); document.write("</br>"); return; } // When no more elements are there // to put in data[] if (i >= n) return; // current is included, put next // at next location data[index] = arr[i]; combinationUtil(arr, n, r, index + 1, data, i + 1); // current is excluded, replace // it with next (Note that i+1 // is passed, but index is not // changed) combinationUtil(arr, n, r, index, data, i + 1); } // The main function that prints all // combinations of size r in arr[] of // size n. This function mainly uses // combinationUtil() function printCombination(arr, n, r) { // A temporary array to store all // combination one by one let data = new Array(r); data.fill(0); // Print all combination using // temporary array 'data[]' combinationUtil(arr, n, r, 0, data, 0); } let arr = [ 10, 20, 30, 40, 50 ]; let r = 3; let n = arr.length; printCombination(arr, n, r); </script>
Output:
10 20 30
10 20 40
10 20 50
10 30 40
10 30 50
10 40 50
20 30 40
20 30 50
20 40 50
30 40 50
Refer to the post below for more solutions and ideas to handle duplicates in the input array. Print all possible combinations of r elements in a given array of size n.
This article is contributed by Dhiman Mayank. 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.
vt_m
AmbujSahu
divine_soul
suresh07
simmytarika5
kk773572498
shivanisinghss2110
rs1686740
Arrays
Combinatorial
Arrays
Combinatorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n24 Nov, 2021"
},
{
"code": null,
"e": 136,
"s": 52,
"text": "Generate all possible subsets of size r of the given array with distinct elements. "
},
{
"code": null,
"e": 148,
"s": 136,
"text": "Examples: "
},
{
"code": null,
"e": 521,
"s": 148,
"text": "Input : arr[] = {1, 2, 3, 4}\n r = 2\nOutput : 1 2\n 1 3\n 1 4\n 2 3\n 2 4\n 3 4\n\nInput : arr[] = {10, 20, 30, 40, 50}\n r = 3\nOutput : 10 20 30 \n 10 20 40 \n 10 20 50 \n 10 30 40 \n 10 30 50 \n 10 40 50 \n 20 30 40 \n 20 30 50 \n 20 40 50 \n 30 40 50 "
},
{
"code": null,
"e": 1166,
"s": 521,
"text": "This problem is the same Print all possible combinations of r elements in a given array of size n.The idea here is similar to Subset Sum Problem. We, one by one, consider every element of the input array, and recur for two cases:1) The element is included in the current combination (We put the element in data[] and increase the next available index in data[]) 2) The element is excluded in the current combination (We do not put the element in and do not change the index)When the number of elements in data[] becomes equal to r (size of a combination), we print it.This method is mainly based on Pascalβs Identity, i.e. ncr = n-1cr + n-1cr-1"
},
{
"code": null,
"e": 1170,
"s": 1166,
"text": "C++"
},
{
"code": null,
"e": 1172,
"s": 1170,
"text": "C"
},
{
"code": null,
"e": 1177,
"s": 1172,
"text": "Java"
},
{
"code": null,
"e": 1185,
"s": 1177,
"text": "Python3"
},
{
"code": null,
"e": 1188,
"s": 1185,
"text": "C#"
},
{
"code": null,
"e": 1192,
"s": 1188,
"text": "PHP"
},
{
"code": null,
"e": 1203,
"s": 1192,
"text": "Javascript"
},
{
"code": "// C++ Program to print all combination of size r in// an array of size n#include <iostream>using namespace std; void combinationUtil(int arr[], int n, int r, int index, int data[], int i); // The main function that prints all combinations of// size r in arr[] of size n. This function mainly// uses combinationUtil()void printCombination(int arr[], int n, int r){ // A temporary array to store all combination // one by one int data[r]; // Print all combination using temporary array 'data[]' combinationUtil(arr, n, r, 0, data, 0);} /* arr[] ---> Input Array n ---> Size of input array r ---> Size of a combination to be printed index ---> Current index in data[] data[] ---> Temporary array to store current combination i ---> index of current element in arr[] */void combinationUtil(int arr[], int n, int r, int index, int data[], int i){ // Current combination is ready, print it if (index == r) { for (int j = 0; j < r; j++) cout <<\" \"<< data[j]; cout <<\"\\n\"; return; } // When no more elements are there to put in data[] if (i >= n) return; // current is included, put next at next location data[index] = arr[i]; combinationUtil(arr, n, r, index + 1, data, i + 1); // current is excluded, replace it with next // (Note that i+1 is passed, but index is not // changed) combinationUtil(arr, n, r, index, data, i + 1);} // Driver program to test above functionsint main(){ int arr[] = { 10, 20, 30, 40, 50 }; int r = 3; int n = sizeof(arr) / sizeof(arr[0]); printCombination(arr, n, r); return 0;} // This code is contributed by shivanisinghss2110",
"e": 2945,
"s": 1203,
"text": null
},
{
"code": "// C++ Program to print all combination of size r in// an array of size n#include <stdio.h>void combinationUtil(int arr[], int n, int r, int index, int data[], int i); // The main function that prints all combinations of// size r in arr[] of size n. This function mainly// uses combinationUtil()void printCombination(int arr[], int n, int r){ // A temporary array to store all combination // one by one int data[r]; // Print all combination using temporary array 'data[]' combinationUtil(arr, n, r, 0, data, 0);} /* arr[] ---> Input Array n ---> Size of input array r ---> Size of a combination to be printed index ---> Current index in data[] data[] ---> Temporary array to store current combination i ---> index of current element in arr[] */void combinationUtil(int arr[], int n, int r, int index, int data[], int i){ // Current combination is ready, print it if (index == r) { for (int j = 0; j < r; j++) printf(\"%d \", data[j]); printf(\"\\n\"); return; } // When no more elements are there to put in data[] if (i >= n) return; // current is included, put next at next location data[index] = arr[i]; combinationUtil(arr, n, r, index + 1, data, i + 1); // current is excluded, replace it with next // (Note that i+1 is passed, but index is not // changed) combinationUtil(arr, n, r, index, data, i + 1);} // Driver program to test above functionsint main(){ int arr[] = { 10, 20, 30, 40, 50 }; int r = 3; int n = sizeof(arr) / sizeof(arr[0]); printCombination(arr, n, r); return 0;}",
"e": 4608,
"s": 2945,
"text": null
},
{
"code": "// Java program to print all combination of size// r in an array of size nimport java.io.*; class Permutation { /* arr[] ---> Input Array data[] ---> Temporary array to store current combination start & end ---> Starting and Ending indexes in arr[] index ---> Current index in data[] r ---> Size of a combination to be printed */ static void combinationUtil(int arr[], int n, int r, int index, int data[], int i) { // Current combination is ready to be printed, // print it if (index == r) { for (int j = 0; j < r; j++) System.out.print(data[j] + \" \"); System.out.println(\"\"); return; } // When no more elements are there to put in data[] if (i >= n) return; // current is included, put next at next // location data[index] = arr[i]; combinationUtil(arr, n, r, index + 1, data, i + 1); // current is excluded, replace it with // next (Note that i+1 is passed, but // index is not changed) combinationUtil(arr, n, r, index, data, i + 1); } // The main function that prints all combinations // of size r in arr[] of size n. This function // mainly uses combinationUtil() static void printCombination(int arr[], int n, int r) { // A temporary array to store all combination // one by one int data[] = new int[r]; // Print all combination using temporary // array 'data[]' combinationUtil(arr, n, r, 0, data, 0); } /* Driver function to check for above function */ public static void main(String[] args) { int arr[] = { 10, 20, 30, 40, 50 }; int r = 3; int n = arr.length; printCombination(arr, n, r); }}/* This code is contributed by Devesh Agrawal */",
"e": 6502,
"s": 4608,
"text": null
},
{
"code": "# Python3 program to print all# subset combination of n# element in given set of r element . # arr[] ---> Input Array# data[] ---> Temporary array to# store current combination# start & end ---> Starting and Ending# indexes in arr[]# index ---> Current index in data[]# r ---> Size of a combination# to be printeddef combinationUtil(arr, n, r, index, data, i): # Current combination is # ready to be printed, # print it if(index == r): for j in range(r): print(data[j], end = \" \") print(\" \") return # When no more elements # are there to put in data[] if(i >= n): return # current is included, # put next at next # location data[index] = arr[i] combinationUtil(arr, n, r, index + 1, data, i + 1) # current is excluded, # replace it with # next (Note that i+1 # is passed, but index # is not changed) combinationUtil(arr, n, r, index, data, i + 1) # The main function that# prints all combinations# of size r in arr[] of# size n. This function# mainly uses combinationUtil()def printcombination(arr, n, r): # A temporary array to # store all combination # one by one data = list(range(r)) # Print all combination # using temporary # array 'data[]' combinationUtil(arr, n, r, 0, data, 0) # Driver Codearr = [10, 20, 30, 40, 50] r = 3n = len(arr)printcombination(arr, n, r) # This code is contributed# by Ambuj sahu",
"e": 8059,
"s": 6502,
"text": null
},
{
"code": "// C# program to print all combination// of size r in an array of size nusing System; class GFG { /* arr[] ---> Input Array data[] ---> Temporary array to store current combination start & end ---> Starting and Ending indexes in arr[] index ---> Current index in data[] r ---> Size of a combination to be printed */ static void combinationUtil(int []arr, int n, int r, int index, int []data, int i) { // Current combination is ready to // be printed, print it if (index == r) { for (int j = 0; j < r; j++) Console.Write(data[j] + \" \"); Console.WriteLine(\"\"); return; } // When no more elements are there // to put in data[] if (i >= n) return; // current is included, put next // at next location data[index] = arr[i]; combinationUtil(arr, n, r, index + 1, data, i + 1); // current is excluded, replace // it with next (Note that i+1 // is passed, but index is not // changed) combinationUtil(arr, n, r, index, data, i + 1); } // The main function that prints all // combinations of size r in arr[] of // size n. This function mainly uses // combinationUtil() static void printCombination(int []arr, int n, int r) { // A temporary array to store all // combination one by one int []data = new int[r]; // Print all combination using // temporary array 'data[]' combinationUtil(arr, n, r, 0, data, 0); } /* Driver function to check for above function */ public static void Main() { int []arr = { 10, 20, 30, 40, 50 }; int r = 3; int n = arr.Length; printCombination(arr, n, r); }} // This code is contributed by vt_m.",
"e": 10088,
"s": 8059,
"text": null
},
{
"code": "<?php// Program to print all combination of// size r in an array of size n // The main function that prints all// combinations of size r in arr[] of// size n. This function mainly uses// combinationUtil()function printCombination( $arr, $n, $r){ // A temporary array to store all // combination one by one $data = array(); // Print all combination using // temporary array 'data[]' combinationUtil($arr, $n, $r, 0, $data, 0);} /* arr[] ---> Input Arrayn ---> Size of input arrayr ---> Size of a combination to be printedindex ---> Current index in data[]data[] ---> Temporary array to storecurrent combinationi ---> index of current element in arr[] */function combinationUtil( $arr, $n, $r, $index, $data, $i){ // Current combination is ready, print it if ($index == $r) { for ( $j = 0; $j < $r; $j++) echo $data[$j],\" \"; echo \"\\n\"; return; } // When no more elements are there to // put in data[] if ($i >= $n) return; // current is included, put next at // next location $data[$index] = $arr[$i]; combinationUtil($arr, $n, $r, $index + 1, $data, $i + 1); // current is excluded, replace it with // next (Note that i+1 is passed, but // index is not changed) combinationUtil($arr, $n, $r, $index, $data, $i + 1);} // Driver program to test above functions $arr = array( 10, 20, 30, 40, 50 ); $r = 3; $n = count($arr); printCombination($arr, $n, $r); // This code is contributed by anuj_67.?>",
"e": 11672,
"s": 10088,
"text": null
},
{
"code": "<script> // Javascript program to print all combination // of size r in an array of size n /* arr[] ---> Input Array data[] ---> Temporary array to store current combination start & end ---> Starting and Ending indexes in arr[] index ---> Current index in data[] r ---> Size of a combination to be printed */ function combinationUtil(arr, n, r, index, data, i) { // Current combination is ready to // be printed, print it if (index == r) { for (let j = 0; j < r; j++) document.write(data[j] + \" \"); document.write(\"</br>\"); return; } // When no more elements are there // to put in data[] if (i >= n) return; // current is included, put next // at next location data[index] = arr[i]; combinationUtil(arr, n, r, index + 1, data, i + 1); // current is excluded, replace // it with next (Note that i+1 // is passed, but index is not // changed) combinationUtil(arr, n, r, index, data, i + 1); } // The main function that prints all // combinations of size r in arr[] of // size n. This function mainly uses // combinationUtil() function printCombination(arr, n, r) { // A temporary array to store all // combination one by one let data = new Array(r); data.fill(0); // Print all combination using // temporary array 'data[]' combinationUtil(arr, n, r, 0, data, 0); } let arr = [ 10, 20, 30, 40, 50 ]; let r = 3; let n = arr.length; printCombination(arr, n, r); </script>",
"e": 13475,
"s": 11672,
"text": null
},
{
"code": null,
"e": 13484,
"s": 13475,
"text": "Output: "
},
{
"code": null,
"e": 13584,
"s": 13484,
"text": "10 20 30 \n10 20 40 \n10 20 50 \n10 30 40 \n10 30 50 \n10 40 50 \n20 30 40 \n20 30 50 \n20 40 50 \n30 40 50 "
},
{
"code": null,
"e": 13752,
"s": 13584,
"text": "Refer to the post below for more solutions and ideas to handle duplicates in the input array. Print all possible combinations of r elements in a given array of size n."
},
{
"code": null,
"e": 14174,
"s": 13752,
"text": "This article is contributed by Dhiman Mayank. 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": 14179,
"s": 14174,
"text": "vt_m"
},
{
"code": null,
"e": 14189,
"s": 14179,
"text": "AmbujSahu"
},
{
"code": null,
"e": 14201,
"s": 14189,
"text": "divine_soul"
},
{
"code": null,
"e": 14210,
"s": 14201,
"text": "suresh07"
},
{
"code": null,
"e": 14223,
"s": 14210,
"text": "simmytarika5"
},
{
"code": null,
"e": 14235,
"s": 14223,
"text": "kk773572498"
},
{
"code": null,
"e": 14254,
"s": 14235,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 14264,
"s": 14254,
"text": "rs1686740"
},
{
"code": null,
"e": 14271,
"s": 14264,
"text": "Arrays"
},
{
"code": null,
"e": 14285,
"s": 14271,
"text": "Combinatorial"
},
{
"code": null,
"e": 14292,
"s": 14285,
"text": "Arrays"
},
{
"code": null,
"e": 14306,
"s": 14292,
"text": "Combinatorial"
}
] |
Scanner toString() method in Java with Examples
|
11 Oct, 2018
The toString() method of java.util.Scanner class returns the string representation of this Scanner. The exact format is unspecified.
Syntax:
public String toString()
Return Value: This function returns the string representation of this scanner.
Below program illustrates the above function:
Program 1:
// Java program to illustrate the// toString() method of Scanner class in Java import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { String s = "GeeksForGeeks - " + "A Computer Science Portal for Geeks"; // create a new scanner // with the specified String Object Scanner scanner = new Scanner(s); // print a line of the scanner System.out.println("Scanner String: \n" + scanner.nextLine()); // display information about this scanner System.out.println("\nString representation " + "of this Scanner:\n" + scanner.toString()); // close the scanner scanner.close(); }}
Scanner String:
GeeksForGeeks - A Computer Science Portal for Geeks
String representation of this Scanner:
java.util.Scanner[delimiters=\p{javaWhitespace}+]
[position=51][match valid=true][need input=false]
[skipped=false][group separator=\,]
[decimal separator=\.][positive prefix=]
[negative prefix=\Q-\E][positive suffix=]
[negative suffix=][NaN string=\Q?\E][infinity string=\Q?\E]
Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#toString()
Java - util package
Java-Library
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
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Collections in Java
Multidimensional Arrays in Java
Stream In Java
Set in Java
Singleton Class in Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Oct, 2018"
},
{
"code": null,
"e": 161,
"s": 28,
"text": "The toString() method of java.util.Scanner class returns the string representation of this Scanner. The exact format is unspecified."
},
{
"code": null,
"e": 169,
"s": 161,
"text": "Syntax:"
},
{
"code": null,
"e": 194,
"s": 169,
"text": "public String toString()"
},
{
"code": null,
"e": 273,
"s": 194,
"text": "Return Value: This function returns the string representation of this scanner."
},
{
"code": null,
"e": 319,
"s": 273,
"text": "Below program illustrates the above function:"
},
{
"code": null,
"e": 330,
"s": 319,
"text": "Program 1:"
},
{
"code": "// Java program to illustrate the// toString() method of Scanner class in Java import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { String s = \"GeeksForGeeks - \" + \"A Computer Science Portal for Geeks\"; // create a new scanner // with the specified String Object Scanner scanner = new Scanner(s); // print a line of the scanner System.out.println(\"Scanner String: \\n\" + scanner.nextLine()); // display information about this scanner System.out.println(\"\\nString representation \" + \"of this Scanner:\\n\" + scanner.toString()); // close the scanner scanner.close(); }}",
"e": 1135,
"s": 330,
"text": null
},
{
"code": null,
"e": 1524,
"s": 1135,
"text": "Scanner String: \nGeeksForGeeks - A Computer Science Portal for Geeks\n\nString representation of this Scanner:\njava.util.Scanner[delimiters=\\p{javaWhitespace}+]\n[position=51][match valid=true][need input=false]\n[skipped=false][group separator=\\,]\n[decimal separator=\\.][positive prefix=]\n[negative prefix=\\Q-\\E][positive suffix=]\n[negative suffix=][NaN string=\\Q?\\E][infinity string=\\Q?\\E]\n"
},
{
"code": null,
"e": 1611,
"s": 1524,
"text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#toString()"
},
{
"code": null,
"e": 1631,
"s": 1611,
"text": "Java - util package"
},
{
"code": null,
"e": 1644,
"s": 1631,
"text": "Java-Library"
},
{
"code": null,
"e": 1649,
"s": 1644,
"text": "Java"
},
{
"code": null,
"e": 1654,
"s": 1649,
"text": "Java"
},
{
"code": null,
"e": 1752,
"s": 1654,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1803,
"s": 1752,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 1834,
"s": 1803,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 1853,
"s": 1834,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 1883,
"s": 1853,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 1901,
"s": 1883,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 1921,
"s": 1901,
"text": "Collections in Java"
},
{
"code": null,
"e": 1953,
"s": 1921,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 1968,
"s": 1953,
"text": "Stream In Java"
},
{
"code": null,
"e": 1980,
"s": 1968,
"text": "Set in Java"
}
] |
Compute the outer product of two given vectors using NumPy in Python
|
29 Aug, 2020
In Python, we can use the outer() function of the NumPy package to find the outer product of two matrices.
Syntax : numpy.outer(a, b, out = None)
Parameters :
a : [array_like] First input vector. Input is flattened if not already 1-dimensional.
b : [array_like] Second input vector. Input is flattened if not already 1-dimensional.
out : [ndarray, optional] A location where the result is stored.
Return : [ndarray] Returns the outer product of two vectors. out[i, j] = a[i] * b[j]
Example 1: Outer Product of 1-D array
Python3
# Importing libraryimport numpy as np # Creating two 1-D arraysarray1 = np.array([6,2])array2 = np.array([2,5])print("Original 1-D arrays:")print(array1)print(array2) # Outputprint("Outer Product of the two array is:")result = np.outer(array1, array2)print(result)
Output:
Original 1-D arrays:
[6 2]
[2 5]
Outer Product of the two array is:
[[12 30]
[ 4 10]]
Example 2: Outer Product of 2X2 matrix
Python3
# Importing libraryimport numpy as np # Creating two 2-D matrixmatrix1 = np.array([[1, 3], [2, 6]])matrix2 = np.array([[0, 1], [1, 9]])print("Original 2-D matrix:")print(matrix1)print(matrix2) # Outputprint("Outer Product of the two matrix is:")result = np.outer(matrix1, matrix2)print(result)
Output:
Original 2-D matrix:
[[1 3]
[2 6]]
[[0 1]
[1 9]]
Outer Product of the two matrix is:
[[ 0 1 1 9]
[ 0 3 3 27]
[ 0 2 2 18]
[ 0 6 6 54]]
Example 3: Outer Product of 3X3 matrix
Python3
# Importing libraryimport numpy as np # Creating two 3-D matrixmatrix1 = np.array([[2, 8, 2], [3, 4, 8], [0, 2, 1]])matrix2 = np.array([[2, 1, 1], [0, 1, 0], [2, 3, 0]])print("Original 3-D matrix:")print(matrix1)print(matrix2) # Outputprint("Outer Product of the two matrix is:")result = np.outer(matrix1, matrix2)print(result)
Output:
Original 3-D matrix:
[[2 8 2]
[3 4 8]
[0 2 1]]
[[2 1 1]
[0 1 0]
[2 3 0]]
Outer Product of the two matrix is:
[[ 4 2 2 0 2 0 4 6 0]
[16 8 8 0 8 0 16 24 0]
[ 4 2 2 0 2 0 4 6 0]
[ 6 3 3 0 3 0 6 9 0]
[ 8 4 4 0 4 0 8 12 0]
[16 8 8 0 8 0 16 24 0]
[ 0 0 0 0 0 0 0 0 0]
[ 4 2 2 0 2 0 4 6 0]
[ 2 1 1 0 1 0 2 3 0]]
Python numpy-Matrix Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Aug, 2020"
},
{
"code": null,
"e": 136,
"s": 28,
"text": "In Python, we can use the outer() function of the NumPy package to find the outer product of two matrices. "
},
{
"code": null,
"e": 175,
"s": 136,
"text": "Syntax : numpy.outer(a, b, out = None)"
},
{
"code": null,
"e": 188,
"s": 175,
"text": "Parameters :"
},
{
"code": null,
"e": 274,
"s": 188,
"text": "a : [array_like] First input vector. Input is flattened if not already 1-dimensional."
},
{
"code": null,
"e": 361,
"s": 274,
"text": "b : [array_like] Second input vector. Input is flattened if not already 1-dimensional."
},
{
"code": null,
"e": 426,
"s": 361,
"text": "out : [ndarray, optional] A location where the result is stored."
},
{
"code": null,
"e": 511,
"s": 426,
"text": "Return : [ndarray] Returns the outer product of two vectors. out[i, j] = a[i] * b[j]"
},
{
"code": null,
"e": 549,
"s": 511,
"text": "Example 1: Outer Product of 1-D array"
},
{
"code": null,
"e": 557,
"s": 549,
"text": "Python3"
},
{
"code": "# Importing libraryimport numpy as np # Creating two 1-D arraysarray1 = np.array([6,2])array2 = np.array([2,5])print(\"Original 1-D arrays:\")print(array1)print(array2) # Outputprint(\"Outer Product of the two array is:\")result = np.outer(array1, array2)print(result)",
"e": 824,
"s": 557,
"text": null
},
{
"code": null,
"e": 832,
"s": 824,
"text": "Output:"
},
{
"code": null,
"e": 920,
"s": 832,
"text": "Original 1-D arrays:\n[6 2]\n[2 5]\nOuter Product of the two array is:\n[[12 30]\n [ 4 10]]\n"
},
{
"code": null,
"e": 959,
"s": 920,
"text": "Example 2: Outer Product of 2X2 matrix"
},
{
"code": null,
"e": 967,
"s": 959,
"text": "Python3"
},
{
"code": "# Importing libraryimport numpy as np # Creating two 2-D matrixmatrix1 = np.array([[1, 3], [2, 6]])matrix2 = np.array([[0, 1], [1, 9]])print(\"Original 2-D matrix:\")print(matrix1)print(matrix2) # Outputprint(\"Outer Product of the two matrix is:\")result = np.outer(matrix1, matrix2)print(result)",
"e": 1263,
"s": 967,
"text": null
},
{
"code": null,
"e": 1271,
"s": 1263,
"text": "Output:"
},
{
"code": null,
"e": 1420,
"s": 1271,
"text": "Original 2-D matrix:\n[[1 3]\n [2 6]]\n[[0 1]\n [1 9]]\nOuter Product of the two matrix is:\n[[ 0 1 1 9]\n [ 0 3 3 27]\n [ 0 2 2 18]\n [ 0 6 6 54]]\n"
},
{
"code": null,
"e": 1459,
"s": 1420,
"text": "Example 3: Outer Product of 3X3 matrix"
},
{
"code": null,
"e": 1467,
"s": 1459,
"text": "Python3"
},
{
"code": "# Importing libraryimport numpy as np # Creating two 3-D matrixmatrix1 = np.array([[2, 8, 2], [3, 4, 8], [0, 2, 1]])matrix2 = np.array([[2, 1, 1], [0, 1, 0], [2, 3, 0]])print(\"Original 3-D matrix:\")print(matrix1)print(matrix2) # Outputprint(\"Outer Product of the two matrix is:\")result = np.outer(matrix1, matrix2)print(result)",
"e": 1797,
"s": 1467,
"text": null
},
{
"code": null,
"e": 1805,
"s": 1797,
"text": "Output:"
},
{
"code": null,
"e": 2190,
"s": 1805,
"text": "Original 3-D matrix:\n[[2 8 2]\n [3 4 8]\n [0 2 1]]\n[[2 1 1]\n [0 1 0]\n [2 3 0]]\nOuter Product of the two matrix is:\n[[ 4 2 2 0 2 0 4 6 0]\n [16 8 8 0 8 0 16 24 0]\n [ 4 2 2 0 2 0 4 6 0]\n [ 6 3 3 0 3 0 6 9 0]\n [ 8 4 4 0 4 0 8 12 0]\n [16 8 8 0 8 0 16 24 0]\n [ 0 0 0 0 0 0 0 0 0]\n [ 4 2 2 0 2 0 4 6 0]\n [ 2 1 1 0 1 0 2 3 0]]\n"
},
{
"code": null,
"e": 2219,
"s": 2190,
"text": "Python numpy-Matrix Function"
},
{
"code": null,
"e": 2232,
"s": 2219,
"text": "Python-numpy"
},
{
"code": null,
"e": 2239,
"s": 2232,
"text": "Python"
}
] |
Java Program to Swap two Strings Without Using any Third Variable
|
30 Sep, 2021
Given two string variables, a and b, your task is to write a Java Program to swap these variables without using any temporary or third variable. Use of library methods is allowed.
Examples:
Input: a = "Hello"
b = "World"
Output:
Strings before swap: a = Hello and b = World
Strings after swap: a = World and b = Hello
Method: In order to swap two string variables without using any temporary or third variable, the idea is to use string concatenation and substring() methods to perform this operation. The substring() method comes in two forms, as listed below:
substring(int beginindex): This function will return the substring of the calling string starting from the index passed as an argument to this function till the last character in the calling string.
substring(int beginindex, int endindex): This function will return Substring of the calling string starting from the beginindex(inclusive) and ending at the endindex(exclusive) passed as an argument to this function.
Algorithm:
1) Append second string to first string and
store in first string:
a = a + b
2) call the method substring(int beginindex, int endindex)
by passing beginindex as 0 and endindex as,
a.length() - b.length():
b = substring(0,a.length()-b.length());
3) call the method substring(int beginindex) by passing
b.length() as argument to store the value of initial
b string in a
a = substring(b.length());
Code:
Java
// Java program to swap two strings without using a temporary// variable.import java.util.*; class Swap{ public static void main(String args[]) { // Declare two strings String a = "Hello"; String b = "World"; // Print String before swapping System.out.println("Strings before swap: a = " + a + " and b = "+b); // append 2nd string to 1st a = a + b; // store initial string a in string b b = a.substring(0,a.length()-b.length()); // store initial string b in string a a = a.substring(b.length()); // print String after swapping System.out.println("Strings after swap: a = " + a + " and b = " + b); } }
Strings before swap: a = Hello and b = World
Strings after swap: a = World and b = Hello
This article is contributed by Harsh Agarwal. 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.
Akanksha_Rai
sweetyty
nishkarshgandhi
Java-String-Programs
Java-Strings
Java
Java-Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
Stream In Java
ArrayList in Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n30 Sep, 2021"
},
{
"code": null,
"e": 232,
"s": 52,
"text": "Given two string variables, a and b, your task is to write a Java Program to swap these variables without using any temporary or third variable. Use of library methods is allowed."
},
{
"code": null,
"e": 243,
"s": 232,
"text": "Examples: "
},
{
"code": null,
"e": 379,
"s": 243,
"text": "Input: a = \"Hello\"\n b = \"World\"\n\nOutput:\nStrings before swap: a = Hello and b = World\nStrings after swap: a = World and b = Hello"
},
{
"code": null,
"e": 624,
"s": 379,
"text": "Method: In order to swap two string variables without using any temporary or third variable, the idea is to use string concatenation and substring() methods to perform this operation. The substring() method comes in two forms, as listed below: "
},
{
"code": null,
"e": 824,
"s": 624,
"text": "substring(int beginindex): This function will return the substring of the calling string starting from the index passed as an argument to this function till the last character in the calling string. "
},
{
"code": null,
"e": 1043,
"s": 824,
"text": "substring(int beginindex, int endindex): This function will return Substring of the calling string starting from the beginindex(inclusive) and ending at the endindex(exclusive) passed as an argument to this function. "
},
{
"code": null,
"e": 1055,
"s": 1043,
"text": "Algorithm: "
},
{
"code": null,
"e": 1482,
"s": 1055,
"text": "1) Append second string to first string and \n store in first string:\n a = a + b\n\n2) call the method substring(int beginindex, int endindex)\n by passing beginindex as 0 and endindex as,\n a.length() - b.length():\n b = substring(0,a.length()-b.length());\n\n3) call the method substring(int beginindex) by passing \n b.length() as argument to store the value of initial \n b string in a\n a = substring(b.length());"
},
{
"code": null,
"e": 1488,
"s": 1482,
"text": "Code:"
},
{
"code": null,
"e": 1493,
"s": 1488,
"text": "Java"
},
{
"code": "// Java program to swap two strings without using a temporary// variable.import java.util.*; class Swap{ public static void main(String args[]) { // Declare two strings String a = \"Hello\"; String b = \"World\"; // Print String before swapping System.out.println(\"Strings before swap: a = \" + a + \" and b = \"+b); // append 2nd string to 1st a = a + b; // store initial string a in string b b = a.substring(0,a.length()-b.length()); // store initial string b in string a a = a.substring(b.length()); // print String after swapping System.out.println(\"Strings after swap: a = \" + a + \" and b = \" + b); } }",
"e": 2336,
"s": 1493,
"text": null
},
{
"code": null,
"e": 2425,
"s": 2336,
"text": "Strings before swap: a = Hello and b = World\nStrings after swap: a = World and b = Hello"
},
{
"code": null,
"e": 2846,
"s": 2425,
"text": "This article is contributed by Harsh Agarwal. 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": 2859,
"s": 2846,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 2868,
"s": 2859,
"text": "sweetyty"
},
{
"code": null,
"e": 2884,
"s": 2868,
"text": "nishkarshgandhi"
},
{
"code": null,
"e": 2905,
"s": 2884,
"text": "Java-String-Programs"
},
{
"code": null,
"e": 2918,
"s": 2905,
"text": "Java-Strings"
},
{
"code": null,
"e": 2923,
"s": 2918,
"text": "Java"
},
{
"code": null,
"e": 2936,
"s": 2923,
"text": "Java-Strings"
},
{
"code": null,
"e": 2941,
"s": 2936,
"text": "Java"
},
{
"code": null,
"e": 3039,
"s": 2941,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3090,
"s": 3039,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 3121,
"s": 3090,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 3140,
"s": 3121,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 3170,
"s": 3140,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 3185,
"s": 3170,
"text": "Stream In Java"
},
{
"code": null,
"e": 3203,
"s": 3185,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 3223,
"s": 3203,
"text": "Collections in Java"
},
{
"code": null,
"e": 3247,
"s": 3223,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 3279,
"s": 3247,
"text": "Multidimensional Arrays in Java"
}
] |
Python String Methods ?
|
Python provides lots of built-in methods which we can use on strings.
Below are the list of string methods available in Python 3.
>>> mystring = "hello python"
>>> print(mystring.capitalize())
Hello python
>>> mystring = "hello PYTHON"
>>> print(mystring.casefold())
hello python
>>> mystring = "Hello"
>>> x = mystring.center(12,
"-")
>>> print(x)
---Hello----
>>> mystr = "Hello Python"
>>> print(mystr.count("o"))
2
>>> print(mystr.count("th"))
1
>>> print(mystr.count("l"))
2
>>> print(mystr.count("h"))
1
>>> print(mystr.count("H"))
1
>>> print(mystr.count("hH"))
0
strict (encoding errors raise a UnicodeError)
strict (encoding errors raise a UnicodeError)
ignore
ignore
replace
replace
xmlcharrefreplace
xmlcharrefreplace
backslashreplace
backslashreplace
any other name registered via codecs.register_error()
any other name registered via codecs.register_error()
>>> mystr = 'python!'
>>> print('The string is:',
mystr)
The string is: python!
>>> print('The encoded
version is: ',
mystr.encode("ascii",
"ignore"))
The encoded version is:
b'python!'
>>> print('The encoded
version (with replace) is:',
mystr.encode("ascii",
"replace"))
The encoded version (with
replace) is: b'python!'
>>> mystr = "Python"
>>>
print(mystr.endswith("y"))
False
>>>
print(mystr.endswith("hon"))
True
>>> mystr = "1\t2\t3"
>>> print(mystr)
1 2 3
>>>
print(mystr.expandtabs())
1 2 3
>>>
print(mystr.expandtabs(tabsi
ze=15))
1 2
3
>>>
print(mystr.expandtabs(tabsi
ze=2))
1 2 3
>>> mystring = "Python"
>>>
print(mystring.find("P"))
0
>>>
print(mystring.find("on"))
4
>>> print("{} and
{}".format("Apple",
"Banana"))
Apple and Banana
>>> print("{1} and
{0}".format("Apple",
"Banana"))
Banana and Apple
>>> print("{lunch} and
{dinner}".format(lunch="Peas
", dinner="Beans"))
Peas and Beans
>>> lunch = {"Food":
"Pizza", "Drink": "Wine"}
>>> print("Lunch: {Food},
{Drink}".format_map(lunch))
Lunch: Pizza, Wine
>>> class Default(dict):
def __missing__(self,
key):
return key
>>> lunch = {"Drink":
"Wine"}
>>> print("Lunch: {Food},
{Drink}".format_map(Default(
lunch)))
Lunch: Food, Wine
>>> mystr = "HelloPython"
>>> print(mystr.index("P"))
5
>>>
print(mystr.index("hon"))
8
>>> print(mystr.index("o"))
4
>>> mystr = "HelloPython"
>>> print(mystr.isalnum())
True
>>> a = "123"
>>> print(a.isalnum())
True
>>> a= "$*%!!!"
>>> print(a.isalnum())
False
>>> mystr = "HelloPython"
>>> print(mystr.isalpha())
True
>>> a = "123"
>>> print(a.isalpha())
False
>>> a= "$*%!!!"
>>> print(a.isalpha())
False
>>> mystr = "HelloPython"
>>> print(mystr.isdecimal())
False
>>> a="1.23"
>>> print(a.isdecimal())
False
>>> c = u"\u00B2"
>>> print(c.isdecimal())
False
>>> c="133"
>>> print(c.isdecimal())
True
>>> c="133"
>>> print(c.isdigit())
True
>>> c = u"\u00B2"
>>> print(c.isdigit())
True
>>> a="1.23"
>>> print(a.isdigit())
False
>>> c="133"
>>> print(c.isidentifier())
False
>>> c="_user_123"
>>> print(c.isidentifier())
True
>>> c="Python"
>>> print(c.isidentifier())
True
>>> c="Python"
>>> print(c.islower())
False
>>> c="_user_123"
>>> print(c.islower())
True
>>> print(c.islower())
False
>>> c="133"
>>> print(c.isnumeric())
True
>>> c="_user_123"
>>> print(c.isnumeric())
False
>>> c="Python"
>>> print(c.isnumeric())
False
>>> c="133"
>>> print(c.isprintable())
True
>>> c="_user_123"
>>> print(c.isprintable())
True
>>> c="\t"
>>> print(c.isprintable())
False
>>> c="133"
>>> print(c.isspace())
False
>>> c="Hello Python"
>>> print(c.isspace())
False
73
>>> c="Hello"
>>> print(c.isspace())
False
>>> c="\t"
>>> print(c.isspace())
True
>>> c="133"
>>> print(c.istitle())
False
>>> c="Python"
>>> print(c.istitle())
True
>>> c="\t"
>>> print(c.istitle())
False
>>> c="Python"
>>> print(c.isupper())
False
>>> c="PYHTON"
>>> print(c.isupper())
True
>>> c="\t"
>>> print(c.isupper())
False
>>> a ="-"
>>> print(a.join("123"))
1-2-3
>>> a="Hello Python"
>>> a="**"
>>> print(a.join("Hello
Python"))
H**e**l**l**o**
**P**y**t**h**o**n
>>> a="Hello"
>>> b = a.ljust(12, "_")
>>> print(b)
Hello_______
>>> a = "Python"
>>> print(a.lower())
Python
>>> a = " Hello "
>>> print(a.lstrip(), "!")
Hello
>>> frm = "SecretCode"
>>> to = "4203040540"
>>> trans_table =
str.maketrans(frm,to)
>>> sec_code = "Secret
Code".translate(trans_table)
>>> print(sec_code)
400304 0540
>>> mystr = "Hello-Python"
>>> print(mystr.partition("-
"))
('Hello', '-', 'Python')
74
>>>
print(mystr.partition("."))
('Hello-Python', '', '')
>>> mystr = "Hello Python.
Hello Java. Hello C++."
>>>
print(mystr.replace("Hello",
"Bye"))
Bye Python. Bye Java. Bye
C++.
>>>
print(mystr.replace("Hello",
"Hell", 2))
Hell Python. Hell Java.
Hello C++.
>>> mystr = "Hello-Python"
>>> print(mystr.rfind("P"))
6
>>> print(mystr.rfind("-"))
5
>>> print(mystr.rfind("z"))
-1
>>> mystr = "Hello-Python"
>>> print(mystr.rindex("P"))
6
>>> print(mystr.rindex("-"))
5
>>> print(mystr.rindex("z"))
Traceback (most recent call
last):
File "<pyshell#253>", line
1, in <module>
print(mystr.rindex("z"))
ValueError: substring not
found
>>> mystr = "Hello Python"
>>> mystr1 = mystr.rjust(20,
"-")
>>> print(mystr1)
--------Hello Python
>>> mystr = "Hello Python"
>>>
print(mystr.rpartition("."))
('', '', 'Hello Python')
>>> print(mystr.rpartition("
"))
('Hello', ' ', 'Python')
>>> mystr = "Hello Python"
>>> print(mystr.rsplit())
['Hello', 'Python']
>>> mystr = "Hello-Python-
Hello"
>>>
print(mystr.rsplit(sep="-",
maxsplit=1))
['Hello-Python', 'Hello']
>>> mystr = "Hello Python"
>>> print(mystr.rstrip(),
"!")
Hello Python !
>>> mystr = "------------
Hello Python-----------"
>>> print(mystr.rstrip(), "-
")
------------Hello Python----
------- -
>>> print(mystr.rstrip(),
"_")
------------Hello Python----
------- _
>>> mystr = "Hello Python"
>>> print(mystr.split())
['Hello', 'Python']
>>> mystr1="Hello,,Python"
>>> print(mystr1.split(","))
['Hello', '', 'Python']
>>> mystr = "Hello:\n\n
Python\r\nJava\nC++\n"
>>>
print(mystr.splitlines())
['Hello:', '', ' Python',
'Java', 'C++']
>>>
print(mystr.splitlines(keepe
nds=True))
['Hello:\n', '\n', '
Python\r\n', 'Java\n',
'C++\n']
>>> mystr = "Hello Python"
>>>
print(mystr.startswith("P"))
False
>>>
print(mystr.startswith("H"))
True
>>>
print(mystr.startswith("Hell
"))
True
>>> mystr = "
Hello Python
"
>>> print(mystr.strip(),
"!")
Hello Python !
>>> print(mystr.strip(), "
")
Hello Python
>>> mystr = "Hello PYthon"
>>> print(mystr.swapcase())
hELLO python
>>> mystr = "Hello PYthon"
>>> print(mystr.title())
Hello Python
>>> mystr = "HELLO JAVA"
>>> print(mystr.title())
Hello Java
>>> frm = "helloPython"
>>> to = "40250666333"
>>> trans_table =
str.maketrans(frm, to)
>>> secret_code = "Secret
Code".translate(trans_table)
>>> print(secret_code)
S0cr06 C3d0
>>> mystr = "hello Python"
>>> print(mystr.upper())
HELLO PYTHON
>>> mystr = "999"
>>> print(mystr.zfill(9))
000000999
>>> mystr = "-40"
>>> print(mystr.zfill(5))
-0040
|
[
{
"code": null,
"e": 1257,
"s": 1187,
"text": "Python provides lots of built-in methods which we can use on strings."
},
{
"code": null,
"e": 1317,
"s": 1257,
"text": "Below are the list of string methods available in Python 3."
},
{
"code": null,
"e": 1393,
"s": 1317,
"text": ">>> mystring = \"hello python\"\n>>> print(mystring.capitalize())\nHello python"
},
{
"code": null,
"e": 1467,
"s": 1393,
"text": ">>> mystring = \"hello PYTHON\"\n>>> print(mystring.casefold())\nhello python"
},
{
"code": null,
"e": 1549,
"s": 1467,
"text": ">>> mystring = \"Hello\"\n>>> x = mystring.center(12,\n\"-\")\n>>> print(x)\n---Hello----"
},
{
"code": null,
"e": 1758,
"s": 1549,
"text": ">>> mystr = \"Hello Python\"\n>>> print(mystr.count(\"o\"))\n2\n>>> print(mystr.count(\"th\"))\n1\n>>> print(mystr.count(\"l\"))\n2\n>>> print(mystr.count(\"h\"))\n1\n>>> print(mystr.count(\"H\"))\n1\n>>> print(mystr.count(\"hH\"))\n0"
},
{
"code": null,
"e": 1804,
"s": 1758,
"text": "strict (encoding errors raise a UnicodeError)"
},
{
"code": null,
"e": 1850,
"s": 1804,
"text": "strict (encoding errors raise a UnicodeError)"
},
{
"code": null,
"e": 1857,
"s": 1850,
"text": "ignore"
},
{
"code": null,
"e": 1864,
"s": 1857,
"text": "ignore"
},
{
"code": null,
"e": 1872,
"s": 1864,
"text": "replace"
},
{
"code": null,
"e": 1880,
"s": 1872,
"text": "replace"
},
{
"code": null,
"e": 1898,
"s": 1880,
"text": "xmlcharrefreplace"
},
{
"code": null,
"e": 1916,
"s": 1898,
"text": "xmlcharrefreplace"
},
{
"code": null,
"e": 1933,
"s": 1916,
"text": "backslashreplace"
},
{
"code": null,
"e": 1950,
"s": 1933,
"text": "backslashreplace"
},
{
"code": null,
"e": 2004,
"s": 1950,
"text": "any other name registered via codecs.register_error()"
},
{
"code": null,
"e": 2058,
"s": 2004,
"text": "any other name registered via codecs.register_error()"
},
{
"code": null,
"e": 2380,
"s": 2058,
"text": ">>> mystr = 'python!'\n>>> print('The string is:',\nmystr)\nThe string is: python!\n>>> print('The encoded\nversion is: ',\nmystr.encode(\"ascii\",\n\"ignore\"))\nThe encoded version is:\nb'python!'\n>>> print('The encoded\nversion (with replace) is:',\nmystr.encode(\"ascii\",\n\"replace\"))\nThe encoded version (with\nreplace) is: b'python!'"
},
{
"code": null,
"e": 2476,
"s": 2380,
"text": ">>> mystr = \"Python\"\n>>>\nprint(mystr.endswith(\"y\"))\nFalse\n>>>\nprint(mystr.endswith(\"hon\"))\nTrue"
},
{
"code": null,
"e": 2650,
"s": 2476,
"text": ">>> mystr = \"1\\t2\\t3\"\n>>> print(mystr)\n1 2 3\n>>>\nprint(mystr.expandtabs())\n1 2 3\n>>>\nprint(mystr.expandtabs(tabsi\nze=15))\n1 2\n3\n>>>\nprint(mystr.expandtabs(tabsi\nze=2))\n1 2 3"
},
{
"code": null,
"e": 2739,
"s": 2650,
"text": ">>> mystring = \"Python\"\n>>>\nprint(mystring.find(\"P\"))\n0\n>>>\nprint(mystring.find(\"on\"))\n4"
},
{
"code": null,
"e": 2960,
"s": 2739,
"text": ">>> print(\"{} and\n{}\".format(\"Apple\",\n\"Banana\"))\nApple and Banana\n>>> print(\"{1} and\n{0}\".format(\"Apple\",\n\"Banana\"))\nBanana and Apple\n>>> print(\"{lunch} and\n{dinner}\".format(lunch=\"Peas\n\", dinner=\"Beans\"))\nPeas and Beans"
},
{
"code": null,
"e": 3256,
"s": 2960,
"text": ">>> lunch = {\"Food\":\n\"Pizza\", \"Drink\": \"Wine\"}\n>>> print(\"Lunch: {Food},\n{Drink}\".format_map(lunch))\nLunch: Pizza, Wine\n>>> class Default(dict):\ndef __missing__(self,\nkey):\nreturn key\n>>> lunch = {\"Drink\":\n\"Wine\"}\n>>> print(\"Lunch: {Food},\n{Drink}\".format_map(Default(\nlunch)))\nLunch: Food, Wine"
},
{
"code": null,
"e": 3374,
"s": 3256,
"text": ">>> mystr = \"HelloPython\"\n>>> print(mystr.index(\"P\"))\n5\n>>>\nprint(mystr.index(\"hon\"))\n8\n>>> print(mystr.index(\"o\"))\n4"
},
{
"code": null,
"e": 3519,
"s": 3374,
"text": ">>> mystr = \"HelloPython\"\n>>> print(mystr.isalnum())\nTrue\n>>> a = \"123\"\n>>> print(a.isalnum())\nTrue\n>>> a= \"$*%!!!\"\n>>> print(a.isalnum())\nFalse"
},
{
"code": null,
"e": 3665,
"s": 3519,
"text": ">>> mystr = \"HelloPython\"\n>>> print(mystr.isalpha())\nTrue\n>>> a = \"123\"\n>>> print(a.isalpha())\nFalse\n>>> a= \"$*%!!!\"\n>>> print(a.isalpha())\nFalse"
},
{
"code": null,
"e": 3861,
"s": 3665,
"text": ">>> mystr = \"HelloPython\"\n>>> print(mystr.isdecimal())\nFalse\n>>> a=\"1.23\"\n>>> print(a.isdecimal())\nFalse\n>>> c = u\"\\u00B2\"\n>>> print(c.isdecimal())\nFalse\n>>> c=\"133\"\n>>> print(c.isdecimal())\nTrue"
},
{
"code": null,
"e": 3989,
"s": 3861,
"text": ">>> c=\"133\"\n>>> print(c.isdigit())\nTrue\n>>> c = u\"\\u00B2\"\n>>> print(c.isdigit())\nTrue\n>>> a=\"1.23\"\n>>> print(a.isdigit())\nFalse"
},
{
"code": null,
"e": 4134,
"s": 3989,
"text": ">>> c=\"133\"\n>>> print(c.isidentifier())\nFalse\n>>> c=\"_user_123\"\n>>> print(c.isidentifier())\nTrue\n>>> c=\"Python\"\n>>> print(c.isidentifier())\nTrue"
},
{
"code": null,
"e": 4253,
"s": 4134,
"text": ">>> c=\"Python\"\n>>> print(c.islower())\nFalse\n>>> c=\"_user_123\"\n>>> print(c.islower())\nTrue\n>>> print(c.islower())\nFalse"
},
{
"code": null,
"e": 4390,
"s": 4253,
"text": ">>> c=\"133\"\n>>> print(c.isnumeric())\nTrue\n>>> c=\"_user_123\"\n>>> print(c.isnumeric())\nFalse\n>>> c=\"Python\"\n>>> print(c.isnumeric())\nFalse"
},
{
"code": null,
"e": 4528,
"s": 4390,
"text": ">>> c=\"133\"\n>>> print(c.isprintable())\nTrue\n>>> c=\"_user_123\"\n>>> print(c.isprintable())\nTrue\n>>> c=\"\\t\"\n>>> print(c.isprintable())\nFalse"
},
{
"code": null,
"e": 4704,
"s": 4528,
"text": ">>> c=\"133\"\n>>> print(c.isspace())\nFalse\n>>> c=\"Hello Python\"\n>>> print(c.isspace())\nFalse\n73\n>>> c=\"Hello\"\n>>> print(c.isspace())\nFalse\n>>> c=\"\\t\"\n>>> print(c.isspace())\nTrue"
},
{
"code": null,
"e": 4828,
"s": 4704,
"text": ">>> c=\"133\"\n>>> print(c.istitle())\nFalse\n>>> c=\"Python\"\n>>> print(c.istitle())\nTrue\n>>> c=\"\\t\"\n>>> print(c.istitle())\nFalse"
},
{
"code": null,
"e": 4955,
"s": 4828,
"text": ">>> c=\"Python\"\n>>> print(c.isupper())\nFalse\n>>> c=\"PYHTON\"\n>>> print(c.isupper())\nTrue\n>>> c=\"\\t\"\n>>> print(c.isupper())\nFalse"
},
{
"code": null,
"e": 5098,
"s": 4955,
"text": ">>> a =\"-\"\n>>> print(a.join(\"123\"))\n1-2-3\n>>> a=\"Hello Python\"\n>>> a=\"**\"\n>>> print(a.join(\"Hello\nPython\"))\nH**e**l**l**o**\n**P**y**t**h**o**n"
},
{
"code": null,
"e": 5163,
"s": 5098,
"text": ">>> a=\"Hello\"\n>>> b = a.ljust(12, \"_\")\n>>> print(b)\nHello_______"
},
{
"code": null,
"e": 5208,
"s": 5163,
"text": ">>> a = \"Python\"\n>>> print(a.lower())\nPython"
},
{
"code": null,
"e": 5259,
"s": 5208,
"text": ">>> a = \" Hello \"\n>>> print(a.lstrip(), \"!\")\nHello"
},
{
"code": null,
"e": 5428,
"s": 5259,
"text": ">>> frm = \"SecretCode\"\n>>> to = \"4203040540\"\n>>> trans_table =\nstr.maketrans(frm,to)\n>>> sec_code = \"Secret\nCode\".translate(trans_table)\n>>> print(sec_code)\n400304 0540"
},
{
"code": null,
"e": 5573,
"s": 5428,
"text": ">>> mystr = \"Hello-Python\"\n>>> print(mystr.partition(\"-\n\"))\n('Hello', '-', 'Python')\n74\n>>>\nprint(mystr.partition(\".\"))\n('Hello-Python', '', '')"
},
{
"code": null,
"e": 5776,
"s": 5573,
"text": ">>> mystr = \"Hello Python.\nHello Java. Hello C++.\"\n>>>\nprint(mystr.replace(\"Hello\",\n\"Bye\"))\nBye Python. Bye Java. Bye\nC++.\n>>>\nprint(mystr.replace(\"Hello\",\n\"Hell\", 2))\nHell Python. Hell Java.\nHello C++."
},
{
"code": null,
"e": 5894,
"s": 5776,
"text": ">>> mystr = \"Hello-Python\"\n>>> print(mystr.rfind(\"P\"))\n6\n>>> print(mystr.rfind(\"-\"))\n5\n>>> print(mystr.rfind(\"z\"))\n-1"
},
{
"code": null,
"e": 6146,
"s": 5894,
"text": ">>> mystr = \"Hello-Python\"\n>>> print(mystr.rindex(\"P\"))\n6\n>>> print(mystr.rindex(\"-\"))\n5\n>>> print(mystr.rindex(\"z\"))\nTraceback (most recent call\nlast):\nFile \"<pyshell#253>\", line\n1, in <module>\nprint(mystr.rindex(\"z\"))\nValueError: substring not\nfound"
},
{
"code": null,
"e": 6246,
"s": 6146,
"text": ">>> mystr = \"Hello Python\"\n>>> mystr1 = mystr.rjust(20,\n\"-\")\n>>> print(mystr1)\n--------Hello Python"
},
{
"code": null,
"e": 6389,
"s": 6246,
"text": ">>> mystr = \"Hello Python\"\n>>>\nprint(mystr.rpartition(\".\"))\n('', '', 'Hello Python')\n>>> print(mystr.rpartition(\"\n\"))\n('Hello', ' ', 'Python')"
},
{
"code": null,
"e": 6567,
"s": 6389,
"text": ">>> mystr = \"Hello Python\"\n>>> print(mystr.rsplit())\n['Hello', 'Python']\n>>> mystr = \"Hello-Python-\nHello\"\n>>>\nprint(mystr.rsplit(sep=\"-\",\nmaxsplit=1))\n['Hello-Python', 'Hello']"
},
{
"code": null,
"e": 6832,
"s": 6567,
"text": ">>> mystr = \"Hello Python\"\n>>> print(mystr.rstrip(),\n\"!\")\nHello Python !\n>>> mystr = \"------------\nHello Python-----------\"\n>>> print(mystr.rstrip(), \"-\n\")\n------------Hello Python----\n------- -\n>>> print(mystr.rstrip(),\n\"_\")\n------------Hello Python----\n------- _"
},
{
"code": null,
"e": 6984,
"s": 6832,
"text": ">>> mystr = \"Hello Python\"\n>>> print(mystr.split())\n['Hello', 'Python']\n>>> mystr1=\"Hello,,Python\"\n>>> print(mystr1.split(\",\"))\n['Hello', '', 'Python']"
},
{
"code": null,
"e": 7199,
"s": 6984,
"text": ">>> mystr = \"Hello:\\n\\n\nPython\\r\\nJava\\nC++\\n\"\n>>>\nprint(mystr.splitlines())\n['Hello:', '', ' Python',\n'Java', 'C++']\n>>>\nprint(mystr.splitlines(keepe\nnds=True))\n['Hello:\\n', '\\n', '\nPython\\r\\n', 'Java\\n',\n'C++\\n']"
},
{
"code": null,
"e": 7345,
"s": 7199,
"text": ">>> mystr = \"Hello Python\"\n>>>\nprint(mystr.startswith(\"P\"))\nFalse\n>>>\nprint(mystr.startswith(\"H\"))\nTrue\n>>>\nprint(mystr.startswith(\"Hell\n\"))\nTrue"
},
{
"code": null,
"e": 7462,
"s": 7345,
"text": ">>> mystr = \"\nHello Python\n\"\n>>> print(mystr.strip(),\n\"!\")\nHello Python !\n>>> print(mystr.strip(), \"\n\")\nHello Python"
},
{
"code": null,
"e": 7530,
"s": 7462,
"text": ">>> mystr = \"Hello PYthon\"\n>>> print(mystr.swapcase())\nhELLO python"
},
{
"code": null,
"e": 7656,
"s": 7530,
"text": ">>> mystr = \"Hello PYthon\"\n>>> print(mystr.title())\nHello Python\n>>> mystr = \"HELLO JAVA\"\n>>> print(mystr.title())\nHello Java"
},
{
"code": null,
"e": 7834,
"s": 7656,
"text": ">>> frm = \"helloPython\"\n>>> to = \"40250666333\"\n>>> trans_table =\nstr.maketrans(frm, to)\n>>> secret_code = \"Secret\nCode\".translate(trans_table)\n>>> print(secret_code)\nS0cr06 C3d0"
},
{
"code": null,
"e": 7899,
"s": 7834,
"text": ">>> mystr = \"hello Python\"\n>>> print(mystr.upper())\nHELLO PYTHON"
},
{
"code": null,
"e": 8003,
"s": 7899,
"text": ">>> mystr = \"999\"\n>>> print(mystr.zfill(9))\n000000999\n>>> mystr = \"-40\"\n>>> print(mystr.zfill(5))\n-0040"
}
] |
p5.js texture() Function
|
04 Mar, 2021
The texture() function in p5.js is used to provide a texture for geometry objects. This texture can be an p5.Image, p5.MediaElement or p5.Graphics object.
Syntax:
texture( tex )
Parameters: This function accepts a single parameter as mentioned above and described below.
tex: It is a p5.Image, p5.MediaElement or p5.Graphics object that specifies the 2D texture that has to be used on a model.
The program below illustrate the texture() function in p5.js:
Example 1:
let cubeObj;let newFont; // Load all the models in preload()function preload() { newFont = loadFont("fonts/Montserrat.otf"); cubeObj = loadModel("models/cube.obj", true); textureImg = loadImage("blue_texture.jpg");} function setup() { createCanvas(400, 300, WEBGL); textFont(newFont, 14);} function draw() { background("green"); text("The model below is using an"+ " image texture", -185, -125); scale(0.60); lights(); rotateX(frameCount * 0.005); rotateY(frameCount * 0.005); noStroke(); texture(textureImg); // Load the given model model(cubeObj);}
Output:
Example 2:
let newFont;let newTexture; function preload() { newFont = loadFont("fonts/Montserrat.otf");} function setup() { createCanvas(400, 300, WEBGL); textFont(newFont, 14); newTexture = createGraphics(400, 200); newTexture.textSize(75);} function draw() { background("green"); text("Use the dropdown to select the"+ " model to display", -185, -125); newTexture.background("yellow"); newTexture.text("Hello World!", 0, 100); // Use the created texture texture(newTexture); rotateX(frameCount * 0.01); rotateY(frameCount * 0.01); box(100);}
Output:
Online editor: https://editor.p5js.org/
Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/
Reference: https://p5js.org/reference/#/p5/texture
JavaScript-p5.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n04 Mar, 2021"
},
{
"code": null,
"e": 183,
"s": 28,
"text": "The texture() function in p5.js is used to provide a texture for geometry objects. This texture can be an p5.Image, p5.MediaElement or p5.Graphics object."
},
{
"code": null,
"e": 191,
"s": 183,
"text": "Syntax:"
},
{
"code": null,
"e": 206,
"s": 191,
"text": "texture( tex )"
},
{
"code": null,
"e": 299,
"s": 206,
"text": "Parameters: This function accepts a single parameter as mentioned above and described below."
},
{
"code": null,
"e": 422,
"s": 299,
"text": "tex: It is a p5.Image, p5.MediaElement or p5.Graphics object that specifies the 2D texture that has to be used on a model."
},
{
"code": null,
"e": 484,
"s": 422,
"text": "The program below illustrate the texture() function in p5.js:"
},
{
"code": null,
"e": 495,
"s": 484,
"text": "Example 1:"
},
{
"code": "let cubeObj;let newFont; // Load all the models in preload()function preload() { newFont = loadFont(\"fonts/Montserrat.otf\"); cubeObj = loadModel(\"models/cube.obj\", true); textureImg = loadImage(\"blue_texture.jpg\");} function setup() { createCanvas(400, 300, WEBGL); textFont(newFont, 14);} function draw() { background(\"green\"); text(\"The model below is using an\"+ \" image texture\", -185, -125); scale(0.60); lights(); rotateX(frameCount * 0.005); rotateY(frameCount * 0.005); noStroke(); texture(textureImg); // Load the given model model(cubeObj);}",
"e": 1078,
"s": 495,
"text": null
},
{
"code": null,
"e": 1086,
"s": 1078,
"text": "Output:"
},
{
"code": null,
"e": 1097,
"s": 1086,
"text": "Example 2:"
},
{
"code": "let newFont;let newTexture; function preload() { newFont = loadFont(\"fonts/Montserrat.otf\");} function setup() { createCanvas(400, 300, WEBGL); textFont(newFont, 14); newTexture = createGraphics(400, 200); newTexture.textSize(75);} function draw() { background(\"green\"); text(\"Use the dropdown to select the\"+ \" model to display\", -185, -125); newTexture.background(\"yellow\"); newTexture.text(\"Hello World!\", 0, 100); // Use the created texture texture(newTexture); rotateX(frameCount * 0.01); rotateY(frameCount * 0.01); box(100);}",
"e": 1663,
"s": 1097,
"text": null
},
{
"code": null,
"e": 1671,
"s": 1663,
"text": "Output:"
},
{
"code": null,
"e": 1711,
"s": 1671,
"text": "Online editor: https://editor.p5js.org/"
},
{
"code": null,
"e": 1809,
"s": 1711,
"text": "Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/"
},
{
"code": null,
"e": 1860,
"s": 1809,
"text": "Reference: https://p5js.org/reference/#/p5/texture"
},
{
"code": null,
"e": 1877,
"s": 1860,
"text": "JavaScript-p5.js"
},
{
"code": null,
"e": 1894,
"s": 1877,
"text": "Web Technologies"
}
] |
std::bsearch in C++
|
07 Aug, 2017
Basics of Binary Search
std::bsearch searches for an element in a sorted array. Finds an element equal to element pointed to by key in an array pointed to by ptr.If the array contains several elements that comp would indicate as equal to the element searched for, then it is unspecified which element the function will return as the result.Syntax :
void* bsearch( const void* key, const void* ptr, std::size_t count,
std::size_t size, * comp );
Parameters :
key - element to be found
ptr - pointer to the array to examine
count - number of element in the array
size - size of each element in the array in bytes
comp - comparison function which returns ?a negative integer value if
the first argument is less than the second,
a positive integer value if the first argument is greater than the second
and zero if the arguments are equal.
Return value :
Pointer to the found element or null pointer if the element has not been found.
Implementing the binary predicate comp :
// Binary predicate which returns 0 if numbers found equalint comp(int* a, int* b){ if (*a < *b) return -1; else if (*a > *b) return 1; // elements found equal else return 0;}
Implementation
// CPP program to implement// std::bsearch#include <bits/stdc++.h> // Binary predicateint compare(const void* ap, const void* bp){ // Typecasting const int* a = (int*)ap; const int* b = (int*)bp; if (*a < *b) return -1; else if (*a > *b) return 1; else return 0;} // Driver codeint main(){ // Given array int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8 }; // Size of array int ARR_SIZE = sizeof(arr) / sizeof(arr[0]); // Element to be found int key1 = 4; // Calling std::bsearch // Typecasting the returned pointer to int int* p1 = (int*)std::bsearch(&key1, arr, ARR_SIZE, sizeof(arr[0]), compare); // If non-zero value is returned, key is found if (p1) std::cout << key1 << " found at position " << (p1 - arr) << '\n'; else std::cout << key1 << " not found\n"; // Element to be found int key2 = 9; // Calling std::bsearch // Typecasting the returned pointer to int int* p2 = (int*)std::bsearch(&key2, arr, ARR_SIZE, sizeof(arr[0]), compare); // If non-zero value is returned, key is found if (p2) std::cout << key2 << " found at position " << (p2 - arr) << '\n'; else std::cout << key2 << " not found\n";}
Output:
4 found at position 3
9 not found
Where to use :Binary search can be used on sorted data where a key is to be found. It can be used in cases like computing frequency of a key in a sorted list.
Why Binary Search?Binary search is much more effective than linear search because it halves the search space at each step. This is not significant for our array of length 9. Here, linear search takes at most 9 steps and binary search takes at most 4 steps. But consider an array with 1000 elements, here linear search takes at most 1000 steps, while binary search takes at most 10 steps.For 1 billion elements, binary search will find our key in at most 30 steps.
Related Article: std::binary_searchThis article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
cpp-algorithm-library
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
std::string class in C++
Queue in C++ Standard Template Library (STL)
Unordered Sets in C++ Standard Template Library
std::find in C++
List in C++ Standard Template Library (STL)
Inline Functions in C++
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n07 Aug, 2017"
},
{
"code": null,
"e": 78,
"s": 54,
"text": "Basics of Binary Search"
},
{
"code": null,
"e": 403,
"s": 78,
"text": "std::bsearch searches for an element in a sorted array. Finds an element equal to element pointed to by key in an array pointed to by ptr.If the array contains several elements that comp would indicate as equal to the element searched for, then it is unspecified which element the function will return as the result.Syntax :"
},
{
"code": null,
"e": 1075,
"s": 403,
"text": "void* bsearch( const void* key, const void* ptr, std::size_t count,\n std::size_t size, * comp );\n\nParameters :\nkey - element to be found\nptr - pointer to the array to examine\ncount - number of element in the array\nsize - size of each element in the array in bytes\ncomp - comparison function which returns ?a negative integer value if \n the first argument is less than the second,\n a positive integer value if the first argument is greater than the second\n and zero if the arguments are equal.\n\nReturn value :\nPointer to the found element or null pointer if the element has not been found.\n"
},
{
"code": null,
"e": 1116,
"s": 1075,
"text": "Implementing the binary predicate comp :"
},
{
"code": "// Binary predicate which returns 0 if numbers found equalint comp(int* a, int* b){ if (*a < *b) return -1; else if (*a > *b) return 1; // elements found equal else return 0;}",
"e": 1331,
"s": 1116,
"text": null
},
{
"code": null,
"e": 1346,
"s": 1331,
"text": "Implementation"
},
{
"code": "// CPP program to implement// std::bsearch#include <bits/stdc++.h> // Binary predicateint compare(const void* ap, const void* bp){ // Typecasting const int* a = (int*)ap; const int* b = (int*)bp; if (*a < *b) return -1; else if (*a > *b) return 1; else return 0;} // Driver codeint main(){ // Given array int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8 }; // Size of array int ARR_SIZE = sizeof(arr) / sizeof(arr[0]); // Element to be found int key1 = 4; // Calling std::bsearch // Typecasting the returned pointer to int int* p1 = (int*)std::bsearch(&key1, arr, ARR_SIZE, sizeof(arr[0]), compare); // If non-zero value is returned, key is found if (p1) std::cout << key1 << \" found at position \" << (p1 - arr) << '\\n'; else std::cout << key1 << \" not found\\n\"; // Element to be found int key2 = 9; // Calling std::bsearch // Typecasting the returned pointer to int int* p2 = (int*)std::bsearch(&key2, arr, ARR_SIZE, sizeof(arr[0]), compare); // If non-zero value is returned, key is found if (p2) std::cout << key2 << \" found at position \" << (p2 - arr) << '\\n'; else std::cout << key2 << \" not found\\n\";}",
"e": 2587,
"s": 1346,
"text": null
},
{
"code": null,
"e": 2595,
"s": 2587,
"text": "Output:"
},
{
"code": null,
"e": 2630,
"s": 2595,
"text": "4 found at position 3\n9 not found\n"
},
{
"code": null,
"e": 2789,
"s": 2630,
"text": "Where to use :Binary search can be used on sorted data where a key is to be found. It can be used in cases like computing frequency of a key in a sorted list."
},
{
"code": null,
"e": 3253,
"s": 2789,
"text": "Why Binary Search?Binary search is much more effective than linear search because it halves the search space at each step. This is not significant for our array of length 9. Here, linear search takes at most 9 steps and binary search takes at most 4 steps. But consider an array with 1000 elements, here linear search takes at most 1000 steps, while binary search takes at most 10 steps.For 1 billion elements, binary search will find our key in at most 30 steps."
},
{
"code": null,
"e": 3591,
"s": 3253,
"text": "Related Article: std::binary_searchThis article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 3716,
"s": 3591,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 3738,
"s": 3716,
"text": "cpp-algorithm-library"
},
{
"code": null,
"e": 3742,
"s": 3738,
"text": "STL"
},
{
"code": null,
"e": 3746,
"s": 3742,
"text": "C++"
},
{
"code": null,
"e": 3750,
"s": 3746,
"text": "STL"
},
{
"code": null,
"e": 3754,
"s": 3750,
"text": "CPP"
},
{
"code": null,
"e": 3852,
"s": 3754,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3876,
"s": 3852,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 3896,
"s": 3876,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 3929,
"s": 3896,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 3973,
"s": 3929,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 3998,
"s": 3973,
"text": "std::string class in C++"
},
{
"code": null,
"e": 4043,
"s": 3998,
"text": "Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 4091,
"s": 4043,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 4108,
"s": 4091,
"text": "std::find in C++"
},
{
"code": null,
"e": 4152,
"s": 4108,
"text": "List in C++ Standard Template Library (STL)"
}
] |
What is the use of the VALUE function in a DB2? Explain with the help of an example
|
The purpose of VALUE function in DB2 is to check for NULL values and it can be used in place of NULL indicator or COALESCE function. The VALUE function replaces the column value with the given argument if it contains a NULL value.
For example, if we have an ORDER table and we have to extract ORDER_ID and ORDER_DESCRIPTION from this table. The ORDER_DECRIPTION column can have NULL values.
If this is the case, we have to replace ORDER_DESCRIPTION with SPACES, then we can use the below query:
EXEC SQL
SELECT ORDER_ID, VALUE(ORDER_DESCRIPTION, β β)
INTO :ORDER-ID, :ORDER-DESCRIPTION
FROM ORDERS
END-EXEC
In this case, the VALUE function will take two arguments. The first one is the name of the column and second one is the expected value if the column contains NULL values.
|
[
{
"code": null,
"e": 1293,
"s": 1062,
"text": "The purpose of VALUE function in DB2 is to check for NULL values and it can be used in place of NULL indicator or COALESCE function. The VALUE function replaces the column value with the given argument if it contains a NULL value."
},
{
"code": null,
"e": 1453,
"s": 1293,
"text": "For example, if we have an ORDER table and we have to extract ORDER_ID and ORDER_DESCRIPTION from this table. The ORDER_DECRIPTION column can have NULL values."
},
{
"code": null,
"e": 1557,
"s": 1453,
"text": "If this is the case, we have to replace ORDER_DESCRIPTION with SPACES, then we can use the below query:"
},
{
"code": null,
"e": 1678,
"s": 1557,
"text": "EXEC SQL\n SELECT ORDER_ID, VALUE(ORDER_DESCRIPTION, β β)\n INTO :ORDER-ID, :ORDER-DESCRIPTION\n FROM ORDERS\nEND-EXEC"
},
{
"code": null,
"e": 1849,
"s": 1678,
"text": "In this case, the VALUE function will take two arguments. The first one is the name of the column and second one is the expected value if the column contains NULL values."
}
] |
SAP BPC - Quick Guide
|
SAP Business Planning and Consolidation (BPC) tool is used to support all operational and financial activities in an organization. SAP BPC helps in automating and streamlining business forecast, planning, and consolidation activities in your organization.
SAP BPC supports two types of migration - SAP NetWeaver and Microsoft Excel. BPC with Microsoft version enables you to perform modeling, application maintenance, importing data and applying transformations, creating scripts, etc. It leverages the power of MS Excel and provides the user with an Enterprise Power Management (EPM) solution, collaborative tool with robust, readily accepted environment.
SAP BPC provides support for existing Microsoft functionality and various enhancement features like drag and drop report builder, etc.
Following are the key benefits provided by SAP BPC β
It allows the user to make better business decisions by supporting What-If analysis and allows you to perform scenario-based planning.
It allows the user to make better business decisions by supporting What-If analysis and allows you to perform scenario-based planning.
It allows you to collaborate data and thus increase accuracy in business planning and accountability.
It allows you to collaborate data and thus increase accuracy in business planning and accountability.
It helps in aligning your plans with strategic goals and hence decrease the cycle time.
It helps in aligning your plans with strategic goals and hence decrease the cycle time.
You have an option to choose the version of SAP NetWeaver or Microsoft Platform.
You have an option to choose the version of SAP NetWeaver or Microsoft Platform.
Following are the key benefits that can be achieved by using BPC β
Business Forecasting
Analytical Reporting and Analysis
Budget Planning
Predictive Analysis and Recommendations
Improve Compliance
Consolidation
Business Process Flows and Smooth Collaboration
SAP Enterprise Performance Management (EPM) allows your organization to improve its financial and operational performance management. SAP EPM supports various functionalities with SAP Business Planning and Consolidation - BPC-NW or BPC-MS, like financial consolidation, financial information management, supply chain performance management, strategy management and many more areas.
SAP Business Planning and Consolidation NW version is based on the functionality of NetWeaver platform. This is built on NetWeaver HTML5 and supports various user environment capabilities. It also provides various prebuilt components to reuse in different applications.
SAP BPC NW version supports RESTful connection to ABAP backend component and provides regular access to user interface. It also supports client-side logging capabilities.
The following table illustrates the name of the platform and the supported components β
SAP BPC for NetWeaver provides various advantages since it is integrated with BW system and allows you to store data in InfoCubes.
Some key advantages of using SAP BPC with NW system are β
Star Schema for Exceptional Reporting β SAP BPC uses NW InfoCubes to store the data. The dimension model used is extended star schema so it makes BPC with NW system and exceptional system for reporting.
No Database Dependence Version β BPC NW version is not dependent on database version and can run common databases like DB2, Oracle, SQL Server, etc.
BW Accelerator Support β SAP NetWeaver BW accelerator tool is an additional feature that can be used to enhance the performance of reporting in the system, even if you are using large datasets. It indirectly helps in saving the cost for a company as less number of performance issues are reported.
BAdI Development and ABAP Support β SAP BPC with NetWeaver allows you to use ABAP programming to develop K2 script logic. It enables to create business add-in BAdi interface in the back-end system, which can be called later from script logic developed in BPC system.
It helps in solving the complex business requirements and to reduce the development time for an organization.
Some key advantages of using SAP BPC MS are β
Apart from common features provided in BPC like currency translation, allocations, validation and account transformations, automatic adjustments and carry forward of opening balance, the following features can be achieved in BPC MS version β
Dimension Logic β This can be configured in BPC system using simple mathematical formulas.
Dimension Logic β This can be configured in BPC system using simple mathematical formulas.
Business Rules β This allows you to create rules in BPC system to perform specific functions.
Business Rules β This allows you to create rules in BPC system to perform specific functions.
K2 Script Logic β This is used to perform some specific functions which canβt be achieved using out-of-box functionality to meet business requirements. You can create K2 script logics to perform certain functions, which can be performed in a standard system.
K2 Script Logic β This is used to perform some specific functions which canβt be achieved using out-of-box functionality to meet business requirements. You can create K2 script logics to perform certain functions, which can be performed in a standard system.
Many organizations use MS Excel to manage business planning and consolidation but it has some disadvantages. Following are the disadvantages of using BPC MS over NetWeaver β
Tough to Manage Excel Spreadsheets β As business planning and consolidation data is stored in the form of spreadsheets, it creates a security issue and an option to control access is by keeping the files on the shared network drive. In SAP BPC, you can save the data in database and this provides security of data.
Tough to Manage Excel Spreadsheets β As business planning and consolidation data is stored in the form of spreadsheets, it creates a security issue and an option to control access is by keeping the files on the shared network drive. In SAP BPC, you can save the data in database and this provides security of data.
Version Control β To create a new version of data, SAP BPC with NW allows you to maintain the version of data in the system and you can maintain the current data too. While using Excel spreadsheets for data store, you need to name the file with new name every time.
Version Control β To create a new version of data, SAP BPC with NW allows you to maintain the version of data in the system and you can maintain the current data too. While using Excel spreadsheets for data store, you need to name the file with new name every time.
Integrity of Spreadsheets β Using spreadsheets make it tough to manage the integrity of the sheets as the same file is accessed by multiple users and itβs tough to find out the latest version of spreadsheet. However, SAP system has a central repository to maintain financial and business planning data.
Integrity of Spreadsheets β Using spreadsheets make it tough to manage the integrity of the sheets as the same file is accessed by multiple users and itβs tough to find out the latest version of spreadsheet. However, SAP system has a central repository to maintain financial and business planning data.
Collaboration β SAP BPC allows you to collaborate data from different users and you can put comments on critical information and Excel doesnβt support collaboration feature.
Collaboration β SAP BPC allows you to collaborate data from different users and you can put comments on critical information and Excel doesnβt support collaboration feature.
Requirement β SAP NetWeaver ABAP 7.3 or 7.31
Database β Any of the above version of SAP NetWeaver support.
Operating System β Any supported version of SAP NetWeaver system and database engine.
The following figure shows SAP BPC 10.0 architecture.
Difference between SAP BPC v7.5 and v10 is Web Server component. SAP BPC 7.5 NetWeaver uses Microsoft ISS, while BPC 10.0 NW and BPC 10 on HANA use the web server that is part of SAP NetWeaver.
SAP NW 10 is more scalable than SAP NW 7.5 (IIS in 32bit mode) and it simplifies the system topology as no separate Web Server and Network Load Balancing components are required as these were part of BPC 7.5 implementations.
Another difference between the two is version of SAP NetWeaver. SAP BPC 7.5 NW supports SAP NetWeaver 7.01 and 7.02. However, SAP BPC 10 NetWeaver and BPC 10 HANA doesnβt support NW 7.01, 7.02 versions. Also note that NW 7.01 and 7.02 requirements are quite different from SAP NetWeaver 7.3.
It means SAP BPC 7.5 NW systems in many organizations are running on older versions of Operating Systems and RDBMS is not supported by SAP NetWeaver 7.3.
Following are the key NetWeaver BW Objects β
InfoObject
InfoProvider
As per the above architecture, following are the key objects in BPC 10.0 β
Client Interface β At the top, you have client interface which is a web-based tool used for configuration and reporting for business planning. It consists of MS Office client, Excel based admin clients, and web-based tool for reporting.
Microsoft-based admin tool is used for configuration of application and Microsoft Office tools such as Word and PowerPoint are used for reporting data.
Web Server and .NET Application Server β This tool uses web services to connect to .NET Application Server. It receives the request from client interface and directs all the requests to ABAP server, which is a part of SAP NetWeaver BW system.
This server is used for data conversion between client tools and SAP NetWeaver BW system.
SAP NetWeaver Application Server β This server is used to process all the requests from client tool. The request from .NET Application server is processed in this server as Remote Function Call RFC. This is used to process requests to create reports or to update the database.
When a request is processed by the Application Server, it gets the data and passes to .NET Application Server, and then sends it back to client interface.
Database Server β This layer is responsible to store all the data in the database. SAP NW back-end system is responsible to create objects and data is stored for BPC system. The NetWeaver supports most of the databases like SQL Server, DB2, Oracle and many more.
Following are the release notes from SAP for SAP BPC 10.0 β
Product Version 10.0, SAP NetWeaver
Area CPM-BPC
BPC now supports the following platforms β
Server Support β Any operating system that is supported by SAP NetWeaver. VMware support as per SAP standard. Virtualization, VMware, Microsoft, Windows, Hyper-V, XEN, vSphere, IBM, INxHY, KVM, zBX. SAP NetWeaver Support for NW 7.3. No support for older versions.
Server Support β Any operating system that is supported by SAP NetWeaver. VMware support as per SAP standard. Virtualization, VMware, Microsoft, Windows, Hyper-V, XEN, vSphere, IBM, INxHY, KVM, zBX. SAP NetWeaver Support for NW 7.3. No support for older versions.
Database Support β BPC supports all database that are supported by SAP NetWeaver system.
Database Support β BPC supports all database that are supported by SAP NetWeaver system.
Client Support β Microsoft Windows, WIN XP (32 bit), Windows Vista (32 bit and 64 bit), and Windows 7 (32 bit and 64 bit).
Client Support β Microsoft Windows, WIN XP (32 bit), Windows Vista (32 bit and 64 bit), and Windows 7 (32 bit and 64 bit).
Microsoft .Net Framework β .Net Framework 3.5 is required.
Microsoft .Net Framework β .Net Framework 3.5 is required.
Web Browser Support β BPC supports the web browsers - IE 8.0 and IE 9.0.
Web Browser Support β BPC supports the web browsers - IE 8.0 and IE 9.0.
Microsoft Office Support β Microsoft Office 2007 (32 bit and 64 bit) and Microsoft Office 2010 (32 bit and 64 bit). .NET server is no longer required in latest BPC versions.
Microsoft Office Support β Microsoft Office 2007 (32 bit and 64 bit) and Microsoft Office 2010 (32 bit and 64 bit). .NET server is no longer required in latest BPC versions.
On comparing BPC 7.5 and BPC 10.0, following are the key terminology differences between the two.
Environment β It is defined as the starting point for creating any application or model. It was called Application sets or AppSet in older versions of BPC.
Dimensions β You can mark a dimension as secure. You need to grant read and write access to the users who use the model so they can access data.
Properties β This is used to provide additional information to the dimension.
Dimension Members β Each dimension member record shows master, text and hierarchy data associated with the keys of dimension.
Model β To meet the Business Planning and Consolidation requirement of an organization, you need to build a model in an environment which is defined as collection of several dimensions.
Data Manager Package β To execute common tasks in BPC, you need data manager package.
Business Rules β To manage operations in different countries, different set of business rules are required. BPC includes rule-based table to meet some requirements for business planning and consolidation. Various rules can be set related to business planning and consolidation like - currency translation, balance carry forward, intercompany elimination, and data validation, etc.
Logic Scripts β This is defined as a set of SQL or MDX programming structure to perform some customize functions for flexibility and manage data models. When some specific requirements are not achieved using business rules that can be met by the use of Logic Scripts.
User β A user is defined as an individual who uses the application in Appset.
Team β A team is defined as a group of users based on user roles.
Task β All the activities that are performed in SAP BPC system are called tasks.
An Application in BPC system is defined as multidimensional data model used in EPM. Few examples of Applications are - Operation, Legal or Finance team.
There are two types of applications in BPC system - Reporting and Non-Reporting. Reporting applications are used for analysis purpose and you can pass inputs from the users. Non-Reporting applications are used to contain reference data like currency rates, carry forward balances, etc.
An Appset consists of one or multiple applications in system. Each application consists of the master data for an application, which is used to control data in the application set. An application can also share one or multiple dimensions with other applications.
Each Reporting application consists of a dimension, properties to hold the additional information, and dimension members.
Consider a Consolidation Rate application, which consists of Rate app to store currency exchange rates and an Owner application, which stores the relationship between Owner company and its subsidiary companies.
To add an application to the Application set, you can use an existing application by selecting reference applications and any set of business rules. You can also add dimensions in new application and these can be defined as secure or non-secure. When you define dimensions as secure it ensures the read and write access is controlled through user profiles.
You can add an application through an admin console β Application β Add a New Application
To copy an application β Application β Copy an Application
To create a Consolidation application, you need to define AppSet for consolidation and dimension set for consolidation.
You should set the following parameters after creating the application set.
ALLOW_FILE_SIZE
UPLOADTEMP
TEMPLATEVERSION
JREPORTZOOM
LOGLEVEL
SYSTEM
MESSAGE
STATUS
In SAP BPC NetWeaver version, all these parameters are maintained in ABAP DDIC table.
Once the application set is created, the next step is to set up the parameters for Dimension set.
You can add a new dimension or copy an existing dimension. In the Administration Console, go to Dimension and Model.
Go to Dimensions and Models β Dimension.
Click on +New β Enter ID, Description, Type β Create
To create a rate application which contains the exchange rate, following dimension types are needed β
C_Acct (A) β For maintaining Charts of Account.
C_Acct (A) β For maintaining Charts of Account.
C_Category (C) β To define Category.
C_Category (C) β To define Category.
Groups (R) β Like GROUP A (USD), GROUP B (EUR), and GROUP C (RMB).
Groups (R) β Like GROUP A (USD), GROUP B (EUR), and GROUP C (RMB).
Entity (E) β It contains the business unit used to derive process.
Entity (E) β It contains the business unit used to derive process.
C_Datasrc (D) β Data Source Dimension.
C_Datasrc (D) β Data Source Dimension.
IntCo (I) β It determines the level of entity hierarchy at which level the elimination needs to be performed.
IntCo (I) β It determines the level of entity hierarchy at which level the elimination needs to be performed.
Time (T) β Time in all dimensions.
Time (T) β Time in all dimensions.
Flow (S) β To keep track of movements in Consolidation.
Flow (S) β To keep track of movements in Consolidation.
To create a rate application which contains the exchange rate, following dimension types are needed β
R_Acct (A) β For maintaining different types of Rate.
R_Acct (A) β For maintaining different types of Rate.
InputCurrency(R) β Currency Type Dimension.
InputCurrency(R) β Currency Type Dimension.
C_Category (C) β To define Category.
C_Category (C) β To define Category.
R_Entity (E) β Rate application.
R_Entity (E) β Rate application.
Time (T) β Time in all dimensions.
Time (T) β Time in all dimensions.
To create an ownership, Consolidation application contains the ownership information. The following dimension types are needed β
O_Acct (A) β for Ownership
O_Acct (A) β for Ownership
C_Category (C) β To define Category
C_Category (C) β To define Category
Entity (E) β It contains the business unit used to derive process.
Entity (E) β It contains the business unit used to derive process.
IntCo (I) β It determines level of the entity hierarchy at which level the elimination needs to be performed.
IntCo (I) β It determines level of the entity hierarchy at which level the elimination needs to be performed.
Groups (R) β Used to implement separate group type.
Groups (R) β Used to implement separate group type.
Time (T) β Time in all dimensions.
Time (T) β Time in all dimensions.
To set up a consolidation application, three applications are required - Rate, Ownership, and Consolidation.
With the release of BPC 10.1 with NetWeaver, there are two models that can be used to fulfill the business requirements. BPC models are often referred to as BPC applications and BPC environment is normally called Application.
The following types of model can be built in BPC β
This model provides an option within host BWβs protected namespace β/CPMB/β. When you separate the BPC transaction data and master data inside the namespace (β/CPMB/β), all the sub-processes that are associated with standard model are closely secured, and only closely managed by the department running the app.
This model is designed by SAP to provide a protected area for customers who to plan and consolidate in their own department without wanting to share or coordinate the resources with other Business Warehouse community users.
As the code set of Standard model has been coordinated with version BPC 10.0 so all the changes to BPC 10.0 are shown in BPC 10.1 Standard model and changes to the version BPC 10.1 Standard model are shown in version BPC 10.0.
This allows a code compatibility between BPC 10.0 and BPC 10.1, and clients can easily perform migrations while upgrading BPC version from 10.0 to 10.1 Standard Model.
In short, you can say in Standard model, BPC environment contains the BPC applications or models and each model generates a BW InfoCube which is hidden.
This model is different from Standard model and includes data access to all community users. For Embedded design model, initial versions used were SAP BW Integrated Planning and Planning Application Kit i.e. BW-IP and PAK.
This model provides a different level of data access where master and transactional data from host EDW environment is accessible by the application. In Embedded model, it allows easy access to transactional and master data within the host BW, and this data is shared with many other users and controlled by the administrator group.
In Embedded model, migration from older versions of Business Warehouse IP, BW-IP to this data model is relatively easy and migration from earlier versions like (BPC 10.0 and earlier) is considered as a new implementation.
In short, you can say that in embedded model, any number of InfoProviders can be assigned to a single BPC model/application.
An application in BPC is also known as a model, like an environment is called an AppSet. You can create an application by going to Admin console in Enterprise Performance Management (EPM) System. BPC environment or AppSet has the group of applications or models. All these applications share the planning dimensions and are linked with each other.
As mentioned earlier, applications are called multidimensional data models in EPM. You can add a new application or also copy an existing application.
Environment management includes setting up work status for applications and adding the business rules to the applications.
Work status determines who can make changes to data or who can change the work state on the data set.
In Environment management, you can also carry out applications optimization. When a new application is created, it contains only a small amount of data. As time passes, data in application increases and it is always recommended to perform application performance optimization in BPC environment.
It is also possible to delete any application in BPC environment when required by going to admin console. You need to be an administrator to perform this function.
Dimension management in BPC includes creating new dimensions, defining members in dimensions, and assigning properties. Dimension contains member and there is a hierarchy between members that is defined like parent, child and sibling.
You can create a new dimension by going to Admin Console β Dimension β New Dimension.
Dimension name is not case sensitive and it should be unique.
When adding a new dimension, you have to enter reference type. Planning and Consolidation checks the value of reference type while processing the dimension.
Click Create button in the above window. You have to enter referential integrity for Rate type in the new window. Click βSaveβ icon.
You can also edit structure, edit members, delete or copy an existing dimension. To copy a dimension, select an existing dimension and go to Copy.
Enter the name of dimension and description. Click βCopyβ button.
Naming Conventions in Dimensions β You shouldnβt use special characters while naming a dimension, member, and application in BW table.
You can create dimension name up to 16 characters and it shouldnβt contain comma, double comma, back slashes, ampersands. However, you can use underscore.
You shouldnβt use the following names - App, AppAccess, AvlObject, CategoryAccess, CollabDoc, CollabIcons, CollabRecipient, CollabSupport, CollabType, DBVERSION, Defaults, DesktopStyleDef, Dimension, DrillDef, DTIParam, Function, Formula, Group, InvestParam, MemberAccess, MessageLog, Packages, PageDef, Permission, PublishedBooks, Rate, ReportParam, SectionDef, Status, StatusCode, TaskAccess, User, UserGroup, UserPackages, UserPovDef, WebContents, SOURCE, SIGNEDDATA.
Description of dimension shouldnβt be more than 50 characters.
You can delete a dimension by selecting it and clicking the βDeleteβ button.
BPC security is managed in Administration console. You have to login to BPC portal and go to Planning and Consolidation Administration.
There are four key components in BPC security β
Users
Teams
Task Profiles
Data Access Profiles
Users β This is used to add users to environment and manage their access rights.
Teams β This is not so important and you can define a team of users with the same access rights.
Task Profiles β This allows setting up profiles for tasks to be performed and assign them to users and teams.
Data Access Profiles β This is used to set up profiles that allow access to data in models and assign them to users and teams.
Click βTeamβ tab under Security, select Admin team and double-click.
You will see the details of Team name β ADMIN, which users are part of this team, task profiles, and data access profiles.
You can edit the team details and click βSaveβ icon to apply changes.
Going to the user tab, you can add new users, edit existing users, and delete any user.
Data loading in BPC is done with the help of Data Manager that allows you to move data in Planning and Consolidation system, copy and move data and export data from an application. Data Manager moves the data in form of packages, which allows scheduled sequences to run in the background and some can initiate other processes.
We can pull the data from different source system like SAP ECC system, SAP CRM, SRM using extractors. You can also load data from non-SAP sources to InfoCube in SAP BW system.
To load the data into InfoCube, go to workbench in BW system.
Transaction Code: RSA1
Data warehousing workbench will open, go to Source Systems on the left side.
Data acquisition in BW system can be done using the following methods β
Service API
Transfer of Flat Files
DB Connect
Universal Data Integration
XML Based Data Integration
Third party ETL tools
Application Specific Data Acquisition
Double-click on File and enter logical system name, source system name, Type and Release.
Next is to create an InfoSource for characteristics data. Right-click on InfoSource right pane β Create Application Component.
Once you create the InfoSource, right-click on it and assign data source.
Then, right-click on Source system β InfoPackage, select master data and save.
Define Load characteristics.
Finally, create an InfoSource for transaction data. Create Updating rules and an Info Package to load transaction data.
You can load data to BPC system from SAP BW InfoCube. With BPC Data Manager, you can use BPC code packages. You can copy or move data in different applications, and can export the data from applications. BPC packages are based on BW process chains and come with BPC installation.
Data Manager Tool is integrated with Excel. To start BPC, go to Planning and Consolidation β eTools β Data Manager.
In Data Manager Package, there are different data transfer modes β
Aggregate Overwrite
Append
While loading data from Info Provider, you have the following options β
Merge
Replace
BPC also supports Delta load as there are many records getting generated for each load. Delta initialization is possible with higher enhancement package and you can perform Delta load in Organize option under Data Manager Tab.
In BW system, full load is supported for Standard InfoCubes, Virtual InfoCubes, Standard and Optimized Data Store Objects DSOβs.
You can Delta load using Data Manager for Standard InfoCubes and Standard, Optimized DSO.
Next is to create a Package which contains conversion file and transformation file with variables, which is responsible to trigger a BW process chain. You can combine different packages for separate tasks in package links.
Transformation file provides the mapping of fields from BW to BPC and is an excel file in BPC. It contains transaction data from Info Objects in BW with BPC dimensions defined in administration console.
There are three sections defined for mapping file β
Options β Contains the general settings.
Options β Contains the general settings.
Mapping β Used to assign dimension in BPC system with a source column in BW InfoObject.
Mapping β Used to assign dimension in BPC system with a source column in BW InfoObject.
Conversion β Contains the link of other Excel sheets to apply the conversion routine.
Conversion β Contains the link of other Excel sheets to apply the conversion routine.
To create a Transformation File β Go to BPC Excel client. Next is to choose App set and Application where these Transformation file will be used.
Now go to Data Manager in Business Planning and Consolidation β More β New Transformation File.
You will see an excel sheet with three sections - Option, Mapping and Conversion. You donβt require to make any changes to Option, Conversion.
Go to Mapping and define Transactional data mapping from InfoObject in BW to BPC Dimension.
ACCOUNT = ZACCOUNT
TIME = ZBPCTIME
SIGNEDDATA = ZAMOUNT
Note that you can also copy an existing transformation file or update an existing transformation file by going to βMoreβ tab under Business Planning and Consolidation ribbon as shown in the following screenshot.
A Conversion file is used to apply the conversion rules for BPC dimension and is an Excel file. It contains three sections β
External β Contains the value from external source.
External β Contains the value from external source.
Internal β Contains the value it should be having for BPC dimension.
Internal β Contains the value it should be having for BPC dimension.
Formula β Defines the conversion formula applied to each record.
Formula β Defines the conversion formula applied to each record.
To create a Conversion File β Go to BPC Excel client. Choose AppSet and Application where these transformation files will be used.
Go to Business Planning and Consolidation Ribbon β More β New conversion File
You can also use other functions like - Manage conversion file, copy conversion file, etc.
You can load the data in BPC dimension from source flat file like CSV, XLS. You have to first create the dimension using administration console and a connection should be established.
Go to BPC Excel β EPM tab and click on the log on the left side panel. Select the connection name, user name and password.
Go to Data Manager tab β EPM β Upload data.
Enter the name and click βSaveβ.
Create a Transformation file as mentioned above. If the number of fields are the same for source and destination, no need to use mapping.
You will only have values under Options section and rest of the fields would be blank in this Transformation file.
If you have source and target with different number of data columns, you have to define it under mapping like for βdescriptionβ in the above screenshot.
Once Transformation file is created, next is to validate and process transformation. Select data type β Master data from flat file and click βSaveβ icon.
Go to βDMβ tab at the top in BPC Excel β Run Package.
Click βData Managementβ and select import master data attribute from flat file.
Click βRunβ at the bottom and enter the path for data file and Transformation file as created above.
Select the dimension in which you want to upload this data and click βRunβ. Once it is completed successfully, you can go to web portal check the data under Dimension.
SAP BPC 10.0 allows you to get data from source systems in to an Excel interface. It allows you to analyze the multidimensional data and BPC 10.0 provides number of inbuilt templates that can be used for analyzing and you can also add different formulas to design reports.
SAP BPC 10.0 provides various exceptional capabilities including integration with SAP HANA over BPC 7.x to handle big data environment for reporting purpose.
SAP BPC also provides use of input schedules that allow you to send the data from report to database. Input schedules provide you with all the functionalities as that are available in BPC reports. The difference between Report and Input Schedules is that reports are used for analyzing data and input schedules are used to write data to database.
You can opt from the following methods to create reports and input schedules in Business Planning and consolidation tool.
Using Default Templates
EvDRE Builder
Drag and Drop Interface
Blank Workbook
You can also create reports in Business Planning and Consolidation EPM Add-in for Excel. Excel Interface in BPC is broadly divided into the following sections β
EPM Add-In Ribbon
Connection and Dimension
EPM Context Menu
Report Area
To create reports in EPM Add-In Interface for Excel, you have to enable the following option. Go to EPM β Options β Sheet Options β Check the box βActivate Member Recognitionβ.
You can simply drag the dimensions and drop it to excel sheets. It is the easiest method and displays the report based on dimension selected from the list of available dimensions.
Other option to create report using Excel Add-in is by adding dimensions to Row axis and Column axis. Once you add the dimensions click βUpdateβ.
You can also create reports by simply typing dimension member in the report area. BPC Excel add-in identifies the member and display result.
Following are the two versions of EPM Add-ins β
EPM Add-in .net 3.5
It supports MS Office 32 bits.
It supports MS Office 32 bits.
It degrades the performance if you are querying using ODBO connection.
It degrades the performance if you are querying using ODBO connection.
It runs on .net 3.5 framework.
It runs on .net 3.5 framework.
It supports .msp file.
It supports .msp file.
It doesnβt support big volume BV mode.
It doesnβt support big volume BV mode.
EPM Add-in .net 4.0
It supports MS Office both 32 and 64 bits.
It supports MS Office both 32 and 64 bits.
It supports BV mode on BW data sources.
It supports BV mode on BW data sources.
It provides performance optimization if you are querying using ODBO connection.
It provides performance optimization if you are querying using ODBO connection.
It also support *.msp file (have to uninstall/re-install).
It also support *.msp file (have to uninstall/re-install).
It supports BW connections for embedded model.
It supports BW connections for embedded model.
There are various templates in sample app set and you can select any of these and customize them to meet the report requirement.
Using this feature, it allows you to save report locally or on the server. When you modify an existing report you can also save it as template for future use. BPC administrator can only have rights to save customized report as template on the server but you can save them locally.
Following are the default templates in BPC β
Launch EPM Office Excel Add-in, to use a template. These templates are available in Company folder and they are created using BPC add-in not like BPC 7.x where templates are created using EvDRE.
There are three ways to create a report in BPC. You can create simple reports using EPM action pane by dragging dimensions and dropping it to the report area.
You can add dimensions to direct axis as shown in the following screenshot.
Similarly, you can create ad-hoc reports using the action pane.
All reports that have been created in BPC 7.5 Excel can be migrated to BPC 10.0 using EPM Excel Add-in. EvDRE migration feature in Add-in is used to migrate as many features as possible to new version but the customized reports and templates can only be partially migrated and requires some manual effort for full migration.
Open the reports created in EvDRE.
Update the report to have correct Dimensions migrated. Next go to EPM Ribbon β More β EvDRE Migration.
To access Business Planning and Consolidation, you can login to web client. To launch web client, open the web browser and use the URL - http://server.domain:port/sap/bpc/web/
When you login to BPC web client, first screen that opens is start page and home tab.
If you want to create reports using Web Client, you can go to create area which has the following options β
New Workspace
New Report
New Input Form
Go to New Report and the following screen will open.
From the dropdown menu, select a new report, input form. On the right side, you have the list of available dimensions. You can add dimension to Row and Columns as per requirement.
You can also edit the existing reports. There is an option to defer report layout. If you select this option it wonβt change the report layout.
SAP BPC provides you with an end-to-end planning process and perform activities like planning, forecasting, budgeting, reporting, etc. It allows you to follow top-down or bottom-up planning with an application and user interface.
In Business Planning and Consolidation, the planning process is supported by automation and workflows. It allows you to create reports and input forms that can write to database.
With reporting interface, you can get data from database to excel spreadsheets and input forms allow you to send data directly to the database.
Input forms contain the same functionality and formatting as reports, only difference is that reports are used for analysis and input forms are used for sending data to database.
Different modeling options are possible with input forms to meet the planning needs while sending data to database.
Spread β Spread modeling option allows you to send a value to specific destination cells. This value can be spread equally or weighted by the range of values.
Trend β Trend modeling method allows you to spread a value or a percentage and spread it by a growing factor in destination cells. You place the source value in first destination cell and rest of the cells are field with increased value by some amount or percentage.
Weighted β It allows you to allocate a set of values by weighted factor in the excel sheets. In this you select some values, grow them and then allocate the new amount based on weights of selected cells.
So input forms provide you with special modeling feature to assist you in your planning needs.
Note that input forms is the terminology used in BPC 10 whereas input schedules were used in BPC 7.x. However, eventually they both represent the same thing.
Input forms allow you to spread data from excel sheets directly to database and contains all the functions that are present with reports in BPC. The difference is that input forms write data to database and reports are used for analysis purpose.
Input forms support the following features β
Data Submission β If you have enough authorize access, using input forms you can send data to database. If data validation is allowed by the system administrator, you can also validate the data and ensure that there is no work lock and validity issues on members.
Modelling Options β Various modeling options can be used with input forms β
Spread
Trend
Weighted
Work Status β After sending the data to database, you can change the work status locks to apply data locks.
Distribution and Collection Option β You can send the input schedules to different members using distribution option and then get back the input schedules using collection option.
Using Special formalities β You can also apply special formatting to read-only cells.
There are various templates provided in the system that you can use and apply the customizations as per your needs.
Following is the list of dynamic schedule templates that are available in the system.
Input schedules can be developed using the following methods.
Dynamic Templates
Using EvDRE
Using Drag and Drop
To create an input form/schedule using drag and drop, login to web client.
In the type select the input form. You can also add dimensions by clicking on + sign.
You can drag the dimension to rows and columns from the list of available dimensions and once you are done, click βSaveβ.
Enter the name of input form and description and click βSaveβ.
You can also view the real-time data from BusinessObjects Planning and Consolidation via Dashboard designer. To create Dashboard with BPC, you need to install Dashboard designer and add EPM Connector Add-on to the Dashboard designer and connect to the EPM data using EPM Connector.
Once connector is installed, you can use BPC real time-data to create dashboard.
Go to Analyzer tab in Dashboard Designer.
Then go to Edit Report.
It will prompt you to add a new connection. Click on Add new button. Select SAP BusinessObjects Planning and Consolidation data source from the dropdown list and click βConnectβ.
It will open a new window promoting for BPC Server name, User name and password. You have to enter the same credentials that you use to login BPC Excel client. Once you enter the details, click βNextβ. Select the AppSet and Finish the wizard.
Select the cube from the dropdown list that contains the data you have to use and select the data source name.
Next select the newly created connection and click βOKβ. Once you click ok, it will open the Report Manager output, which can be used to design the report output.
These are the steps that can be used to integrate Dashboard Designer with SAP BusinessObjects Planning and Consolidation BPC tool. There are various features in the Dashboard designer that can be used to create interactive dashboard, which can be used by decision makers.
You can perform business logic and script logic on the data in BPC. There are various calculations that can be performed.
Business Rules β These are monetary functions which are used to post common accounting tasks in Business Planning and Consolidation model.
Script Logic β This includes the formulas which are used to perform different calculations on the members, dimensions, and data in BPC system.
Dimension logic is used to apply calculations and formulas on the dimensions. Calculations are performed as per the dimension formula at retrieval time. It is important to use the dimension formulas correctly as they can affect the system performance if used incorrectly.
Key points to remember while applying Dimension logic β
Dimension formula affects the system performance so they should be applied correctly.
Dimension formula affects the system performance so they should be applied correctly.
Dimension formulas should be applied only on the members for which calculations are required after the aggregation.
Dimension formulas should be applied only on the members for which calculations are required after the aggregation.
Dimension formulas should be used only for those ratios which has to be calculated at both the levels - Base and Parent Level.
Dimension formulas should be used only for those ratios which has to be calculated at both the levels - Base and Parent Level.
Common Dimension member formulas are used to perform calculations - costs per unit, growth rates, etc.
Common Dimension member formulas are used to perform calculations - costs per unit, growth rates, etc.
You should be familiar with Multi Dimension Expression language to create complex Dimension formulas. The list of supported MDX functions is available from functional module BAPI_MDPROVIDER_GET_FUNCTIONS.
Prerequisites β To use a formula in dimension, you should add a property called Formula to member sheets using manage dimension task option.
You should also define the length of field and it should be more than 60 characters. Higher field lengths are preferred as any length greater than 60 is stored as string in SAP NetWeaver.
If you want to use Dimension formula in AppSet then you should maintain a special dimension member of type R. This member is called as Local Currency (LC).
App set β Select Maintain Dimension Members.
The formula can be manually created or taken from a library dimension formula. To define member dimension formula, you have to put a Square bracket around the dimension and there is a dot between the two.
[PRODUCT].[PRODUCT1] β [PRODUCT].[PRODUCT2]
[SALES].[SALES1] / [SALES].[SALES2]
Standard Arithmetic functions has to be used in dimension formula - addition (+), subtraction (β), multiplication (*), Division (/) - these are used in SAP NetWeaver.
Once you save the dimension formulas, next is to validate the syntax.
Logic scripts allow you to automate the calculations in BPC for the financial statements.
Business rules are used to customize the data manipulation task like bulk data imports with currency translations, input data to database, etc. Business rules can be modified using table-based logic or scripts-based filters. Table-based logic provides the features available in UCON accelerator and Script-based files can be customized using MDX or SQL syntax.
You can define business rules for the following activities β
Carry forward rules β Includes initializing balances when a new fiscal year starts.
Carry forward rules β Includes initializing balances when a new fiscal year starts.
Validation rules β Validates the input data.
Validation rules β Validates the input data.
Currency conversion rules β Converts the local currencies into the currency used in BPC reporting.
Currency conversion rules β Converts the local currencies into the currency used in BPC reporting.
Intercompany booking rules β Matches intercompany transactions.
Intercompany booking rules β Matches intercompany transactions.
Automatic Adjustments and Other Calculations.
Automatic Adjustments and Other Calculations.
To manage business rules in BPC system β Go to Administration as shown in the following screenshot. Go to Rules β Expand β Business Rules.
With help of script logic, you can write your own logic in SQL or MDX language. There are various MDX functions that can be used in dimension formulas. Some of the common MDX functions are β
Avg β Returns average value of a numeric expression.
Avg β Returns average value of a numeric expression.
Count β Returns the number of tuples in one set and also includes null cells.
Count β Returns the number of tuples in one set and also includes null cells.
Max β Returns the maximum value of a numeric expression.
Max β Returns the maximum value of a numeric expression.
Min β Returns the minimum value of a numeric expression.
Min β Returns the minimum value of a numeric expression.
Sum β Returns the sum of numeric expression.
Sum β Returns the sum of numeric expression.
There are other MDX functions that can be used in dimension formulas.
Examples of simple rule formulas
[PRODUCT].[PRODUCT1] β [PRODUCT].[PRODUCT2]
[SALES].[SALES1] / [SALES].[SALES2]
Standard Arithmetic functions have to be used in dimension formula - addition (+), subtraction (β), multiplication (*), Division (/) - these are used in SAP NetWeaver.
Once you save the dimension formulas, next is to validate the syntax.
Examples of Advance Rule Formulas
This includes movement of calculation dimension formulas from one time period to another.
[AccRec] Accounts Receivable
[AccPay] Accounts Payable
Syntax for creating script logic in dimension formulas are already covered.
Exceptions in MDX Syntax
Following are the exceptions to MDX syntax with BPC β
Replace the keyword AS with an β=β (equal) sign.
Not to use single quotes around expressions.
Example
[ACCOUNT].[#GROSSSALES] = -[ACCOUNT].[UNITS]*[ACCOUNT].[INPUTPRICE]
[ACCOUNT].[#COST] = -[ACCOUNT].[#GROSSSALES]*80/100
All the calculations performed in Excel worksheet is known as Worksheet logic. Worksheet logic includes all the functions that are available in an Excel spreadsheet and functions provided in BPC.
Business Planning and Consolidation performs various business functions such as audit, business process flows, finance statements and reporting, and work status.
Various inbuilt functions are provided to perform these functions.
Currency conversion is required if your monetary figures are present in more than one currency in your application set. If app set contains monetary figures in single currency, in that case you donβt need a rate application, currency time dimensions, etc.
If most of your data is entered in one currency and you have only few figures in other currency, this can be handled by creating duplicate members in entity dimension. In this case, you can duplicate few entities present in foreign operations to separate local currency from translated amounts.
Example β The US corporate mostly deals in the US but also has few subsidiaries functioning in other countries like Canada and Mexico.
There should be rate application where you store the exchange rates. You should have an account dimension, which includes RATETYPE. Then Entity dimension should include a property CURRENCY. FXTRANS logic should be available and DEFAULT logic should include a call to FXTRANS logic. Entity dimension should include the property TRANSALATE_TO.
There should be rate application where you store the exchange rates. Application should contain a CURRENCY type dimension. There should be property REPORTING for the CURRENCY dimension. Entity dimension must include the property CURRENCY. Account dimension must include property RATETYPE. FXTRANS logic should be available. DEFAULT logic should include a call to FXTRANS logic.
All valid rate types corresponds to an account of RATE application and belongs to GROUP FX Rate. If there is any account which is not part of this group, it will be multiplied by a factor 1. You can also define a special case NOTRANS, which results in an account being ignored during the translation.
Cross-rate translation includes multiplying the amount in local currency by ratio between the rate of destination currency and the rate of source currency. Using this, application can use only one table of rates for translating any source currency to destination currency.
You can also define the following default translations using business rules β
Using different tables of rate by reporting currency.
Using different tables of rate by reporting currency.
Identifying the difference between multiply currencies and divide currencies.
Identifying the difference between multiply currencies and divide currencies.
To perform currency conversion and intercompany eliminations, you need a dimension type - Intercompany dimension (I). To execute intercompany elimination, an application should have the following β
Dimension Type βIβ for intercompany elimination.
Dimension βIβ should include a property ENTITY.
Account dimension should include the property ELIMACC.
Entity dimension should include the property ELIM.
You should set the appropriate business tables.
There should be DPT package to execute intercompany logic.
Default elimination logic performs the following functions β
Checks all base level entities where ELIM<>Y.
Restricts currency dimension to all reporting currencies only.
Removes all accounts to be eliminated into desired plug account.
Elimination is performed below first common parent in βelimination entityβ.
This is used to manage processes created by users and to create and manage business process flow templates. To manage business process flows, you need to have manage processes task profile.
Process template is defined as business process, which contains all the tasks that is spread across multiple modules of BPC system. It includes step-by-step process flow, user performed activities link, process context and timing when process takes place, all the participants and their roles.
An area manager entering monthly budget data, which includes each manager creating a process and entering the data for each department.
To create a new Business Process Template, login to Web portal β Planning and Consolidation Administration.
On the left side, you can see the option of Business Process Flows.
Expand this tab and you will see Process Templates and Process Instances.
To create a new Business Process template, go to tab Process Templates. Click β+Newβ.
BPC admins are responsible to create and manage process templates. Once process templates are created, the business user can use the templates to create processes.
Work status is used to lock a region of data in a model. This is used to override userβs member access privilege to write to a particular region.
There are multiple dimensions defined for a region with one property called as OWNER. While defining the work status, following are defined β
Work Status β It belongs to physical state of data.
Work Status β It belongs to physical state of data.
Security β You can set different level of security on changing data in the system β All or Locked. You can set who can change the work state - Manager or Owner.
Security β You can set different level of security on changing data in the system β All or Locked. You can set who can change the work state - Manager or Owner.
Data Update β This defines how data will be updated by the customer.
Data Update β This defines how data will be updated by the customer.
Push β This option is used to push same work state for all the children of a member.
Push β This option is used to push same work state for all the children of a member.
Once work status is defined, they can be used by the users to lock the data for review and approval, etc. To implement e-mail notification of work status, you should set the parameters, APPROVALSTATUSMAIL, APPROVALSTATUSMSG, SMTPPASSWORD, SMTPPORT, SMTP SERVER, SMTPAUTH, etc.
Go to Business Planning and Administration β Features.
On the left side, you have Features tab. Expand this tab and you will see Work Status as the first option.
Go to Work Status and on the right side you will get options to create and manage work status.
You can define in BPC system, who can change the data. This includes the following access levels β
All β This allows all users with appropriate access to change the data.
Locked β This locks the change on the data. None can change the data.
Manager β Only parents of owners/manager can change the data.
Owner - Only the owner can change the data.
Both β If you select both, owner of the specific member ID and the owner of the parent to the specific member ID.
Owner β Owner of the specific member ID.
Manager β Owner of the parent to member ID.
Parent member owners act as an owner for that specific parent member ID and work as manager for direct children.
This allows parent member owner to change the work status of direct children. In case you are selecting all children, owner of a parent can update children at all levels.
Base membersβ owners act as owner only.
Members with no parent but have children act as their own manager and owner too.
An owner is defined by one dimension hierarchy β OWNER dimension.
You can set a work state on a single member ID, in this Manager doesnβt include - All Children.
You can also set work state on multiple member IDs, manager uses Include - All Children.
To edit a work status β Select the Work Status, click on Edit button at the top.
You can set from the above βControlled byβ fields.
To delete a Work Status, select the work state and click βDeleteβ.
You can publish books to BPC web. Administrators and power users have an option to create books of reports by collecting series of reports. You can select an output as Printer copy or .pdf file, which can be stored on the server.
You can use Book Publishing wizard for this. Go to ePublish option and select Book Publishing wizard from there.
It will open Book Publishing Wizard β Select Publish Now as shown in the following screenshot.
You get two options - Publish to a PDF file or print to a printer.
To delete books in BPC web, go to BPC administration.
Select Administration Configuration action pane β Manage Books.
Select the book you want to manage by using the checkbox and click βDeleteβ.
It is easier to integrate BPC with MS Word and to create reports. BPC 10.0 has the capability to directly integrate and report using Microsoft Word and PowerPoint as well.
BPC 10.0 version of NetWeaver helps you combine the BPC features with rich functionality of Microsoft Word, Excel, and PowerPoint. Using BPC for office you can use all default features of Microsoft and worksheets, presentations can be directly linked to BPC database.
Following tasks can be performed for client maintenance.
Reset the Current View Bar
Clear Local Application Information
Refresh Dimension Members
Refresh Dynamic Templates
Set Local folder for Planning and Consolidation for Clients
You can open these interfaces via BPC Web β List of available interfaces
Go to File β Save As. Select Save as Web Page as shown in the following screenshot.
Enter the file name and select the Web folder that points to your BPC application set location.
You can select from the following directories β
AppSetPublications β Used for publication that applies to all applications within AppSet.
[application] β Used to publish for a specific application.
_private β User specific.
Once you select the directory, click βSaveβ icon.
As discussed earlier, you can integrate PowerPoint to BPC 10.0.
Go to File β Save As. Select Save as Web Page as shown in the following screenshot.
Enter the file name and select the Web folder that points to your BPC application set location.
You can select from the following directories β
AppSetPublications β Used for publication that applies to all applications within AppSet.
AppSetPublications β Used for publication that applies to all applications within AppSet.
[application] β Used to publish for a specific application.
[application] β Used to publish for a specific application.
_site β Used to publish for a specific site.
_site β Used to publish for a specific site.
_private β User specific
_private β User specific
SAP BPC also provides essential tools β Documents (repository to store files), Journals (to make adjustments to data in database), statistics, audit, etc.
This provides a central repository for storing and sharing files and web sites. There is a feature named Document View that can be used to post, share, and retrieve files or contents of a website.
You can post files or URL to add to documents view. You can set the description, set access, and determine if you want to send an email notification about the document.
You can save a file to a local drive or network folder. Files with the following extension can be uploaded β
XLS, .XML, .MHT, .MHTML, .HTM, XLT, .DOC, , .HTML, .XLSX, .XLSM, .XLSB, .ZIP, .PDF, .PPTX, .PPTM, , .CDM, .TDM, .PNG, .GIF, .JPG, .CSS, .MRC, .DOT, .PPT, .POT, .POTX, .POTM, .DOCX, .DOCM, .DOTX, .DOTM
BPC Administrator can also change the environment parameters (DEFAULT_EXTENSIONS) to allow other files to be posted.
Categorization of documents, sorting, and filtering of documents is also possible based on the following elements β
Document type and subtype
Model context
Access rights
Date
To access the Document Type, go to BPC Web Portal β Administration.
On the left side of the screen, you have an option to select βFeaturesβ.
Once you expand Features, you will get an option of Document Types. You can select the document type and sub type from here and edit.
Audit function allows you to create reports that contains history of user sessions and system information. You can create Audit reports on the following topics β
Business Process Flow β You can create these reports in BPF.
Standard
Step
Audit
Security β You can create these reports in Security.
User
Team
Task Profiles
Data Access Profiles
BPF
General β You can create these reports under general.
Work Status
Administration Activities
Comments
Data Changes
Go to Business Planning and Consolidation Administration. On the left side of the screen, you have an option to create Audit reports.
Once you click on Audit tab, you will see all three reporting options.
To create a report, click on any of the report type.
Select the Audit level - template, instance and Duration and click on Display.
Similarly, you can create Security and General Reports.
Journals in BPC are used to update data in database. This is normally done to post quarter end or year-end data in BPC.
Suppose an administrator has uploaded a general ledger information into an application for the Area manager to review using data manager. The Area Manager can make necessary changes to the data using journal entry.
Following are the tasks that can be performed from Journal manager. If you have any open journal entry, you can perform these from Journal options.
There are many more Journal entry functions that can be performed using Journal Manager or from Action Pane.
To create, edit, delete and modify Journal Parameters, go to Business Planning and Consolidation Administration β Features.
Expand the Feature tab β Select Journals.
From here, you can create new journals, delete template, journal parameters, delete journals, etc.
Business Process Flows are used to guide users with predefined set of application tasks. These steps should be performed in a series and can have sub steps too.
Sub steps in process flow shouldnβt be executed in a sequence and may not be required at each iteration. Also note that Business Process Flows can only be defined for end user tasks and not for administrative tasks.
Following Business Process Flow features can be used β
This list is used to display the steps and sub steps assigned to you or the completed steps that you need to review. These are called step regions.
To-do list contains the name and status of each step region. They can have the following statuses β
Action Required β Waiting for completion as new step
Action Required β Waiting for completion as new step
Review Required β Step is awaiting review and action is completed
Review Required β Step is awaiting review and action is completed
Completed β Step is completed
Completed β Step is completed
Rejected β Step has failed to pass the conditions in completion status
Rejected β Step has failed to pass the conditions in completion status
Pending β Step is waiting for reopened step to be completed
Pending β Step is waiting for reopened step to be completed
There are various other βTo-do listβ status like reopen, waiting proper work status, waiting for reopen and unavailable.
You can also reopen a completed step or reset a particular instance or a set of business process flow instances. To reopen a step, it should have the following criteria β
Allow reopen attribute should be included in step.
Allow reopen attribute should be included in step.
Step status should be complete.
Step status should be complete.
You can only open one previous step at a time and steps can be opened in a sequence.
You can only open one previous step at a time and steps can be opened in a sequence.
If a step has an attribute Enable Reviewers, users canβt reopen this step directly but can send an email request to reviewer.
If a step has an attribute Enable Reviewers, users canβt reopen this step directly but can send an email request to reviewer.
The user has ReopenBPFStep task security assignment.
The user has ReopenBPFStep task security assignment.
All completed steps are audited by system and displayed in the report.
All the locked dimensions that are not specified in Business Process flow current view remain locked in any open worksheet.
Copying a Business Process Flow β Login to Business Planning and Consolidation Administration β Business Process Flows.
List of all BPF is displayed. To copy a BPF, select BPF and click βSave Asβ. Enter the name and description of BPF and save as BPF.
Similarly, you can reset a Business Process flow, using manage option by selecting reset process flow instances.
Custom menu provides a summary of a business process and also provides a link to useful information used in the process. BPC administrators are responsible to create custom menus and assign access rights so that only required people see these menus. There is a possibility that you can have multiple users with different access rights on a single custom menu.
A custom menu is defined using custom menu template. EV_MENUSTYLE worksheet of custom menu template is used to define format, content, functions and parameters of custom menu.
You can use custom menu template to define format, content, and functions in custom menu. You can use sample templates in ApShell or can create a custom menu by creating a new worksheet within an existing menu.
The sample template contains multiple worksheets β
EV_DEFAULT β To define content of custom menu.
EV_DEFAULT β To define content of custom menu.
EV_MENUSTYLE β To define format of custom menu.
EV_MENUSTYLE β To define format of custom menu.
ADMINGROUP β This is the same as EV_DEFAULT but only edited for users in admin group.
ADMINGROUP β This is the same as EV_DEFAULT but only edited for users in admin group.
To create a custom menu template
Go to BPC Excel eTools β Custom menu manager β Open Custom menu.
You can find sample custom menu templates under EXCEL/Reports/Wizard/ProcessMenu. There are various custom menu functions that can be used to perform various common excel activities such as β
HIGHLIGHT
OPENLOCALFILE
NAVIGATION
OPENWEBFILE
OPENLOCALFOLDER
OPENWEBFOLDER
MEMBERLOOKUP
OPENMYEVEREST
OPENURL
CHANGEGROUP
PUBLISHBOOK
Custom menu content is defined by two section in custom menu template - Default section and Menu item section.
Following default parameters can be defined for EVDEFAULT.
Value is True β It opens the custom menu in Excel interface.
Value is False β It opens the custom menu in Standard Excel.
If Value is True β It will hide the Planning and Consolidation Toolbar.
If Value is False β It will display the Planning and Consolidation Toolbar.
It is used to define the dimensions that has to be displayed on the top of custom menu page. These dimensions can be changed into the report mentioned in Custom menu.
Menu Item section includes the following parameters β
Menu Item β Text description that the user can select for menu item.
Menu Item β Text description that the user can select for menu item.
Actions β Highlight, custom menu function or Menu command.
Actions β Highlight, custom menu function or Menu command.
Level β Level can be selected from section, item or sub item.
Level β Level can be selected from section, item or sub item.
Parameters β For custom menu functions.
Parameters β For custom menu functions.
Normal Screen β Default is full screen. This is set true, open custom menu in Normal screen
Normal Screen β Default is full screen. This is set true, open custom menu in Normal screen
CVOverride β This is used to change current view dimensions while switching applications.
CVOverride β This is used to change current view dimensions while switching applications.
SAP BPC Consolidation module is used to manage and prepare consolidated data and provides a correct view of consolidated data in an organization. Consolidation module also provides an environment to perform consolidation tasks over the web.
In SAP Business Planning and Consolidation NetWeaver version, you have consolidation monitor that is used to manage consolidated data reported by groups and entity members. Consolidation monitor also controls the reported data.
Consolidation central contains journals, which are used to create and manage journal entries for updated consolidated data in database.
It contains Ownership Manager to manage ownership-based hierarchies.
Setting up environment includes managing master data load after you have completed the installation of BPC. Business users can set up to refresh master data on nightly or weekly basis. This can be achieved in the following different ways.
First option is you download the data from SAP BW system to a flat file and then using BPC DM Manager load the data from flat file to BPC dimensions.
Other option is to load the data directly to BPC dimension through SAP BW Transformations. The selection of option depends on your business requirement to find out which solution has to be implemented.
Following steps illustrate how to import a transport and create a new data manager package to process master data import.
First step is to Import Transport - Transaction Code: STMS
Next step is to create Data Manager Package to load from Application Server. Open BPC Excel and login. Go to Action Pane and select Manage Data.
Now to create a new package, go to Maintain Data Management β Manage Packages.
To create a new package, right-click on the blank area and select Add Package.
Click Process chain dropdown option and select Z_IMPORT_MASTER_DATA_LOAD. Click on the Select option.
Enter the Package name and description. Click on Add and Save.
Now go to Manage Packages option under Maintain Data Management. Select the package which has been created in the previous step and click on Modify.
In next window, click on View Package and then click βAdvanceβ button.
In next window of maintain dynamic script, click βOKβ.
Click βSaveβ and βOKβ and close the setup.
Models are used to hold the relationships, calculations and data in an organization. There are two types of models that can be created β
Reporting Model
Non Reporting Model
We use reporting models for analysis purpose. Non Reporting modules include Driver and Rates model and are used for currency rates, price, ownership data, etc.
Types of Reporting Models β Following are the types of non reporting models.
Consolidation
Finance
Generic
Types of Non Reporting Models β Following are the types of non reporting models.
Rate
Ownership
Note that you can do reporting on non-reporting models but you canβt assign work status to them.
To create a model, login to Business Planning and Consolidation Administration.
Go to Dimensions and Models on the left side of the screen, click βModelsβ tab. To create a new model, click on β+ Newβ sign.
In the next window, you have to enter model Id and description and go to Next button.
Select the Model Type - Reporting or Drivers and Rate and click βNextβ.
In the next screen, you have an option to select a blank model or you can copy from an existing model.
Once you select next, in the new screen you have to select dimensions to be included in the new model. You have to add specific dimensions as per model type.
Click βNextβ. In the last window, you will get a summary and create option. Click βCreateβ option to create a new model.
Similarly, you can copy an Existing model.
A logic is defined as calculations performed at different level. Execution of consolidation logic requires some sort of expertise and business requirement. A logic can be defined at different levels β
Within a dimension using Microsoft MDX language.
Within a dimension using Microsoft MDX language.
With the help of scripts.
With the help of scripts.
Using business rules that are executed with predefined business requirements.
Using business rules that are executed with predefined business requirements.
BPC Excel formulas.
BPC Excel formulas.
A logic can be executed at different levels β
Analysis Services
BPC Application Server
Excel/Live Reporting
Login to Business Planning and Consolidation Administration β Rules.
Select Logic Scripts option on the left side of the screen. Select the Model from the right side of the screen.
Click on + New sign and enter the Logic Script File Name. Go to βCreateβ button.
Enter the Logic script and click βValidateβ.
Once the script is validated, click βSaveβ button.
To perform currency conversion and intercompany eliminations, you need a dimension type - Intercompany dimension (I). To execute intercompany elimination, an application should have the following β
Dimension Type βIβ for intercompany elimination.
Dimension βIβ should include a property ENTITY.
Account dimension should include the property ELIMACC.
Entity dimension should include the property ELIM.
You should set the appropriate business tables.
There should be DPT package to execute intercompany logic.
Default elimination logic performs the following functions β
Checks all base level entities where ELIM<>Y.
Restricts currency dimension to all reporting currencies only.
It removes all accounts to be eliminated into desired plug account.
Elimination is performed below first common parent in βelimination entityβ.
SAP BPC Consolidation central is used to manage and prepare consolidated data and provides a correct view of consolidated data in an organization. Consolidation module also provides an environment to perform consolidation tasks over the web.
Following are the key features in Consolidation Central β
In SAP Business Planning and Consolidation NetWeaver version, you have consolidation monitor that is used to manage consolidated data reported by groups and entity members. Consolidation monitor also controls the reported data.
It is one of the key components while executing incremental consolidation as it communicates with consolidation engine to perform currency translation execution. Consolidation monitor also displays the group-entity hierarchy that is defined in Ownership manager. Using the consolidation monitor, you can execute full consolidation that contains group-entity hierarchy. You can also perform incremental consolidation with only updated entities.
Consolidation central contain journals which are used to create and manage journal entries for updated consolidated data in database.
It contains Ownership Manager to manage ownership-based hierarchies.
It is used to manage controls which is used to validate reported data.
Journals in BPC are used to update data in the database. This is normally done to post quarter end or year-end data in BPC.
Example β Suppose the administrator has uploaded general ledger information into an application for Area Manager to review using data manager. The Area Manager can make necessary changes to the data using journal entry.
Following are the tasks that can be performed by Journal manager. If you have any open journal entry, you can perform these from Journal options.
There are other Journal entry functions that can be performed using the Journal Manager or from the Action Pane.
To create, edit, delete and modify Journal Parameters, go to Business Planning and Consolidation Administration β Features.
Expand the Feature tab β Select Journals.
Using this, you can create new journals, delete template, journal parameters, delete journals, etc.
Translating local currency means converting the amount in source currency to a target currency. You can perform currency translation at any group/entity level.
Translating local currency is performed in consolidation central of Business Planning and Consolidation system. To run the currency translation on a specific entity, your BPC administrator should grant you write access on that entity.
Following are the main facts in performing local currency translation β
Category β This includes categorization of reported data to which you linked the translated amount.
Category β This includes categorization of reported data to which you linked the translated amount.
Time β It displays the data entry period in which the amount to be translated was entered.
Time β It displays the data entry period in which the amount to be translated was entered.
Reporting Currency β This tells you to select the currency in which you want to run the translation.
Reporting Currency β This tells you to select the currency in which you want to run the translation.
Group/Entity β This defines the fields on which translation is performed.
Group/Entity β This defines the fields on which translation is performed.
Translation Execution Mode β You can perform a full translation of local currency or you can select an incremental translation.
Translation Execution Mode β You can perform a full translation of local currency or you can select an incremental translation.
Rate Entry β This contains the exchange rates to select while performing currency translation.
Rate Entry β This contains the exchange rates to select while performing currency translation.
Go to BPC web portal β Select Consolidation Central.
Go to Consolidation Monitor after expanding Consolidation Central.
Select the entity/group row for which you want to perform currency translation.
In the next dialog box, select the Execution mode - full translation or Incremental Translation. Click βOkβ after selecting the fields.
In BPC, it is necessary to configure intercompany eliminations between subsidiaries or parents to avoid double counting. Intercompany eliminations is performed with help of script logic.
If you have transactions between subsidiaries Co. XP02, XP03, these transactions should be eliminated. These transactions are for intercompany account payable and account receivables, and intercompany sales and cost.
Before performing intercompany elimination, you should have the following prerequisites β
A consolidation environment
You should perform currency conversion before elimination.
To start with, first create a dimension for IC elimination. Application where you have to perform IC elimination must have dimension of type βIβ and βRβ for account and rate. Account dimension must have an elimination account property to post IC transfer balances.
Next is to have an Entity dimension with a property ELIM (Y/N) to post elimination entity results. This property is set to βYβ for elimination entity.
Account Dimension βIβ should have an ENTITY property and should be maintained β
XP01_Input
XP02
XP03
XP04
XP05
Your currency dimension βRβ should have a property βReportingβ and should be maintained β
IC Elimination is managed by inbuilt procedures - INITIALIZE_ELIM and ELIMINATE_ORG. Both of these procedures are maintained in ICELIMWITHCURR.LGL file.
The following logic should be entered in application ICELIM logic file and should be validated and saved.
//Logic for Intercompany Elimination
//========================================================
*INCLUDE SYSTEM_CONSTANTS.LGL
*SYSLIB ICELIMWITHCURR.LGL
//========================================================
//Elimination logic
for organizations in the hierarchy H1
//========================================================
*INITIALIZE_ELIM()
*ELIMINATE_ORG(H1)
*COMMIT
To validate this logic, go to Action pane and select βValidate and saveβ option.
Once the above configuration is in place, you have to create an input schedule or import package to load the data to be eliminated.
To run the import package for IC elimination, login to BPC Excel. Click on Manage Data and go to Run a Data Management Package.
Go to Company folder of application, click on Financial Processes β Select Package IC Eliminations and click βRunβ.
Once this package is executed successfully, you can check the values of the following components in Profit and Loss statement and balance sheets.
Ownership terms is managed by the Ownership Manager. The Ownership Manager is used to manage ownership-based hierarchies. These hierarchies combine groups and entities and these entities can be connected or disconnected from groups as per the category and time.
Ownership-based hierarchies are used to meet the reporting requirements which canβt be managed using fixed hierarchies.
To display the Ownership manager, login to BPC web portal home page. Go to consolidation Central on the left side of the screen β Ownership Manager.
To create an Ownership-based hierarchy β Go to Ownership manager as mentioned above. Click on Edit option provided in the Ownership Manager.
In the next window, you will get an option to add members to hierarchy. Click βAddβ button and you will have an option to select members.
Once hierarchy members are added, click βSaveβ option on the top right corner of the screen.
Purchase method is sometimes also called the Global method. Business Planning and Consolidation supports the following consolidation methods β
Global (Purchase) method
Proportional method
Equity method
In this method of consolidation, balance sheet accounts and Profit and Loss accounts are fully included and minority interests are calculated if necessary.
In this method, you include balance sheet and P&L accounts at the percentage of ownership.
Example β Including P&L statement and balance sheet are included 50% at the percentage of ownership.
In this method, you donβt include balance sheet and P&L accounts. However, Net Value and Result of the Period are included.
BPC Embedded model is based on Business Warehouse-Integrated Planning (BW-IP) in which it uses BW objects directly. This model is different from Standard model and includes data access to all community users. For Embedded design model, initial versions used were SAP BW Integrated Planning and Planning Application Kit i.e. BW-IP and PAK.
This model provides a different level of data access where master and transactional data from host EDW environment is accessible by the application. In Embedded model, it allows an easy access to transactional and master data within the host BW, and this data is shared with many other users and controlled by the administrator group.
In Embedded model, migration from older versions of BW-IP to this data model is relatively easy and migration from earlier versions like (BPC 10.0 and earlier) is considered as a new implementation.
In short you can say that in embedded model, any number of InfoProviders can be assigned to a single BPC model /application.
Following are the key features and functions offered in BPC 10.1 Embedded model β
It uses exception real-time SAP HANA functionalities and hence safeguards SAP HANA performance through the Planning Application Kit. Using SAP HANA allows to perform certain planning functions like copy, distribute, etc.
It uses exception real-time SAP HANA functionalities and hence safeguards SAP HANA performance through the Planning Application Kit. Using SAP HANA allows to perform certain planning functions like copy, distribute, etc.
BPC-Integration planning supports the use of real-time InfoProviders and aggregations levels.
BPC-Integration planning supports the use of real-time InfoProviders and aggregations levels.
Embedded model supports SAP BW Queries that you can execute directly in the SAP EPM add-in for Microsoft Office.
Embedded model supports SAP BW Queries that you can execute directly in the SAP EPM add-in for Microsoft Office.
Embedded model provides audit functions to allow creating various audit reports and use of the business process flows.
Embedded model provides audit functions to allow creating various audit reports and use of the business process flows.
SAP BW Integrated Planning provides BPC experts with an infrastructure to create and operate planning scenarios. This includes planning from common data entry processes to complex planning situations.
Planning model in BW-IP includes β
Data stored in InfoProviders for Planning.
Data stored in InfoProviders for Planning.
Structured view of data includes aggregation levels, multi provider, and characteristic relationships.
Structured view of data includes aggregation levels, multi provider, and characteristic relationships.
Changing data includes planning functions, planning sequences, manual planning in the form of input-ready queries, and process chains.
Changing data includes planning functions, planning sequences, manual planning in the form of input-ready queries, and process chains.
Utilities, i.e. filters that can be used in queries and planning functions.
Utilities, i.e. filters that can be used in queries and planning functions.
Data protecting centrally.
Data protecting centrally.
Following tools can be used for model planning scenarios β
BW modeling tools in Eclipse and the Data Warehousing Workbench to create data models in BW.
BW modeling tools in Eclipse and the Data Warehousing Workbench to create data models in BW.
Planning Modeler to model planning-specific metadata objects.
Planning Modeler to model planning-specific metadata objects.
BW modeling tools in Eclipse and also BEx Query Designer to enter plan data manually.
BW modeling tools in Eclipse and also BEx Query Designer to enter plan data manually.
BEx Web Application Designer or BEx Analyzer (Excel applications) to create applications for planning.
BEx Web Application Designer or BEx Analyzer (Excel applications) to create applications for planning.
Applications to execute either on the Web or in BEx Analyzer to enter data manually.
Applications to execute either on the Web or in BEx Analyzer to enter data manually.
Transaction Code: RSA1
A data model is defined as an Info Cube in SAP BW, which consists of fact table and dimension tables.
To create an InfoCube β First create an Info Area, which is a building block for an InfoCube.
Enter the name and description of Info Area and click βOkβ.
Next create InfoObject Catalog which is used to define characteristics and key figures for different type of objects. Go to InfoObjects on the left side of the screen. Select the Info Area created above β Create InfoObject Catalog.
Enter the name and description of InfoObject Catalog, InfoObject Type and click βCreate (F5)β.
Now validate and activate IOC_Demo_CH to check InfoObject Catalog.
To activate InfoObject Catalog, go to activate icon.
Similarly, you can create InfoObject Catalog to hold key figures.
Let us create InfoObject. Right-click on InfoObject Catalog IOC_demo_CH and select create InfoObject. Enter the name and description of InfoObject.
Click βContinueβ.
Select Data Type with Character and Length as 15. Then click βAttributeβ tab.
Enter the Attribute name and click βCreateβ.
Select Create Attribute as Characteristics and click βCreateβ icon.
Select Character as data type and Length 30. Note that βAttribute onlyβ option is automatically checked. Click the green tick at the bottom.
Click βCheck and Activateβ option to validate and activate the characteristics.
Similarly, you can create InfoObjects for key figures.
Once you define InfoObjects for characteristics and key figures, create an InfoCube.
Right-click on Info Provider Demo β Create InfoCube.
Enter the name of InfoCube, select standard for the description of InfoCube and click βCreateβ.
Select characteristics from template table and move them to structure table using arrows. Click the Dimensions tab to assign these characteristics to dimension.
Click βCreateβ and add a description of dimension. Once you assign all the characteristics and key figures, validate and activate the InfoCube.
Security in SAP BPC system is defined using two components β Authentication and Authorization. Authentication defines who can access system and data, while authorization tells the level of access for each authenticated user.
SAP BPC security is based on access profiles and task profiles. When you donβt assign task profiles to users or teams, no access to BPC tasks will be provided. Thus you have to assign access to members of a secured dimension.
BPC Security provides the following key functions β
Add Users
Add Teams
Add Task Profiles
Add Member access profiles
To manage the above functions, login to BPC Administration and go to Security.
There are four tabs under Security β
Users β This is used to add users to the environment and manage access rights.
Teams β You can add users with the same access rights to the same team.
Task Profiles β This is used to set up profiles that allow tasks to be performed and assign them to users and teams.
Data Access Profiles β This is used to set up profiles that allow access to data in models and assign them to users and teams.
To Add/Edit/Delete any of the objects under Security, select the object as shown in the following screenshot.
Hot Analysis is used to set up hot link to another report or cell in another report. EvHOT functions are used by BPC Application Set and AP Shell to provide a sample report called Hot Analysis. Hot links are used by the users for ad hoc reporting and also used in the process selector reporting.
This is used to switch between reports that are in different applications.
EvHOT(AppName,ReportName,DisplayName,Member1,Member2,Member3,Member4, ......................, Member N)
You have to pass the following parameters in EvHOT function.
AppName β This is the name of application. Note that in BPC system there is a setting in Workbook Option, which allows the system to remember the current view. By default, this setting is disabled. In this case, if you switch to a new application using EvHOT, it changes the application in the current view of workbook and other reports that you access in this session tries to get data from that application.
If this option is enabled, current view will revert to the workbook's application setting when switching focus to it.
ReportName β This is the name of the report. The root directory for BPC reports is the Wizard directory for the given application.
When you create a report - use eTools β Save Template Library option.
DisplayName β The text the user clicks to go to the specified report location.
Member1-Member N β This represents the CurrentView member. Here you can mention as many number of members you want.
EvHot("Finance","Report2","2010 Quarter 2","2010.Q2")
Note β This report should be stored in \Reports\Wizard folder. Exact path is Report Wizard folder β
..\Data\Webfolders\ApShellCopy\PLANNING\eExcel\Reports\Wizard
In case of a new report, you will also have to increase the template version in the BPC administration client.
Using Park N Go feature, you can lock down a BPC report and save it locally on your system as well as send the report through email to someone who doesnβt have access to BPC system.
If you donβt save the report with correct setting or sequence, you get an error in the report that makes the report unusable. You can use Park n Go feature to work it correctly.
Following are the steps you should follow to use Park n Go β
Login to BPC Excel and open the report that you want to Park. Go to Save β Save my Reports.
You will get a dialog box asking if you want to lock the report before saving it. Select βYesβ.
In the next window, you will get a message - Select a Park n Go state for active workbook with four options.
Once you click βOkβ, a report will flash and you will get an option βSave Asβ. You can save the Excel of report to the location where you want to save.
This option allows you to open the report in Excel and all the data will appear correctly in the report.
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": 2430,
"s": 2174,
"text": "SAP Business Planning and Consolidation (BPC) tool is used to support all operational and financial activities in an organization. SAP BPC helps in automating and streamlining business forecast, planning, and consolidation activities in your organization."
},
{
"code": null,
"e": 2831,
"s": 2430,
"text": "SAP BPC supports two types of migration - SAP NetWeaver and Microsoft Excel. BPC with Microsoft version enables you to perform modeling, application maintenance, importing data and applying transformations, creating scripts, etc. It leverages the power of MS Excel and provides the user with an Enterprise Power Management (EPM) solution, collaborative tool with robust, readily accepted environment."
},
{
"code": null,
"e": 2966,
"s": 2831,
"text": "SAP BPC provides support for existing Microsoft functionality and various enhancement features like drag and drop report builder, etc."
},
{
"code": null,
"e": 3019,
"s": 2966,
"text": "Following are the key benefits provided by SAP BPC β"
},
{
"code": null,
"e": 3154,
"s": 3019,
"text": "It allows the user to make better business decisions by supporting What-If analysis and allows you to perform scenario-based planning."
},
{
"code": null,
"e": 3289,
"s": 3154,
"text": "It allows the user to make better business decisions by supporting What-If analysis and allows you to perform scenario-based planning."
},
{
"code": null,
"e": 3391,
"s": 3289,
"text": "It allows you to collaborate data and thus increase accuracy in business planning and accountability."
},
{
"code": null,
"e": 3493,
"s": 3391,
"text": "It allows you to collaborate data and thus increase accuracy in business planning and accountability."
},
{
"code": null,
"e": 3581,
"s": 3493,
"text": "It helps in aligning your plans with strategic goals and hence decrease the cycle time."
},
{
"code": null,
"e": 3669,
"s": 3581,
"text": "It helps in aligning your plans with strategic goals and hence decrease the cycle time."
},
{
"code": null,
"e": 3750,
"s": 3669,
"text": "You have an option to choose the version of SAP NetWeaver or Microsoft Platform."
},
{
"code": null,
"e": 3831,
"s": 3750,
"text": "You have an option to choose the version of SAP NetWeaver or Microsoft Platform."
},
{
"code": null,
"e": 3898,
"s": 3831,
"text": "Following are the key benefits that can be achieved by using BPC β"
},
{
"code": null,
"e": 3919,
"s": 3898,
"text": "Business Forecasting"
},
{
"code": null,
"e": 3953,
"s": 3919,
"text": "Analytical Reporting and Analysis"
},
{
"code": null,
"e": 3969,
"s": 3953,
"text": "Budget Planning"
},
{
"code": null,
"e": 4009,
"s": 3969,
"text": "Predictive Analysis and Recommendations"
},
{
"code": null,
"e": 4028,
"s": 4009,
"text": "Improve Compliance"
},
{
"code": null,
"e": 4042,
"s": 4028,
"text": "Consolidation"
},
{
"code": null,
"e": 4090,
"s": 4042,
"text": "Business Process Flows and Smooth Collaboration"
},
{
"code": null,
"e": 4472,
"s": 4090,
"text": "SAP Enterprise Performance Management (EPM) allows your organization to improve its financial and operational performance management. SAP EPM supports various functionalities with SAP Business Planning and Consolidation - BPC-NW or BPC-MS, like financial consolidation, financial information management, supply chain performance management, strategy management and many more areas."
},
{
"code": null,
"e": 4742,
"s": 4472,
"text": "SAP Business Planning and Consolidation NW version is based on the functionality of NetWeaver platform. This is built on NetWeaver HTML5 and supports various user environment capabilities. It also provides various prebuilt components to reuse in different applications."
},
{
"code": null,
"e": 4913,
"s": 4742,
"text": "SAP BPC NW version supports RESTful connection to ABAP backend component and provides regular access to user interface. It also supports client-side logging capabilities."
},
{
"code": null,
"e": 5001,
"s": 4913,
"text": "The following table illustrates the name of the platform and the supported components β"
},
{
"code": null,
"e": 5132,
"s": 5001,
"text": "SAP BPC for NetWeaver provides various advantages since it is integrated with BW system and allows you to store data in InfoCubes."
},
{
"code": null,
"e": 5190,
"s": 5132,
"text": "Some key advantages of using SAP BPC with NW system are β"
},
{
"code": null,
"e": 5393,
"s": 5190,
"text": "Star Schema for Exceptional Reporting β SAP BPC uses NW InfoCubes to store the data. The dimension model used is extended star schema so it makes BPC with NW system and exceptional system for reporting."
},
{
"code": null,
"e": 5542,
"s": 5393,
"text": "No Database Dependence Version β BPC NW version is not dependent on database version and can run common databases like DB2, Oracle, SQL Server, etc."
},
{
"code": null,
"e": 5840,
"s": 5542,
"text": "BW Accelerator Support β SAP NetWeaver BW accelerator tool is an additional feature that can be used to enhance the performance of reporting in the system, even if you are using large datasets. It indirectly helps in saving the cost for a company as less number of performance issues are reported."
},
{
"code": null,
"e": 6107,
"s": 5840,
"text": "BAdI Development and ABAP Support β SAP BPC with NetWeaver allows you to use ABAP programming to develop K2 script logic. It enables to create business add-in BAdi interface in the back-end system, which can be called later from script logic developed in BPC system."
},
{
"code": null,
"e": 6217,
"s": 6107,
"text": "It helps in solving the complex business requirements and to reduce the development time for an organization."
},
{
"code": null,
"e": 6263,
"s": 6217,
"text": "Some key advantages of using SAP BPC MS are β"
},
{
"code": null,
"e": 6505,
"s": 6263,
"text": "Apart from common features provided in BPC like currency translation, allocations, validation and account transformations, automatic adjustments and carry forward of opening balance, the following features can be achieved in BPC MS version β"
},
{
"code": null,
"e": 6596,
"s": 6505,
"text": "Dimension Logic β This can be configured in BPC system using simple mathematical formulas."
},
{
"code": null,
"e": 6687,
"s": 6596,
"text": "Dimension Logic β This can be configured in BPC system using simple mathematical formulas."
},
{
"code": null,
"e": 6781,
"s": 6687,
"text": "Business Rules β This allows you to create rules in BPC system to perform specific functions."
},
{
"code": null,
"e": 6875,
"s": 6781,
"text": "Business Rules β This allows you to create rules in BPC system to perform specific functions."
},
{
"code": null,
"e": 7134,
"s": 6875,
"text": "K2 Script Logic β This is used to perform some specific functions which canβt be achieved using out-of-box functionality to meet business requirements. You can create K2 script logics to perform certain functions, which can be performed in a standard system."
},
{
"code": null,
"e": 7393,
"s": 7134,
"text": "K2 Script Logic β This is used to perform some specific functions which canβt be achieved using out-of-box functionality to meet business requirements. You can create K2 script logics to perform certain functions, which can be performed in a standard system."
},
{
"code": null,
"e": 7567,
"s": 7393,
"text": "Many organizations use MS Excel to manage business planning and consolidation but it has some disadvantages. Following are the disadvantages of using BPC MS over NetWeaver β"
},
{
"code": null,
"e": 7882,
"s": 7567,
"text": "Tough to Manage Excel Spreadsheets β As business planning and consolidation data is stored in the form of spreadsheets, it creates a security issue and an option to control access is by keeping the files on the shared network drive. In SAP BPC, you can save the data in database and this provides security of data."
},
{
"code": null,
"e": 8197,
"s": 7882,
"text": "Tough to Manage Excel Spreadsheets β As business planning and consolidation data is stored in the form of spreadsheets, it creates a security issue and an option to control access is by keeping the files on the shared network drive. In SAP BPC, you can save the data in database and this provides security of data."
},
{
"code": null,
"e": 8463,
"s": 8197,
"text": "Version Control β To create a new version of data, SAP BPC with NW allows you to maintain the version of data in the system and you can maintain the current data too. While using Excel spreadsheets for data store, you need to name the file with new name every time."
},
{
"code": null,
"e": 8729,
"s": 8463,
"text": "Version Control β To create a new version of data, SAP BPC with NW allows you to maintain the version of data in the system and you can maintain the current data too. While using Excel spreadsheets for data store, you need to name the file with new name every time."
},
{
"code": null,
"e": 9032,
"s": 8729,
"text": "Integrity of Spreadsheets β Using spreadsheets make it tough to manage the integrity of the sheets as the same file is accessed by multiple users and itβs tough to find out the latest version of spreadsheet. However, SAP system has a central repository to maintain financial and business planning data."
},
{
"code": null,
"e": 9335,
"s": 9032,
"text": "Integrity of Spreadsheets β Using spreadsheets make it tough to manage the integrity of the sheets as the same file is accessed by multiple users and itβs tough to find out the latest version of spreadsheet. However, SAP system has a central repository to maintain financial and business planning data."
},
{
"code": null,
"e": 9509,
"s": 9335,
"text": "Collaboration β SAP BPC allows you to collaborate data from different users and you can put comments on critical information and Excel doesnβt support collaboration feature."
},
{
"code": null,
"e": 9683,
"s": 9509,
"text": "Collaboration β SAP BPC allows you to collaborate data from different users and you can put comments on critical information and Excel doesnβt support collaboration feature."
},
{
"code": null,
"e": 9728,
"s": 9683,
"text": "Requirement β SAP NetWeaver ABAP 7.3 or 7.31"
},
{
"code": null,
"e": 9790,
"s": 9728,
"text": "Database β Any of the above version of SAP NetWeaver support."
},
{
"code": null,
"e": 9876,
"s": 9790,
"text": "Operating System β Any supported version of SAP NetWeaver system and database engine."
},
{
"code": null,
"e": 9930,
"s": 9876,
"text": "The following figure shows SAP BPC 10.0 architecture."
},
{
"code": null,
"e": 10124,
"s": 9930,
"text": "Difference between SAP BPC v7.5 and v10 is Web Server component. SAP BPC 7.5 NetWeaver uses Microsoft ISS, while BPC 10.0 NW and BPC 10 on HANA use the web server that is part of SAP NetWeaver."
},
{
"code": null,
"e": 10349,
"s": 10124,
"text": "SAP NW 10 is more scalable than SAP NW 7.5 (IIS in 32bit mode) and it simplifies the system topology as no separate Web Server and Network Load Balancing components are required as these were part of BPC 7.5 implementations."
},
{
"code": null,
"e": 10641,
"s": 10349,
"text": "Another difference between the two is version of SAP NetWeaver. SAP BPC 7.5 NW supports SAP NetWeaver 7.01 and 7.02. However, SAP BPC 10 NetWeaver and BPC 10 HANA doesnβt support NW 7.01, 7.02 versions. Also note that NW 7.01 and 7.02 requirements are quite different from SAP NetWeaver 7.3."
},
{
"code": null,
"e": 10795,
"s": 10641,
"text": "It means SAP BPC 7.5 NW systems in many organizations are running on older versions of Operating Systems and RDBMS is not supported by SAP NetWeaver 7.3."
},
{
"code": null,
"e": 10840,
"s": 10795,
"text": "Following are the key NetWeaver BW Objects β"
},
{
"code": null,
"e": 10851,
"s": 10840,
"text": "InfoObject"
},
{
"code": null,
"e": 10864,
"s": 10851,
"text": "InfoProvider"
},
{
"code": null,
"e": 10939,
"s": 10864,
"text": "As per the above architecture, following are the key objects in BPC 10.0 β"
},
{
"code": null,
"e": 11176,
"s": 10939,
"text": "Client Interface β At the top, you have client interface which is a web-based tool used for configuration and reporting for business planning. It consists of MS Office client, Excel based admin clients, and web-based tool for reporting."
},
{
"code": null,
"e": 11328,
"s": 11176,
"text": "Microsoft-based admin tool is used for configuration of application and Microsoft Office tools such as Word and PowerPoint are used for reporting data."
},
{
"code": null,
"e": 11571,
"s": 11328,
"text": "Web Server and .NET Application Server β This tool uses web services to connect to .NET Application Server. It receives the request from client interface and directs all the requests to ABAP server, which is a part of SAP NetWeaver BW system."
},
{
"code": null,
"e": 11661,
"s": 11571,
"text": "This server is used for data conversion between client tools and SAP NetWeaver BW system."
},
{
"code": null,
"e": 11938,
"s": 11661,
"text": "SAP NetWeaver Application Server β This server is used to process all the requests from client tool. The request from .NET Application server is processed in this server as Remote Function Call RFC. This is used to process requests to create reports or to update the database."
},
{
"code": null,
"e": 12093,
"s": 11938,
"text": "When a request is processed by the Application Server, it gets the data and passes to .NET Application Server, and then sends it back to client interface."
},
{
"code": null,
"e": 12356,
"s": 12093,
"text": "Database Server β This layer is responsible to store all the data in the database. SAP NW back-end system is responsible to create objects and data is stored for BPC system. The NetWeaver supports most of the databases like SQL Server, DB2, Oracle and many more."
},
{
"code": null,
"e": 12416,
"s": 12356,
"text": "Following are the release notes from SAP for SAP BPC 10.0 β"
},
{
"code": null,
"e": 12452,
"s": 12416,
"text": "Product Version 10.0, SAP NetWeaver"
},
{
"code": null,
"e": 12465,
"s": 12452,
"text": "Area CPM-BPC"
},
{
"code": null,
"e": 12508,
"s": 12465,
"text": "BPC now supports the following platforms β"
},
{
"code": null,
"e": 12772,
"s": 12508,
"text": "Server Support β Any operating system that is supported by SAP NetWeaver. VMware support as per SAP standard. Virtualization, VMware, Microsoft, Windows, Hyper-V, XEN, vSphere, IBM, INxHY, KVM, zBX. SAP NetWeaver Support for NW 7.3. No support for older versions."
},
{
"code": null,
"e": 13036,
"s": 12772,
"text": "Server Support β Any operating system that is supported by SAP NetWeaver. VMware support as per SAP standard. Virtualization, VMware, Microsoft, Windows, Hyper-V, XEN, vSphere, IBM, INxHY, KVM, zBX. SAP NetWeaver Support for NW 7.3. No support for older versions."
},
{
"code": null,
"e": 13125,
"s": 13036,
"text": "Database Support β BPC supports all database that are supported by SAP NetWeaver system."
},
{
"code": null,
"e": 13214,
"s": 13125,
"text": "Database Support β BPC supports all database that are supported by SAP NetWeaver system."
},
{
"code": null,
"e": 13337,
"s": 13214,
"text": "Client Support β Microsoft Windows, WIN XP (32 bit), Windows Vista (32 bit and 64 bit), and Windows 7 (32 bit and 64 bit)."
},
{
"code": null,
"e": 13460,
"s": 13337,
"text": "Client Support β Microsoft Windows, WIN XP (32 bit), Windows Vista (32 bit and 64 bit), and Windows 7 (32 bit and 64 bit)."
},
{
"code": null,
"e": 13519,
"s": 13460,
"text": "Microsoft .Net Framework β .Net Framework 3.5 is required."
},
{
"code": null,
"e": 13578,
"s": 13519,
"text": "Microsoft .Net Framework β .Net Framework 3.5 is required."
},
{
"code": null,
"e": 13651,
"s": 13578,
"text": "Web Browser Support β BPC supports the web browsers - IE 8.0 and IE 9.0."
},
{
"code": null,
"e": 13724,
"s": 13651,
"text": "Web Browser Support β BPC supports the web browsers - IE 8.0 and IE 9.0."
},
{
"code": null,
"e": 13898,
"s": 13724,
"text": "Microsoft Office Support β Microsoft Office 2007 (32 bit and 64 bit) and Microsoft Office 2010 (32 bit and 64 bit). .NET server is no longer required in latest BPC versions."
},
{
"code": null,
"e": 14072,
"s": 13898,
"text": "Microsoft Office Support β Microsoft Office 2007 (32 bit and 64 bit) and Microsoft Office 2010 (32 bit and 64 bit). .NET server is no longer required in latest BPC versions."
},
{
"code": null,
"e": 14170,
"s": 14072,
"text": "On comparing BPC 7.5 and BPC 10.0, following are the key terminology differences between the two."
},
{
"code": null,
"e": 14326,
"s": 14170,
"text": "Environment β It is defined as the starting point for creating any application or model. It was called Application sets or AppSet in older versions of BPC."
},
{
"code": null,
"e": 14471,
"s": 14326,
"text": "Dimensions β You can mark a dimension as secure. You need to grant read and write access to the users who use the model so they can access data."
},
{
"code": null,
"e": 14549,
"s": 14471,
"text": "Properties β This is used to provide additional information to the dimension."
},
{
"code": null,
"e": 14675,
"s": 14549,
"text": "Dimension Members β Each dimension member record shows master, text and hierarchy data associated with the keys of dimension."
},
{
"code": null,
"e": 14861,
"s": 14675,
"text": "Model β To meet the Business Planning and Consolidation requirement of an organization, you need to build a model in an environment which is defined as collection of several dimensions."
},
{
"code": null,
"e": 14947,
"s": 14861,
"text": "Data Manager Package β To execute common tasks in BPC, you need data manager package."
},
{
"code": null,
"e": 15328,
"s": 14947,
"text": "Business Rules β To manage operations in different countries, different set of business rules are required. BPC includes rule-based table to meet some requirements for business planning and consolidation. Various rules can be set related to business planning and consolidation like - currency translation, balance carry forward, intercompany elimination, and data validation, etc."
},
{
"code": null,
"e": 15596,
"s": 15328,
"text": "Logic Scripts β This is defined as a set of SQL or MDX programming structure to perform some customize functions for flexibility and manage data models. When some specific requirements are not achieved using business rules that can be met by the use of Logic Scripts."
},
{
"code": null,
"e": 15674,
"s": 15596,
"text": "User β A user is defined as an individual who uses the application in Appset."
},
{
"code": null,
"e": 15740,
"s": 15674,
"text": "Team β A team is defined as a group of users based on user roles."
},
{
"code": null,
"e": 15821,
"s": 15740,
"text": "Task β All the activities that are performed in SAP BPC system are called tasks."
},
{
"code": null,
"e": 15974,
"s": 15821,
"text": "An Application in BPC system is defined as multidimensional data model used in EPM. Few examples of Applications are - Operation, Legal or Finance team."
},
{
"code": null,
"e": 16260,
"s": 15974,
"text": "There are two types of applications in BPC system - Reporting and Non-Reporting. Reporting applications are used for analysis purpose and you can pass inputs from the users. Non-Reporting applications are used to contain reference data like currency rates, carry forward balances, etc."
},
{
"code": null,
"e": 16523,
"s": 16260,
"text": "An Appset consists of one or multiple applications in system. Each application consists of the master data for an application, which is used to control data in the application set. An application can also share one or multiple dimensions with other applications."
},
{
"code": null,
"e": 16645,
"s": 16523,
"text": "Each Reporting application consists of a dimension, properties to hold the additional information, and dimension members."
},
{
"code": null,
"e": 16856,
"s": 16645,
"text": "Consider a Consolidation Rate application, which consists of Rate app to store currency exchange rates and an Owner application, which stores the relationship between Owner company and its subsidiary companies."
},
{
"code": null,
"e": 17213,
"s": 16856,
"text": "To add an application to the Application set, you can use an existing application by selecting reference applications and any set of business rules. You can also add dimensions in new application and these can be defined as secure or non-secure. When you define dimensions as secure it ensures the read and write access is controlled through user profiles."
},
{
"code": null,
"e": 17303,
"s": 17213,
"text": "You can add an application through an admin console β Application β Add a New Application"
},
{
"code": null,
"e": 17362,
"s": 17303,
"text": "To copy an application β Application β Copy an Application"
},
{
"code": null,
"e": 17482,
"s": 17362,
"text": "To create a Consolidation application, you need to define AppSet for consolidation and dimension set for consolidation."
},
{
"code": null,
"e": 17558,
"s": 17482,
"text": "You should set the following parameters after creating the application set."
},
{
"code": null,
"e": 17574,
"s": 17558,
"text": "ALLOW_FILE_SIZE"
},
{
"code": null,
"e": 17585,
"s": 17574,
"text": "UPLOADTEMP"
},
{
"code": null,
"e": 17601,
"s": 17585,
"text": "TEMPLATEVERSION"
},
{
"code": null,
"e": 17613,
"s": 17601,
"text": "JREPORTZOOM"
},
{
"code": null,
"e": 17622,
"s": 17613,
"text": "LOGLEVEL"
},
{
"code": null,
"e": 17629,
"s": 17622,
"text": "SYSTEM"
},
{
"code": null,
"e": 17637,
"s": 17629,
"text": "MESSAGE"
},
{
"code": null,
"e": 17644,
"s": 17637,
"text": "STATUS"
},
{
"code": null,
"e": 17730,
"s": 17644,
"text": "In SAP BPC NetWeaver version, all these parameters are maintained in ABAP DDIC table."
},
{
"code": null,
"e": 17828,
"s": 17730,
"text": "Once the application set is created, the next step is to set up the parameters for Dimension set."
},
{
"code": null,
"e": 17945,
"s": 17828,
"text": "You can add a new dimension or copy an existing dimension. In the Administration Console, go to Dimension and Model."
},
{
"code": null,
"e": 17986,
"s": 17945,
"text": "Go to Dimensions and Models β Dimension."
},
{
"code": null,
"e": 18039,
"s": 17986,
"text": "Click on +New β Enter ID, Description, Type β Create"
},
{
"code": null,
"e": 18141,
"s": 18039,
"text": "To create a rate application which contains the exchange rate, following dimension types are needed β"
},
{
"code": null,
"e": 18189,
"s": 18141,
"text": "C_Acct (A) β For maintaining Charts of Account."
},
{
"code": null,
"e": 18237,
"s": 18189,
"text": "C_Acct (A) β For maintaining Charts of Account."
},
{
"code": null,
"e": 18274,
"s": 18237,
"text": "C_Category (C) β To define Category."
},
{
"code": null,
"e": 18311,
"s": 18274,
"text": "C_Category (C) β To define Category."
},
{
"code": null,
"e": 18378,
"s": 18311,
"text": "Groups (R) β Like GROUP A (USD), GROUP B (EUR), and GROUP C (RMB)."
},
{
"code": null,
"e": 18445,
"s": 18378,
"text": "Groups (R) β Like GROUP A (USD), GROUP B (EUR), and GROUP C (RMB)."
},
{
"code": null,
"e": 18512,
"s": 18445,
"text": "Entity (E) β It contains the business unit used to derive process."
},
{
"code": null,
"e": 18579,
"s": 18512,
"text": "Entity (E) β It contains the business unit used to derive process."
},
{
"code": null,
"e": 18618,
"s": 18579,
"text": "C_Datasrc (D) β Data Source Dimension."
},
{
"code": null,
"e": 18657,
"s": 18618,
"text": "C_Datasrc (D) β Data Source Dimension."
},
{
"code": null,
"e": 18767,
"s": 18657,
"text": "IntCo (I) β It determines the level of entity hierarchy at which level the elimination needs to be performed."
},
{
"code": null,
"e": 18877,
"s": 18767,
"text": "IntCo (I) β It determines the level of entity hierarchy at which level the elimination needs to be performed."
},
{
"code": null,
"e": 18912,
"s": 18877,
"text": "Time (T) β Time in all dimensions."
},
{
"code": null,
"e": 18947,
"s": 18912,
"text": "Time (T) β Time in all dimensions."
},
{
"code": null,
"e": 19003,
"s": 18947,
"text": "Flow (S) β To keep track of movements in Consolidation."
},
{
"code": null,
"e": 19059,
"s": 19003,
"text": "Flow (S) β To keep track of movements in Consolidation."
},
{
"code": null,
"e": 19161,
"s": 19059,
"text": "To create a rate application which contains the exchange rate, following dimension types are needed β"
},
{
"code": null,
"e": 19215,
"s": 19161,
"text": "R_Acct (A) β For maintaining different types of Rate."
},
{
"code": null,
"e": 19269,
"s": 19215,
"text": "R_Acct (A) β For maintaining different types of Rate."
},
{
"code": null,
"e": 19313,
"s": 19269,
"text": "InputCurrency(R) β Currency Type Dimension."
},
{
"code": null,
"e": 19357,
"s": 19313,
"text": "InputCurrency(R) β Currency Type Dimension."
},
{
"code": null,
"e": 19394,
"s": 19357,
"text": "C_Category (C) β To define Category."
},
{
"code": null,
"e": 19431,
"s": 19394,
"text": "C_Category (C) β To define Category."
},
{
"code": null,
"e": 19464,
"s": 19431,
"text": "R_Entity (E) β Rate application."
},
{
"code": null,
"e": 19497,
"s": 19464,
"text": "R_Entity (E) β Rate application."
},
{
"code": null,
"e": 19532,
"s": 19497,
"text": "Time (T) β Time in all dimensions."
},
{
"code": null,
"e": 19567,
"s": 19532,
"text": "Time (T) β Time in all dimensions."
},
{
"code": null,
"e": 19696,
"s": 19567,
"text": "To create an ownership, Consolidation application contains the ownership information. The following dimension types are needed β"
},
{
"code": null,
"e": 19723,
"s": 19696,
"text": "O_Acct (A) β for Ownership"
},
{
"code": null,
"e": 19750,
"s": 19723,
"text": "O_Acct (A) β for Ownership"
},
{
"code": null,
"e": 19786,
"s": 19750,
"text": "C_Category (C) β To define Category"
},
{
"code": null,
"e": 19822,
"s": 19786,
"text": "C_Category (C) β To define Category"
},
{
"code": null,
"e": 19889,
"s": 19822,
"text": "Entity (E) β It contains the business unit used to derive process."
},
{
"code": null,
"e": 19956,
"s": 19889,
"text": "Entity (E) β It contains the business unit used to derive process."
},
{
"code": null,
"e": 20066,
"s": 19956,
"text": "IntCo (I) β It determines level of the entity hierarchy at which level the elimination needs to be performed."
},
{
"code": null,
"e": 20176,
"s": 20066,
"text": "IntCo (I) β It determines level of the entity hierarchy at which level the elimination needs to be performed."
},
{
"code": null,
"e": 20228,
"s": 20176,
"text": "Groups (R) β Used to implement separate group type."
},
{
"code": null,
"e": 20280,
"s": 20228,
"text": "Groups (R) β Used to implement separate group type."
},
{
"code": null,
"e": 20315,
"s": 20280,
"text": "Time (T) β Time in all dimensions."
},
{
"code": null,
"e": 20350,
"s": 20315,
"text": "Time (T) β Time in all dimensions."
},
{
"code": null,
"e": 20459,
"s": 20350,
"text": "To set up a consolidation application, three applications are required - Rate, Ownership, and Consolidation."
},
{
"code": null,
"e": 20685,
"s": 20459,
"text": "With the release of BPC 10.1 with NetWeaver, there are two models that can be used to fulfill the business requirements. BPC models are often referred to as BPC applications and BPC environment is normally called Application."
},
{
"code": null,
"e": 20736,
"s": 20685,
"text": "The following types of model can be built in BPC β"
},
{
"code": null,
"e": 21048,
"s": 20736,
"text": "This model provides an option within host BWβs protected namespace β/CPMB/β. When you separate the BPC transaction data and master data inside the namespace (β/CPMB/β), all the sub-processes that are associated with standard model are closely secured, and only closely managed by the department running the app."
},
{
"code": null,
"e": 21272,
"s": 21048,
"text": "This model is designed by SAP to provide a protected area for customers who to plan and consolidate in their own department without wanting to share or coordinate the resources with other Business Warehouse community users."
},
{
"code": null,
"e": 21499,
"s": 21272,
"text": "As the code set of Standard model has been coordinated with version BPC 10.0 so all the changes to BPC 10.0 are shown in BPC 10.1 Standard model and changes to the version BPC 10.1 Standard model are shown in version BPC 10.0."
},
{
"code": null,
"e": 21667,
"s": 21499,
"text": "This allows a code compatibility between BPC 10.0 and BPC 10.1, and clients can easily perform migrations while upgrading BPC version from 10.0 to 10.1 Standard Model."
},
{
"code": null,
"e": 21820,
"s": 21667,
"text": "In short, you can say in Standard model, BPC environment contains the BPC applications or models and each model generates a BW InfoCube which is hidden."
},
{
"code": null,
"e": 22043,
"s": 21820,
"text": "This model is different from Standard model and includes data access to all community users. For Embedded design model, initial versions used were SAP BW Integrated Planning and Planning Application Kit i.e. BW-IP and PAK."
},
{
"code": null,
"e": 22375,
"s": 22043,
"text": "This model provides a different level of data access where master and transactional data from host EDW environment is accessible by the application. In Embedded model, it allows easy access to transactional and master data within the host BW, and this data is shared with many other users and controlled by the administrator group."
},
{
"code": null,
"e": 22597,
"s": 22375,
"text": "In Embedded model, migration from older versions of Business Warehouse IP, BW-IP to this data model is relatively easy and migration from earlier versions like (BPC 10.0 and earlier) is considered as a new implementation."
},
{
"code": null,
"e": 22722,
"s": 22597,
"text": "In short, you can say that in embedded model, any number of InfoProviders can be assigned to a single BPC model/application."
},
{
"code": null,
"e": 23070,
"s": 22722,
"text": "An application in BPC is also known as a model, like an environment is called an AppSet. You can create an application by going to Admin console in Enterprise Performance Management (EPM) System. BPC environment or AppSet has the group of applications or models. All these applications share the planning dimensions and are linked with each other."
},
{
"code": null,
"e": 23221,
"s": 23070,
"text": "As mentioned earlier, applications are called multidimensional data models in EPM. You can add a new application or also copy an existing application."
},
{
"code": null,
"e": 23344,
"s": 23221,
"text": "Environment management includes setting up work status for applications and adding the business rules to the applications."
},
{
"code": null,
"e": 23446,
"s": 23344,
"text": "Work status determines who can make changes to data or who can change the work state on the data set."
},
{
"code": null,
"e": 23742,
"s": 23446,
"text": "In Environment management, you can also carry out applications optimization. When a new application is created, it contains only a small amount of data. As time passes, data in application increases and it is always recommended to perform application performance optimization in BPC environment."
},
{
"code": null,
"e": 23906,
"s": 23742,
"text": "It is also possible to delete any application in BPC environment when required by going to admin console. You need to be an administrator to perform this function."
},
{
"code": null,
"e": 24141,
"s": 23906,
"text": "Dimension management in BPC includes creating new dimensions, defining members in dimensions, and assigning properties. Dimension contains member and there is a hierarchy between members that is defined like parent, child and sibling."
},
{
"code": null,
"e": 24227,
"s": 24141,
"text": "You can create a new dimension by going to Admin Console β Dimension β New Dimension."
},
{
"code": null,
"e": 24289,
"s": 24227,
"text": "Dimension name is not case sensitive and it should be unique."
},
{
"code": null,
"e": 24446,
"s": 24289,
"text": "When adding a new dimension, you have to enter reference type. Planning and Consolidation checks the value of reference type while processing the dimension."
},
{
"code": null,
"e": 24579,
"s": 24446,
"text": "Click Create button in the above window. You have to enter referential integrity for Rate type in the new window. Click βSaveβ icon."
},
{
"code": null,
"e": 24726,
"s": 24579,
"text": "You can also edit structure, edit members, delete or copy an existing dimension. To copy a dimension, select an existing dimension and go to Copy."
},
{
"code": null,
"e": 24792,
"s": 24726,
"text": "Enter the name of dimension and description. Click βCopyβ button."
},
{
"code": null,
"e": 24927,
"s": 24792,
"text": "Naming Conventions in Dimensions β You shouldnβt use special characters while naming a dimension, member, and application in BW table."
},
{
"code": null,
"e": 25082,
"s": 24927,
"text": "You can create dimension name up to 16 characters and it shouldnβt contain comma, double comma, back slashes, ampersands. However, you can use underscore."
},
{
"code": null,
"e": 25553,
"s": 25082,
"text": "You shouldnβt use the following names - App, AppAccess, AvlObject, CategoryAccess, CollabDoc, CollabIcons, CollabRecipient, CollabSupport, CollabType, DBVERSION, Defaults, DesktopStyleDef, Dimension, DrillDef, DTIParam, Function, Formula, Group, InvestParam, MemberAccess, MessageLog, Packages, PageDef, Permission, PublishedBooks, Rate, ReportParam, SectionDef, Status, StatusCode, TaskAccess, User, UserGroup, UserPackages, UserPovDef, WebContents, SOURCE, SIGNEDDATA."
},
{
"code": null,
"e": 25616,
"s": 25553,
"text": "Description of dimension shouldnβt be more than 50 characters."
},
{
"code": null,
"e": 25693,
"s": 25616,
"text": "You can delete a dimension by selecting it and clicking the βDeleteβ button."
},
{
"code": null,
"e": 25829,
"s": 25693,
"text": "BPC security is managed in Administration console. You have to login to BPC portal and go to Planning and Consolidation Administration."
},
{
"code": null,
"e": 25877,
"s": 25829,
"text": "There are four key components in BPC security β"
},
{
"code": null,
"e": 25883,
"s": 25877,
"text": "Users"
},
{
"code": null,
"e": 25889,
"s": 25883,
"text": "Teams"
},
{
"code": null,
"e": 25903,
"s": 25889,
"text": "Task Profiles"
},
{
"code": null,
"e": 25924,
"s": 25903,
"text": "Data Access Profiles"
},
{
"code": null,
"e": 26005,
"s": 25924,
"text": "Users β This is used to add users to environment and manage their access rights."
},
{
"code": null,
"e": 26102,
"s": 26005,
"text": "Teams β This is not so important and you can define a team of users with the same access rights."
},
{
"code": null,
"e": 26212,
"s": 26102,
"text": "Task Profiles β This allows setting up profiles for tasks to be performed and assign them to users and teams."
},
{
"code": null,
"e": 26339,
"s": 26212,
"text": "Data Access Profiles β This is used to set up profiles that allow access to data in models and assign them to users and teams."
},
{
"code": null,
"e": 26408,
"s": 26339,
"text": "Click βTeamβ tab under Security, select Admin team and double-click."
},
{
"code": null,
"e": 26531,
"s": 26408,
"text": "You will see the details of Team name β ADMIN, which users are part of this team, task profiles, and data access profiles."
},
{
"code": null,
"e": 26601,
"s": 26531,
"text": "You can edit the team details and click βSaveβ icon to apply changes."
},
{
"code": null,
"e": 26689,
"s": 26601,
"text": "Going to the user tab, you can add new users, edit existing users, and delete any user."
},
{
"code": null,
"e": 27016,
"s": 26689,
"text": "Data loading in BPC is done with the help of Data Manager that allows you to move data in Planning and Consolidation system, copy and move data and export data from an application. Data Manager moves the data in form of packages, which allows scheduled sequences to run in the background and some can initiate other processes."
},
{
"code": null,
"e": 27192,
"s": 27016,
"text": "We can pull the data from different source system like SAP ECC system, SAP CRM, SRM using extractors. You can also load data from non-SAP sources to InfoCube in SAP BW system."
},
{
"code": null,
"e": 27254,
"s": 27192,
"text": "To load the data into InfoCube, go to workbench in BW system."
},
{
"code": null,
"e": 27277,
"s": 27254,
"text": "Transaction Code: RSA1"
},
{
"code": null,
"e": 27354,
"s": 27277,
"text": "Data warehousing workbench will open, go to Source Systems on the left side."
},
{
"code": null,
"e": 27426,
"s": 27354,
"text": "Data acquisition in BW system can be done using the following methods β"
},
{
"code": null,
"e": 27438,
"s": 27426,
"text": "Service API"
},
{
"code": null,
"e": 27461,
"s": 27438,
"text": "Transfer of Flat Files"
},
{
"code": null,
"e": 27472,
"s": 27461,
"text": "DB Connect"
},
{
"code": null,
"e": 27499,
"s": 27472,
"text": "Universal Data Integration"
},
{
"code": null,
"e": 27526,
"s": 27499,
"text": "XML Based Data Integration"
},
{
"code": null,
"e": 27548,
"s": 27526,
"text": "Third party ETL tools"
},
{
"code": null,
"e": 27586,
"s": 27548,
"text": "Application Specific Data Acquisition"
},
{
"code": null,
"e": 27676,
"s": 27586,
"text": "Double-click on File and enter logical system name, source system name, Type and Release."
},
{
"code": null,
"e": 27803,
"s": 27676,
"text": "Next is to create an InfoSource for characteristics data. Right-click on InfoSource right pane β Create Application Component."
},
{
"code": null,
"e": 27877,
"s": 27803,
"text": "Once you create the InfoSource, right-click on it and assign data source."
},
{
"code": null,
"e": 27956,
"s": 27877,
"text": "Then, right-click on Source system β InfoPackage, select master data and save."
},
{
"code": null,
"e": 27985,
"s": 27956,
"text": "Define Load characteristics."
},
{
"code": null,
"e": 28105,
"s": 27985,
"text": "Finally, create an InfoSource for transaction data. Create Updating rules and an Info Package to load transaction data."
},
{
"code": null,
"e": 28385,
"s": 28105,
"text": "You can load data to BPC system from SAP BW InfoCube. With BPC Data Manager, you can use BPC code packages. You can copy or move data in different applications, and can export the data from applications. BPC packages are based on BW process chains and come with BPC installation."
},
{
"code": null,
"e": 28501,
"s": 28385,
"text": "Data Manager Tool is integrated with Excel. To start BPC, go to Planning and Consolidation β eTools β Data Manager."
},
{
"code": null,
"e": 28568,
"s": 28501,
"text": "In Data Manager Package, there are different data transfer modes β"
},
{
"code": null,
"e": 28588,
"s": 28568,
"text": "Aggregate Overwrite"
},
{
"code": null,
"e": 28595,
"s": 28588,
"text": "Append"
},
{
"code": null,
"e": 28667,
"s": 28595,
"text": "While loading data from Info Provider, you have the following options β"
},
{
"code": null,
"e": 28673,
"s": 28667,
"text": "Merge"
},
{
"code": null,
"e": 28681,
"s": 28673,
"text": "Replace"
},
{
"code": null,
"e": 28908,
"s": 28681,
"text": "BPC also supports Delta load as there are many records getting generated for each load. Delta initialization is possible with higher enhancement package and you can perform Delta load in Organize option under Data Manager Tab."
},
{
"code": null,
"e": 29037,
"s": 28908,
"text": "In BW system, full load is supported for Standard InfoCubes, Virtual InfoCubes, Standard and Optimized Data Store Objects DSOβs."
},
{
"code": null,
"e": 29127,
"s": 29037,
"text": "You can Delta load using Data Manager for Standard InfoCubes and Standard, Optimized DSO."
},
{
"code": null,
"e": 29350,
"s": 29127,
"text": "Next is to create a Package which contains conversion file and transformation file with variables, which is responsible to trigger a BW process chain. You can combine different packages for separate tasks in package links."
},
{
"code": null,
"e": 29553,
"s": 29350,
"text": "Transformation file provides the mapping of fields from BW to BPC and is an excel file in BPC. It contains transaction data from Info Objects in BW with BPC dimensions defined in administration console."
},
{
"code": null,
"e": 29605,
"s": 29553,
"text": "There are three sections defined for mapping file β"
},
{
"code": null,
"e": 29646,
"s": 29605,
"text": "Options β Contains the general settings."
},
{
"code": null,
"e": 29687,
"s": 29646,
"text": "Options β Contains the general settings."
},
{
"code": null,
"e": 29775,
"s": 29687,
"text": "Mapping β Used to assign dimension in BPC system with a source column in BW InfoObject."
},
{
"code": null,
"e": 29863,
"s": 29775,
"text": "Mapping β Used to assign dimension in BPC system with a source column in BW InfoObject."
},
{
"code": null,
"e": 29949,
"s": 29863,
"text": "Conversion β Contains the link of other Excel sheets to apply the conversion routine."
},
{
"code": null,
"e": 30035,
"s": 29949,
"text": "Conversion β Contains the link of other Excel sheets to apply the conversion routine."
},
{
"code": null,
"e": 30181,
"s": 30035,
"text": "To create a Transformation File β Go to BPC Excel client. Next is to choose App set and Application where these Transformation file will be used."
},
{
"code": null,
"e": 30277,
"s": 30181,
"text": "Now go to Data Manager in Business Planning and Consolidation β More β New Transformation File."
},
{
"code": null,
"e": 30420,
"s": 30277,
"text": "You will see an excel sheet with three sections - Option, Mapping and Conversion. You donβt require to make any changes to Option, Conversion."
},
{
"code": null,
"e": 30512,
"s": 30420,
"text": "Go to Mapping and define Transactional data mapping from InfoObject in BW to BPC Dimension."
},
{
"code": null,
"e": 30531,
"s": 30512,
"text": "ACCOUNT = ZACCOUNT"
},
{
"code": null,
"e": 30547,
"s": 30531,
"text": "TIME = ZBPCTIME"
},
{
"code": null,
"e": 30568,
"s": 30547,
"text": "SIGNEDDATA = ZAMOUNT"
},
{
"code": null,
"e": 30780,
"s": 30568,
"text": "Note that you can also copy an existing transformation file or update an existing transformation file by going to βMoreβ tab under Business Planning and Consolidation ribbon as shown in the following screenshot."
},
{
"code": null,
"e": 30905,
"s": 30780,
"text": "A Conversion file is used to apply the conversion rules for BPC dimension and is an Excel file. It contains three sections β"
},
{
"code": null,
"e": 30957,
"s": 30905,
"text": "External β Contains the value from external source."
},
{
"code": null,
"e": 31009,
"s": 30957,
"text": "External β Contains the value from external source."
},
{
"code": null,
"e": 31078,
"s": 31009,
"text": "Internal β Contains the value it should be having for BPC dimension."
},
{
"code": null,
"e": 31147,
"s": 31078,
"text": "Internal β Contains the value it should be having for BPC dimension."
},
{
"code": null,
"e": 31212,
"s": 31147,
"text": "Formula β Defines the conversion formula applied to each record."
},
{
"code": null,
"e": 31277,
"s": 31212,
"text": "Formula β Defines the conversion formula applied to each record."
},
{
"code": null,
"e": 31408,
"s": 31277,
"text": "To create a Conversion File β Go to BPC Excel client. Choose AppSet and Application where these transformation files will be used."
},
{
"code": null,
"e": 31486,
"s": 31408,
"text": "Go to Business Planning and Consolidation Ribbon β More β New conversion File"
},
{
"code": null,
"e": 31577,
"s": 31486,
"text": "You can also use other functions like - Manage conversion file, copy conversion file, etc."
},
{
"code": null,
"e": 31761,
"s": 31577,
"text": "You can load the data in BPC dimension from source flat file like CSV, XLS. You have to first create the dimension using administration console and a connection should be established."
},
{
"code": null,
"e": 31884,
"s": 31761,
"text": "Go to BPC Excel β EPM tab and click on the log on the left side panel. Select the connection name, user name and password."
},
{
"code": null,
"e": 31928,
"s": 31884,
"text": "Go to Data Manager tab β EPM β Upload data."
},
{
"code": null,
"e": 31961,
"s": 31928,
"text": "Enter the name and click βSaveβ."
},
{
"code": null,
"e": 32099,
"s": 31961,
"text": "Create a Transformation file as mentioned above. If the number of fields are the same for source and destination, no need to use mapping."
},
{
"code": null,
"e": 32214,
"s": 32099,
"text": "You will only have values under Options section and rest of the fields would be blank in this Transformation file."
},
{
"code": null,
"e": 32367,
"s": 32214,
"text": "If you have source and target with different number of data columns, you have to define it under mapping like for βdescriptionβ in the above screenshot."
},
{
"code": null,
"e": 32521,
"s": 32367,
"text": "Once Transformation file is created, next is to validate and process transformation. Select data type β Master data from flat file and click βSaveβ icon."
},
{
"code": null,
"e": 32575,
"s": 32521,
"text": "Go to βDMβ tab at the top in BPC Excel β Run Package."
},
{
"code": null,
"e": 32655,
"s": 32575,
"text": "Click βData Managementβ and select import master data attribute from flat file."
},
{
"code": null,
"e": 32756,
"s": 32655,
"text": "Click βRunβ at the bottom and enter the path for data file and Transformation file as created above."
},
{
"code": null,
"e": 32924,
"s": 32756,
"text": "Select the dimension in which you want to upload this data and click βRunβ. Once it is completed successfully, you can go to web portal check the data under Dimension."
},
{
"code": null,
"e": 33197,
"s": 32924,
"text": "SAP BPC 10.0 allows you to get data from source systems in to an Excel interface. It allows you to analyze the multidimensional data and BPC 10.0 provides number of inbuilt templates that can be used for analyzing and you can also add different formulas to design reports."
},
{
"code": null,
"e": 33355,
"s": 33197,
"text": "SAP BPC 10.0 provides various exceptional capabilities including integration with SAP HANA over BPC 7.x to handle big data environment for reporting purpose."
},
{
"code": null,
"e": 33702,
"s": 33355,
"text": "SAP BPC also provides use of input schedules that allow you to send the data from report to database. Input schedules provide you with all the functionalities as that are available in BPC reports. The difference between Report and Input Schedules is that reports are used for analyzing data and input schedules are used to write data to database."
},
{
"code": null,
"e": 33824,
"s": 33702,
"text": "You can opt from the following methods to create reports and input schedules in Business Planning and consolidation tool."
},
{
"code": null,
"e": 33848,
"s": 33824,
"text": "Using Default Templates"
},
{
"code": null,
"e": 33862,
"s": 33848,
"text": "EvDRE Builder"
},
{
"code": null,
"e": 33886,
"s": 33862,
"text": "Drag and Drop Interface"
},
{
"code": null,
"e": 33901,
"s": 33886,
"text": "Blank Workbook"
},
{
"code": null,
"e": 34062,
"s": 33901,
"text": "You can also create reports in Business Planning and Consolidation EPM Add-in for Excel. Excel Interface in BPC is broadly divided into the following sections β"
},
{
"code": null,
"e": 34080,
"s": 34062,
"text": "EPM Add-In Ribbon"
},
{
"code": null,
"e": 34105,
"s": 34080,
"text": "Connection and Dimension"
},
{
"code": null,
"e": 34122,
"s": 34105,
"text": "EPM Context Menu"
},
{
"code": null,
"e": 34134,
"s": 34122,
"text": "Report Area"
},
{
"code": null,
"e": 34311,
"s": 34134,
"text": "To create reports in EPM Add-In Interface for Excel, you have to enable the following option. Go to EPM β Options β Sheet Options β Check the box βActivate Member Recognitionβ."
},
{
"code": null,
"e": 34491,
"s": 34311,
"text": "You can simply drag the dimensions and drop it to excel sheets. It is the easiest method and displays the report based on dimension selected from the list of available dimensions."
},
{
"code": null,
"e": 34637,
"s": 34491,
"text": "Other option to create report using Excel Add-in is by adding dimensions to Row axis and Column axis. Once you add the dimensions click βUpdateβ."
},
{
"code": null,
"e": 34778,
"s": 34637,
"text": "You can also create reports by simply typing dimension member in the report area. BPC Excel add-in identifies the member and display result."
},
{
"code": null,
"e": 34826,
"s": 34778,
"text": "Following are the two versions of EPM Add-ins β"
},
{
"code": null,
"e": 34846,
"s": 34826,
"text": "EPM Add-in .net 3.5"
},
{
"code": null,
"e": 34877,
"s": 34846,
"text": "It supports MS Office 32 bits."
},
{
"code": null,
"e": 34908,
"s": 34877,
"text": "It supports MS Office 32 bits."
},
{
"code": null,
"e": 34979,
"s": 34908,
"text": "It degrades the performance if you are querying using ODBO connection."
},
{
"code": null,
"e": 35050,
"s": 34979,
"text": "It degrades the performance if you are querying using ODBO connection."
},
{
"code": null,
"e": 35081,
"s": 35050,
"text": "It runs on .net 3.5 framework."
},
{
"code": null,
"e": 35112,
"s": 35081,
"text": "It runs on .net 3.5 framework."
},
{
"code": null,
"e": 35135,
"s": 35112,
"text": "It supports .msp file."
},
{
"code": null,
"e": 35158,
"s": 35135,
"text": "It supports .msp file."
},
{
"code": null,
"e": 35197,
"s": 35158,
"text": "It doesnβt support big volume BV mode."
},
{
"code": null,
"e": 35236,
"s": 35197,
"text": "It doesnβt support big volume BV mode."
},
{
"code": null,
"e": 35256,
"s": 35236,
"text": "EPM Add-in .net 4.0"
},
{
"code": null,
"e": 35299,
"s": 35256,
"text": "It supports MS Office both 32 and 64 bits."
},
{
"code": null,
"e": 35342,
"s": 35299,
"text": "It supports MS Office both 32 and 64 bits."
},
{
"code": null,
"e": 35382,
"s": 35342,
"text": "It supports BV mode on BW data sources."
},
{
"code": null,
"e": 35422,
"s": 35382,
"text": "It supports BV mode on BW data sources."
},
{
"code": null,
"e": 35502,
"s": 35422,
"text": "It provides performance optimization if you are querying using ODBO connection."
},
{
"code": null,
"e": 35582,
"s": 35502,
"text": "It provides performance optimization if you are querying using ODBO connection."
},
{
"code": null,
"e": 35641,
"s": 35582,
"text": "It also support *.msp file (have to uninstall/re-install)."
},
{
"code": null,
"e": 35700,
"s": 35641,
"text": "It also support *.msp file (have to uninstall/re-install)."
},
{
"code": null,
"e": 35747,
"s": 35700,
"text": "It supports BW connections for embedded model."
},
{
"code": null,
"e": 35794,
"s": 35747,
"text": "It supports BW connections for embedded model."
},
{
"code": null,
"e": 35923,
"s": 35794,
"text": "There are various templates in sample app set and you can select any of these and customize them to meet the report requirement."
},
{
"code": null,
"e": 36204,
"s": 35923,
"text": "Using this feature, it allows you to save report locally or on the server. When you modify an existing report you can also save it as template for future use. BPC administrator can only have rights to save customized report as template on the server but you can save them locally."
},
{
"code": null,
"e": 36249,
"s": 36204,
"text": "Following are the default templates in BPC β"
},
{
"code": null,
"e": 36444,
"s": 36249,
"text": "Launch EPM Office Excel Add-in, to use a template. These templates are available in Company folder and they are created using BPC add-in not like BPC 7.x where templates are created using EvDRE."
},
{
"code": null,
"e": 36603,
"s": 36444,
"text": "There are three ways to create a report in BPC. You can create simple reports using EPM action pane by dragging dimensions and dropping it to the report area."
},
{
"code": null,
"e": 36679,
"s": 36603,
"text": "You can add dimensions to direct axis as shown in the following screenshot."
},
{
"code": null,
"e": 36743,
"s": 36679,
"text": "Similarly, you can create ad-hoc reports using the action pane."
},
{
"code": null,
"e": 37068,
"s": 36743,
"text": "All reports that have been created in BPC 7.5 Excel can be migrated to BPC 10.0 using EPM Excel Add-in. EvDRE migration feature in Add-in is used to migrate as many features as possible to new version but the customized reports and templates can only be partially migrated and requires some manual effort for full migration."
},
{
"code": null,
"e": 37103,
"s": 37068,
"text": "Open the reports created in EvDRE."
},
{
"code": null,
"e": 37206,
"s": 37103,
"text": "Update the report to have correct Dimensions migrated. Next go to EPM Ribbon β More β EvDRE Migration."
},
{
"code": null,
"e": 37382,
"s": 37206,
"text": "To access Business Planning and Consolidation, you can login to web client. To launch web client, open the web browser and use the URL - http://server.domain:port/sap/bpc/web/"
},
{
"code": null,
"e": 37468,
"s": 37382,
"text": "When you login to BPC web client, first screen that opens is start page and home tab."
},
{
"code": null,
"e": 37576,
"s": 37468,
"text": "If you want to create reports using Web Client, you can go to create area which has the following options β"
},
{
"code": null,
"e": 37590,
"s": 37576,
"text": "New Workspace"
},
{
"code": null,
"e": 37601,
"s": 37590,
"text": "New Report"
},
{
"code": null,
"e": 37616,
"s": 37601,
"text": "New Input Form"
},
{
"code": null,
"e": 37669,
"s": 37616,
"text": "Go to New Report and the following screen will open."
},
{
"code": null,
"e": 37849,
"s": 37669,
"text": "From the dropdown menu, select a new report, input form. On the right side, you have the list of available dimensions. You can add dimension to Row and Columns as per requirement."
},
{
"code": null,
"e": 37993,
"s": 37849,
"text": "You can also edit the existing reports. There is an option to defer report layout. If you select this option it wonβt change the report layout."
},
{
"code": null,
"e": 38223,
"s": 37993,
"text": "SAP BPC provides you with an end-to-end planning process and perform activities like planning, forecasting, budgeting, reporting, etc. It allows you to follow top-down or bottom-up planning with an application and user interface."
},
{
"code": null,
"e": 38402,
"s": 38223,
"text": "In Business Planning and Consolidation, the planning process is supported by automation and workflows. It allows you to create reports and input forms that can write to database."
},
{
"code": null,
"e": 38546,
"s": 38402,
"text": "With reporting interface, you can get data from database to excel spreadsheets and input forms allow you to send data directly to the database."
},
{
"code": null,
"e": 38725,
"s": 38546,
"text": "Input forms contain the same functionality and formatting as reports, only difference is that reports are used for analysis and input forms are used for sending data to database."
},
{
"code": null,
"e": 38841,
"s": 38725,
"text": "Different modeling options are possible with input forms to meet the planning needs while sending data to database."
},
{
"code": null,
"e": 39000,
"s": 38841,
"text": "Spread β Spread modeling option allows you to send a value to specific destination cells. This value can be spread equally or weighted by the range of values."
},
{
"code": null,
"e": 39267,
"s": 39000,
"text": "Trend β Trend modeling method allows you to spread a value or a percentage and spread it by a growing factor in destination cells. You place the source value in first destination cell and rest of the cells are field with increased value by some amount or percentage."
},
{
"code": null,
"e": 39471,
"s": 39267,
"text": "Weighted β It allows you to allocate a set of values by weighted factor in the excel sheets. In this you select some values, grow them and then allocate the new amount based on weights of selected cells."
},
{
"code": null,
"e": 39566,
"s": 39471,
"text": "So input forms provide you with special modeling feature to assist you in your planning needs."
},
{
"code": null,
"e": 39724,
"s": 39566,
"text": "Note that input forms is the terminology used in BPC 10 whereas input schedules were used in BPC 7.x. However, eventually they both represent the same thing."
},
{
"code": null,
"e": 39970,
"s": 39724,
"text": "Input forms allow you to spread data from excel sheets directly to database and contains all the functions that are present with reports in BPC. The difference is that input forms write data to database and reports are used for analysis purpose."
},
{
"code": null,
"e": 40015,
"s": 39970,
"text": "Input forms support the following features β"
},
{
"code": null,
"e": 40279,
"s": 40015,
"text": "Data Submission β If you have enough authorize access, using input forms you can send data to database. If data validation is allowed by the system administrator, you can also validate the data and ensure that there is no work lock and validity issues on members."
},
{
"code": null,
"e": 40355,
"s": 40279,
"text": "Modelling Options β Various modeling options can be used with input forms β"
},
{
"code": null,
"e": 40362,
"s": 40355,
"text": "Spread"
},
{
"code": null,
"e": 40368,
"s": 40362,
"text": "Trend"
},
{
"code": null,
"e": 40377,
"s": 40368,
"text": "Weighted"
},
{
"code": null,
"e": 40485,
"s": 40377,
"text": "Work Status β After sending the data to database, you can change the work status locks to apply data locks."
},
{
"code": null,
"e": 40665,
"s": 40485,
"text": "Distribution and Collection Option β You can send the input schedules to different members using distribution option and then get back the input schedules using collection option."
},
{
"code": null,
"e": 40751,
"s": 40665,
"text": "Using Special formalities β You can also apply special formatting to read-only cells."
},
{
"code": null,
"e": 40867,
"s": 40751,
"text": "There are various templates provided in the system that you can use and apply the customizations as per your needs."
},
{
"code": null,
"e": 40953,
"s": 40867,
"text": "Following is the list of dynamic schedule templates that are available in the system."
},
{
"code": null,
"e": 41015,
"s": 40953,
"text": "Input schedules can be developed using the following methods."
},
{
"code": null,
"e": 41033,
"s": 41015,
"text": "Dynamic Templates"
},
{
"code": null,
"e": 41045,
"s": 41033,
"text": "Using EvDRE"
},
{
"code": null,
"e": 41065,
"s": 41045,
"text": "Using Drag and Drop"
},
{
"code": null,
"e": 41140,
"s": 41065,
"text": "To create an input form/schedule using drag and drop, login to web client."
},
{
"code": null,
"e": 41226,
"s": 41140,
"text": "In the type select the input form. You can also add dimensions by clicking on + sign."
},
{
"code": null,
"e": 41348,
"s": 41226,
"text": "You can drag the dimension to rows and columns from the list of available dimensions and once you are done, click βSaveβ."
},
{
"code": null,
"e": 41411,
"s": 41348,
"text": "Enter the name of input form and description and click βSaveβ."
},
{
"code": null,
"e": 41693,
"s": 41411,
"text": "You can also view the real-time data from BusinessObjects Planning and Consolidation via Dashboard designer. To create Dashboard with BPC, you need to install Dashboard designer and add EPM Connector Add-on to the Dashboard designer and connect to the EPM data using EPM Connector."
},
{
"code": null,
"e": 41774,
"s": 41693,
"text": "Once connector is installed, you can use BPC real time-data to create dashboard."
},
{
"code": null,
"e": 41816,
"s": 41774,
"text": "Go to Analyzer tab in Dashboard Designer."
},
{
"code": null,
"e": 41840,
"s": 41816,
"text": "Then go to Edit Report."
},
{
"code": null,
"e": 42019,
"s": 41840,
"text": "It will prompt you to add a new connection. Click on Add new button. Select SAP BusinessObjects Planning and Consolidation data source from the dropdown list and click βConnectβ."
},
{
"code": null,
"e": 42262,
"s": 42019,
"text": "It will open a new window promoting for BPC Server name, User name and password. You have to enter the same credentials that you use to login BPC Excel client. Once you enter the details, click βNextβ. Select the AppSet and Finish the wizard."
},
{
"code": null,
"e": 42373,
"s": 42262,
"text": "Select the cube from the dropdown list that contains the data you have to use and select the data source name."
},
{
"code": null,
"e": 42536,
"s": 42373,
"text": "Next select the newly created connection and click βOKβ. Once you click ok, it will open the Report Manager output, which can be used to design the report output."
},
{
"code": null,
"e": 42808,
"s": 42536,
"text": "These are the steps that can be used to integrate Dashboard Designer with SAP BusinessObjects Planning and Consolidation BPC tool. There are various features in the Dashboard designer that can be used to create interactive dashboard, which can be used by decision makers."
},
{
"code": null,
"e": 42930,
"s": 42808,
"text": "You can perform business logic and script logic on the data in BPC. There are various calculations that can be performed."
},
{
"code": null,
"e": 43069,
"s": 42930,
"text": "Business Rules β These are monetary functions which are used to post common accounting tasks in Business Planning and Consolidation model."
},
{
"code": null,
"e": 43212,
"s": 43069,
"text": "Script Logic β This includes the formulas which are used to perform different calculations on the members, dimensions, and data in BPC system."
},
{
"code": null,
"e": 43484,
"s": 43212,
"text": "Dimension logic is used to apply calculations and formulas on the dimensions. Calculations are performed as per the dimension formula at retrieval time. It is important to use the dimension formulas correctly as they can affect the system performance if used incorrectly."
},
{
"code": null,
"e": 43540,
"s": 43484,
"text": "Key points to remember while applying Dimension logic β"
},
{
"code": null,
"e": 43626,
"s": 43540,
"text": "Dimension formula affects the system performance so they should be applied correctly."
},
{
"code": null,
"e": 43712,
"s": 43626,
"text": "Dimension formula affects the system performance so they should be applied correctly."
},
{
"code": null,
"e": 43828,
"s": 43712,
"text": "Dimension formulas should be applied only on the members for which calculations are required after the aggregation."
},
{
"code": null,
"e": 43944,
"s": 43828,
"text": "Dimension formulas should be applied only on the members for which calculations are required after the aggregation."
},
{
"code": null,
"e": 44071,
"s": 43944,
"text": "Dimension formulas should be used only for those ratios which has to be calculated at both the levels - Base and Parent Level."
},
{
"code": null,
"e": 44198,
"s": 44071,
"text": "Dimension formulas should be used only for those ratios which has to be calculated at both the levels - Base and Parent Level."
},
{
"code": null,
"e": 44301,
"s": 44198,
"text": "Common Dimension member formulas are used to perform calculations - costs per unit, growth rates, etc."
},
{
"code": null,
"e": 44404,
"s": 44301,
"text": "Common Dimension member formulas are used to perform calculations - costs per unit, growth rates, etc."
},
{
"code": null,
"e": 44609,
"s": 44404,
"text": "You should be familiar with Multi Dimension Expression language to create complex Dimension formulas. The list of supported MDX functions is available from functional module BAPI_MDPROVIDER_GET_FUNCTIONS."
},
{
"code": null,
"e": 44750,
"s": 44609,
"text": "Prerequisites β To use a formula in dimension, you should add a property called Formula to member sheets using manage dimension task option."
},
{
"code": null,
"e": 44938,
"s": 44750,
"text": "You should also define the length of field and it should be more than 60 characters. Higher field lengths are preferred as any length greater than 60 is stored as string in SAP NetWeaver."
},
{
"code": null,
"e": 45094,
"s": 44938,
"text": "If you want to use Dimension formula in AppSet then you should maintain a special dimension member of type R. This member is called as Local Currency (LC)."
},
{
"code": null,
"e": 45139,
"s": 45094,
"text": "App set β Select Maintain Dimension Members."
},
{
"code": null,
"e": 45344,
"s": 45139,
"text": "The formula can be manually created or taken from a library dimension formula. To define member dimension formula, you have to put a Square bracket around the dimension and there is a dot between the two."
},
{
"code": null,
"e": 45388,
"s": 45344,
"text": "[PRODUCT].[PRODUCT1] β [PRODUCT].[PRODUCT2]"
},
{
"code": null,
"e": 45424,
"s": 45388,
"text": "[SALES].[SALES1] / [SALES].[SALES2]"
},
{
"code": null,
"e": 45591,
"s": 45424,
"text": "Standard Arithmetic functions has to be used in dimension formula - addition (+), subtraction (β), multiplication (*), Division (/) - these are used in SAP NetWeaver."
},
{
"code": null,
"e": 45661,
"s": 45591,
"text": "Once you save the dimension formulas, next is to validate the syntax."
},
{
"code": null,
"e": 45751,
"s": 45661,
"text": "Logic scripts allow you to automate the calculations in BPC for the financial statements."
},
{
"code": null,
"e": 46112,
"s": 45751,
"text": "Business rules are used to customize the data manipulation task like bulk data imports with currency translations, input data to database, etc. Business rules can be modified using table-based logic or scripts-based filters. Table-based logic provides the features available in UCON accelerator and Script-based files can be customized using MDX or SQL syntax."
},
{
"code": null,
"e": 46173,
"s": 46112,
"text": "You can define business rules for the following activities β"
},
{
"code": null,
"e": 46257,
"s": 46173,
"text": "Carry forward rules β Includes initializing balances when a new fiscal year starts."
},
{
"code": null,
"e": 46341,
"s": 46257,
"text": "Carry forward rules β Includes initializing balances when a new fiscal year starts."
},
{
"code": null,
"e": 46386,
"s": 46341,
"text": "Validation rules β Validates the input data."
},
{
"code": null,
"e": 46431,
"s": 46386,
"text": "Validation rules β Validates the input data."
},
{
"code": null,
"e": 46530,
"s": 46431,
"text": "Currency conversion rules β Converts the local currencies into the currency used in BPC reporting."
},
{
"code": null,
"e": 46629,
"s": 46530,
"text": "Currency conversion rules β Converts the local currencies into the currency used in BPC reporting."
},
{
"code": null,
"e": 46693,
"s": 46629,
"text": "Intercompany booking rules β Matches intercompany transactions."
},
{
"code": null,
"e": 46757,
"s": 46693,
"text": "Intercompany booking rules β Matches intercompany transactions."
},
{
"code": null,
"e": 46803,
"s": 46757,
"text": "Automatic Adjustments and Other Calculations."
},
{
"code": null,
"e": 46849,
"s": 46803,
"text": "Automatic Adjustments and Other Calculations."
},
{
"code": null,
"e": 46988,
"s": 46849,
"text": "To manage business rules in BPC system β Go to Administration as shown in the following screenshot. Go to Rules β Expand β Business Rules."
},
{
"code": null,
"e": 47179,
"s": 46988,
"text": "With help of script logic, you can write your own logic in SQL or MDX language. There are various MDX functions that can be used in dimension formulas. Some of the common MDX functions are β"
},
{
"code": null,
"e": 47232,
"s": 47179,
"text": "Avg β Returns average value of a numeric expression."
},
{
"code": null,
"e": 47285,
"s": 47232,
"text": "Avg β Returns average value of a numeric expression."
},
{
"code": null,
"e": 47363,
"s": 47285,
"text": "Count β Returns the number of tuples in one set and also includes null cells."
},
{
"code": null,
"e": 47441,
"s": 47363,
"text": "Count β Returns the number of tuples in one set and also includes null cells."
},
{
"code": null,
"e": 47498,
"s": 47441,
"text": "Max β Returns the maximum value of a numeric expression."
},
{
"code": null,
"e": 47555,
"s": 47498,
"text": "Max β Returns the maximum value of a numeric expression."
},
{
"code": null,
"e": 47612,
"s": 47555,
"text": "Min β Returns the minimum value of a numeric expression."
},
{
"code": null,
"e": 47669,
"s": 47612,
"text": "Min β Returns the minimum value of a numeric expression."
},
{
"code": null,
"e": 47714,
"s": 47669,
"text": "Sum β Returns the sum of numeric expression."
},
{
"code": null,
"e": 47759,
"s": 47714,
"text": "Sum β Returns the sum of numeric expression."
},
{
"code": null,
"e": 47829,
"s": 47759,
"text": "There are other MDX functions that can be used in dimension formulas."
},
{
"code": null,
"e": 47862,
"s": 47829,
"text": "Examples of simple rule formulas"
},
{
"code": null,
"e": 47906,
"s": 47862,
"text": "[PRODUCT].[PRODUCT1] β [PRODUCT].[PRODUCT2]"
},
{
"code": null,
"e": 47942,
"s": 47906,
"text": "[SALES].[SALES1] / [SALES].[SALES2]"
},
{
"code": null,
"e": 48110,
"s": 47942,
"text": "Standard Arithmetic functions have to be used in dimension formula - addition (+), subtraction (β), multiplication (*), Division (/) - these are used in SAP NetWeaver."
},
{
"code": null,
"e": 48180,
"s": 48110,
"text": "Once you save the dimension formulas, next is to validate the syntax."
},
{
"code": null,
"e": 48214,
"s": 48180,
"text": "Examples of Advance Rule Formulas"
},
{
"code": null,
"e": 48304,
"s": 48214,
"text": "This includes movement of calculation dimension formulas from one time period to another."
},
{
"code": null,
"e": 48333,
"s": 48304,
"text": "[AccRec] Accounts Receivable"
},
{
"code": null,
"e": 48359,
"s": 48333,
"text": "[AccPay] Accounts Payable"
},
{
"code": null,
"e": 48435,
"s": 48359,
"text": "Syntax for creating script logic in dimension formulas are already covered."
},
{
"code": null,
"e": 48460,
"s": 48435,
"text": "Exceptions in MDX Syntax"
},
{
"code": null,
"e": 48514,
"s": 48460,
"text": "Following are the exceptions to MDX syntax with BPC β"
},
{
"code": null,
"e": 48563,
"s": 48514,
"text": "Replace the keyword AS with an β=β (equal) sign."
},
{
"code": null,
"e": 48608,
"s": 48563,
"text": "Not to use single quotes around expressions."
},
{
"code": null,
"e": 48616,
"s": 48608,
"text": "Example"
},
{
"code": null,
"e": 48684,
"s": 48616,
"text": "[ACCOUNT].[#GROSSSALES] = -[ACCOUNT].[UNITS]*[ACCOUNT].[INPUTPRICE]"
},
{
"code": null,
"e": 48736,
"s": 48684,
"text": "[ACCOUNT].[#COST] = -[ACCOUNT].[#GROSSSALES]*80/100"
},
{
"code": null,
"e": 48932,
"s": 48736,
"text": "All the calculations performed in Excel worksheet is known as Worksheet logic. Worksheet logic includes all the functions that are available in an Excel spreadsheet and functions provided in BPC."
},
{
"code": null,
"e": 49094,
"s": 48932,
"text": "Business Planning and Consolidation performs various business functions such as audit, business process flows, finance statements and reporting, and work status."
},
{
"code": null,
"e": 49161,
"s": 49094,
"text": "Various inbuilt functions are provided to perform these functions."
},
{
"code": null,
"e": 49417,
"s": 49161,
"text": "Currency conversion is required if your monetary figures are present in more than one currency in your application set. If app set contains monetary figures in single currency, in that case you donβt need a rate application, currency time dimensions, etc."
},
{
"code": null,
"e": 49712,
"s": 49417,
"text": "If most of your data is entered in one currency and you have only few figures in other currency, this can be handled by creating duplicate members in entity dimension. In this case, you can duplicate few entities present in foreign operations to separate local currency from translated amounts."
},
{
"code": null,
"e": 49847,
"s": 49712,
"text": "Example β The US corporate mostly deals in the US but also has few subsidiaries functioning in other countries like Canada and Mexico."
},
{
"code": null,
"e": 50189,
"s": 49847,
"text": "There should be rate application where you store the exchange rates. You should have an account dimension, which includes RATETYPE. Then Entity dimension should include a property CURRENCY. FXTRANS logic should be available and DEFAULT logic should include a call to FXTRANS logic. Entity dimension should include the property TRANSALATE_TO."
},
{
"code": null,
"e": 50567,
"s": 50189,
"text": "There should be rate application where you store the exchange rates. Application should contain a CURRENCY type dimension. There should be property REPORTING for the CURRENCY dimension. Entity dimension must include the property CURRENCY. Account dimension must include property RATETYPE. FXTRANS logic should be available. DEFAULT logic should include a call to FXTRANS logic."
},
{
"code": null,
"e": 50868,
"s": 50567,
"text": "All valid rate types corresponds to an account of RATE application and belongs to GROUP FX Rate. If there is any account which is not part of this group, it will be multiplied by a factor 1. You can also define a special case NOTRANS, which results in an account being ignored during the translation."
},
{
"code": null,
"e": 51141,
"s": 50868,
"text": "Cross-rate translation includes multiplying the amount in local currency by ratio between the rate of destination currency and the rate of source currency. Using this, application can use only one table of rates for translating any source currency to destination currency."
},
{
"code": null,
"e": 51219,
"s": 51141,
"text": "You can also define the following default translations using business rules β"
},
{
"code": null,
"e": 51273,
"s": 51219,
"text": "Using different tables of rate by reporting currency."
},
{
"code": null,
"e": 51327,
"s": 51273,
"text": "Using different tables of rate by reporting currency."
},
{
"code": null,
"e": 51405,
"s": 51327,
"text": "Identifying the difference between multiply currencies and divide currencies."
},
{
"code": null,
"e": 51483,
"s": 51405,
"text": "Identifying the difference between multiply currencies and divide currencies."
},
{
"code": null,
"e": 51681,
"s": 51483,
"text": "To perform currency conversion and intercompany eliminations, you need a dimension type - Intercompany dimension (I). To execute intercompany elimination, an application should have the following β"
},
{
"code": null,
"e": 51730,
"s": 51681,
"text": "Dimension Type βIβ for intercompany elimination."
},
{
"code": null,
"e": 51778,
"s": 51730,
"text": "Dimension βIβ should include a property ENTITY."
},
{
"code": null,
"e": 51833,
"s": 51778,
"text": "Account dimension should include the property ELIMACC."
},
{
"code": null,
"e": 51884,
"s": 51833,
"text": "Entity dimension should include the property ELIM."
},
{
"code": null,
"e": 51932,
"s": 51884,
"text": "You should set the appropriate business tables."
},
{
"code": null,
"e": 51991,
"s": 51932,
"text": "There should be DPT package to execute intercompany logic."
},
{
"code": null,
"e": 52052,
"s": 51991,
"text": "Default elimination logic performs the following functions β"
},
{
"code": null,
"e": 52098,
"s": 52052,
"text": "Checks all base level entities where ELIM<>Y."
},
{
"code": null,
"e": 52161,
"s": 52098,
"text": "Restricts currency dimension to all reporting currencies only."
},
{
"code": null,
"e": 52226,
"s": 52161,
"text": "Removes all accounts to be eliminated into desired plug account."
},
{
"code": null,
"e": 52302,
"s": 52226,
"text": "Elimination is performed below first common parent in βelimination entityβ."
},
{
"code": null,
"e": 52492,
"s": 52302,
"text": "This is used to manage processes created by users and to create and manage business process flow templates. To manage business process flows, you need to have manage processes task profile."
},
{
"code": null,
"e": 52786,
"s": 52492,
"text": "Process template is defined as business process, which contains all the tasks that is spread across multiple modules of BPC system. It includes step-by-step process flow, user performed activities link, process context and timing when process takes place, all the participants and their roles."
},
{
"code": null,
"e": 52922,
"s": 52786,
"text": "An area manager entering monthly budget data, which includes each manager creating a process and entering the data for each department."
},
{
"code": null,
"e": 53030,
"s": 52922,
"text": "To create a new Business Process Template, login to Web portal β Planning and Consolidation Administration."
},
{
"code": null,
"e": 53098,
"s": 53030,
"text": "On the left side, you can see the option of Business Process Flows."
},
{
"code": null,
"e": 53172,
"s": 53098,
"text": "Expand this tab and you will see Process Templates and Process Instances."
},
{
"code": null,
"e": 53258,
"s": 53172,
"text": "To create a new Business Process template, go to tab Process Templates. Click β+Newβ."
},
{
"code": null,
"e": 53422,
"s": 53258,
"text": "BPC admins are responsible to create and manage process templates. Once process templates are created, the business user can use the templates to create processes."
},
{
"code": null,
"e": 53568,
"s": 53422,
"text": "Work status is used to lock a region of data in a model. This is used to override userβs member access privilege to write to a particular region."
},
{
"code": null,
"e": 53710,
"s": 53568,
"text": "There are multiple dimensions defined for a region with one property called as OWNER. While defining the work status, following are defined β"
},
{
"code": null,
"e": 53762,
"s": 53710,
"text": "Work Status β It belongs to physical state of data."
},
{
"code": null,
"e": 53814,
"s": 53762,
"text": "Work Status β It belongs to physical state of data."
},
{
"code": null,
"e": 53975,
"s": 53814,
"text": "Security β You can set different level of security on changing data in the system β All or Locked. You can set who can change the work state - Manager or Owner."
},
{
"code": null,
"e": 54136,
"s": 53975,
"text": "Security β You can set different level of security on changing data in the system β All or Locked. You can set who can change the work state - Manager or Owner."
},
{
"code": null,
"e": 54205,
"s": 54136,
"text": "Data Update β This defines how data will be updated by the customer."
},
{
"code": null,
"e": 54274,
"s": 54205,
"text": "Data Update β This defines how data will be updated by the customer."
},
{
"code": null,
"e": 54359,
"s": 54274,
"text": "Push β This option is used to push same work state for all the children of a member."
},
{
"code": null,
"e": 54444,
"s": 54359,
"text": "Push β This option is used to push same work state for all the children of a member."
},
{
"code": null,
"e": 54721,
"s": 54444,
"text": "Once work status is defined, they can be used by the users to lock the data for review and approval, etc. To implement e-mail notification of work status, you should set the parameters, APPROVALSTATUSMAIL, APPROVALSTATUSMSG, SMTPPASSWORD, SMTPPORT, SMTP SERVER, SMTPAUTH, etc."
},
{
"code": null,
"e": 54776,
"s": 54721,
"text": "Go to Business Planning and Administration β Features."
},
{
"code": null,
"e": 54883,
"s": 54776,
"text": "On the left side, you have Features tab. Expand this tab and you will see Work Status as the first option."
},
{
"code": null,
"e": 54978,
"s": 54883,
"text": "Go to Work Status and on the right side you will get options to create and manage work status."
},
{
"code": null,
"e": 55077,
"s": 54978,
"text": "You can define in BPC system, who can change the data. This includes the following access levels β"
},
{
"code": null,
"e": 55149,
"s": 55077,
"text": "All β This allows all users with appropriate access to change the data."
},
{
"code": null,
"e": 55219,
"s": 55149,
"text": "Locked β This locks the change on the data. None can change the data."
},
{
"code": null,
"e": 55281,
"s": 55219,
"text": "Manager β Only parents of owners/manager can change the data."
},
{
"code": null,
"e": 55325,
"s": 55281,
"text": "Owner - Only the owner can change the data."
},
{
"code": null,
"e": 55439,
"s": 55325,
"text": "Both β If you select both, owner of the specific member ID and the owner of the parent to the specific member ID."
},
{
"code": null,
"e": 55480,
"s": 55439,
"text": "Owner β Owner of the specific member ID."
},
{
"code": null,
"e": 55524,
"s": 55480,
"text": "Manager β Owner of the parent to member ID."
},
{
"code": null,
"e": 55637,
"s": 55524,
"text": "Parent member owners act as an owner for that specific parent member ID and work as manager for direct children."
},
{
"code": null,
"e": 55808,
"s": 55637,
"text": "This allows parent member owner to change the work status of direct children. In case you are selecting all children, owner of a parent can update children at all levels."
},
{
"code": null,
"e": 55848,
"s": 55808,
"text": "Base membersβ owners act as owner only."
},
{
"code": null,
"e": 55929,
"s": 55848,
"text": "Members with no parent but have children act as their own manager and owner too."
},
{
"code": null,
"e": 55995,
"s": 55929,
"text": "An owner is defined by one dimension hierarchy β OWNER dimension."
},
{
"code": null,
"e": 56091,
"s": 55995,
"text": "You can set a work state on a single member ID, in this Manager doesnβt include - All Children."
},
{
"code": null,
"e": 56180,
"s": 56091,
"text": "You can also set work state on multiple member IDs, manager uses Include - All Children."
},
{
"code": null,
"e": 56261,
"s": 56180,
"text": "To edit a work status β Select the Work Status, click on Edit button at the top."
},
{
"code": null,
"e": 56312,
"s": 56261,
"text": "You can set from the above βControlled byβ fields."
},
{
"code": null,
"e": 56379,
"s": 56312,
"text": "To delete a Work Status, select the work state and click βDeleteβ."
},
{
"code": null,
"e": 56609,
"s": 56379,
"text": "You can publish books to BPC web. Administrators and power users have an option to create books of reports by collecting series of reports. You can select an output as Printer copy or .pdf file, which can be stored on the server."
},
{
"code": null,
"e": 56722,
"s": 56609,
"text": "You can use Book Publishing wizard for this. Go to ePublish option and select Book Publishing wizard from there."
},
{
"code": null,
"e": 56817,
"s": 56722,
"text": "It will open Book Publishing Wizard β Select Publish Now as shown in the following screenshot."
},
{
"code": null,
"e": 56884,
"s": 56817,
"text": "You get two options - Publish to a PDF file or print to a printer."
},
{
"code": null,
"e": 56938,
"s": 56884,
"text": "To delete books in BPC web, go to BPC administration."
},
{
"code": null,
"e": 57002,
"s": 56938,
"text": "Select Administration Configuration action pane β Manage Books."
},
{
"code": null,
"e": 57079,
"s": 57002,
"text": "Select the book you want to manage by using the checkbox and click βDeleteβ."
},
{
"code": null,
"e": 57251,
"s": 57079,
"text": "It is easier to integrate BPC with MS Word and to create reports. BPC 10.0 has the capability to directly integrate and report using Microsoft Word and PowerPoint as well."
},
{
"code": null,
"e": 57519,
"s": 57251,
"text": "BPC 10.0 version of NetWeaver helps you combine the BPC features with rich functionality of Microsoft Word, Excel, and PowerPoint. Using BPC for office you can use all default features of Microsoft and worksheets, presentations can be directly linked to BPC database."
},
{
"code": null,
"e": 57576,
"s": 57519,
"text": "Following tasks can be performed for client maintenance."
},
{
"code": null,
"e": 57603,
"s": 57576,
"text": "Reset the Current View Bar"
},
{
"code": null,
"e": 57639,
"s": 57603,
"text": "Clear Local Application Information"
},
{
"code": null,
"e": 57665,
"s": 57639,
"text": "Refresh Dimension Members"
},
{
"code": null,
"e": 57691,
"s": 57665,
"text": "Refresh Dynamic Templates"
},
{
"code": null,
"e": 57751,
"s": 57691,
"text": "Set Local folder for Planning and Consolidation for Clients"
},
{
"code": null,
"e": 57824,
"s": 57751,
"text": "You can open these interfaces via BPC Web β List of available interfaces"
},
{
"code": null,
"e": 57908,
"s": 57824,
"text": "Go to File β Save As. Select Save as Web Page as shown in the following screenshot."
},
{
"code": null,
"e": 58004,
"s": 57908,
"text": "Enter the file name and select the Web folder that points to your BPC application set location."
},
{
"code": null,
"e": 58052,
"s": 58004,
"text": "You can select from the following directories β"
},
{
"code": null,
"e": 58142,
"s": 58052,
"text": "AppSetPublications β Used for publication that applies to all applications within AppSet."
},
{
"code": null,
"e": 58202,
"s": 58142,
"text": "[application] β Used to publish for a specific application."
},
{
"code": null,
"e": 58228,
"s": 58202,
"text": "_private β User specific."
},
{
"code": null,
"e": 58278,
"s": 58228,
"text": "Once you select the directory, click βSaveβ icon."
},
{
"code": null,
"e": 58342,
"s": 58278,
"text": "As discussed earlier, you can integrate PowerPoint to BPC 10.0."
},
{
"code": null,
"e": 58426,
"s": 58342,
"text": "Go to File β Save As. Select Save as Web Page as shown in the following screenshot."
},
{
"code": null,
"e": 58522,
"s": 58426,
"text": "Enter the file name and select the Web folder that points to your BPC application set location."
},
{
"code": null,
"e": 58570,
"s": 58522,
"text": "You can select from the following directories β"
},
{
"code": null,
"e": 58660,
"s": 58570,
"text": "AppSetPublications β Used for publication that applies to all applications within AppSet."
},
{
"code": null,
"e": 58750,
"s": 58660,
"text": "AppSetPublications β Used for publication that applies to all applications within AppSet."
},
{
"code": null,
"e": 58810,
"s": 58750,
"text": "[application] β Used to publish for a specific application."
},
{
"code": null,
"e": 58870,
"s": 58810,
"text": "[application] β Used to publish for a specific application."
},
{
"code": null,
"e": 58915,
"s": 58870,
"text": "_site β Used to publish for a specific site."
},
{
"code": null,
"e": 58960,
"s": 58915,
"text": "_site β Used to publish for a specific site."
},
{
"code": null,
"e": 58985,
"s": 58960,
"text": "_private β User specific"
},
{
"code": null,
"e": 59010,
"s": 58985,
"text": "_private β User specific"
},
{
"code": null,
"e": 59165,
"s": 59010,
"text": "SAP BPC also provides essential tools β Documents (repository to store files), Journals (to make adjustments to data in database), statistics, audit, etc."
},
{
"code": null,
"e": 59362,
"s": 59165,
"text": "This provides a central repository for storing and sharing files and web sites. There is a feature named Document View that can be used to post, share, and retrieve files or contents of a website."
},
{
"code": null,
"e": 59531,
"s": 59362,
"text": "You can post files or URL to add to documents view. You can set the description, set access, and determine if you want to send an email notification about the document."
},
{
"code": null,
"e": 59640,
"s": 59531,
"text": "You can save a file to a local drive or network folder. Files with the following extension can be uploaded β"
},
{
"code": null,
"e": 59841,
"s": 59640,
"text": "XLS, .XML, .MHT, .MHTML, .HTM, XLT, .DOC, , .HTML, .XLSX, .XLSM, .XLSB, .ZIP, .PDF, .PPTX, .PPTM, , .CDM, .TDM, .PNG, .GIF, .JPG, .CSS, .MRC, .DOT, .PPT, .POT, .POTX, .POTM, .DOCX, .DOCM, .DOTX, .DOTM"
},
{
"code": null,
"e": 59958,
"s": 59841,
"text": "BPC Administrator can also change the environment parameters (DEFAULT_EXTENSIONS) to allow other files to be posted."
},
{
"code": null,
"e": 60074,
"s": 59958,
"text": "Categorization of documents, sorting, and filtering of documents is also possible based on the following elements β"
},
{
"code": null,
"e": 60100,
"s": 60074,
"text": "Document type and subtype"
},
{
"code": null,
"e": 60114,
"s": 60100,
"text": "Model context"
},
{
"code": null,
"e": 60128,
"s": 60114,
"text": "Access rights"
},
{
"code": null,
"e": 60133,
"s": 60128,
"text": "Date"
},
{
"code": null,
"e": 60201,
"s": 60133,
"text": "To access the Document Type, go to BPC Web Portal β Administration."
},
{
"code": null,
"e": 60274,
"s": 60201,
"text": "On the left side of the screen, you have an option to select βFeaturesβ."
},
{
"code": null,
"e": 60408,
"s": 60274,
"text": "Once you expand Features, you will get an option of Document Types. You can select the document type and sub type from here and edit."
},
{
"code": null,
"e": 60570,
"s": 60408,
"text": "Audit function allows you to create reports that contains history of user sessions and system information. You can create Audit reports on the following topics β"
},
{
"code": null,
"e": 60631,
"s": 60570,
"text": "Business Process Flow β You can create these reports in BPF."
},
{
"code": null,
"e": 60640,
"s": 60631,
"text": "Standard"
},
{
"code": null,
"e": 60645,
"s": 60640,
"text": "Step"
},
{
"code": null,
"e": 60651,
"s": 60645,
"text": "Audit"
},
{
"code": null,
"e": 60704,
"s": 60651,
"text": "Security β You can create these reports in Security."
},
{
"code": null,
"e": 60709,
"s": 60704,
"text": "User"
},
{
"code": null,
"e": 60714,
"s": 60709,
"text": "Team"
},
{
"code": null,
"e": 60728,
"s": 60714,
"text": "Task Profiles"
},
{
"code": null,
"e": 60749,
"s": 60728,
"text": "Data Access Profiles"
},
{
"code": null,
"e": 60753,
"s": 60749,
"text": "BPF"
},
{
"code": null,
"e": 60807,
"s": 60753,
"text": "General β You can create these reports under general."
},
{
"code": null,
"e": 60819,
"s": 60807,
"text": "Work Status"
},
{
"code": null,
"e": 60845,
"s": 60819,
"text": "Administration Activities"
},
{
"code": null,
"e": 60854,
"s": 60845,
"text": "Comments"
},
{
"code": null,
"e": 60867,
"s": 60854,
"text": "Data Changes"
},
{
"code": null,
"e": 61001,
"s": 60867,
"text": "Go to Business Planning and Consolidation Administration. On the left side of the screen, you have an option to create Audit reports."
},
{
"code": null,
"e": 61072,
"s": 61001,
"text": "Once you click on Audit tab, you will see all three reporting options."
},
{
"code": null,
"e": 61125,
"s": 61072,
"text": "To create a report, click on any of the report type."
},
{
"code": null,
"e": 61204,
"s": 61125,
"text": "Select the Audit level - template, instance and Duration and click on Display."
},
{
"code": null,
"e": 61260,
"s": 61204,
"text": "Similarly, you can create Security and General Reports."
},
{
"code": null,
"e": 61380,
"s": 61260,
"text": "Journals in BPC are used to update data in database. This is normally done to post quarter end or year-end data in BPC."
},
{
"code": null,
"e": 61595,
"s": 61380,
"text": "Suppose an administrator has uploaded a general ledger information into an application for the Area manager to review using data manager. The Area Manager can make necessary changes to the data using journal entry."
},
{
"code": null,
"e": 61743,
"s": 61595,
"text": "Following are the tasks that can be performed from Journal manager. If you have any open journal entry, you can perform these from Journal options."
},
{
"code": null,
"e": 61852,
"s": 61743,
"text": "There are many more Journal entry functions that can be performed using Journal Manager or from Action Pane."
},
{
"code": null,
"e": 61976,
"s": 61852,
"text": "To create, edit, delete and modify Journal Parameters, go to Business Planning and Consolidation Administration β Features."
},
{
"code": null,
"e": 62018,
"s": 61976,
"text": "Expand the Feature tab β Select Journals."
},
{
"code": null,
"e": 62117,
"s": 62018,
"text": "From here, you can create new journals, delete template, journal parameters, delete journals, etc."
},
{
"code": null,
"e": 62278,
"s": 62117,
"text": "Business Process Flows are used to guide users with predefined set of application tasks. These steps should be performed in a series and can have sub steps too."
},
{
"code": null,
"e": 62494,
"s": 62278,
"text": "Sub steps in process flow shouldnβt be executed in a sequence and may not be required at each iteration. Also note that Business Process Flows can only be defined for end user tasks and not for administrative tasks."
},
{
"code": null,
"e": 62549,
"s": 62494,
"text": "Following Business Process Flow features can be used β"
},
{
"code": null,
"e": 62697,
"s": 62549,
"text": "This list is used to display the steps and sub steps assigned to you or the completed steps that you need to review. These are called step regions."
},
{
"code": null,
"e": 62797,
"s": 62697,
"text": "To-do list contains the name and status of each step region. They can have the following statuses β"
},
{
"code": null,
"e": 62850,
"s": 62797,
"text": "Action Required β Waiting for completion as new step"
},
{
"code": null,
"e": 62903,
"s": 62850,
"text": "Action Required β Waiting for completion as new step"
},
{
"code": null,
"e": 62969,
"s": 62903,
"text": "Review Required β Step is awaiting review and action is completed"
},
{
"code": null,
"e": 63035,
"s": 62969,
"text": "Review Required β Step is awaiting review and action is completed"
},
{
"code": null,
"e": 63065,
"s": 63035,
"text": "Completed β Step is completed"
},
{
"code": null,
"e": 63095,
"s": 63065,
"text": "Completed β Step is completed"
},
{
"code": null,
"e": 63166,
"s": 63095,
"text": "Rejected β Step has failed to pass the conditions in completion status"
},
{
"code": null,
"e": 63237,
"s": 63166,
"text": "Rejected β Step has failed to pass the conditions in completion status"
},
{
"code": null,
"e": 63297,
"s": 63237,
"text": "Pending β Step is waiting for reopened step to be completed"
},
{
"code": null,
"e": 63357,
"s": 63297,
"text": "Pending β Step is waiting for reopened step to be completed"
},
{
"code": null,
"e": 63478,
"s": 63357,
"text": "There are various other βTo-do listβ status like reopen, waiting proper work status, waiting for reopen and unavailable."
},
{
"code": null,
"e": 63649,
"s": 63478,
"text": "You can also reopen a completed step or reset a particular instance or a set of business process flow instances. To reopen a step, it should have the following criteria β"
},
{
"code": null,
"e": 63700,
"s": 63649,
"text": "Allow reopen attribute should be included in step."
},
{
"code": null,
"e": 63751,
"s": 63700,
"text": "Allow reopen attribute should be included in step."
},
{
"code": null,
"e": 63783,
"s": 63751,
"text": "Step status should be complete."
},
{
"code": null,
"e": 63815,
"s": 63783,
"text": "Step status should be complete."
},
{
"code": null,
"e": 63900,
"s": 63815,
"text": "You can only open one previous step at a time and steps can be opened in a sequence."
},
{
"code": null,
"e": 63985,
"s": 63900,
"text": "You can only open one previous step at a time and steps can be opened in a sequence."
},
{
"code": null,
"e": 64111,
"s": 63985,
"text": "If a step has an attribute Enable Reviewers, users canβt reopen this step directly but can send an email request to reviewer."
},
{
"code": null,
"e": 64237,
"s": 64111,
"text": "If a step has an attribute Enable Reviewers, users canβt reopen this step directly but can send an email request to reviewer."
},
{
"code": null,
"e": 64290,
"s": 64237,
"text": "The user has ReopenBPFStep task security assignment."
},
{
"code": null,
"e": 64343,
"s": 64290,
"text": "The user has ReopenBPFStep task security assignment."
},
{
"code": null,
"e": 64414,
"s": 64343,
"text": "All completed steps are audited by system and displayed in the report."
},
{
"code": null,
"e": 64538,
"s": 64414,
"text": "All the locked dimensions that are not specified in Business Process flow current view remain locked in any open worksheet."
},
{
"code": null,
"e": 64658,
"s": 64538,
"text": "Copying a Business Process Flow β Login to Business Planning and Consolidation Administration β Business Process Flows."
},
{
"code": null,
"e": 64790,
"s": 64658,
"text": "List of all BPF is displayed. To copy a BPF, select BPF and click βSave Asβ. Enter the name and description of BPF and save as BPF."
},
{
"code": null,
"e": 64903,
"s": 64790,
"text": "Similarly, you can reset a Business Process flow, using manage option by selecting reset process flow instances."
},
{
"code": null,
"e": 65263,
"s": 64903,
"text": "Custom menu provides a summary of a business process and also provides a link to useful information used in the process. BPC administrators are responsible to create custom menus and assign access rights so that only required people see these menus. There is a possibility that you can have multiple users with different access rights on a single custom menu."
},
{
"code": null,
"e": 65439,
"s": 65263,
"text": "A custom menu is defined using custom menu template. EV_MENUSTYLE worksheet of custom menu template is used to define format, content, functions and parameters of custom menu."
},
{
"code": null,
"e": 65650,
"s": 65439,
"text": "You can use custom menu template to define format, content, and functions in custom menu. You can use sample templates in ApShell or can create a custom menu by creating a new worksheet within an existing menu."
},
{
"code": null,
"e": 65701,
"s": 65650,
"text": "The sample template contains multiple worksheets β"
},
{
"code": null,
"e": 65748,
"s": 65701,
"text": "EV_DEFAULT β To define content of custom menu."
},
{
"code": null,
"e": 65795,
"s": 65748,
"text": "EV_DEFAULT β To define content of custom menu."
},
{
"code": null,
"e": 65843,
"s": 65795,
"text": "EV_MENUSTYLE β To define format of custom menu."
},
{
"code": null,
"e": 65891,
"s": 65843,
"text": "EV_MENUSTYLE β To define format of custom menu."
},
{
"code": null,
"e": 65977,
"s": 65891,
"text": "ADMINGROUP β This is the same as EV_DEFAULT but only edited for users in admin group."
},
{
"code": null,
"e": 66063,
"s": 65977,
"text": "ADMINGROUP β This is the same as EV_DEFAULT but only edited for users in admin group."
},
{
"code": null,
"e": 66096,
"s": 66063,
"text": "To create a custom menu template"
},
{
"code": null,
"e": 66161,
"s": 66096,
"text": "Go to BPC Excel eTools β Custom menu manager β Open Custom menu."
},
{
"code": null,
"e": 66353,
"s": 66161,
"text": "You can find sample custom menu templates under EXCEL/Reports/Wizard/ProcessMenu. There are various custom menu functions that can be used to perform various common excel activities such as β"
},
{
"code": null,
"e": 66363,
"s": 66353,
"text": "HIGHLIGHT"
},
{
"code": null,
"e": 66377,
"s": 66363,
"text": "OPENLOCALFILE"
},
{
"code": null,
"e": 66388,
"s": 66377,
"text": "NAVIGATION"
},
{
"code": null,
"e": 66400,
"s": 66388,
"text": "OPENWEBFILE"
},
{
"code": null,
"e": 66416,
"s": 66400,
"text": "OPENLOCALFOLDER"
},
{
"code": null,
"e": 66430,
"s": 66416,
"text": "OPENWEBFOLDER"
},
{
"code": null,
"e": 66443,
"s": 66430,
"text": "MEMBERLOOKUP"
},
{
"code": null,
"e": 66457,
"s": 66443,
"text": "OPENMYEVEREST"
},
{
"code": null,
"e": 66465,
"s": 66457,
"text": "OPENURL"
},
{
"code": null,
"e": 66477,
"s": 66465,
"text": "CHANGEGROUP"
},
{
"code": null,
"e": 66489,
"s": 66477,
"text": "PUBLISHBOOK"
},
{
"code": null,
"e": 66600,
"s": 66489,
"text": "Custom menu content is defined by two section in custom menu template - Default section and Menu item section."
},
{
"code": null,
"e": 66659,
"s": 66600,
"text": "Following default parameters can be defined for EVDEFAULT."
},
{
"code": null,
"e": 66720,
"s": 66659,
"text": "Value is True β It opens the custom menu in Excel interface."
},
{
"code": null,
"e": 66781,
"s": 66720,
"text": "Value is False β It opens the custom menu in Standard Excel."
},
{
"code": null,
"e": 66853,
"s": 66781,
"text": "If Value is True β It will hide the Planning and Consolidation Toolbar."
},
{
"code": null,
"e": 66929,
"s": 66853,
"text": "If Value is False β It will display the Planning and Consolidation Toolbar."
},
{
"code": null,
"e": 67096,
"s": 66929,
"text": "It is used to define the dimensions that has to be displayed on the top of custom menu page. These dimensions can be changed into the report mentioned in Custom menu."
},
{
"code": null,
"e": 67150,
"s": 67096,
"text": "Menu Item section includes the following parameters β"
},
{
"code": null,
"e": 67219,
"s": 67150,
"text": "Menu Item β Text description that the user can select for menu item."
},
{
"code": null,
"e": 67288,
"s": 67219,
"text": "Menu Item β Text description that the user can select for menu item."
},
{
"code": null,
"e": 67347,
"s": 67288,
"text": "Actions β Highlight, custom menu function or Menu command."
},
{
"code": null,
"e": 67406,
"s": 67347,
"text": "Actions β Highlight, custom menu function or Menu command."
},
{
"code": null,
"e": 67468,
"s": 67406,
"text": "Level β Level can be selected from section, item or sub item."
},
{
"code": null,
"e": 67530,
"s": 67468,
"text": "Level β Level can be selected from section, item or sub item."
},
{
"code": null,
"e": 67570,
"s": 67530,
"text": "Parameters β For custom menu functions."
},
{
"code": null,
"e": 67610,
"s": 67570,
"text": "Parameters β For custom menu functions."
},
{
"code": null,
"e": 67702,
"s": 67610,
"text": "Normal Screen β Default is full screen. This is set true, open custom menu in Normal screen"
},
{
"code": null,
"e": 67794,
"s": 67702,
"text": "Normal Screen β Default is full screen. This is set true, open custom menu in Normal screen"
},
{
"code": null,
"e": 67884,
"s": 67794,
"text": "CVOverride β This is used to change current view dimensions while switching applications."
},
{
"code": null,
"e": 67974,
"s": 67884,
"text": "CVOverride β This is used to change current view dimensions while switching applications."
},
{
"code": null,
"e": 68215,
"s": 67974,
"text": "SAP BPC Consolidation module is used to manage and prepare consolidated data and provides a correct view of consolidated data in an organization. Consolidation module also provides an environment to perform consolidation tasks over the web."
},
{
"code": null,
"e": 68443,
"s": 68215,
"text": "In SAP Business Planning and Consolidation NetWeaver version, you have consolidation monitor that is used to manage consolidated data reported by groups and entity members. Consolidation monitor also controls the reported data."
},
{
"code": null,
"e": 68579,
"s": 68443,
"text": "Consolidation central contains journals, which are used to create and manage journal entries for updated consolidated data in database."
},
{
"code": null,
"e": 68648,
"s": 68579,
"text": "It contains Ownership Manager to manage ownership-based hierarchies."
},
{
"code": null,
"e": 68887,
"s": 68648,
"text": "Setting up environment includes managing master data load after you have completed the installation of BPC. Business users can set up to refresh master data on nightly or weekly basis. This can be achieved in the following different ways."
},
{
"code": null,
"e": 69037,
"s": 68887,
"text": "First option is you download the data from SAP BW system to a flat file and then using BPC DM Manager load the data from flat file to BPC dimensions."
},
{
"code": null,
"e": 69239,
"s": 69037,
"text": "Other option is to load the data directly to BPC dimension through SAP BW Transformations. The selection of option depends on your business requirement to find out which solution has to be implemented."
},
{
"code": null,
"e": 69361,
"s": 69239,
"text": "Following steps illustrate how to import a transport and create a new data manager package to process master data import."
},
{
"code": null,
"e": 69420,
"s": 69361,
"text": "First step is to Import Transport - Transaction Code: STMS"
},
{
"code": null,
"e": 69565,
"s": 69420,
"text": "Next step is to create Data Manager Package to load from Application Server. Open BPC Excel and login. Go to Action Pane and select Manage Data."
},
{
"code": null,
"e": 69644,
"s": 69565,
"text": "Now to create a new package, go to Maintain Data Management β Manage Packages."
},
{
"code": null,
"e": 69723,
"s": 69644,
"text": "To create a new package, right-click on the blank area and select Add Package."
},
{
"code": null,
"e": 69825,
"s": 69723,
"text": "Click Process chain dropdown option and select Z_IMPORT_MASTER_DATA_LOAD. Click on the Select option."
},
{
"code": null,
"e": 69888,
"s": 69825,
"text": "Enter the Package name and description. Click on Add and Save."
},
{
"code": null,
"e": 70037,
"s": 69888,
"text": "Now go to Manage Packages option under Maintain Data Management. Select the package which has been created in the previous step and click on Modify."
},
{
"code": null,
"e": 70108,
"s": 70037,
"text": "In next window, click on View Package and then click βAdvanceβ button."
},
{
"code": null,
"e": 70163,
"s": 70108,
"text": "In next window of maintain dynamic script, click βOKβ."
},
{
"code": null,
"e": 70206,
"s": 70163,
"text": "Click βSaveβ and βOKβ and close the setup."
},
{
"code": null,
"e": 70343,
"s": 70206,
"text": "Models are used to hold the relationships, calculations and data in an organization. There are two types of models that can be created β"
},
{
"code": null,
"e": 70359,
"s": 70343,
"text": "Reporting Model"
},
{
"code": null,
"e": 70379,
"s": 70359,
"text": "Non Reporting Model"
},
{
"code": null,
"e": 70539,
"s": 70379,
"text": "We use reporting models for analysis purpose. Non Reporting modules include Driver and Rates model and are used for currency rates, price, ownership data, etc."
},
{
"code": null,
"e": 70616,
"s": 70539,
"text": "Types of Reporting Models β Following are the types of non reporting models."
},
{
"code": null,
"e": 70630,
"s": 70616,
"text": "Consolidation"
},
{
"code": null,
"e": 70638,
"s": 70630,
"text": "Finance"
},
{
"code": null,
"e": 70646,
"s": 70638,
"text": "Generic"
},
{
"code": null,
"e": 70727,
"s": 70646,
"text": "Types of Non Reporting Models β Following are the types of non reporting models."
},
{
"code": null,
"e": 70732,
"s": 70727,
"text": "Rate"
},
{
"code": null,
"e": 70742,
"s": 70732,
"text": "Ownership"
},
{
"code": null,
"e": 70839,
"s": 70742,
"text": "Note that you can do reporting on non-reporting models but you canβt assign work status to them."
},
{
"code": null,
"e": 70919,
"s": 70839,
"text": "To create a model, login to Business Planning and Consolidation Administration."
},
{
"code": null,
"e": 71045,
"s": 70919,
"text": "Go to Dimensions and Models on the left side of the screen, click βModelsβ tab. To create a new model, click on β+ Newβ sign."
},
{
"code": null,
"e": 71131,
"s": 71045,
"text": "In the next window, you have to enter model Id and description and go to Next button."
},
{
"code": null,
"e": 71203,
"s": 71131,
"text": "Select the Model Type - Reporting or Drivers and Rate and click βNextβ."
},
{
"code": null,
"e": 71306,
"s": 71203,
"text": "In the next screen, you have an option to select a blank model or you can copy from an existing model."
},
{
"code": null,
"e": 71464,
"s": 71306,
"text": "Once you select next, in the new screen you have to select dimensions to be included in the new model. You have to add specific dimensions as per model type."
},
{
"code": null,
"e": 71585,
"s": 71464,
"text": "Click βNextβ. In the last window, you will get a summary and create option. Click βCreateβ option to create a new model."
},
{
"code": null,
"e": 71628,
"s": 71585,
"text": "Similarly, you can copy an Existing model."
},
{
"code": null,
"e": 71829,
"s": 71628,
"text": "A logic is defined as calculations performed at different level. Execution of consolidation logic requires some sort of expertise and business requirement. A logic can be defined at different levels β"
},
{
"code": null,
"e": 71878,
"s": 71829,
"text": "Within a dimension using Microsoft MDX language."
},
{
"code": null,
"e": 71927,
"s": 71878,
"text": "Within a dimension using Microsoft MDX language."
},
{
"code": null,
"e": 71953,
"s": 71927,
"text": "With the help of scripts."
},
{
"code": null,
"e": 71979,
"s": 71953,
"text": "With the help of scripts."
},
{
"code": null,
"e": 72057,
"s": 71979,
"text": "Using business rules that are executed with predefined business requirements."
},
{
"code": null,
"e": 72135,
"s": 72057,
"text": "Using business rules that are executed with predefined business requirements."
},
{
"code": null,
"e": 72155,
"s": 72135,
"text": "BPC Excel formulas."
},
{
"code": null,
"e": 72175,
"s": 72155,
"text": "BPC Excel formulas."
},
{
"code": null,
"e": 72221,
"s": 72175,
"text": "A logic can be executed at different levels β"
},
{
"code": null,
"e": 72239,
"s": 72221,
"text": "Analysis Services"
},
{
"code": null,
"e": 72262,
"s": 72239,
"text": "BPC Application Server"
},
{
"code": null,
"e": 72283,
"s": 72262,
"text": "Excel/Live Reporting"
},
{
"code": null,
"e": 72352,
"s": 72283,
"text": "Login to Business Planning and Consolidation Administration β Rules."
},
{
"code": null,
"e": 72464,
"s": 72352,
"text": "Select Logic Scripts option on the left side of the screen. Select the Model from the right side of the screen."
},
{
"code": null,
"e": 72545,
"s": 72464,
"text": "Click on + New sign and enter the Logic Script File Name. Go to βCreateβ button."
},
{
"code": null,
"e": 72590,
"s": 72545,
"text": "Enter the Logic script and click βValidateβ."
},
{
"code": null,
"e": 72641,
"s": 72590,
"text": "Once the script is validated, click βSaveβ button."
},
{
"code": null,
"e": 72839,
"s": 72641,
"text": "To perform currency conversion and intercompany eliminations, you need a dimension type - Intercompany dimension (I). To execute intercompany elimination, an application should have the following β"
},
{
"code": null,
"e": 72888,
"s": 72839,
"text": "Dimension Type βIβ for intercompany elimination."
},
{
"code": null,
"e": 72936,
"s": 72888,
"text": "Dimension βIβ should include a property ENTITY."
},
{
"code": null,
"e": 72991,
"s": 72936,
"text": "Account dimension should include the property ELIMACC."
},
{
"code": null,
"e": 73042,
"s": 72991,
"text": "Entity dimension should include the property ELIM."
},
{
"code": null,
"e": 73090,
"s": 73042,
"text": "You should set the appropriate business tables."
},
{
"code": null,
"e": 73149,
"s": 73090,
"text": "There should be DPT package to execute intercompany logic."
},
{
"code": null,
"e": 73210,
"s": 73149,
"text": "Default elimination logic performs the following functions β"
},
{
"code": null,
"e": 73256,
"s": 73210,
"text": "Checks all base level entities where ELIM<>Y."
},
{
"code": null,
"e": 73319,
"s": 73256,
"text": "Restricts currency dimension to all reporting currencies only."
},
{
"code": null,
"e": 73387,
"s": 73319,
"text": "It removes all accounts to be eliminated into desired plug account."
},
{
"code": null,
"e": 73463,
"s": 73387,
"text": "Elimination is performed below first common parent in βelimination entityβ."
},
{
"code": null,
"e": 73705,
"s": 73463,
"text": "SAP BPC Consolidation central is used to manage and prepare consolidated data and provides a correct view of consolidated data in an organization. Consolidation module also provides an environment to perform consolidation tasks over the web."
},
{
"code": null,
"e": 73763,
"s": 73705,
"text": "Following are the key features in Consolidation Central β"
},
{
"code": null,
"e": 73991,
"s": 73763,
"text": "In SAP Business Planning and Consolidation NetWeaver version, you have consolidation monitor that is used to manage consolidated data reported by groups and entity members. Consolidation monitor also controls the reported data."
},
{
"code": null,
"e": 74435,
"s": 73991,
"text": "It is one of the key components while executing incremental consolidation as it communicates with consolidation engine to perform currency translation execution. Consolidation monitor also displays the group-entity hierarchy that is defined in Ownership manager. Using the consolidation monitor, you can execute full consolidation that contains group-entity hierarchy. You can also perform incremental consolidation with only updated entities."
},
{
"code": null,
"e": 74569,
"s": 74435,
"text": "Consolidation central contain journals which are used to create and manage journal entries for updated consolidated data in database."
},
{
"code": null,
"e": 74638,
"s": 74569,
"text": "It contains Ownership Manager to manage ownership-based hierarchies."
},
{
"code": null,
"e": 74709,
"s": 74638,
"text": "It is used to manage controls which is used to validate reported data."
},
{
"code": null,
"e": 74833,
"s": 74709,
"text": "Journals in BPC are used to update data in the database. This is normally done to post quarter end or year-end data in BPC."
},
{
"code": null,
"e": 75053,
"s": 74833,
"text": "Example β Suppose the administrator has uploaded general ledger information into an application for Area Manager to review using data manager. The Area Manager can make necessary changes to the data using journal entry."
},
{
"code": null,
"e": 75199,
"s": 75053,
"text": "Following are the tasks that can be performed by Journal manager. If you have any open journal entry, you can perform these from Journal options."
},
{
"code": null,
"e": 75312,
"s": 75199,
"text": "There are other Journal entry functions that can be performed using the Journal Manager or from the Action Pane."
},
{
"code": null,
"e": 75436,
"s": 75312,
"text": "To create, edit, delete and modify Journal Parameters, go to Business Planning and Consolidation Administration β Features."
},
{
"code": null,
"e": 75478,
"s": 75436,
"text": "Expand the Feature tab β Select Journals."
},
{
"code": null,
"e": 75578,
"s": 75478,
"text": "Using this, you can create new journals, delete template, journal parameters, delete journals, etc."
},
{
"code": null,
"e": 75738,
"s": 75578,
"text": "Translating local currency means converting the amount in source currency to a target currency. You can perform currency translation at any group/entity level."
},
{
"code": null,
"e": 75973,
"s": 75738,
"text": "Translating local currency is performed in consolidation central of Business Planning and Consolidation system. To run the currency translation on a specific entity, your BPC administrator should grant you write access on that entity."
},
{
"code": null,
"e": 76045,
"s": 75973,
"text": "Following are the main facts in performing local currency translation β"
},
{
"code": null,
"e": 76145,
"s": 76045,
"text": "Category β This includes categorization of reported data to which you linked the translated amount."
},
{
"code": null,
"e": 76245,
"s": 76145,
"text": "Category β This includes categorization of reported data to which you linked the translated amount."
},
{
"code": null,
"e": 76336,
"s": 76245,
"text": "Time β It displays the data entry period in which the amount to be translated was entered."
},
{
"code": null,
"e": 76427,
"s": 76336,
"text": "Time β It displays the data entry period in which the amount to be translated was entered."
},
{
"code": null,
"e": 76528,
"s": 76427,
"text": "Reporting Currency β This tells you to select the currency in which you want to run the translation."
},
{
"code": null,
"e": 76629,
"s": 76528,
"text": "Reporting Currency β This tells you to select the currency in which you want to run the translation."
},
{
"code": null,
"e": 76703,
"s": 76629,
"text": "Group/Entity β This defines the fields on which translation is performed."
},
{
"code": null,
"e": 76777,
"s": 76703,
"text": "Group/Entity β This defines the fields on which translation is performed."
},
{
"code": null,
"e": 76905,
"s": 76777,
"text": "Translation Execution Mode β You can perform a full translation of local currency or you can select an incremental translation."
},
{
"code": null,
"e": 77033,
"s": 76905,
"text": "Translation Execution Mode β You can perform a full translation of local currency or you can select an incremental translation."
},
{
"code": null,
"e": 77128,
"s": 77033,
"text": "Rate Entry β This contains the exchange rates to select while performing currency translation."
},
{
"code": null,
"e": 77223,
"s": 77128,
"text": "Rate Entry β This contains the exchange rates to select while performing currency translation."
},
{
"code": null,
"e": 77276,
"s": 77223,
"text": "Go to BPC web portal β Select Consolidation Central."
},
{
"code": null,
"e": 77343,
"s": 77276,
"text": "Go to Consolidation Monitor after expanding Consolidation Central."
},
{
"code": null,
"e": 77423,
"s": 77343,
"text": "Select the entity/group row for which you want to perform currency translation."
},
{
"code": null,
"e": 77559,
"s": 77423,
"text": "In the next dialog box, select the Execution mode - full translation or Incremental Translation. Click βOkβ after selecting the fields."
},
{
"code": null,
"e": 77746,
"s": 77559,
"text": "In BPC, it is necessary to configure intercompany eliminations between subsidiaries or parents to avoid double counting. Intercompany eliminations is performed with help of script logic."
},
{
"code": null,
"e": 77963,
"s": 77746,
"text": "If you have transactions between subsidiaries Co. XP02, XP03, these transactions should be eliminated. These transactions are for intercompany account payable and account receivables, and intercompany sales and cost."
},
{
"code": null,
"e": 78053,
"s": 77963,
"text": "Before performing intercompany elimination, you should have the following prerequisites β"
},
{
"code": null,
"e": 78081,
"s": 78053,
"text": "A consolidation environment"
},
{
"code": null,
"e": 78140,
"s": 78081,
"text": "You should perform currency conversion before elimination."
},
{
"code": null,
"e": 78405,
"s": 78140,
"text": "To start with, first create a dimension for IC elimination. Application where you have to perform IC elimination must have dimension of type βIβ and βRβ for account and rate. Account dimension must have an elimination account property to post IC transfer balances."
},
{
"code": null,
"e": 78556,
"s": 78405,
"text": "Next is to have an Entity dimension with a property ELIM (Y/N) to post elimination entity results. This property is set to βYβ for elimination entity."
},
{
"code": null,
"e": 78636,
"s": 78556,
"text": "Account Dimension βIβ should have an ENTITY property and should be maintained β"
},
{
"code": null,
"e": 78647,
"s": 78636,
"text": "XP01_Input"
},
{
"code": null,
"e": 78652,
"s": 78647,
"text": "XP02"
},
{
"code": null,
"e": 78657,
"s": 78652,
"text": "XP03"
},
{
"code": null,
"e": 78662,
"s": 78657,
"text": "XP04"
},
{
"code": null,
"e": 78667,
"s": 78662,
"text": "XP05"
},
{
"code": null,
"e": 78757,
"s": 78667,
"text": "Your currency dimension βRβ should have a property βReportingβ and should be maintained β"
},
{
"code": null,
"e": 78910,
"s": 78757,
"text": "IC Elimination is managed by inbuilt procedures - INITIALIZE_ELIM and ELIMINATE_ORG. Both of these procedures are maintained in ICELIMWITHCURR.LGL file."
},
{
"code": null,
"e": 79016,
"s": 78910,
"text": "The following logic should be entered in application ICELIM logic file and should be validated and saved."
},
{
"code": null,
"e": 79392,
"s": 79016,
"text": "//Logic for Intercompany Elimination\n//========================================================\n*INCLUDE SYSTEM_CONSTANTS.LGL\n*SYSLIB ICELIMWITHCURR.LGL\n//========================================================\n//Elimination logic\nfor organizations in the hierarchy H1\n//========================================================\n*INITIALIZE_ELIM()\n*ELIMINATE_ORG(H1)\n*COMMIT\n"
},
{
"code": null,
"e": 79473,
"s": 79392,
"text": "To validate this logic, go to Action pane and select βValidate and saveβ option."
},
{
"code": null,
"e": 79605,
"s": 79473,
"text": "Once the above configuration is in place, you have to create an input schedule or import package to load the data to be eliminated."
},
{
"code": null,
"e": 79733,
"s": 79605,
"text": "To run the import package for IC elimination, login to BPC Excel. Click on Manage Data and go to Run a Data Management Package."
},
{
"code": null,
"e": 79849,
"s": 79733,
"text": "Go to Company folder of application, click on Financial Processes β Select Package IC Eliminations and click βRunβ."
},
{
"code": null,
"e": 79995,
"s": 79849,
"text": "Once this package is executed successfully, you can check the values of the following components in Profit and Loss statement and balance sheets."
},
{
"code": null,
"e": 80257,
"s": 79995,
"text": "Ownership terms is managed by the Ownership Manager. The Ownership Manager is used to manage ownership-based hierarchies. These hierarchies combine groups and entities and these entities can be connected or disconnected from groups as per the category and time."
},
{
"code": null,
"e": 80377,
"s": 80257,
"text": "Ownership-based hierarchies are used to meet the reporting requirements which canβt be managed using fixed hierarchies."
},
{
"code": null,
"e": 80526,
"s": 80377,
"text": "To display the Ownership manager, login to BPC web portal home page. Go to consolidation Central on the left side of the screen β Ownership Manager."
},
{
"code": null,
"e": 80667,
"s": 80526,
"text": "To create an Ownership-based hierarchy β Go to Ownership manager as mentioned above. Click on Edit option provided in the Ownership Manager."
},
{
"code": null,
"e": 80805,
"s": 80667,
"text": "In the next window, you will get an option to add members to hierarchy. Click βAddβ button and you will have an option to select members."
},
{
"code": null,
"e": 80898,
"s": 80805,
"text": "Once hierarchy members are added, click βSaveβ option on the top right corner of the screen."
},
{
"code": null,
"e": 81041,
"s": 80898,
"text": "Purchase method is sometimes also called the Global method. Business Planning and Consolidation supports the following consolidation methods β"
},
{
"code": null,
"e": 81066,
"s": 81041,
"text": "Global (Purchase) method"
},
{
"code": null,
"e": 81086,
"s": 81066,
"text": "Proportional method"
},
{
"code": null,
"e": 81100,
"s": 81086,
"text": "Equity method"
},
{
"code": null,
"e": 81256,
"s": 81100,
"text": "In this method of consolidation, balance sheet accounts and Profit and Loss accounts are fully included and minority interests are calculated if necessary."
},
{
"code": null,
"e": 81347,
"s": 81256,
"text": "In this method, you include balance sheet and P&L accounts at the percentage of ownership."
},
{
"code": null,
"e": 81448,
"s": 81347,
"text": "Example β Including P&L statement and balance sheet are included 50% at the percentage of ownership."
},
{
"code": null,
"e": 81572,
"s": 81448,
"text": "In this method, you donβt include balance sheet and P&L accounts. However, Net Value and Result of the Period are included."
},
{
"code": null,
"e": 81911,
"s": 81572,
"text": "BPC Embedded model is based on Business Warehouse-Integrated Planning (BW-IP) in which it uses BW objects directly. This model is different from Standard model and includes data access to all community users. For Embedded design model, initial versions used were SAP BW Integrated Planning and Planning Application Kit i.e. BW-IP and PAK."
},
{
"code": null,
"e": 82246,
"s": 81911,
"text": "This model provides a different level of data access where master and transactional data from host EDW environment is accessible by the application. In Embedded model, it allows an easy access to transactional and master data within the host BW, and this data is shared with many other users and controlled by the administrator group."
},
{
"code": null,
"e": 82445,
"s": 82246,
"text": "In Embedded model, migration from older versions of BW-IP to this data model is relatively easy and migration from earlier versions like (BPC 10.0 and earlier) is considered as a new implementation."
},
{
"code": null,
"e": 82570,
"s": 82445,
"text": "In short you can say that in embedded model, any number of InfoProviders can be assigned to a single BPC model /application."
},
{
"code": null,
"e": 82652,
"s": 82570,
"text": "Following are the key features and functions offered in BPC 10.1 Embedded model β"
},
{
"code": null,
"e": 82873,
"s": 82652,
"text": "It uses exception real-time SAP HANA functionalities and hence safeguards SAP HANA performance through the Planning Application Kit. Using SAP HANA allows to perform certain planning functions like copy, distribute, etc."
},
{
"code": null,
"e": 83094,
"s": 82873,
"text": "It uses exception real-time SAP HANA functionalities and hence safeguards SAP HANA performance through the Planning Application Kit. Using SAP HANA allows to perform certain planning functions like copy, distribute, etc."
},
{
"code": null,
"e": 83188,
"s": 83094,
"text": "BPC-Integration planning supports the use of real-time InfoProviders and aggregations levels."
},
{
"code": null,
"e": 83282,
"s": 83188,
"text": "BPC-Integration planning supports the use of real-time InfoProviders and aggregations levels."
},
{
"code": null,
"e": 83395,
"s": 83282,
"text": "Embedded model supports SAP BW Queries that you can execute directly in the SAP EPM add-in for Microsoft Office."
},
{
"code": null,
"e": 83508,
"s": 83395,
"text": "Embedded model supports SAP BW Queries that you can execute directly in the SAP EPM add-in for Microsoft Office."
},
{
"code": null,
"e": 83627,
"s": 83508,
"text": "Embedded model provides audit functions to allow creating various audit reports and use of the business process flows."
},
{
"code": null,
"e": 83746,
"s": 83627,
"text": "Embedded model provides audit functions to allow creating various audit reports and use of the business process flows."
},
{
"code": null,
"e": 83947,
"s": 83746,
"text": "SAP BW Integrated Planning provides BPC experts with an infrastructure to create and operate planning scenarios. This includes planning from common data entry processes to complex planning situations."
},
{
"code": null,
"e": 83982,
"s": 83947,
"text": "Planning model in BW-IP includes β"
},
{
"code": null,
"e": 84025,
"s": 83982,
"text": "Data stored in InfoProviders for Planning."
},
{
"code": null,
"e": 84068,
"s": 84025,
"text": "Data stored in InfoProviders for Planning."
},
{
"code": null,
"e": 84171,
"s": 84068,
"text": "Structured view of data includes aggregation levels, multi provider, and characteristic relationships."
},
{
"code": null,
"e": 84274,
"s": 84171,
"text": "Structured view of data includes aggregation levels, multi provider, and characteristic relationships."
},
{
"code": null,
"e": 84409,
"s": 84274,
"text": "Changing data includes planning functions, planning sequences, manual planning in the form of input-ready queries, and process chains."
},
{
"code": null,
"e": 84544,
"s": 84409,
"text": "Changing data includes planning functions, planning sequences, manual planning in the form of input-ready queries, and process chains."
},
{
"code": null,
"e": 84620,
"s": 84544,
"text": "Utilities, i.e. filters that can be used in queries and planning functions."
},
{
"code": null,
"e": 84696,
"s": 84620,
"text": "Utilities, i.e. filters that can be used in queries and planning functions."
},
{
"code": null,
"e": 84723,
"s": 84696,
"text": "Data protecting centrally."
},
{
"code": null,
"e": 84750,
"s": 84723,
"text": "Data protecting centrally."
},
{
"code": null,
"e": 84809,
"s": 84750,
"text": "Following tools can be used for model planning scenarios β"
},
{
"code": null,
"e": 84902,
"s": 84809,
"text": "BW modeling tools in Eclipse and the Data Warehousing Workbench to create data models in BW."
},
{
"code": null,
"e": 84995,
"s": 84902,
"text": "BW modeling tools in Eclipse and the Data Warehousing Workbench to create data models in BW."
},
{
"code": null,
"e": 85057,
"s": 84995,
"text": "Planning Modeler to model planning-specific metadata objects."
},
{
"code": null,
"e": 85119,
"s": 85057,
"text": "Planning Modeler to model planning-specific metadata objects."
},
{
"code": null,
"e": 85205,
"s": 85119,
"text": "BW modeling tools in Eclipse and also BEx Query Designer to enter plan data manually."
},
{
"code": null,
"e": 85291,
"s": 85205,
"text": "BW modeling tools in Eclipse and also BEx Query Designer to enter plan data manually."
},
{
"code": null,
"e": 85394,
"s": 85291,
"text": "BEx Web Application Designer or BEx Analyzer (Excel applications) to create applications for planning."
},
{
"code": null,
"e": 85497,
"s": 85394,
"text": "BEx Web Application Designer or BEx Analyzer (Excel applications) to create applications for planning."
},
{
"code": null,
"e": 85582,
"s": 85497,
"text": "Applications to execute either on the Web or in BEx Analyzer to enter data manually."
},
{
"code": null,
"e": 85667,
"s": 85582,
"text": "Applications to execute either on the Web or in BEx Analyzer to enter data manually."
},
{
"code": null,
"e": 85690,
"s": 85667,
"text": "Transaction Code: RSA1"
},
{
"code": null,
"e": 85792,
"s": 85690,
"text": "A data model is defined as an Info Cube in SAP BW, which consists of fact table and dimension tables."
},
{
"code": null,
"e": 85886,
"s": 85792,
"text": "To create an InfoCube β First create an Info Area, which is a building block for an InfoCube."
},
{
"code": null,
"e": 85946,
"s": 85886,
"text": "Enter the name and description of Info Area and click βOkβ."
},
{
"code": null,
"e": 86178,
"s": 85946,
"text": "Next create InfoObject Catalog which is used to define characteristics and key figures for different type of objects. Go to InfoObjects on the left side of the screen. Select the Info Area created above β Create InfoObject Catalog."
},
{
"code": null,
"e": 86273,
"s": 86178,
"text": "Enter the name and description of InfoObject Catalog, InfoObject Type and click βCreate (F5)β."
},
{
"code": null,
"e": 86340,
"s": 86273,
"text": "Now validate and activate IOC_Demo_CH to check InfoObject Catalog."
},
{
"code": null,
"e": 86393,
"s": 86340,
"text": "To activate InfoObject Catalog, go to activate icon."
},
{
"code": null,
"e": 86459,
"s": 86393,
"text": "Similarly, you can create InfoObject Catalog to hold key figures."
},
{
"code": null,
"e": 86607,
"s": 86459,
"text": "Let us create InfoObject. Right-click on InfoObject Catalog IOC_demo_CH and select create InfoObject. Enter the name and description of InfoObject."
},
{
"code": null,
"e": 86625,
"s": 86607,
"text": "Click βContinueβ."
},
{
"code": null,
"e": 86703,
"s": 86625,
"text": "Select Data Type with Character and Length as 15. Then click βAttributeβ tab."
},
{
"code": null,
"e": 86748,
"s": 86703,
"text": "Enter the Attribute name and click βCreateβ."
},
{
"code": null,
"e": 86816,
"s": 86748,
"text": "Select Create Attribute as Characteristics and click βCreateβ icon."
},
{
"code": null,
"e": 86957,
"s": 86816,
"text": "Select Character as data type and Length 30. Note that βAttribute onlyβ option is automatically checked. Click the green tick at the bottom."
},
{
"code": null,
"e": 87037,
"s": 86957,
"text": "Click βCheck and Activateβ option to validate and activate the characteristics."
},
{
"code": null,
"e": 87092,
"s": 87037,
"text": "Similarly, you can create InfoObjects for key figures."
},
{
"code": null,
"e": 87177,
"s": 87092,
"text": "Once you define InfoObjects for characteristics and key figures, create an InfoCube."
},
{
"code": null,
"e": 87230,
"s": 87177,
"text": "Right-click on Info Provider Demo β Create InfoCube."
},
{
"code": null,
"e": 87326,
"s": 87230,
"text": "Enter the name of InfoCube, select standard for the description of InfoCube and click βCreateβ."
},
{
"code": null,
"e": 87487,
"s": 87326,
"text": "Select characteristics from template table and move them to structure table using arrows. Click the Dimensions tab to assign these characteristics to dimension."
},
{
"code": null,
"e": 87631,
"s": 87487,
"text": "Click βCreateβ and add a description of dimension. Once you assign all the characteristics and key figures, validate and activate the InfoCube."
},
{
"code": null,
"e": 87856,
"s": 87631,
"text": "Security in SAP BPC system is defined using two components β Authentication and Authorization. Authentication defines who can access system and data, while authorization tells the level of access for each authenticated user."
},
{
"code": null,
"e": 88082,
"s": 87856,
"text": "SAP BPC security is based on access profiles and task profiles. When you donβt assign task profiles to users or teams, no access to BPC tasks will be provided. Thus you have to assign access to members of a secured dimension."
},
{
"code": null,
"e": 88134,
"s": 88082,
"text": "BPC Security provides the following key functions β"
},
{
"code": null,
"e": 88144,
"s": 88134,
"text": "Add Users"
},
{
"code": null,
"e": 88154,
"s": 88144,
"text": "Add Teams"
},
{
"code": null,
"e": 88172,
"s": 88154,
"text": "Add Task Profiles"
},
{
"code": null,
"e": 88199,
"s": 88172,
"text": "Add Member access profiles"
},
{
"code": null,
"e": 88278,
"s": 88199,
"text": "To manage the above functions, login to BPC Administration and go to Security."
},
{
"code": null,
"e": 88315,
"s": 88278,
"text": "There are four tabs under Security β"
},
{
"code": null,
"e": 88394,
"s": 88315,
"text": "Users β This is used to add users to the environment and manage access rights."
},
{
"code": null,
"e": 88466,
"s": 88394,
"text": "Teams β You can add users with the same access rights to the same team."
},
{
"code": null,
"e": 88583,
"s": 88466,
"text": "Task Profiles β This is used to set up profiles that allow tasks to be performed and assign them to users and teams."
},
{
"code": null,
"e": 88710,
"s": 88583,
"text": "Data Access Profiles β This is used to set up profiles that allow access to data in models and assign them to users and teams."
},
{
"code": null,
"e": 88820,
"s": 88710,
"text": "To Add/Edit/Delete any of the objects under Security, select the object as shown in the following screenshot."
},
{
"code": null,
"e": 89116,
"s": 88820,
"text": "Hot Analysis is used to set up hot link to another report or cell in another report. EvHOT functions are used by BPC Application Set and AP Shell to provide a sample report called Hot Analysis. Hot links are used by the users for ad hoc reporting and also used in the process selector reporting."
},
{
"code": null,
"e": 89191,
"s": 89116,
"text": "This is used to switch between reports that are in different applications."
},
{
"code": null,
"e": 89296,
"s": 89191,
"text": "EvHOT(AppName,ReportName,DisplayName,Member1,Member2,Member3,Member4, ......................, Member N)\n"
},
{
"code": null,
"e": 89357,
"s": 89296,
"text": "You have to pass the following parameters in EvHOT function."
},
{
"code": null,
"e": 89767,
"s": 89357,
"text": "AppName β This is the name of application. Note that in BPC system there is a setting in Workbook Option, which allows the system to remember the current view. By default, this setting is disabled. In this case, if you switch to a new application using EvHOT, it changes the application in the current view of workbook and other reports that you access in this session tries to get data from that application."
},
{
"code": null,
"e": 89885,
"s": 89767,
"text": "If this option is enabled, current view will revert to the workbook's application setting when switching focus to it."
},
{
"code": null,
"e": 90016,
"s": 89885,
"text": "ReportName β This is the name of the report. The root directory for BPC reports is the Wizard directory for the given application."
},
{
"code": null,
"e": 90086,
"s": 90016,
"text": "When you create a report - use eTools β Save Template Library option."
},
{
"code": null,
"e": 90165,
"s": 90086,
"text": "DisplayName β The text the user clicks to go to the specified report location."
},
{
"code": null,
"e": 90281,
"s": 90165,
"text": "Member1-Member N β This represents the CurrentView member. Here you can mention as many number of members you want."
},
{
"code": null,
"e": 90336,
"s": 90281,
"text": "EvHot(\"Finance\",\"Report2\",\"2010 Quarter 2\",\"2010.Q2\")\n"
},
{
"code": null,
"e": 90436,
"s": 90336,
"text": "Note β This report should be stored in \\Reports\\Wizard folder. Exact path is Report Wizard folder β"
},
{
"code": null,
"e": 90498,
"s": 90436,
"text": "..\\Data\\Webfolders\\ApShellCopy\\PLANNING\\eExcel\\Reports\\Wizard"
},
{
"code": null,
"e": 90609,
"s": 90498,
"text": "In case of a new report, you will also have to increase the template version in the BPC administration client."
},
{
"code": null,
"e": 90791,
"s": 90609,
"text": "Using Park N Go feature, you can lock down a BPC report and save it locally on your system as well as send the report through email to someone who doesnβt have access to BPC system."
},
{
"code": null,
"e": 90969,
"s": 90791,
"text": "If you donβt save the report with correct setting or sequence, you get an error in the report that makes the report unusable. You can use Park n Go feature to work it correctly."
},
{
"code": null,
"e": 91030,
"s": 90969,
"text": "Following are the steps you should follow to use Park n Go β"
},
{
"code": null,
"e": 91122,
"s": 91030,
"text": "Login to BPC Excel and open the report that you want to Park. Go to Save β Save my Reports."
},
{
"code": null,
"e": 91218,
"s": 91122,
"text": "You will get a dialog box asking if you want to lock the report before saving it. Select βYesβ."
},
{
"code": null,
"e": 91327,
"s": 91218,
"text": "In the next window, you will get a message - Select a Park n Go state for active workbook with four options."
},
{
"code": null,
"e": 91479,
"s": 91327,
"text": "Once you click βOkβ, a report will flash and you will get an option βSave Asβ. You can save the Excel of report to the location where you want to save."
},
{
"code": null,
"e": 91584,
"s": 91479,
"text": "This option allows you to open the report in Excel and all the data will appear correctly in the report."
},
{
"code": null,
"e": 91617,
"s": 91584,
"text": "\n 25 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 91631,
"s": 91617,
"text": " Sanjo Thomas"
},
{
"code": null,
"e": 91664,
"s": 91631,
"text": "\n 26 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 91676,
"s": 91664,
"text": " Neha Gupta"
},
{
"code": null,
"e": 91711,
"s": 91676,
"text": "\n 30 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 91726,
"s": 91711,
"text": " Sumit Agarwal"
},
{
"code": null,
"e": 91759,
"s": 91726,
"text": "\n 30 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 91774,
"s": 91759,
"text": " Sumit Agarwal"
},
{
"code": null,
"e": 91809,
"s": 91774,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 91821,
"s": 91809,
"text": " Neha Malik"
},
{
"code": null,
"e": 91856,
"s": 91821,
"text": "\n 13 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 91868,
"s": 91856,
"text": " Neha Malik"
},
{
"code": null,
"e": 91875,
"s": 91868,
"text": " Print"
},
{
"code": null,
"e": 91886,
"s": 91875,
"text": " Add Notes"
}
] |
Can we do better than Convolutional Neural Networks? | by Boris Knyazev | Towards Data Science
|
The British Machine Vision Conference (BMVC), finished about two weeks ago in Cardiff, UK, is one of the top conferences in computer vision & pattern recognition with a competitive acceptance rate of 28%. Compared to others, itβs a small event, so you have plenty of time to walk around posters and talk to presenters one-on-one, which I found really nice.
I presented a poster on Image Classification with Hierarchical Multigraph Networks on which I mainly worked during my internship at SRI International under the supervision of Xiao Lin, Mohamed Amer (homepage) and my PhD advisor Graham Taylor.
In the paper, we basically try to answer the question βCan we do better than Convolutional Neural Networks?β. Here I discuss this question and support my arguments by results. I also walk you through the forward pass of the whole pipeline for a single image from PASCAL VOC 2012 using PyTorch.
The complete code for this post is in my notebook on Github. It should be easy to adapt it for training and validating on the whole PASCAL dataset.
So, why do we want to do better than ConvNets? Havenβt they outperformed humans in many tasks?
For example, you could say that image classification is a solved task. Well, in terms of ImageNet, yes. But despite great contribution of ImageNet, it is a weird task. Why would you want to discriminate between hundreds of dog breeds? So, in result we have models succeeding in that, but failing to discriminate between slightly rotated dogs and cats. Fortunately, we now have ImageNet-C and other similar benchmarks showing that we are nowhere close to solving it.
Another open problem arising in related tasks, like object detection, is training on really large images (e.g., 4000Γ3000), which is addressed, for example, by Katharopoulos & Fleuret (ICML, 2019) and Ramapuram et al. (BMVC, 2019). Thanks to the latter I now know that if the background of a poster is black, then itβs likely from Apple. I should reserve some color too!
So, maybe we need something different than a Convolutional Neural Network? Instead of constantly patching its bugs, maybe we should use a model that has nicer properties from the beginning?
We argue that such a model can be a Graph Neural Network (GNN) β a neural network that can learn from graph-structured data. GNNs have some appealing properties. For example, compared to ConvNets, GNNs are inherently rotation and translation invariant, because there is simply no notion of rotation or translation in graphs, i.e. there is no left and right, there are only βneighborsβ in some sense (Khasanova & Frossard, ICML, 2017). So, the problem of making a ConvNet generalize better to different rotations, that people have been trying to solve for years, is solved automatically with GNNs!
Regarding learning from large images, how about extracting superpixels from images and feeding a much lower dimensional input to a GNN instead of feeding a downsampled (e.g. 224Γ224) image to a ConvNet? Superpixels seem to be a much better way to downsample an image compared to, say, bilinear interpolation, because they often preserve a lot of semantics by keeping the boundaries between objects. With a ConvNet we cannot directly learn from this kind of an input, however, there are some nice works proposing to leverage them (Kwak et al., AAAI, 2017).
So, a GNN sounds wonderful! Letβs see how it performs in practice.
Oh no! Our baseline GNN based on (Kipf & Welling, ICLR, 2017) achieves merely 19.2% (mean average precision or mAP) on PASCAL, compared to 32.7% of a ConvNet with the same number of layers and filters in each layer.
We propose several improvements that eventually beat the ConvNet!
In ConvNets, the hierarchical structure of images is implicitly modeled by pooling layers. In GNNs, you can achieve this in at least two ways. First, you can use pooling similar to ConvNets, but for graphs, defining a fast and good pooling method is really challenging. Instead, we can compute superpixels at multiple scales and pool superpixels by their correspondence to a larger parent superpixel. However, for some reasons this kind of pooling didnβt work well in our case (I still think it should work well). So, instead we model a hierarchy at the input level. In particular, we combine superpixels of all scales into a single set and compute hierarchical relations based on intersection over union (IoU), commonly used in semantic segmentation.
Based on that principle, I build the hierarchical graph in the code below. I also build a multiscale version of the spatial graph, but it encodes only spatial relationships, while IoU should better encode hierarchical ones. For example, using IoU we can create shortcuts between remote child nodes, i.e. connect two small superpixels (e.g., wheels) that are far away spatially, but belong to the same parent node (e.g., a car) as shown on the image above.
And indeed, the hierarchical graph boosts mAP to 31.7%, making it just 1% lower than a ConvNet while having 4 times fewer trainable parameters! If we use only the spatial multiscale graph, the results are much worse as explored in the paper.
Great! What else can we do to further improve results?
So far, if we visualize our filters, they will look very primitive (as Gaussians). See my tutorial on GNNs for more details. We want to learn some edge detectors similar to ConvNets, because they work so well. But it turned out to be very challenging to learn them with GNNs. To do that, we basically need to generate edges between superpixels depending on the difference between coordinates. By doing so, we will endow our GNN with the ability to understand the coordinate system (rotation, translation). We will use a 2 layer neural network defined in PyTorch like this:
pred_edge = nn.Sequential(nn.Linear(2, 32), nn.ReLU(True), nn.Linear(32, L))
where L is the number of predicted edges or the number of filters, such as 4 in the visualization below.
We restrict the filter to learn edges only based on the absolute difference between coordinates, |(x1,y1) - (x2,y2)|, instead of raw values, so that the filters become symmetric. This limits the capacity of filters, but it is still much better than a simple Gaussian filter used by our baseline GCN.
In my Jupyter notebook, I created a class LearnableGraph that implements the logic to predict edges given node coordinates (or any other features) and the spatial graph. The latter is used to define a small local neighborhood around each node to avoid predicting edges for all possible node pairs, because itβs expensive and doesnβt make much sense to connect very remote superpixels.
Below, I visualize the trained pred_edge function. To do that, I assume that the current node with index 1, where we apply the convolution, is in the center of a coordinate system, (x1,y1)=0. Then I simply sample coordinates of other nodes, (x2,y2), and feed them to pred_edge. The color shows the strength of an edge depending on the distance from a center node.
The learned graph is also very powerful, but at a larger computational cost, which is negligible if we generate a very sparse graph. The result of 32.3% is just 0.4% lower than a ConvNet and can be easily improved if we generate more filters!
We now have three graphs: spatial, hierarchical and learned. A single graph convolutional layer with the spatial or hierarchical graph permits feature propagation only within the βfirst neighborsβ. Neighbors are soft in our case, since we use a Gaussian to define the spatial graph and IoU for the hierarchical one. Defferrard et al. (NIPS, 2016) proposed a multiscale (multihop) graph convolution, which aggregates features within a K-hop neighborhood and approximates spectral graph convolution. See my other post for an extensive explanation of this method. For our spatial graph, it essentially corresponds to using multiple Gaussians of different width. For the hierarchical graph, this way we can create K-hop shortcuts between remote child nodes. For the learned graph, this method will create multiple scales of the learned filters visualized above.
Using multiscale graph convolution, implemented in my GraphLayerMultiscale class, turned out to be extremely important allowing us to outperform the baseline ConvNet by 0.3%!
So far, to learn from our three graphs, we have used a standard concatenation method. This method, however, has a couple of problems. First, the number of trainable parameters of such a fusion operator is linear w.r.t. the input and output feature dimensionalities, scale (K) and number of relation types, so it can really grow fast if we increase two or more of these parameters at once. Second, the relation types we try to fuse can have very different natures and occupy very different subspaces of a manifold. To solve both problems at the same time, we propose learnable projections similar to (Knyazev et al., NeurIPS-W, 2018). This way we decouple the linear dependency reducing the number of parameters by a factor of 2β3 compared to concatenation. In addition, learnable projections transform multirelational features so that they should occupy nearby subspaces of the manifold, facilitating the propagation of information from one relationship to another.
By using the proposed fusion method, implemented in the GraphLayerFusion class below, we achieve 34.5% beating the ConvNet by 1.8%, while having 2 times fewer parameters! Quite impressive for the model that initially didnβt know anything about the spatial structure of images, except for information encoded in superpixels. It would be interesting to explore other fusion methods, like this one, to get even better results.
It turned out that with a multirelational graph network and some tricks, we can do better than a Convolutional Neural Network!
Unfortunately, during our process of improving the GNN we slowly lost its invariance properties. For example, the shape of superpixels might change after rotating the image, and superpixel coordinates that we use for node features to improve the model also make it less robust.
Nevertheless, our work is a small step towards a better image reasoning model and we show that GNNs can pave a promising direction.
See my notebook on Github for implementation details.
I also highly recommend Matthias Feyβs Masterβs thesis with the code on a very related topic.
Find me on Github, LinkedIn and Twitter. My homepage.
|
[
{
"code": null,
"e": 529,
"s": 172,
"text": "The British Machine Vision Conference (BMVC), finished about two weeks ago in Cardiff, UK, is one of the top conferences in computer vision & pattern recognition with a competitive acceptance rate of 28%. Compared to others, itβs a small event, so you have plenty of time to walk around posters and talk to presenters one-on-one, which I found really nice."
},
{
"code": null,
"e": 772,
"s": 529,
"text": "I presented a poster on Image Classification with Hierarchical Multigraph Networks on which I mainly worked during my internship at SRI International under the supervision of Xiao Lin, Mohamed Amer (homepage) and my PhD advisor Graham Taylor."
},
{
"code": null,
"e": 1066,
"s": 772,
"text": "In the paper, we basically try to answer the question βCan we do better than Convolutional Neural Networks?β. Here I discuss this question and support my arguments by results. I also walk you through the forward pass of the whole pipeline for a single image from PASCAL VOC 2012 using PyTorch."
},
{
"code": null,
"e": 1214,
"s": 1066,
"text": "The complete code for this post is in my notebook on Github. It should be easy to adapt it for training and validating on the whole PASCAL dataset."
},
{
"code": null,
"e": 1309,
"s": 1214,
"text": "So, why do we want to do better than ConvNets? Havenβt they outperformed humans in many tasks?"
},
{
"code": null,
"e": 1775,
"s": 1309,
"text": "For example, you could say that image classification is a solved task. Well, in terms of ImageNet, yes. But despite great contribution of ImageNet, it is a weird task. Why would you want to discriminate between hundreds of dog breeds? So, in result we have models succeeding in that, but failing to discriminate between slightly rotated dogs and cats. Fortunately, we now have ImageNet-C and other similar benchmarks showing that we are nowhere close to solving it."
},
{
"code": null,
"e": 2146,
"s": 1775,
"text": "Another open problem arising in related tasks, like object detection, is training on really large images (e.g., 4000Γ3000), which is addressed, for example, by Katharopoulos & Fleuret (ICML, 2019) and Ramapuram et al. (BMVC, 2019). Thanks to the latter I now know that if the background of a poster is black, then itβs likely from Apple. I should reserve some color too!"
},
{
"code": null,
"e": 2336,
"s": 2146,
"text": "So, maybe we need something different than a Convolutional Neural Network? Instead of constantly patching its bugs, maybe we should use a model that has nicer properties from the beginning?"
},
{
"code": null,
"e": 2933,
"s": 2336,
"text": "We argue that such a model can be a Graph Neural Network (GNN) β a neural network that can learn from graph-structured data. GNNs have some appealing properties. For example, compared to ConvNets, GNNs are inherently rotation and translation invariant, because there is simply no notion of rotation or translation in graphs, i.e. there is no left and right, there are only βneighborsβ in some sense (Khasanova & Frossard, ICML, 2017). So, the problem of making a ConvNet generalize better to different rotations, that people have been trying to solve for years, is solved automatically with GNNs!"
},
{
"code": null,
"e": 3489,
"s": 2933,
"text": "Regarding learning from large images, how about extracting superpixels from images and feeding a much lower dimensional input to a GNN instead of feeding a downsampled (e.g. 224Γ224) image to a ConvNet? Superpixels seem to be a much better way to downsample an image compared to, say, bilinear interpolation, because they often preserve a lot of semantics by keeping the boundaries between objects. With a ConvNet we cannot directly learn from this kind of an input, however, there are some nice works proposing to leverage them (Kwak et al., AAAI, 2017)."
},
{
"code": null,
"e": 3556,
"s": 3489,
"text": "So, a GNN sounds wonderful! Letβs see how it performs in practice."
},
{
"code": null,
"e": 3772,
"s": 3556,
"text": "Oh no! Our baseline GNN based on (Kipf & Welling, ICLR, 2017) achieves merely 19.2% (mean average precision or mAP) on PASCAL, compared to 32.7% of a ConvNet with the same number of layers and filters in each layer."
},
{
"code": null,
"e": 3838,
"s": 3772,
"text": "We propose several improvements that eventually beat the ConvNet!"
},
{
"code": null,
"e": 4590,
"s": 3838,
"text": "In ConvNets, the hierarchical structure of images is implicitly modeled by pooling layers. In GNNs, you can achieve this in at least two ways. First, you can use pooling similar to ConvNets, but for graphs, defining a fast and good pooling method is really challenging. Instead, we can compute superpixels at multiple scales and pool superpixels by their correspondence to a larger parent superpixel. However, for some reasons this kind of pooling didnβt work well in our case (I still think it should work well). So, instead we model a hierarchy at the input level. In particular, we combine superpixels of all scales into a single set and compute hierarchical relations based on intersection over union (IoU), commonly used in semantic segmentation."
},
{
"code": null,
"e": 5046,
"s": 4590,
"text": "Based on that principle, I build the hierarchical graph in the code below. I also build a multiscale version of the spatial graph, but it encodes only spatial relationships, while IoU should better encode hierarchical ones. For example, using IoU we can create shortcuts between remote child nodes, i.e. connect two small superpixels (e.g., wheels) that are far away spatially, but belong to the same parent node (e.g., a car) as shown on the image above."
},
{
"code": null,
"e": 5288,
"s": 5046,
"text": "And indeed, the hierarchical graph boosts mAP to 31.7%, making it just 1% lower than a ConvNet while having 4 times fewer trainable parameters! If we use only the spatial multiscale graph, the results are much worse as explored in the paper."
},
{
"code": null,
"e": 5343,
"s": 5288,
"text": "Great! What else can we do to further improve results?"
},
{
"code": null,
"e": 5916,
"s": 5343,
"text": "So far, if we visualize our filters, they will look very primitive (as Gaussians). See my tutorial on GNNs for more details. We want to learn some edge detectors similar to ConvNets, because they work so well. But it turned out to be very challenging to learn them with GNNs. To do that, we basically need to generate edges between superpixels depending on the difference between coordinates. By doing so, we will endow our GNN with the ability to understand the coordinate system (rotation, translation). We will use a 2 layer neural network defined in PyTorch like this:"
},
{
"code": null,
"e": 6043,
"s": 5916,
"text": "pred_edge = nn.Sequential(nn.Linear(2, 32), nn.ReLU(True), nn.Linear(32, L))"
},
{
"code": null,
"e": 6148,
"s": 6043,
"text": "where L is the number of predicted edges or the number of filters, such as 4 in the visualization below."
},
{
"code": null,
"e": 6448,
"s": 6148,
"text": "We restrict the filter to learn edges only based on the absolute difference between coordinates, |(x1,y1) - (x2,y2)|, instead of raw values, so that the filters become symmetric. This limits the capacity of filters, but it is still much better than a simple Gaussian filter used by our baseline GCN."
},
{
"code": null,
"e": 6833,
"s": 6448,
"text": "In my Jupyter notebook, I created a class LearnableGraph that implements the logic to predict edges given node coordinates (or any other features) and the spatial graph. The latter is used to define a small local neighborhood around each node to avoid predicting edges for all possible node pairs, because itβs expensive and doesnβt make much sense to connect very remote superpixels."
},
{
"code": null,
"e": 7197,
"s": 6833,
"text": "Below, I visualize the trained pred_edge function. To do that, I assume that the current node with index 1, where we apply the convolution, is in the center of a coordinate system, (x1,y1)=0. Then I simply sample coordinates of other nodes, (x2,y2), and feed them to pred_edge. The color shows the strength of an edge depending on the distance from a center node."
},
{
"code": null,
"e": 7440,
"s": 7197,
"text": "The learned graph is also very powerful, but at a larger computational cost, which is negligible if we generate a very sparse graph. The result of 32.3% is just 0.4% lower than a ConvNet and can be easily improved if we generate more filters!"
},
{
"code": null,
"e": 8298,
"s": 7440,
"text": "We now have three graphs: spatial, hierarchical and learned. A single graph convolutional layer with the spatial or hierarchical graph permits feature propagation only within the βfirst neighborsβ. Neighbors are soft in our case, since we use a Gaussian to define the spatial graph and IoU for the hierarchical one. Defferrard et al. (NIPS, 2016) proposed a multiscale (multihop) graph convolution, which aggregates features within a K-hop neighborhood and approximates spectral graph convolution. See my other post for an extensive explanation of this method. For our spatial graph, it essentially corresponds to using multiple Gaussians of different width. For the hierarchical graph, this way we can create K-hop shortcuts between remote child nodes. For the learned graph, this method will create multiple scales of the learned filters visualized above."
},
{
"code": null,
"e": 8473,
"s": 8298,
"text": "Using multiscale graph convolution, implemented in my GraphLayerMultiscale class, turned out to be extremely important allowing us to outperform the baseline ConvNet by 0.3%!"
},
{
"code": null,
"e": 9439,
"s": 8473,
"text": "So far, to learn from our three graphs, we have used a standard concatenation method. This method, however, has a couple of problems. First, the number of trainable parameters of such a fusion operator is linear w.r.t. the input and output feature dimensionalities, scale (K) and number of relation types, so it can really grow fast if we increase two or more of these parameters at once. Second, the relation types we try to fuse can have very different natures and occupy very different subspaces of a manifold. To solve both problems at the same time, we propose learnable projections similar to (Knyazev et al., NeurIPS-W, 2018). This way we decouple the linear dependency reducing the number of parameters by a factor of 2β3 compared to concatenation. In addition, learnable projections transform multirelational features so that they should occupy nearby subspaces of the manifold, facilitating the propagation of information from one relationship to another."
},
{
"code": null,
"e": 9863,
"s": 9439,
"text": "By using the proposed fusion method, implemented in the GraphLayerFusion class below, we achieve 34.5% beating the ConvNet by 1.8%, while having 2 times fewer parameters! Quite impressive for the model that initially didnβt know anything about the spatial structure of images, except for information encoded in superpixels. It would be interesting to explore other fusion methods, like this one, to get even better results."
},
{
"code": null,
"e": 9990,
"s": 9863,
"text": "It turned out that with a multirelational graph network and some tricks, we can do better than a Convolutional Neural Network!"
},
{
"code": null,
"e": 10268,
"s": 9990,
"text": "Unfortunately, during our process of improving the GNN we slowly lost its invariance properties. For example, the shape of superpixels might change after rotating the image, and superpixel coordinates that we use for node features to improve the model also make it less robust."
},
{
"code": null,
"e": 10400,
"s": 10268,
"text": "Nevertheless, our work is a small step towards a better image reasoning model and we show that GNNs can pave a promising direction."
},
{
"code": null,
"e": 10454,
"s": 10400,
"text": "See my notebook on Github for implementation details."
},
{
"code": null,
"e": 10548,
"s": 10454,
"text": "I also highly recommend Matthias Feyβs Masterβs thesis with the code on a very related topic."
}
] |
How to create a link to send email with a subject in HTML?
|
To create a link to send email, use <a> tag, with href attribute. The mail to link is added inside the <a> tag. To add a subject, you need to add ? and then include the subject. All this comes inside the <a> tag.
Just keep in mind to add the email address where you want to receive the email in the mail to link. Also, the spaces between words for the subject shouldnβt be space, instead include %20. This is to ensure the browser displays the text properly.
You can try to run the following code to create a link to send an email with a subject in HTML.
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>HTML Email with subject</title>
</head>
<body>
<h1>Contact</h1>
<p>For any queries:<a href="mailto:demo@example.com?Subject=My%20Query">Contact us</a></p>
</body>
</html>
|
[
{
"code": null,
"e": 1275,
"s": 1062,
"text": "To create a link to send email, use <a> tag, with href attribute. The mail to link is added inside the <a> tag. To add a subject, you need to add ? and then include the subject. All this comes inside the <a> tag."
},
{
"code": null,
"e": 1521,
"s": 1275,
"text": "Just keep in mind to add the email address where you want to receive the email in the mail to link. Also, the spaces between words for the subject shouldnβt be space, instead include %20. This is to ensure the browser displays the text properly."
},
{
"code": null,
"e": 1617,
"s": 1521,
"text": "You can try to run the following code to create a link to send an email with a subject in HTML."
},
{
"code": null,
"e": 1627,
"s": 1617,
"text": "Live Demo"
},
{
"code": null,
"e": 1866,
"s": 1627,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML Email with subject</title>\n </head>\n\n <body>\n <h1>Contact</h1>\n <p>For any queries:<a href=\"mailto:demo@example.com?Subject=My%20Query\">Contact us</a></p>\n </body>\n</html>"
}
] |
How to Determine the Right Number of Clusters (with Code) | by Adam Brownell | Towards Data Science
|
Clustering is a fundamental skill in your Data Science toolkit. It can solve a huge array of problems β from user segmentation to anomaly detection β and can help your team derive very interesting insights.
Determining the right number of clusters for your project is a little more art than science. In this article, I will go over a few common ways to determine the right number of clusters.
All of the following examples will involve the following imports:
import pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom sklearn.cluster import KMeans
and the following variables:
min_clusters = 2max_clusters = 15
The objective of this metric is to find the βElbowβ of the WSS curve in order to determine the smallest number of clusters that captures the most amount of signal in your data. If this definition sounds vague and subjective, itβs because it is β finding the βelbowβ of the chart is certainly a subjective decision.
Within-Cluster Sum of Squares (WSS) is a measure of how far away each centroid is from their respective class instances. The larger the WSS, the more dispersed the cluster values are from the centroid. We can define WSS as:
def within_sum_of_squares(data, centroids, labels): SSW = 0 for l in np.unique(labels): data_l = data[labels == l] resid = data_l - centroids[l] SSW += (resid**2).sum() return SSW
And by simply iterating through our data for every cluster, we can generate the elbow curve:
wss_list = []for i in range(min_clusters, max_clusters+1): print('Training {} cluster algo...'.format(i)) km = KMeans(n_clusters=i) km.fit(data) wss = within_sum_of_squares(np.array(data),km.cluster_centers_, km.predict(data)) wss_list.append(wss)plt.plot(wss_list)plt.title('WSS Plot')plt.xlabel('# of Clusters')plt.ylabel('WSS')plt.show()
From the above example, we may decide that 4β5 cluster is the appropriate number of clusters, since adding additional clusters.
Another way to cut up this data is by the relative improvement of each cluster. By setting a threshold, say 5%, we can see at what number of clusters would start to see diminished returns on additional clusters of less than 5%
perc_improve_list = [0]rel_improvement = []base_wss = wss_list[0]for i in range(len(wss_list)): improvement = (wss_list[0] - wss_list[i])/wss_list[0] rel_improvement.append(improvement - perc_improve_list[-1]) perc_improve_list.append(improvement) threshold = 0.05plt.plot([i for i in range(min_clusters+1,max_clusters+1)], rel_improvement[1:])plt.axhline(threshold, linestyle='--', color='grey')plt.title('WSS Improvement Plot')plt.xlabel('# of Clusters')plt.ylabel('% improvement in WSS')plt.ylim([0,1])plt.show()
This chart points to the same outcome as the first, 4β5 clusters, albeit a little clearer. I prefer this output since it provides an objective threshold to the chart that we can modify at a later date.
βThe optimal number of clusters k is the one that maximize the average silhouette over a range of possible values for kβ β (Kaufman and Rousseeuw 1990)
A Silhouette Score is (other than being a word I can never spell correctly on first attempt) how close a specific example is to examples from other clusters. The larger the distance from other clustersβ examples, the cleaner the division between clusters and therefore the better clustering.
As the above quote states, by the number of clusters that maximizes the average silhouette score is preferred over other options.
To calculate silhouette scores, we can use SKLearns built in function:
from sklearn.metrics import silhouette_scoresil_score_list = []for i in range(min_clusters, max_clusters+1): print('Training {} cluster algo...'.format(i)) km = KMeans(n_clusters=i) km.fit(data) sil = silhouette_score(np.array(data),km.predict(data)) sil_score_list.append(sil) plt.bar([i for i in range(2,len(sil_score_list)+2)],sil_score_list)plt.title('Sil Plot')plt.xlabel('# of Clusters')plt.ylabel('Sil Score')plt.show()
For this metric, it seems to point to using 3 clusters to maximize the average Silhouette score. WSS and Sil scores wonβt always agree, as they are measuring different things. Using both in conjunction will help you make the most informed decision, along with method #3 outlined below.
Please Note: While I donβt know the Big O Notation for the SKLearn Silhouette algo (someone please comment if you know!) but this took significantly longer than the WSS search outlined above. Whereas the WSS code finish in about a half hour, the Silhouette code took well over 4 hours. Be prepared!
The real answer to how many clusters are right is:
Whatever makes the most sense for your team & project
It may seem like a cop-out answer (and it certainly isnβt a data science answer) but what matters more than WSS or Silhouette scores is that the clustering you generate helps you accomplish the task at hand.
There are many more ways to validate clustering strength, from Dunn Statics to Gap Metrics, but the real way to validate your clustering approach is to ensure that it is able to answer the questions you are seeking. Oftentimes Data Scientists canβt see the forest for the trees, and stressing over multiple data-driven success criteria rather than on producing outcomes for your team is a common mistake.
If you are looking to these clusters to generate human-interpretable archetypes for your business, perhaps to inform marketing, then you donβt want to use more than 10 clusters; otherwise, your marketing team will get bogged down with too many personas to generate copy for.
On the other end of the spectrum, if you are using clustering for personalization, you want as many meaningful clusters as possible, since the more clusters you create the more unique experiences you can provide your customers. Micro-segmentation is excellent for recommendations but at the cost of interpretability.
So when determining clusters β ensure you are on the same page with the stakeholder on the project and feel confident that you can justify the number of clusters, whether it be 2 or 200, from a non-technical perspective.
Hope you enjoyed!
|
[
{
"code": null,
"e": 379,
"s": 172,
"text": "Clustering is a fundamental skill in your Data Science toolkit. It can solve a huge array of problems β from user segmentation to anomaly detection β and can help your team derive very interesting insights."
},
{
"code": null,
"e": 565,
"s": 379,
"text": "Determining the right number of clusters for your project is a little more art than science. In this article, I will go over a few common ways to determine the right number of clusters."
},
{
"code": null,
"e": 631,
"s": 565,
"text": "All of the following examples will involve the following imports:"
},
{
"code": null,
"e": 734,
"s": 631,
"text": "import pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom sklearn.cluster import KMeans"
},
{
"code": null,
"e": 763,
"s": 734,
"text": "and the following variables:"
},
{
"code": null,
"e": 797,
"s": 763,
"text": "min_clusters = 2max_clusters = 15"
},
{
"code": null,
"e": 1112,
"s": 797,
"text": "The objective of this metric is to find the βElbowβ of the WSS curve in order to determine the smallest number of clusters that captures the most amount of signal in your data. If this definition sounds vague and subjective, itβs because it is β finding the βelbowβ of the chart is certainly a subjective decision."
},
{
"code": null,
"e": 1336,
"s": 1112,
"text": "Within-Cluster Sum of Squares (WSS) is a measure of how far away each centroid is from their respective class instances. The larger the WSS, the more dispersed the cluster values are from the centroid. We can define WSS as:"
},
{
"code": null,
"e": 1548,
"s": 1336,
"text": "def within_sum_of_squares(data, centroids, labels): SSW = 0 for l in np.unique(labels): data_l = data[labels == l] resid = data_l - centroids[l] SSW += (resid**2).sum() return SSW"
},
{
"code": null,
"e": 1641,
"s": 1548,
"text": "And by simply iterating through our data for every cluster, we can generate the elbow curve:"
},
{
"code": null,
"e": 1991,
"s": 1641,
"text": "wss_list = []for i in range(min_clusters, max_clusters+1): print('Training {} cluster algo...'.format(i)) km = KMeans(n_clusters=i) km.fit(data) wss = within_sum_of_squares(np.array(data),km.cluster_centers_, km.predict(data)) wss_list.append(wss)plt.plot(wss_list)plt.title('WSS Plot')plt.xlabel('# of Clusters')plt.ylabel('WSS')plt.show()"
},
{
"code": null,
"e": 2119,
"s": 1991,
"text": "From the above example, we may decide that 4β5 cluster is the appropriate number of clusters, since adding additional clusters."
},
{
"code": null,
"e": 2346,
"s": 2119,
"text": "Another way to cut up this data is by the relative improvement of each cluster. By setting a threshold, say 5%, we can see at what number of clusters would start to see diminished returns on additional clusters of less than 5%"
},
{
"code": null,
"e": 2866,
"s": 2346,
"text": "perc_improve_list = [0]rel_improvement = []base_wss = wss_list[0]for i in range(len(wss_list)): improvement = (wss_list[0] - wss_list[i])/wss_list[0] rel_improvement.append(improvement - perc_improve_list[-1]) perc_improve_list.append(improvement) threshold = 0.05plt.plot([i for i in range(min_clusters+1,max_clusters+1)], rel_improvement[1:])plt.axhline(threshold, linestyle='--', color='grey')plt.title('WSS Improvement Plot')plt.xlabel('# of Clusters')plt.ylabel('% improvement in WSS')plt.ylim([0,1])plt.show()"
},
{
"code": null,
"e": 3068,
"s": 2866,
"text": "This chart points to the same outcome as the first, 4β5 clusters, albeit a little clearer. I prefer this output since it provides an objective threshold to the chart that we can modify at a later date."
},
{
"code": null,
"e": 3220,
"s": 3068,
"text": "βThe optimal number of clusters k is the one that maximize the average silhouette over a range of possible values for kβ β (Kaufman and Rousseeuw 1990)"
},
{
"code": null,
"e": 3512,
"s": 3220,
"text": "A Silhouette Score is (other than being a word I can never spell correctly on first attempt) how close a specific example is to examples from other clusters. The larger the distance from other clustersβ examples, the cleaner the division between clusters and therefore the better clustering."
},
{
"code": null,
"e": 3642,
"s": 3512,
"text": "As the above quote states, by the number of clusters that maximizes the average silhouette score is preferred over other options."
},
{
"code": null,
"e": 3713,
"s": 3642,
"text": "To calculate silhouette scores, we can use SKLearns built in function:"
},
{
"code": null,
"e": 4146,
"s": 3713,
"text": "from sklearn.metrics import silhouette_scoresil_score_list = []for i in range(min_clusters, max_clusters+1): print('Training {} cluster algo...'.format(i)) km = KMeans(n_clusters=i) km.fit(data) sil = silhouette_score(np.array(data),km.predict(data)) sil_score_list.append(sil) plt.bar([i for i in range(2,len(sil_score_list)+2)],sil_score_list)plt.title('Sil Plot')plt.xlabel('# of Clusters')plt.ylabel('Sil Score')plt.show()"
},
{
"code": null,
"e": 4432,
"s": 4146,
"text": "For this metric, it seems to point to using 3 clusters to maximize the average Silhouette score. WSS and Sil scores wonβt always agree, as they are measuring different things. Using both in conjunction will help you make the most informed decision, along with method #3 outlined below."
},
{
"code": null,
"e": 4731,
"s": 4432,
"text": "Please Note: While I donβt know the Big O Notation for the SKLearn Silhouette algo (someone please comment if you know!) but this took significantly longer than the WSS search outlined above. Whereas the WSS code finish in about a half hour, the Silhouette code took well over 4 hours. Be prepared!"
},
{
"code": null,
"e": 4782,
"s": 4731,
"text": "The real answer to how many clusters are right is:"
},
{
"code": null,
"e": 4836,
"s": 4782,
"text": "Whatever makes the most sense for your team & project"
},
{
"code": null,
"e": 5044,
"s": 4836,
"text": "It may seem like a cop-out answer (and it certainly isnβt a data science answer) but what matters more than WSS or Silhouette scores is that the clustering you generate helps you accomplish the task at hand."
},
{
"code": null,
"e": 5449,
"s": 5044,
"text": "There are many more ways to validate clustering strength, from Dunn Statics to Gap Metrics, but the real way to validate your clustering approach is to ensure that it is able to answer the questions you are seeking. Oftentimes Data Scientists canβt see the forest for the trees, and stressing over multiple data-driven success criteria rather than on producing outcomes for your team is a common mistake."
},
{
"code": null,
"e": 5724,
"s": 5449,
"text": "If you are looking to these clusters to generate human-interpretable archetypes for your business, perhaps to inform marketing, then you donβt want to use more than 10 clusters; otherwise, your marketing team will get bogged down with too many personas to generate copy for."
},
{
"code": null,
"e": 6041,
"s": 5724,
"text": "On the other end of the spectrum, if you are using clustering for personalization, you want as many meaningful clusters as possible, since the more clusters you create the more unique experiences you can provide your customers. Micro-segmentation is excellent for recommendations but at the cost of interpretability."
},
{
"code": null,
"e": 6262,
"s": 6041,
"text": "So when determining clusters β ensure you are on the same page with the stakeholder on the project and feel confident that you can justify the number of clusters, whether it be 2 or 200, from a non-technical perspective."
}
] |
Array findIndex() function in JavaScript
|
The findIndex() function in JavaScript returns the index of the first element value that satisfy a given condition in an array.
Following is the code for the array find() function β
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;
}
.findIndex {
font-size: 20px;
font-weight: 500;
}
</style>
</head>
<body>
<h1>JavaScript Array FindIndex() example</h1>
<div class="findIndex"></div>
<button class="findArr">CLICK HERE</button>
<h3>Click on the above button to get the index of lion in the array</h3>
<script>
function findLion(animal) {
return animal === "lion";
}
let fillEle = document.querySelector(".findIndex");
let arr = ["cow", "lion", "bull", "tiger"];
fillEle.innerHTML = arr;
document.querySelector(".findArr").addEventListener("click", () => {
fillEle.innerHTML = arr.findIndex(findLion);
});
</script>
</body>
</html>
On clicking the βCLICK HEREβ button the index of lion will be returned as follows β
|
[
{
"code": null,
"e": 1190,
"s": 1062,
"text": "The findIndex() function in JavaScript returns the index of the first element value that satisfy a given condition in an array."
},
{
"code": null,
"e": 1244,
"s": 1190,
"text": "Following is the code for the array find() function β"
},
{
"code": null,
"e": 1255,
"s": 1244,
"text": " Live Demo"
},
{
"code": null,
"e": 2156,
"s": 1255,
"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 .findIndex {\n font-size: 20px;\n font-weight: 500;\n }\n</style>\n</head>\n<body>\n<h1>JavaScript Array FindIndex() example</h1>\n<div class=\"findIndex\"></div>\n<button class=\"findArr\">CLICK HERE</button>\n<h3>Click on the above button to get the index of lion in the array</h3>\n<script>\n function findLion(animal) {\n return animal === \"lion\";\n }\n let fillEle = document.querySelector(\".findIndex\");\n let arr = [\"cow\", \"lion\", \"bull\", \"tiger\"];\n fillEle.innerHTML = arr;\n document.querySelector(\".findArr\").addEventListener(\"click\", () => {\n fillEle.innerHTML = arr.findIndex(findLion);\n });\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2240,
"s": 2156,
"text": "On clicking the βCLICK HEREβ button the index of lion will be returned as follows β"
}
] |
Creating custom lists in Python. Exploring OOP basics to experiment with... | by Roman Penza | Towards Data Science
|
In this article, we will look at the basics of Object-Oriented Programming and how we can use Python classes to create our own custom lists. We will do so without using any packages (no import statements!).
Let's say we want to create a new data container type that would act as a list (i.e. we can index and slice it) but at the same time could contain data from multiple sources that we can extract just like in a dictionary.
So, say, we have a dictionary of lists:
d ={βkey1β : [βval11β, βval12β, βval13β], βkey2β : [βval21β, βval22β, βval23β], βkey3β : [βval31β, βval32β, βval33β]}
but we want to be able to easily work with all of the lists in d.values() as if it was one big list:
l = [βval11β, βval12β, βval13β, βval21β, βval22β, βval23β, βval31β, βval32β, βval33β]
but at the same time, we donβt want to lose the key-value binding of a dictionary. Imagine an object that has these characteristics:
So it is an object that acts as a list but keeps keys for each element in the background. Let's call it a dinx.
To start with, we know that to initiate this object we want a dictionary of lists. Letβs allow tuples as well and say that they will represent static elements that will not change if we mutate the dinx βlistβ. Therefore, we need to assert for input (letβs call it comp, short for components) to be a dictionary and to contain either lists or tuples. The latter can be achieved with either [list, tuple] or (list, tuple) in isinstance second argument. We should also allow only strings in dictionary keys, to avoid confusion when calling numeric indices.
We will assign comp to self and put an underscore prefix to indicate that it is for internal use within the class.
We also need to define a function to get a mapping variable that we can use to get the order of elements in the list representation of the dictionary that we will call _comp_map (will be useful later):
So, self._comp_map is going to look like this:
[(βkey1β, βval11β), (βkey1β, βval12β), (βkey1β, βval13β), (βkey2β, βval21β), (βkey2β, βval22β), (βkey2β, βval23β), (βkey3β, βval31β), (βkey3β, βval32β), (βkey3β, βval33β)]
which is already a list of key-value tuples, but we want to make it pretty-looking.
What we need to do now is to code a dunder method of dinx, called __repr__, that will show the representation of dinx every time we call it. Since we want our dinx to look like a list when we call it, we will start with _sum_lists and _getall methods that we can use to flatten the dictionary of lists we have in _comp.
We can then use _getall output in __repr__ to specify the way dinx is going to look like when we call it in the console:
So, now, we can initiate and call our dinx:
Great! Letβs implement the ability to call values by indices and slices. The idea is that we want to combine dictionary and list indices. So, say an item l[0] in the above example should be a dinx(1), i.e. have a value of 1 and a key βAβ. A slice l[:5] should be a dinx(1,2,3,0,1) with keys βAβ and βBβ respectively.
Since we are only allowing string dictionary keys in _comp, we can assume that if it sees string index input, it should return values of the underlying _comp key. Thus, we can combine list and dictionary type of indexing in dinx.
First of all, when we are getting the value of dinx by index we want a dinx to be returned. So, we need to define cls variable as type(self) that we can then use to initiate a new dinx in the return statement:
To generate dinx from int or slice types, we need to define a method that would convert our _comp_map list of tuples to a dictionary that we can use to initiate a new dinx in the return statement:
getting back to __getitem__:
So letβs run a few tests:
In Python, there two most commonly used dunder methods for implementing addition operation: __add__ (+) and __iadd__ (+=). We will start with the latter:
Here, we take two inputs, self and other, where other is another dinx, and we iterate through each element in other._comp and add it to self._comp if the key exists or create a new key in self._comp otherwise. We only do so for lists, thus keeping tuples untouched, which allows us to define elements in our dinx that we donβt want to mutate.
Having defined inplace addition method (x+=y), we can now use it to define x+y type of addition. The idea is pretty simple, we will use a temporary deepcopy of dinx, do an inplace addition of other on it and return the result:
So letβs test and see how it all works:
Another important feature of a list is the ability to sort it. We can also sort lists according to our own functions using key parameter in sort method. In this section, we will create sort method for dinx
The first thing to keep in mind is that we already have a list of key-value tuples that we use to get the order of dinx elements (self._comp_map). Therefore, any sorting function we apply on dinx we can simply pass to self._comp_map. The only problem is that we need to sort by the second element of the tuple. This can be done using lambda x: x[1] as the key. Then, if we want to apply key to the dinx we can apply it to x[1] internally through lambda x: key(x[1]). Lastly, we can apply sorting inplace or make it return a new dinx:
Letβs test our new sort method:
The aim of this article was to show that Python offers fairly simple-to-use tools that we can utilize to configure a project for our needs. An example of a custom data container above is not necessarily applicable in a real-world scenario but nevertheless demonstrates that we can build our own basic data structures to have better control and management over the data being processed.
I have also implemented some smaller things like __contains__ that returns a boolean to x in dinx, __len__ to get the length of dinx, count that returns the count of a variable passed to it, and update, values and keys dictionary methods. Here is the code in full:
|
[
{
"code": null,
"e": 379,
"s": 172,
"text": "In this article, we will look at the basics of Object-Oriented Programming and how we can use Python classes to create our own custom lists. We will do so without using any packages (no import statements!)."
},
{
"code": null,
"e": 600,
"s": 379,
"text": "Let's say we want to create a new data container type that would act as a list (i.e. we can index and slice it) but at the same time could contain data from multiple sources that we can extract just like in a dictionary."
},
{
"code": null,
"e": 640,
"s": 600,
"text": "So, say, we have a dictionary of lists:"
},
{
"code": null,
"e": 764,
"s": 640,
"text": "d ={βkey1β : [βval11β, βval12β, βval13β], βkey2β : [βval21β, βval22β, βval23β], βkey3β : [βval31β, βval32β, βval33β]}"
},
{
"code": null,
"e": 865,
"s": 764,
"text": "but we want to be able to easily work with all of the lists in d.values() as if it was one big list:"
},
{
"code": null,
"e": 959,
"s": 865,
"text": "l = [βval11β, βval12β, βval13β, βval21β, βval22β, βval23β, βval31β, βval32β, βval33β]"
},
{
"code": null,
"e": 1092,
"s": 959,
"text": "but at the same time, we donβt want to lose the key-value binding of a dictionary. Imagine an object that has these characteristics:"
},
{
"code": null,
"e": 1204,
"s": 1092,
"text": "So it is an object that acts as a list but keeps keys for each element in the background. Let's call it a dinx."
},
{
"code": null,
"e": 1758,
"s": 1204,
"text": "To start with, we know that to initiate this object we want a dictionary of lists. Letβs allow tuples as well and say that they will represent static elements that will not change if we mutate the dinx βlistβ. Therefore, we need to assert for input (letβs call it comp, short for components) to be a dictionary and to contain either lists or tuples. The latter can be achieved with either [list, tuple] or (list, tuple) in isinstance second argument. We should also allow only strings in dictionary keys, to avoid confusion when calling numeric indices."
},
{
"code": null,
"e": 1873,
"s": 1758,
"text": "We will assign comp to self and put an underscore prefix to indicate that it is for internal use within the class."
},
{
"code": null,
"e": 2075,
"s": 1873,
"text": "We also need to define a function to get a mapping variable that we can use to get the order of elements in the list representation of the dictionary that we will call _comp_map (will be useful later):"
},
{
"code": null,
"e": 2122,
"s": 2075,
"text": "So, self._comp_map is going to look like this:"
},
{
"code": null,
"e": 2294,
"s": 2122,
"text": "[(βkey1β, βval11β), (βkey1β, βval12β), (βkey1β, βval13β), (βkey2β, βval21β), (βkey2β, βval22β), (βkey2β, βval23β), (βkey3β, βval31β), (βkey3β, βval32β), (βkey3β, βval33β)]"
},
{
"code": null,
"e": 2378,
"s": 2294,
"text": "which is already a list of key-value tuples, but we want to make it pretty-looking."
},
{
"code": null,
"e": 2698,
"s": 2378,
"text": "What we need to do now is to code a dunder method of dinx, called __repr__, that will show the representation of dinx every time we call it. Since we want our dinx to look like a list when we call it, we will start with _sum_lists and _getall methods that we can use to flatten the dictionary of lists we have in _comp."
},
{
"code": null,
"e": 2819,
"s": 2698,
"text": "We can then use _getall output in __repr__ to specify the way dinx is going to look like when we call it in the console:"
},
{
"code": null,
"e": 2863,
"s": 2819,
"text": "So, now, we can initiate and call our dinx:"
},
{
"code": null,
"e": 3180,
"s": 2863,
"text": "Great! Letβs implement the ability to call values by indices and slices. The idea is that we want to combine dictionary and list indices. So, say an item l[0] in the above example should be a dinx(1), i.e. have a value of 1 and a key βAβ. A slice l[:5] should be a dinx(1,2,3,0,1) with keys βAβ and βBβ respectively."
},
{
"code": null,
"e": 3410,
"s": 3180,
"text": "Since we are only allowing string dictionary keys in _comp, we can assume that if it sees string index input, it should return values of the underlying _comp key. Thus, we can combine list and dictionary type of indexing in dinx."
},
{
"code": null,
"e": 3620,
"s": 3410,
"text": "First of all, when we are getting the value of dinx by index we want a dinx to be returned. So, we need to define cls variable as type(self) that we can then use to initiate a new dinx in the return statement:"
},
{
"code": null,
"e": 3817,
"s": 3620,
"text": "To generate dinx from int or slice types, we need to define a method that would convert our _comp_map list of tuples to a dictionary that we can use to initiate a new dinx in the return statement:"
},
{
"code": null,
"e": 3846,
"s": 3817,
"text": "getting back to __getitem__:"
},
{
"code": null,
"e": 3872,
"s": 3846,
"text": "So letβs run a few tests:"
},
{
"code": null,
"e": 4026,
"s": 3872,
"text": "In Python, there two most commonly used dunder methods for implementing addition operation: __add__ (+) and __iadd__ (+=). We will start with the latter:"
},
{
"code": null,
"e": 4369,
"s": 4026,
"text": "Here, we take two inputs, self and other, where other is another dinx, and we iterate through each element in other._comp and add it to self._comp if the key exists or create a new key in self._comp otherwise. We only do so for lists, thus keeping tuples untouched, which allows us to define elements in our dinx that we donβt want to mutate."
},
{
"code": null,
"e": 4596,
"s": 4369,
"text": "Having defined inplace addition method (x+=y), we can now use it to define x+y type of addition. The idea is pretty simple, we will use a temporary deepcopy of dinx, do an inplace addition of other on it and return the result:"
},
{
"code": null,
"e": 4636,
"s": 4596,
"text": "So letβs test and see how it all works:"
},
{
"code": null,
"e": 4842,
"s": 4636,
"text": "Another important feature of a list is the ability to sort it. We can also sort lists according to our own functions using key parameter in sort method. In this section, we will create sort method for dinx"
},
{
"code": null,
"e": 5376,
"s": 4842,
"text": "The first thing to keep in mind is that we already have a list of key-value tuples that we use to get the order of dinx elements (self._comp_map). Therefore, any sorting function we apply on dinx we can simply pass to self._comp_map. The only problem is that we need to sort by the second element of the tuple. This can be done using lambda x: x[1] as the key. Then, if we want to apply key to the dinx we can apply it to x[1] internally through lambda x: key(x[1]). Lastly, we can apply sorting inplace or make it return a new dinx:"
},
{
"code": null,
"e": 5408,
"s": 5376,
"text": "Letβs test our new sort method:"
},
{
"code": null,
"e": 5794,
"s": 5408,
"text": "The aim of this article was to show that Python offers fairly simple-to-use tools that we can utilize to configure a project for our needs. An example of a custom data container above is not necessarily applicable in a real-world scenario but nevertheless demonstrates that we can build our own basic data structures to have better control and management over the data being processed."
}
] |
Java program to calculate student grades
|
The following program accepts average from the user, calculates the grade and prints it.
public class CalculateStudentGrades {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter average of your marks (less than 100)::");
int average = sc.nextInt();
char grade;
if(average>=80){
grade = 'A';
}else if(average>=60 && average<80){
grade = 'B';
}
else if(average>=40 && average<60){
grade = 'C';
}
else {
grade = 'D';
}
switch(grade) {
case 'A' :
System.out.println("Excellent!");
break;
case 'B' :
case 'C' :
System.out.println("Well done");
break;
case 'D' :
System.out.println("You passed");
case 'F' :
System.out.println("Better try again");
break;
default :
System.out.println("Invalid grade");
}
System.out.println("Your grade is " + grade);
}
}
Enter average of your marks (less than 100)::
59
Well done
Your grade is C
|
[
{
"code": null,
"e": 1151,
"s": 1062,
"text": "The following program accepts average from the user, calculates the grade and prints it."
},
{
"code": null,
"e": 2138,
"s": 1151,
"text": "public class CalculateStudentGrades {\n public static void main(String args[]) {\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter average of your marks (less than 100)::\");\n int average = sc.nextInt();\n char grade;\n\n if(average>=80){\n grade = 'A';\n }else if(average>=60 && average<80){\n grade = 'B';\n }\n else if(average>=40 && average<60){\n grade = 'C';\n }\n else {\n grade = 'D';\n }\n\n switch(grade) {\n case 'A' :\n System.out.println(\"Excellent!\");\n break;\n case 'B' :\n case 'C' :\n System.out.println(\"Well done\");\n break;\n case 'D' :\n System.out.println(\"You passed\");\n case 'F' :\n System.out.println(\"Better try again\");\n break;\n default :\n System.out.println(\"Invalid grade\");\n }\n System.out.println(\"Your grade is \" + grade);\n }\n}"
},
{
"code": null,
"e": 2213,
"s": 2138,
"text": "Enter average of your marks (less than 100)::\n59\nWell done\nYour grade is C"
}
] |
C# | Check if two Tuple Objects are equal - GeeksforGeeks
|
10 May, 2019
A tuple is a data structure which gives you the easiest way to represent a data set. You can also check if the given tuple object is equal to the specified object or not using the Equals Method. This method will return true if the given tuple object is equal to the specified object, otherwise, return false.
Syntax:
public override bool Equals (object obj);
Here, obj is the object to compare with this instance.
Return Type: The return type of this method is Boolean. Means it will return true if the tuple object is equal to the given object. Otherwise, return false.
Importatnt Points: This obj parameter is considered to be equal when it meets the following conditions:
If it it is a Tuple<> object. Here Tuple<> is may be of 1-tuple, or 2-tuple, or 3-tuple, or 4-tuple, or 5-tuple, or 6-tuple, or 7-tuple, or 8-tuple.
It must contain the same number of elements that are of the same types as the current instance.
Its elements (including its nested components) are equal to those of the current instance. The equality is determined by the default equality comparer for each element.
Below programs illustrate the use of the above-discussed method:
Example 1:
// C# program to illustrate the // Equals methodusing System; class GFG { // Main Method static public void Main() { // Taking tuple variables var t1 = Tuple.Create(12, 34, 56, 78); var t2 = Tuple.Create(12, 34, 67, 89); var t3 = Tuple.Create(12, 34, 56, 78); var t4 = Tuple.Create(34, 56, 78); // Check whether the given // tuples are Equal or not // Using Equals() method Console.WriteLine(t1.Equals(t2)); Console.WriteLine(t1.Equals(t3)); Console.WriteLine(t1.Equals(t4)); }}
False
True
False
Example 2:
// C# program to illustrate Equals// method with nested tupleusing System; class GFG { // Main Method static public void Main() { // Taking Tuples var t1 = Tuple.Create(34, 56, 78, Tuple.Create(12, 34, 56, 78)); var t2 = Tuple.Create(12, 34, 67, 89); var t3 = Tuple.Create(12, 34, 56, Tuple.Create(23, 56)); var t4 = Tuple.Create(34, 56, 78, Tuple.Create(12, 34, 56, 78)); var t5 = Tuple.Create(12, 34, 56, Tuple.Create(24, 56)); // Check whether the given // tuples are Equal or not // Using Equals() method Console.WriteLine(t1.Equals(t2)); Console.WriteLine(t1.Equals(t3)); Console.WriteLine(t1.Equals(t4)); Console.WriteLine(t3.Equals(t5)); Console.WriteLine(t1.Equals(t5)); }}
False
False
True
False
False
Akanksha_Rai
CSharp-Tuple
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Destructors in C#
Extension Method in C#
HashSet in C# with Examples
Top 50 C# Interview Questions & Answers
C# | How to insert an element in an Array?
Partial Classes in C#
C# | Inheritance
C# | List Class
Difference between Hashtable and Dictionary in C#
Lambda Expressions in C#
|
[
{
"code": null,
"e": 24302,
"s": 24274,
"text": "\n10 May, 2019"
},
{
"code": null,
"e": 24611,
"s": 24302,
"text": "A tuple is a data structure which gives you the easiest way to represent a data set. You can also check if the given tuple object is equal to the specified object or not using the Equals Method. This method will return true if the given tuple object is equal to the specified object, otherwise, return false."
},
{
"code": null,
"e": 24619,
"s": 24611,
"text": "Syntax:"
},
{
"code": null,
"e": 24661,
"s": 24619,
"text": "public override bool Equals (object obj);"
},
{
"code": null,
"e": 24716,
"s": 24661,
"text": "Here, obj is the object to compare with this instance."
},
{
"code": null,
"e": 24873,
"s": 24716,
"text": "Return Type: The return type of this method is Boolean. Means it will return true if the tuple object is equal to the given object. Otherwise, return false."
},
{
"code": null,
"e": 24977,
"s": 24873,
"text": "Importatnt Points: This obj parameter is considered to be equal when it meets the following conditions:"
},
{
"code": null,
"e": 25126,
"s": 24977,
"text": "If it it is a Tuple<> object. Here Tuple<> is may be of 1-tuple, or 2-tuple, or 3-tuple, or 4-tuple, or 5-tuple, or 6-tuple, or 7-tuple, or 8-tuple."
},
{
"code": null,
"e": 25222,
"s": 25126,
"text": "It must contain the same number of elements that are of the same types as the current instance."
},
{
"code": null,
"e": 25391,
"s": 25222,
"text": "Its elements (including its nested components) are equal to those of the current instance. The equality is determined by the default equality comparer for each element."
},
{
"code": null,
"e": 25456,
"s": 25391,
"text": "Below programs illustrate the use of the above-discussed method:"
},
{
"code": null,
"e": 25467,
"s": 25456,
"text": "Example 1:"
},
{
"code": "// C# program to illustrate the // Equals methodusing System; class GFG { // Main Method static public void Main() { // Taking tuple variables var t1 = Tuple.Create(12, 34, 56, 78); var t2 = Tuple.Create(12, 34, 67, 89); var t3 = Tuple.Create(12, 34, 56, 78); var t4 = Tuple.Create(34, 56, 78); // Check whether the given // tuples are Equal or not // Using Equals() method Console.WriteLine(t1.Equals(t2)); Console.WriteLine(t1.Equals(t3)); Console.WriteLine(t1.Equals(t4)); }}",
"e": 26043,
"s": 25467,
"text": null
},
{
"code": null,
"e": 26061,
"s": 26043,
"text": "False\nTrue\nFalse\n"
},
{
"code": null,
"e": 26072,
"s": 26061,
"text": "Example 2:"
},
{
"code": "// C# program to illustrate Equals// method with nested tupleusing System; class GFG { // Main Method static public void Main() { // Taking Tuples var t1 = Tuple.Create(34, 56, 78, Tuple.Create(12, 34, 56, 78)); var t2 = Tuple.Create(12, 34, 67, 89); var t3 = Tuple.Create(12, 34, 56, Tuple.Create(23, 56)); var t4 = Tuple.Create(34, 56, 78, Tuple.Create(12, 34, 56, 78)); var t5 = Tuple.Create(12, 34, 56, Tuple.Create(24, 56)); // Check whether the given // tuples are Equal or not // Using Equals() method Console.WriteLine(t1.Equals(t2)); Console.WriteLine(t1.Equals(t3)); Console.WriteLine(t1.Equals(t4)); Console.WriteLine(t3.Equals(t5)); Console.WriteLine(t1.Equals(t5)); }}",
"e": 26872,
"s": 26072,
"text": null
},
{
"code": null,
"e": 26902,
"s": 26872,
"text": "False\nFalse\nTrue\nFalse\nFalse\n"
},
{
"code": null,
"e": 26915,
"s": 26902,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 26928,
"s": 26915,
"text": "CSharp-Tuple"
},
{
"code": null,
"e": 26931,
"s": 26928,
"text": "C#"
},
{
"code": null,
"e": 27029,
"s": 26931,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27047,
"s": 27029,
"text": "Destructors in C#"
},
{
"code": null,
"e": 27070,
"s": 27047,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 27098,
"s": 27070,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 27138,
"s": 27098,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 27181,
"s": 27138,
"text": "C# | How to insert an element in an Array?"
},
{
"code": null,
"e": 27203,
"s": 27181,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 27220,
"s": 27203,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 27236,
"s": 27220,
"text": "C# | List Class"
},
{
"code": null,
"e": 27286,
"s": 27236,
"text": "Difference between Hashtable and Dictionary in C#"
}
] |
Basics of Kernels and Convolutions with OpenCV | by Thiago Carvalho | Towards Data Science
|
Iβve been trying to learn computer vision with Python and OpenCV, and I always stumble upon the terms kernel and convolution.
At first, I tried to rely on those gifs and some brief explanations, but I often get confused with their use, so I decided to get a better look at it.
In this article, Iβll share some of what I learned about kernels and convolutions while exploring some of its primary applications, such as blurring, sharpening, distilling and eroding.
Like me, you may think this has something to do with corn, but it doesnβt.
Kernels in computer vision are matrices, used to perform some kind of convolution in our data. Letβs try to break this down.
Convolutions are mathematical operations between two functions that create a third function. In image processing, it happens by going through each pixel to perform a calculation with the pixel and its neighbours.
The kernels will define the size of the convolution, the weights applied to it, and an anchor point usually positioned at the center.
So in a 3x3 matrix, each pixel is affected only by the pixels around it, wherein a 7x7 farther pixels would change it.
Alright, so to apply it to an image, we would: Position it over a given pixel using its anchor point, perform some operation between the values in the kernels and the values of the pixels, define a new value for that pixel, and move to the next.
Summarizing:
We can filter and modify images by interacting with their pixels;
That interaction may occur with convolutions;
Those convolutions use kernels to describe how the pixels will be affected;
Kernels represent the area for each operation, the values/weights, and the anchor point;
Enough talk, letβs see how we can put those kernels to use.Weβll use OpenCV, Numpy, and Matplotlib.
import cv2import numpy as npimport matplotlib.pyplot as plt
After importing the libraries, we can plot the original image, so we know whatβs changing.
image = cv2.imread('Images/6.jpg')image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)fig, ax = plt.subplots(1, figsize=(12,8))plt.imshow(image)
Cool, now letβs make a kernel for blurring the image. Weβll use Numpy to build a 3x3 matrix of ones, and divide it by 9.
>>> kernel = np.ones((3, 3), np.float32) / 9>>> kernel...array([[0.11111111, 0.11111111, 0.11111111], [0.11111111, 0.11111111, 0.11111111], [0.11111111, 0.11111111, 0.11111111]], dtype=float32)
We can apply it to the image with .filter2D.
img = cv2.filter2D(image, -1, kernel)fig, ax = plt.subplots(1, figsize=(12,8))plt.imshow(img)
Letβs try this with a Sharpen kernel.
kernel = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]])
By using .filter2D, we can apply linear filters with any kernel we want. But there are also more comfortable ways of achieving those results.
OpenCV has some handy functions to filter images, and many times you wonβt even have to define the kernel.
We can use .blur to apply a box blur, and we just need to pass the image and the size of the kernel.
image = cv2.imread('Images/6.jpg')image = cv2.blur(img, (5,5))image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)fig, ax = plt.subplots(1, figsize=(12,8))plt.imshow(image)
Gaussian and Median blur:
image = cv2.imread('Images/6.jpg')image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)fig, ax = plt.subplots(1, figsize=(12,16))ax = plt.subplot(211)g = cv2.GaussianBlur(image, (3,3), 0)plt.imshow(g)ax = plt.subplot(212)m = cv2.medianBlur(image, 3)plt.imshow(m)
Kernels can also help dilate and erode images β That seems to be useful when working pictures with text.
image = cv2.imread('Images/9.png')# convert to black and whiteimage = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) r ,image = cv2.threshold(image, 150, 255, cv2.THRESH_BINARY)# create kernelkernel = np.ones((5,5), np.uint8)fig, ax = plt.subplots(1, figsize=(16,12))# originalax = plt.subplot(232)plt.imshow(image, cmap='Greys')plt.title('original')# erosione = cv2.erode(image, kernel)ax = plt.subplot(234)plt.imshow(e, cmap='Greys')plt.title('erosion')# dilationd = cv2.dilate(image, kernel)ax = plt.subplot(235)plt.imshow(d, cmap='Greys')plt.title('dilation')# morphological gradient (dilation - erosion)m = cv2.morphologyEx(image, cv2.MORPH_GRADIENT, kernel)ax = plt.subplot(236)plt.imshow(m, cmap='Greys')plt.title('dilation - erosion')
In that application, the kernels are a structuring element that defines the shape and extension of the applied effect. Even though you do have to create a matrix, OpenCV has some functions to facilitate this process.
Kernels and convolutions are way more straightforward than I expected, and itβs easier to understand why theyβre so widely used in image processing and how they can increase in complexity to support tasks such as image classification, object detection, and much more.
Thanks for reading my article. I hope you could get a clearer understanding of how convolutions use kernels to perform operations.
Resources:OpenCV 2D filter;OpenCV Smoothing;OpenCV filtering;OpenCV Morphological Transformations;
Going Further:OpenCV denoising;OpenCV Edge Detection;
|
[
{
"code": null,
"e": 298,
"s": 172,
"text": "Iβve been trying to learn computer vision with Python and OpenCV, and I always stumble upon the terms kernel and convolution."
},
{
"code": null,
"e": 449,
"s": 298,
"text": "At first, I tried to rely on those gifs and some brief explanations, but I often get confused with their use, so I decided to get a better look at it."
},
{
"code": null,
"e": 635,
"s": 449,
"text": "In this article, Iβll share some of what I learned about kernels and convolutions while exploring some of its primary applications, such as blurring, sharpening, distilling and eroding."
},
{
"code": null,
"e": 710,
"s": 635,
"text": "Like me, you may think this has something to do with corn, but it doesnβt."
},
{
"code": null,
"e": 835,
"s": 710,
"text": "Kernels in computer vision are matrices, used to perform some kind of convolution in our data. Letβs try to break this down."
},
{
"code": null,
"e": 1048,
"s": 835,
"text": "Convolutions are mathematical operations between two functions that create a third function. In image processing, it happens by going through each pixel to perform a calculation with the pixel and its neighbours."
},
{
"code": null,
"e": 1182,
"s": 1048,
"text": "The kernels will define the size of the convolution, the weights applied to it, and an anchor point usually positioned at the center."
},
{
"code": null,
"e": 1301,
"s": 1182,
"text": "So in a 3x3 matrix, each pixel is affected only by the pixels around it, wherein a 7x7 farther pixels would change it."
},
{
"code": null,
"e": 1547,
"s": 1301,
"text": "Alright, so to apply it to an image, we would: Position it over a given pixel using its anchor point, perform some operation between the values in the kernels and the values of the pixels, define a new value for that pixel, and move to the next."
},
{
"code": null,
"e": 1560,
"s": 1547,
"text": "Summarizing:"
},
{
"code": null,
"e": 1626,
"s": 1560,
"text": "We can filter and modify images by interacting with their pixels;"
},
{
"code": null,
"e": 1672,
"s": 1626,
"text": "That interaction may occur with convolutions;"
},
{
"code": null,
"e": 1748,
"s": 1672,
"text": "Those convolutions use kernels to describe how the pixels will be affected;"
},
{
"code": null,
"e": 1837,
"s": 1748,
"text": "Kernels represent the area for each operation, the values/weights, and the anchor point;"
},
{
"code": null,
"e": 1937,
"s": 1837,
"text": "Enough talk, letβs see how we can put those kernels to use.Weβll use OpenCV, Numpy, and Matplotlib."
},
{
"code": null,
"e": 1997,
"s": 1937,
"text": "import cv2import numpy as npimport matplotlib.pyplot as plt"
},
{
"code": null,
"e": 2088,
"s": 1997,
"text": "After importing the libraries, we can plot the original image, so we know whatβs changing."
},
{
"code": null,
"e": 2227,
"s": 2088,
"text": "image = cv2.imread('Images/6.jpg')image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)fig, ax = plt.subplots(1, figsize=(12,8))plt.imshow(image)"
},
{
"code": null,
"e": 2348,
"s": 2227,
"text": "Cool, now letβs make a kernel for blurring the image. Weβll use Numpy to build a 3x3 matrix of ones, and divide it by 9."
},
{
"code": null,
"e": 2554,
"s": 2348,
"text": ">>> kernel = np.ones((3, 3), np.float32) / 9>>> kernel...array([[0.11111111, 0.11111111, 0.11111111], [0.11111111, 0.11111111, 0.11111111], [0.11111111, 0.11111111, 0.11111111]], dtype=float32)"
},
{
"code": null,
"e": 2599,
"s": 2554,
"text": "We can apply it to the image with .filter2D."
},
{
"code": null,
"e": 2693,
"s": 2599,
"text": "img = cv2.filter2D(image, -1, kernel)fig, ax = plt.subplots(1, figsize=(12,8))plt.imshow(img)"
},
{
"code": null,
"e": 2731,
"s": 2693,
"text": "Letβs try this with a Sharpen kernel."
},
{
"code": null,
"e": 2824,
"s": 2731,
"text": "kernel = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]])"
},
{
"code": null,
"e": 2966,
"s": 2824,
"text": "By using .filter2D, we can apply linear filters with any kernel we want. But there are also more comfortable ways of achieving those results."
},
{
"code": null,
"e": 3073,
"s": 2966,
"text": "OpenCV has some handy functions to filter images, and many times you wonβt even have to define the kernel."
},
{
"code": null,
"e": 3174,
"s": 3073,
"text": "We can use .blur to apply a box blur, and we just need to pass the image and the size of the kernel."
},
{
"code": null,
"e": 3341,
"s": 3174,
"text": "image = cv2.imread('Images/6.jpg')image = cv2.blur(img, (5,5))image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)fig, ax = plt.subplots(1, figsize=(12,8))plt.imshow(image)"
},
{
"code": null,
"e": 3367,
"s": 3341,
"text": "Gaussian and Median blur:"
},
{
"code": null,
"e": 3623,
"s": 3367,
"text": "image = cv2.imread('Images/6.jpg')image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)fig, ax = plt.subplots(1, figsize=(12,16))ax = plt.subplot(211)g = cv2.GaussianBlur(image, (3,3), 0)plt.imshow(g)ax = plt.subplot(212)m = cv2.medianBlur(image, 3)plt.imshow(m)"
},
{
"code": null,
"e": 3728,
"s": 3623,
"text": "Kernels can also help dilate and erode images β That seems to be useful when working pictures with text."
},
{
"code": null,
"e": 4464,
"s": 3728,
"text": "image = cv2.imread('Images/9.png')# convert to black and whiteimage = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) r ,image = cv2.threshold(image, 150, 255, cv2.THRESH_BINARY)# create kernelkernel = np.ones((5,5), np.uint8)fig, ax = plt.subplots(1, figsize=(16,12))# originalax = plt.subplot(232)plt.imshow(image, cmap='Greys')plt.title('original')# erosione = cv2.erode(image, kernel)ax = plt.subplot(234)plt.imshow(e, cmap='Greys')plt.title('erosion')# dilationd = cv2.dilate(image, kernel)ax = plt.subplot(235)plt.imshow(d, cmap='Greys')plt.title('dilation')# morphological gradient (dilation - erosion)m = cv2.morphologyEx(image, cv2.MORPH_GRADIENT, kernel)ax = plt.subplot(236)plt.imshow(m, cmap='Greys')plt.title('dilation - erosion')"
},
{
"code": null,
"e": 4681,
"s": 4464,
"text": "In that application, the kernels are a structuring element that defines the shape and extension of the applied effect. Even though you do have to create a matrix, OpenCV has some functions to facilitate this process."
},
{
"code": null,
"e": 4949,
"s": 4681,
"text": "Kernels and convolutions are way more straightforward than I expected, and itβs easier to understand why theyβre so widely used in image processing and how they can increase in complexity to support tasks such as image classification, object detection, and much more."
},
{
"code": null,
"e": 5080,
"s": 4949,
"text": "Thanks for reading my article. I hope you could get a clearer understanding of how convolutions use kernels to perform operations."
},
{
"code": null,
"e": 5179,
"s": 5080,
"text": "Resources:OpenCV 2D filter;OpenCV Smoothing;OpenCV filtering;OpenCV Morphological Transformations;"
}
] |
Generating Indonesian Lyric using Deep Learning - First part | by Haryo Akbarianto Wibowo | Towards Data Science
|
Hello everyone, Iβm really interested in Artificial Intelligence (AI) which is really hype now. Iβm also really interested on making something by using it. Currently, itβs one of my hobby creating several AI applications. In my free time, sometimes, I make an AI apps to release my boredom.
I want to get used to writing. To practice, I need to start writing . As I have a hobby about making AI, I want to share my knowledge and experience on making AI to practice my writing skill. βIndonesian Lyric Generator β is one of my AI apps that I made on my free time.
I will make this article newbie-friendly. I hope this article is useful for you :D.
This article is targeted for one who has interest in Artificial Intelligence, especially in Machine Learning and Deep Learning. I will also make this article math-free. If you want to know how it works, I will attach some articles in sources section.
Hereβs our intro lyric.
saat senyum manismu kalbuku
yang mungkin menjadi milikmu
terakhir kali ku hilang dariku
yang kau ajak kau disana
If you want to see the implementation and code of this article, you can see the notebook in this GitHub link
New music always pop up to replace old music. People should be creative on making a new song. They need time to create a new song. a component that they should think on making song is lyric . For people who is hard to find a right word on creating lyric (like me), this will be a problem. They will spend a lot of time to make the lyric. Have you ever thought to help them solve the problem?
In this article, I want to create an apps that can ease them on creating a lyric. I will make an apps based on AI. AI knowledge is one of my interest that I hope will help them.
Currently, AI is one of the hottest trendy buzz word, that people talk in every nook and corner. It can solve some problems easily that that are pretty hard for humans. One of the branch of AI is Machine Learning ( ML ). Machine Learning is a branch of field Artificial Intelligence which will predict an output based on given data. It will learn from the data. When we want to make a lyric, I think we should take a peek on some old song to learn how they write the lyric. We need to search the βpatternβ on how they connect each words. This is similar to Machine Learning which learn from the given data.
In this article, we will generate a new lyric based on lyric dataset that Iβve scrapped. we will use Deep Learning, one of a machine learning technique. we will use Recurrent Neural Network (RNN) to make the generatorβs model.
Even I choose the lyric to be Indonesian language, Donβt worry. I will write this article in English. If you want to see the meaning of the lyric, Translate it using Google Translate or any other familiar tools.
Donβt worry if you are still unfamiliar with terms on Deep Learning. I will tell you a brief description each of them. I will tell you the pipeline on how to make from start (scraping). As I state in the start, I will make it newbie-friendly as possible.
I will write the article in this order:
ToolsStepGather dataPreprocessing dataBuild ModelGenerate LyricConclusionAfterwordsSources
Tools
Step
Gather data
Preprocessing data
Build Model
Generate Lyric
Conclusion
Afterwords
Sources
The library, tools, and language programming that will be used are :
Python 3.6Python library βnumpy, math tools in pythonPython library β pandas, data tabular tools in pythonPython library β Keras, deep learning framework. Must have Tensorflow , CNTK, or Theano libraryPython library β Scrapy, popular scrapper tools in PythonJupyter Notebook, (optional) Awesome Python IDE that can also be used to make a presentation or educational code.
Python 3.6
Python library βnumpy, math tools in python
Python library β pandas, data tabular tools in python
Python library β Keras, deep learning framework. Must have Tensorflow , CNTK, or Theano library
Python library β Scrapy, popular scrapper tools in Python
Jupyter Notebook, (optional) Awesome Python IDE that can also be used to make a presentation or educational code.
I use GPU NVIDIA GTX 1050 to train my model.
Hereβs the step how we make the generator.
First, gather the data by scraping some website that contains Indonesian lyric by using scrapy. Then clean the text lyric that still contains HTML tag by using regex. After that, process the text in the lyric so that it can be used for modelβs input. we will need to construct the deep learning architecture. Finally train the model to generate the lyric. I will tell you how I did this in every step.
I gathered all the lyrics from scraping an Indonesia lyric collection website (lirik.kapanlagi.com). web scraping is a extraction of data from websites. All the job is carried out by an app which we will create. We will use scrapy library to scrape a website. The information that we should extract is songβs lyric and title.
In this article we will use lirik.kapanlagi.com as our target.
First, Create the scrapy project by using this command in your terminal or command prompt:
scrapy startproject lyric_scrapper
It will create a new directory directory. Change to the new directory and do this command
scrapy genspider lyric_scrapper lirik.kapanlagi.com
It will create a lyricscrapper.py inside the tutorial/spiders folder. We will call it web-crawler because it scrape by βcrawlingβ into the targeted website. Hereβs our code:
# -*- coding: utf-8 -*-import scrapyfrom scrapy.spiders import CrawlSpider, Rulefrom scrapy.linkextractors import LinkExtractorclass LyricScrapperSpider(CrawlSpider): name = 'lyric_scrapper' allowed_domains = ['lirik.kapanlagi.com'] start_urls = ['https://lirik.kapanlagi.com/lagu/a_id'] rules = (Rule(LinkExtractor(allow=(), restrict_css=(".pagination2 ul li a",".col-lirik .div-horizontal2-list a", "div .letterLinksAnchor")), callback="parse_page", follow=True),) def parse_page(self, response): song = response.css('.col-lirik').extract_first() title= response.css('.head-lirik h5::text').extract_first() if len(title) > 0 and len(song) > 0:scraped_info = { 'song' : song, 'title' : title, }yield scraped_info
Letβs see this part:
start_urls = ['https://lirik.kapanlagi.com/lagu/a_id'] rules = (Rule(LinkExtractor(allow=(), restrict_css=(".pagination2 ul li a",".col-lirik .div-horizontal2-list a", "div .letterLinksAnchor")), callback="parse_page", follow=True),)
We will start from URL in start_urls. To determine the start URL, we should find the page which contains the index list of the lyric. I found that https://lirik.kapanlagi.com/lagu/a_id is the index list.
The crawler will find its next target to scrape by finding URLs inside the current web page . To make the crawler follow our desired page, we must specify what part or section of web page our crawler have to see. In this case, we need to target this part shown on Image 2:
We will need the part or section that we want by inspecting its HTML code. For me, I used Inspect Element to do it (Firefox). For this website, we will restrict the crawler will target (β.pagination2 ul li aβ,β.col-lirik .div-horizontal2-list aβ, βdiv .letterLinksAnchorβ) . It will crawl the website until there are no more URLs to crawl (it also check if the url has been visited).
Next, we want to extract the lyric and titleβs song from the web page. To do that, we need to find the HTML tag which contains them ( the red and blue one in the Image 3).
song = response.css('.col-lirik').extract_first() title = response.css('.head-lirik h5::text').extract_first()
For the lyric (i named it βsongβ variable), we need the HTML code because this siteβs HTML composition is a bit messy. We need to clean it later.
Save your lyricscrapper.py . Then, open the settings.py inside the folder.
Add or uncomment these lines:
FEED_FORMAT = "csv"FEED_URI = "scrape.csv"DOWNLOAD_DELAY = 1 # important, sometimes you will get banned if you set it to 0.
Save it and then do the following command on the console:
scrapy crawl lyric_scrapper
Voila, our crawler will crawl our targeted site. Just wait till it end or force it to end if you are bored. After it ends, it will generate scrape.csv inside the folder. You can open it with spreadsheet tools to see it. Itβs a bit messy, isnβt it?. As I state above, we will need to clean the lyricβs text. So letβs move into the next step.
Now is the time to clean our dirty data. As we only want to generate lyric, we only need the song column from the scrape.csv. Before we start, I suggest that we use Python IDE such as Jupyter Notebook or Spyder to see our data better. In this part, we will use pandas library too see our data in tabular.
Open your code, then lets import our csv data and make it into a dataframe type (pd.DataFrame) . To check a lyricβs song, we will sample 5 instances. Be sure to put the scrape.csv file into our pythonβs code folder.
import pandas as pdscrape_lyric = pd.read_csv('scrape.csv')scrape_lyric.sample(5)
First, we need to ensure that our data donβt have missing data. Then we remove unwanted data if there are some wrong page that is extracted. In our case, we will find that our lyric web page should contains span tag. So remove instance that donβt have span tag.We will remove instance that have βBelum ada Lirikβ text (translate : Donβt have any lyric).
Before we clean it, we should check the size of our data. use scrape_lyric.shape to check it. I had 20259 rows.
scrape_lyric = scrape_lyric.dropna()scrape_lyric = scrape_lyric[scrape_lyric.song.str.contains('span')]scrape_lyric = scrape_lyric[~(scrape_lyric.song.str.contains('Belum Ada Lirik'))]
Check the size of your dataframe scrape_lyric.shape, I had 13791 rows. It had omitted 6468 rows!
We will only see βsongβ column. By looking at the song column, we will see that the text still has HTML tag. We need to clean it. We will use regex to do it.
This cleaning regex is special only to our targeted website. If we target other website, we need to see how the HTML pattern is and use appropriate regex to clean it (or maybe no need to clean the data if the website is good to parse).
Here are the regex to clean our scraped web page:
def clean_text_lyric(lyric, max_length): lyric_sample = lyric.split('</span>') lyric_sample = lyric_sample[:-1] clean_song_lyric = "" for sentence in lyric_sample: if 'http' not in sentence: sentence = re.sub(r'<div .*>','',sentence) sentence = re.sub(r'<span .*>','',sentence) sentence = sentence.strip() if len(sentence) > 0: sentence = re.sub(r'[^a-zA-Z0-9<\/>\s]',' ', sentence) sentence = " <div> " + sentence + " </div> " sentence = re.sub(r'<div>\s+<br>','<br> <div> ', sentence) sentence = re.sub(r'(\d|\r|\t|\n)','',sentence) clean_song_lyric += sentence clean_song_lyric = ' <start> ' * (max_length-1) + clean_song_lyric return clean_song_lyric
We will see one by one:
lyric_sample = lyric.split('</span>')lyric_sample = lyric_sample[:-1]
If we look at our extracted lyric, they separate their verse by HTML tag β<br>β. 1 verse contains several rows. Every rows is separated by HTML tag β</span>β. We need to split the row by splitting with β</span>β .
Now we remove the HTML tag (div, span)
sentence = re.sub(r'<div .*>','',sentence)sentence = re.sub(r'<span .*>','',sentence)
Then we will remove all character except [^a-zA-Z0β9<\/>\s] . We remove the escape character and excess white space. If you are not familiar with regex, i suggest that you try this site to play regex.
sentence = re.sub(r'[^a-zA-Z0-9<\/>\s]',' ', sentence)sentence = " <div> " + sentence + " </div> "sentence = re.sub(r'<div>\s+<br>','<br> <div> ', sentence)sentence = re.sub(r'(\d|\r|\t|\n)','',sentence)
I hate this websiteβs HTML code . The extracted lyric sometimes has an URL inside the lyric. Thatβs why I put the loop guard to ensure there are no URL inside it.
After we clean the text, we want to mark where our start and end lyricβs row.
For me, i used <div> and </div> tag to mark the start and end of our lyric.
We wonβt remove <br> tag. It is a tag to separate each verses.
Finally, we will append β<start>β tag at the start of the lyric by the desired max_length-1. Why do we do it? I will tell you later.
Apply it into the dataframe:
scrape_lyric['song'] = scrape_lyric['song'].apply(lambda x: clean_text_lyric(x))
This is the desired lyricβs format text that we want to use.
After weβre done cleaning the data, letβs move into preprocessing the data. Why do we need to do this? Our Deep Learning modelβs input is a sequence of text. It canβt read the text in string mode. We need to encode all of the word in our dataset into index number which map an index number into a word in one hot encoding. As we use embedding, in keras, we donβt have to encode the text into one hot encoding. We can use key index map to map a word with an index number in the model.
Before we do that, letβs change our lyric which contains several rows into a collection of sequence text arrays with desired length.
def generate_train_dataset(song_series, window): train_data = [] train_label = [] for song_string in song_series: song_arr = song_string.split() len_song_arr = len(song_arr) for i in range(0,len_song_arr-window+1): train_data.append(' '.join(song_arr[i:i+window-1])) train_label.append(song_arr[i+window-1]) return np.array(train_data), np.array(train_label)
Look at Image 6 to visualize how the generate_train_dataset function will work. It will slice from the start till window-1 and add it into the train_data list. Then add the last index into the train_label list. This is called sliding window with window length equal to our window parameter. In this article, we will set the window equal to 10.
The function that we create need a pandas.Series type as input.
max_length = 10 #windowX, y = generate_train_dataset(scrape_lyric.song, sent_len=max_length)
Did it work? Great, next we will use keras.preprocessing.text.Tokenizer library to make a input map which will map a word into an index number that the function choose. Make sure to change the parameter filter not to include β<β and β>β .
pre = keras.preprocessing.text.Tokenizer(filters='!"#$%&()*+,-.:;=?@[\\]^_`{|}~\t\n')pre.fit_on_texts(X.flatten()) # need to flatten the array
We will get the vocabulary size which contains how many unique word are in our data.
vocab_size = len(pre.word_index)
We transform our data into sequence of word index:
X = pre.texts_to_sequences(X)y = pre.texts_to_sequences(y)
Weβre done on preprocessing our input data. I had around 2 million instances.
Letβs move on into creating model.
Before we dive into the code and implementation, letβs recall what is Deep Learning, Dense Layer, RNN, LSTM layer, and activation function. We will recall them.
Deep Learning is a subset of Machine Learning technique. According to Yoshua Bengio, he said βDeep learning algorithms seek to exploit the unknown structure in the input distribution in order to discover good representations, often at multiple levels, with higher-level learned features defined in terms of lower-level featuresβ .
Deep Learning will learn about the features representation from the data. We donβt have to extract feature from data. Itβs different from the others Machine Learning algorithm which need to extract features. It consists of several layers and network which mimics humanβs brain. It has many alias such as Deep Neural Network. The main part of the Deep Neural Network is backpropagation algorithm, which will update our modelβs weight to make the error become minimum with optimizer algorithm . If you want to learn more, visit this site.
Embedding is a technique which will make our instance in the dataset into a learned representation. In this tutorial we will use Word Embedding. Word embedding will represent our word into a learned representation as real-valued vector. It often consists of ten or hundreds dimensional vector. The vector usually will capture the meaning of the words.
There are several algorithms that can make Word Embedding. There are:
Embedding LayerWord2vecGloVeFastexteLMo (NEW)
Embedding Layer
Word2vec
GloVe
Fastext
eLMo (NEW)
In our model, we will use Embedding Layer. It will update the vector according to our model.
Itβs an alias of Fully Connected Layer. Itβs a linear layer which propagate a linear function and backpropagate from neuron to neuron using the derivative of the function (gradient). To make it simpler, itβs a network which only take the input and multiply it with weight that is learned from backprogation. I found a medium article which can help you better on understanding Fully Connected Layer.
Recurrent Neural Network (RNN) is a layer which has a internal memory so it can remember the sequence information of inputs. The connection between neuron is a sequence of directed graph. It will remember previous neuronβs information (weight) and pass it into the present neuron.
There is several weakness in using RNN. It canβt learn βlong-term dependenciesβ. It will suffer a problem called βvanishing gradientβ . It wonβt update the neuronβs weight anymore. To solve this problem, Long Short Term Memory (LSTM) is used.
LSTM is a remedy on RNNβs problem. itβs capable to solve βlong-term dependenciesβ problem. LSTM has the ability to remove or add information to the new neuron with a structures called gates. There are 3 gates in the LSTM : forget gate, input gate, and output gate. They will control the neuron state. For further information, you can visit this site .
Normalize the output values of the targeted layer. They will have a mean output activation of zero and standard deviation of one. It has several benefits such as speeding up our training speed. See this article if you want to know more detail about BatchNormalization.
It is used to determine the output of a layer is activated or not. It maps the output to the range of the activation function. To know more detail, visit this article.
Done recalling? letβs move into the code
What we will build is a simple architecture Deep Network. It consists of Embedding Layer, LSTM Layer, and Dense Layer with categorical cross entropy and softmax activation as the output. Image 7 is the visualization of our architecture that we want to create.
model = Sequential()e = Embedding(vocab_size,100 ,input_length=max_length-1, trainable=True)model.add(e)model.add(keras.layers.BatchNormalization())model.add(keras.layers.Bidirectional(keras.layers.CuDNNLSTM(100)))model.add(keras.layers.BatchNormalization())model.add(Dense(100, activation='relu'))model.add(keras.layers.BatchNormalization())model.add(Dense(vocab_size+1, activation='softmax')) # vocab_size +1 to avoid out of bound# compile the modelmodel.compile(optimizer='adam', loss='categorical_crossentropy')
In this article we will use the model with the stated hyperparameter. Of course, you can tweak the hyperparameter of our model. For simplicity, we will use only 1 bi-LSTM and 1 Dense Layer. We use BatchNormalization to speed up our learner. If we use GPU, we should use CuDNNLSTM to speed up our training speed.
I use adam optimizer because itβs a populer optimizer right now. Itβs fast and can adapt our modelβs learning rate on backpropagation nicely.
Before we fit or train our model. We have a problem to tackle. If we see our vocab_size, it has around 45.000 unique words. In keras, we should encode the train label into one hot encoding [0 0 0 ... 1 ... 0]. If we change all of our train label into one hot encoding, it will cause MemoryError (It need 45.000 * 2 milion * 4 byte memory. It is impossible to save it into the memory). So we need to change our train label to one hot encoding in a batch.
def batch_data(start,end): global X,y,y_input, X_input X_input = np.array(X)[start:end] y_input = np.array(y)[start:end] y_input = keras.utils.to_categorical(y_input,vocab_size+1)max_epoch = 40instance_max = len(X)batch_size = 10000for i in range(max_epoch): start_idx_counter = 0 while start_idx_counter < instance_max: batch_data(start_idx_counter, min(start_idx_counter+batch_size,instance_max)) model.fit(X_input, y_input, epochs=1, batch_size=64) start_idx_counter += batch_size
We will define 10000 as our batch size. Feel free to decrease or increase the size as you wish. We fit our model with 40 epochs (iteration). Execute the code! The batch_size in the fit method can also be tweaked.
Wait for it!!
It took 1 day to train my model with GPU. If you donβt want to wait that long, decrease the max_epoch.
Done? Donβt forget to save the model and the tokenizer. Do you want to wait another day to train our model? No? Donβt forget to save the model!
model.save('lyric_gen_model.h5')
We will use pickle library to save our tokenizer
import picklepickle.dump( pre, open( "tokenizer_pre_lyric.p", "wb" ) )
Weβre done. Letβs generate our lyric!!!
Letβs use our model to generate lyric. Weβve trained our model and we will use it. Now to do that, we need to load our model and tokenizer.
model = keras.models.load_model('lyric_gen_model.h5')pre = pickle.load( open( "tokenizer_pre_lyric.p", "rb" ) )
Then we need to preprocess our input first.
def preprocess_predict(X): X = pre.texts_to_sequences(X) return X
In our article we have inserted β<start>β token into the start of the lyric. We do this to mark the start of the songβs lyric. If we want to generate without any start words. We can do this:
seed = "<start> " * (max_length-1)
Alternatively, you can also include some start words.
seed = "<start> " * (max_length-3)seed = "<div> love"
We should define the function to help us generating lyric
def is_word_in_dict(words, word_idx): for word in words.split(): if word not in word_idx: return False return Truedef generate_song_by_model(model, idx_word, X_sent, word_idx, total_classes, word_generated=80): string_returned = X_sent if is_word_in_dict(X_sent, word_idx): X = np.array(preprocess_predict([X_sent])) counter = 1 for i in range(word_generated): y_pred = model.predict(X) rnd_choice = np.random.choice(range(0,total_classes),size=1,replace=False, p=y_pred[0]) word_predict = idx_word[rnd_choice[0]] string_returned += " " + word_predict X = ' '.join(string_returned.split()[counter:]) X = np.array(preprocess_predict([X])) counter += 1 return string_returned
In this function, we will predict word based on our seed (X_sent variable in our generate function). We take window size length-1 tokens as a input of our model and the model will predict the next token. In the next loop, it will take the predicted output and size-length-2 tokens into the model. It will loop until the end that we set. We will get a random word based on the probability distribution produced by the output of softmax. If you are using Jupyter Notebook, use this command to display the generated lyric
from IPython.display import HTMLgenerated_lyric = generate_song_by_model(model, pre.index_word, seed, max_length, pre.word_index, vocab_size+1,loop_count=50)HTML(generated_lyric)
It will generate 50 new tokens/words (including tags). The generated lyric should have HTML tag <div> and <br> that serve as separator of rows and verses. We use HTML function in IPython.display to clean the tag in the display. Hereβs some example of our generated lyric.
i try to take you home
i m a light of the one
one day s erat a can fly away
who have lookin my hands down
and one if i didn t fine
you start a way to
In this generated lyric. Itβs very consistent to use english word. Itβs not bad although there are some confusing meaning. Our result is based on randomness. If your model has learnt less, it can generate bad lyrics!
If you are wondering why it generate english word, sometimes Indonesian song contains mixed language. Some songs contain full english word.
Here is another generated lyric.
dara kau bertanya siapa namamu
yang senyum tangismu
pasti pahit di ayahku
pada bermula dekat di pandang luka
dan semua karena cintamu
tersimpan nama jiwa ku masih ada di jendela hatimu
ku tak ingin sendiri
Translate it if you want to know the meaning of the lyric. Itβs also very consistent about using Indonesian language and talk about love. And again, its randomness will decide whether the generated lyric is good or not.
If you follow this article, weβve built a tool to generate Indonesian Lyric. Weβve utilized web crawler and deep learning library to build the generator. It can generate some good lyrics although it depend on our luck (randomness on probability).
In this article, we skip some steps such as Exploratory Analysis. We should have tried another architecture or hyperparameter. We also need to evaluate the generated lyric.
Thank you for reading my first article about Artificial Intelligence. Since itβs my first and Iβm still not too expert in this area, I need some constructive feedback to make me better on writing and deep learning. Go easy on me please >_<!
Sorry for any spelling mistake,grammar, and inefficient code.
Oh did I mention part 1? Yeah , I plan to make improvement on this lyric generator by making the architecture more complex (maybe using GAN), using another embedding, and hyperparameter.
For the next article, Iβm going to do some reinforcement learning from a game that will be developed from scratch.
See you on the next article!
|
[
{
"code": null,
"e": 462,
"s": 171,
"text": "Hello everyone, Iβm really interested in Artificial Intelligence (AI) which is really hype now. Iβm also really interested on making something by using it. Currently, itβs one of my hobby creating several AI applications. In my free time, sometimes, I make an AI apps to release my boredom."
},
{
"code": null,
"e": 734,
"s": 462,
"text": "I want to get used to writing. To practice, I need to start writing . As I have a hobby about making AI, I want to share my knowledge and experience on making AI to practice my writing skill. βIndonesian Lyric Generator β is one of my AI apps that I made on my free time."
},
{
"code": null,
"e": 818,
"s": 734,
"text": "I will make this article newbie-friendly. I hope this article is useful for you :D."
},
{
"code": null,
"e": 1069,
"s": 818,
"text": "This article is targeted for one who has interest in Artificial Intelligence, especially in Machine Learning and Deep Learning. I will also make this article math-free. If you want to know how it works, I will attach some articles in sources section."
},
{
"code": null,
"e": 1093,
"s": 1069,
"text": "Hereβs our intro lyric."
},
{
"code": null,
"e": 1121,
"s": 1093,
"text": "saat senyum manismu kalbuku"
},
{
"code": null,
"e": 1150,
"s": 1121,
"text": "yang mungkin menjadi milikmu"
},
{
"code": null,
"e": 1181,
"s": 1150,
"text": "terakhir kali ku hilang dariku"
},
{
"code": null,
"e": 1206,
"s": 1181,
"text": "yang kau ajak kau disana"
},
{
"code": null,
"e": 1315,
"s": 1206,
"text": "If you want to see the implementation and code of this article, you can see the notebook in this GitHub link"
},
{
"code": null,
"e": 1707,
"s": 1315,
"text": "New music always pop up to replace old music. People should be creative on making a new song. They need time to create a new song. a component that they should think on making song is lyric . For people who is hard to find a right word on creating lyric (like me), this will be a problem. They will spend a lot of time to make the lyric. Have you ever thought to help them solve the problem?"
},
{
"code": null,
"e": 1885,
"s": 1707,
"text": "In this article, I want to create an apps that can ease them on creating a lyric. I will make an apps based on AI. AI knowledge is one of my interest that I hope will help them."
},
{
"code": null,
"e": 2492,
"s": 1885,
"text": "Currently, AI is one of the hottest trendy buzz word, that people talk in every nook and corner. It can solve some problems easily that that are pretty hard for humans. One of the branch of AI is Machine Learning ( ML ). Machine Learning is a branch of field Artificial Intelligence which will predict an output based on given data. It will learn from the data. When we want to make a lyric, I think we should take a peek on some old song to learn how they write the lyric. We need to search the βpatternβ on how they connect each words. This is similar to Machine Learning which learn from the given data."
},
{
"code": null,
"e": 2719,
"s": 2492,
"text": "In this article, we will generate a new lyric based on lyric dataset that Iβve scrapped. we will use Deep Learning, one of a machine learning technique. we will use Recurrent Neural Network (RNN) to make the generatorβs model."
},
{
"code": null,
"e": 2931,
"s": 2719,
"text": "Even I choose the lyric to be Indonesian language, Donβt worry. I will write this article in English. If you want to see the meaning of the lyric, Translate it using Google Translate or any other familiar tools."
},
{
"code": null,
"e": 3186,
"s": 2931,
"text": "Donβt worry if you are still unfamiliar with terms on Deep Learning. I will tell you a brief description each of them. I will tell you the pipeline on how to make from start (scraping). As I state in the start, I will make it newbie-friendly as possible."
},
{
"code": null,
"e": 3226,
"s": 3186,
"text": "I will write the article in this order:"
},
{
"code": null,
"e": 3317,
"s": 3226,
"text": "ToolsStepGather dataPreprocessing dataBuild ModelGenerate LyricConclusionAfterwordsSources"
},
{
"code": null,
"e": 3323,
"s": 3317,
"text": "Tools"
},
{
"code": null,
"e": 3328,
"s": 3323,
"text": "Step"
},
{
"code": null,
"e": 3340,
"s": 3328,
"text": "Gather data"
},
{
"code": null,
"e": 3359,
"s": 3340,
"text": "Preprocessing data"
},
{
"code": null,
"e": 3371,
"s": 3359,
"text": "Build Model"
},
{
"code": null,
"e": 3386,
"s": 3371,
"text": "Generate Lyric"
},
{
"code": null,
"e": 3397,
"s": 3386,
"text": "Conclusion"
},
{
"code": null,
"e": 3408,
"s": 3397,
"text": "Afterwords"
},
{
"code": null,
"e": 3416,
"s": 3408,
"text": "Sources"
},
{
"code": null,
"e": 3485,
"s": 3416,
"text": "The library, tools, and language programming that will be used are :"
},
{
"code": null,
"e": 3857,
"s": 3485,
"text": "Python 3.6Python library βnumpy, math tools in pythonPython library β pandas, data tabular tools in pythonPython library β Keras, deep learning framework. Must have Tensorflow , CNTK, or Theano libraryPython library β Scrapy, popular scrapper tools in PythonJupyter Notebook, (optional) Awesome Python IDE that can also be used to make a presentation or educational code."
},
{
"code": null,
"e": 3868,
"s": 3857,
"text": "Python 3.6"
},
{
"code": null,
"e": 3912,
"s": 3868,
"text": "Python library βnumpy, math tools in python"
},
{
"code": null,
"e": 3966,
"s": 3912,
"text": "Python library β pandas, data tabular tools in python"
},
{
"code": null,
"e": 4062,
"s": 3966,
"text": "Python library β Keras, deep learning framework. Must have Tensorflow , CNTK, or Theano library"
},
{
"code": null,
"e": 4120,
"s": 4062,
"text": "Python library β Scrapy, popular scrapper tools in Python"
},
{
"code": null,
"e": 4234,
"s": 4120,
"text": "Jupyter Notebook, (optional) Awesome Python IDE that can also be used to make a presentation or educational code."
},
{
"code": null,
"e": 4279,
"s": 4234,
"text": "I use GPU NVIDIA GTX 1050 to train my model."
},
{
"code": null,
"e": 4322,
"s": 4279,
"text": "Hereβs the step how we make the generator."
},
{
"code": null,
"e": 4724,
"s": 4322,
"text": "First, gather the data by scraping some website that contains Indonesian lyric by using scrapy. Then clean the text lyric that still contains HTML tag by using regex. After that, process the text in the lyric so that it can be used for modelβs input. we will need to construct the deep learning architecture. Finally train the model to generate the lyric. I will tell you how I did this in every step."
},
{
"code": null,
"e": 5050,
"s": 4724,
"text": "I gathered all the lyrics from scraping an Indonesia lyric collection website (lirik.kapanlagi.com). web scraping is a extraction of data from websites. All the job is carried out by an app which we will create. We will use scrapy library to scrape a website. The information that we should extract is songβs lyric and title."
},
{
"code": null,
"e": 5113,
"s": 5050,
"text": "In this article we will use lirik.kapanlagi.com as our target."
},
{
"code": null,
"e": 5204,
"s": 5113,
"text": "First, Create the scrapy project by using this command in your terminal or command prompt:"
},
{
"code": null,
"e": 5239,
"s": 5204,
"text": "scrapy startproject lyric_scrapper"
},
{
"code": null,
"e": 5329,
"s": 5239,
"text": "It will create a new directory directory. Change to the new directory and do this command"
},
{
"code": null,
"e": 5381,
"s": 5329,
"text": "scrapy genspider lyric_scrapper lirik.kapanlagi.com"
},
{
"code": null,
"e": 5555,
"s": 5381,
"text": "It will create a lyricscrapper.py inside the tutorial/spiders folder. We will call it web-crawler because it scrape by βcrawlingβ into the targeted website. Hereβs our code:"
},
{
"code": null,
"e": 6334,
"s": 5555,
"text": "# -*- coding: utf-8 -*-import scrapyfrom scrapy.spiders import CrawlSpider, Rulefrom scrapy.linkextractors import LinkExtractorclass LyricScrapperSpider(CrawlSpider): name = 'lyric_scrapper' allowed_domains = ['lirik.kapanlagi.com'] start_urls = ['https://lirik.kapanlagi.com/lagu/a_id'] rules = (Rule(LinkExtractor(allow=(), restrict_css=(\".pagination2 ul li a\",\".col-lirik .div-horizontal2-list a\", \"div .letterLinksAnchor\")), callback=\"parse_page\", follow=True),) def parse_page(self, response): song = response.css('.col-lirik').extract_first() title= response.css('.head-lirik h5::text').extract_first() if len(title) > 0 and len(song) > 0:scraped_info = { 'song' : song, 'title' : title, }yield scraped_info"
},
{
"code": null,
"e": 6355,
"s": 6334,
"text": "Letβs see this part:"
},
{
"code": null,
"e": 6592,
"s": 6355,
"text": "start_urls = ['https://lirik.kapanlagi.com/lagu/a_id'] rules = (Rule(LinkExtractor(allow=(), restrict_css=(\".pagination2 ul li a\",\".col-lirik .div-horizontal2-list a\", \"div .letterLinksAnchor\")), callback=\"parse_page\", follow=True),)"
},
{
"code": null,
"e": 6796,
"s": 6592,
"text": "We will start from URL in start_urls. To determine the start URL, we should find the page which contains the index list of the lyric. I found that https://lirik.kapanlagi.com/lagu/a_id is the index list."
},
{
"code": null,
"e": 7069,
"s": 6796,
"text": "The crawler will find its next target to scrape by finding URLs inside the current web page . To make the crawler follow our desired page, we must specify what part or section of web page our crawler have to see. In this case, we need to target this part shown on Image 2:"
},
{
"code": null,
"e": 7453,
"s": 7069,
"text": "We will need the part or section that we want by inspecting its HTML code. For me, I used Inspect Element to do it (Firefox). For this website, we will restrict the crawler will target (β.pagination2 ul li aβ,β.col-lirik .div-horizontal2-list aβ, βdiv .letterLinksAnchorβ) . It will crawl the website until there are no more URLs to crawl (it also check if the url has been visited)."
},
{
"code": null,
"e": 7625,
"s": 7453,
"text": "Next, we want to extract the lyric and titleβs song from the web page. To do that, we need to find the HTML tag which contains them ( the red and blue one in the Image 3)."
},
{
"code": null,
"e": 7736,
"s": 7625,
"text": "song = response.css('.col-lirik').extract_first() title = response.css('.head-lirik h5::text').extract_first()"
},
{
"code": null,
"e": 7882,
"s": 7736,
"text": "For the lyric (i named it βsongβ variable), we need the HTML code because this siteβs HTML composition is a bit messy. We need to clean it later."
},
{
"code": null,
"e": 7957,
"s": 7882,
"text": "Save your lyricscrapper.py . Then, open the settings.py inside the folder."
},
{
"code": null,
"e": 7987,
"s": 7957,
"text": "Add or uncomment these lines:"
},
{
"code": null,
"e": 8112,
"s": 7987,
"text": "FEED_FORMAT = \"csv\"FEED_URI = \"scrape.csv\"DOWNLOAD_DELAY = 1 # important, sometimes you will get banned if you set it to 0. "
},
{
"code": null,
"e": 8170,
"s": 8112,
"text": "Save it and then do the following command on the console:"
},
{
"code": null,
"e": 8198,
"s": 8170,
"text": "scrapy crawl lyric_scrapper"
},
{
"code": null,
"e": 8539,
"s": 8198,
"text": "Voila, our crawler will crawl our targeted site. Just wait till it end or force it to end if you are bored. After it ends, it will generate scrape.csv inside the folder. You can open it with spreadsheet tools to see it. Itβs a bit messy, isnβt it?. As I state above, we will need to clean the lyricβs text. So letβs move into the next step."
},
{
"code": null,
"e": 8844,
"s": 8539,
"text": "Now is the time to clean our dirty data. As we only want to generate lyric, we only need the song column from the scrape.csv. Before we start, I suggest that we use Python IDE such as Jupyter Notebook or Spyder to see our data better. In this part, we will use pandas library too see our data in tabular."
},
{
"code": null,
"e": 9060,
"s": 8844,
"text": "Open your code, then lets import our csv data and make it into a dataframe type (pd.DataFrame) . To check a lyricβs song, we will sample 5 instances. Be sure to put the scrape.csv file into our pythonβs code folder."
},
{
"code": null,
"e": 9142,
"s": 9060,
"text": "import pandas as pdscrape_lyric = pd.read_csv('scrape.csv')scrape_lyric.sample(5)"
},
{
"code": null,
"e": 9496,
"s": 9142,
"text": "First, we need to ensure that our data donβt have missing data. Then we remove unwanted data if there are some wrong page that is extracted. In our case, we will find that our lyric web page should contains span tag. So remove instance that donβt have span tag.We will remove instance that have βBelum ada Lirikβ text (translate : Donβt have any lyric)."
},
{
"code": null,
"e": 9608,
"s": 9496,
"text": "Before we clean it, we should check the size of our data. use scrape_lyric.shape to check it. I had 20259 rows."
},
{
"code": null,
"e": 9793,
"s": 9608,
"text": "scrape_lyric = scrape_lyric.dropna()scrape_lyric = scrape_lyric[scrape_lyric.song.str.contains('span')]scrape_lyric = scrape_lyric[~(scrape_lyric.song.str.contains('Belum Ada Lirik'))]"
},
{
"code": null,
"e": 9890,
"s": 9793,
"text": "Check the size of your dataframe scrape_lyric.shape, I had 13791 rows. It had omitted 6468 rows!"
},
{
"code": null,
"e": 10048,
"s": 9890,
"text": "We will only see βsongβ column. By looking at the song column, we will see that the text still has HTML tag. We need to clean it. We will use regex to do it."
},
{
"code": null,
"e": 10284,
"s": 10048,
"text": "This cleaning regex is special only to our targeted website. If we target other website, we need to see how the HTML pattern is and use appropriate regex to clean it (or maybe no need to clean the data if the website is good to parse)."
},
{
"code": null,
"e": 10334,
"s": 10284,
"text": "Here are the regex to clean our scraped web page:"
},
{
"code": null,
"e": 11077,
"s": 10334,
"text": "def clean_text_lyric(lyric, max_length): lyric_sample = lyric.split('</span>') lyric_sample = lyric_sample[:-1] clean_song_lyric = \"\" for sentence in lyric_sample: if 'http' not in sentence: sentence = re.sub(r'<div .*>','',sentence) sentence = re.sub(r'<span .*>','',sentence) sentence = sentence.strip() if len(sentence) > 0: sentence = re.sub(r'[^a-zA-Z0-9<\\/>\\s]',' ', sentence) sentence = \" <div> \" + sentence + \" </div> \" sentence = re.sub(r'<div>\\s+<br>','<br> <div> ', sentence) sentence = re.sub(r'(\\d|\\r|\\t|\\n)','',sentence) clean_song_lyric += sentence clean_song_lyric = ' <start> ' * (max_length-1) + clean_song_lyric return clean_song_lyric"
},
{
"code": null,
"e": 11101,
"s": 11077,
"text": "We will see one by one:"
},
{
"code": null,
"e": 11171,
"s": 11101,
"text": "lyric_sample = lyric.split('</span>')lyric_sample = lyric_sample[:-1]"
},
{
"code": null,
"e": 11385,
"s": 11171,
"text": "If we look at our extracted lyric, they separate their verse by HTML tag β<br>β. 1 verse contains several rows. Every rows is separated by HTML tag β</span>β. We need to split the row by splitting with β</span>β ."
},
{
"code": null,
"e": 11424,
"s": 11385,
"text": "Now we remove the HTML tag (div, span)"
},
{
"code": null,
"e": 11510,
"s": 11424,
"text": "sentence = re.sub(r'<div .*>','',sentence)sentence = re.sub(r'<span .*>','',sentence)"
},
{
"code": null,
"e": 11711,
"s": 11510,
"text": "Then we will remove all character except [^a-zA-Z0β9<\\/>\\s] . We remove the escape character and excess white space. If you are not familiar with regex, i suggest that you try this site to play regex."
},
{
"code": null,
"e": 11915,
"s": 11711,
"text": "sentence = re.sub(r'[^a-zA-Z0-9<\\/>\\s]',' ', sentence)sentence = \" <div> \" + sentence + \" </div> \"sentence = re.sub(r'<div>\\s+<br>','<br> <div> ', sentence)sentence = re.sub(r'(\\d|\\r|\\t|\\n)','',sentence)"
},
{
"code": null,
"e": 12078,
"s": 11915,
"text": "I hate this websiteβs HTML code . The extracted lyric sometimes has an URL inside the lyric. Thatβs why I put the loop guard to ensure there are no URL inside it."
},
{
"code": null,
"e": 12156,
"s": 12078,
"text": "After we clean the text, we want to mark where our start and end lyricβs row."
},
{
"code": null,
"e": 12232,
"s": 12156,
"text": "For me, i used <div> and </div> tag to mark the start and end of our lyric."
},
{
"code": null,
"e": 12295,
"s": 12232,
"text": "We wonβt remove <br> tag. It is a tag to separate each verses."
},
{
"code": null,
"e": 12428,
"s": 12295,
"text": "Finally, we will append β<start>β tag at the start of the lyric by the desired max_length-1. Why do we do it? I will tell you later."
},
{
"code": null,
"e": 12457,
"s": 12428,
"text": "Apply it into the dataframe:"
},
{
"code": null,
"e": 12538,
"s": 12457,
"text": "scrape_lyric['song'] = scrape_lyric['song'].apply(lambda x: clean_text_lyric(x))"
},
{
"code": null,
"e": 12599,
"s": 12538,
"text": "This is the desired lyricβs format text that we want to use."
},
{
"code": null,
"e": 13083,
"s": 12599,
"text": "After weβre done cleaning the data, letβs move into preprocessing the data. Why do we need to do this? Our Deep Learning modelβs input is a sequence of text. It canβt read the text in string mode. We need to encode all of the word in our dataset into index number which map an index number into a word in one hot encoding. As we use embedding, in keras, we donβt have to encode the text into one hot encoding. We can use key index map to map a word with an index number in the model."
},
{
"code": null,
"e": 13216,
"s": 13083,
"text": "Before we do that, letβs change our lyric which contains several rows into a collection of sequence text arrays with desired length."
},
{
"code": null,
"e": 13630,
"s": 13216,
"text": "def generate_train_dataset(song_series, window): train_data = [] train_label = [] for song_string in song_series: song_arr = song_string.split() len_song_arr = len(song_arr) for i in range(0,len_song_arr-window+1): train_data.append(' '.join(song_arr[i:i+window-1])) train_label.append(song_arr[i+window-1]) return np.array(train_data), np.array(train_label)"
},
{
"code": null,
"e": 13974,
"s": 13630,
"text": "Look at Image 6 to visualize how the generate_train_dataset function will work. It will slice from the start till window-1 and add it into the train_data list. Then add the last index into the train_label list. This is called sliding window with window length equal to our window parameter. In this article, we will set the window equal to 10."
},
{
"code": null,
"e": 14038,
"s": 13974,
"text": "The function that we create need a pandas.Series type as input."
},
{
"code": null,
"e": 14131,
"s": 14038,
"text": "max_length = 10 #windowX, y = generate_train_dataset(scrape_lyric.song, sent_len=max_length)"
},
{
"code": null,
"e": 14370,
"s": 14131,
"text": "Did it work? Great, next we will use keras.preprocessing.text.Tokenizer library to make a input map which will map a word into an index number that the function choose. Make sure to change the parameter filter not to include β<β and β>β ."
},
{
"code": null,
"e": 14513,
"s": 14370,
"text": "pre = keras.preprocessing.text.Tokenizer(filters='!\"#$%&()*+,-.:;=?@[\\\\]^_`{|}~\\t\\n')pre.fit_on_texts(X.flatten()) # need to flatten the array"
},
{
"code": null,
"e": 14598,
"s": 14513,
"text": "We will get the vocabulary size which contains how many unique word are in our data."
},
{
"code": null,
"e": 14631,
"s": 14598,
"text": "vocab_size = len(pre.word_index)"
},
{
"code": null,
"e": 14682,
"s": 14631,
"text": "We transform our data into sequence of word index:"
},
{
"code": null,
"e": 14741,
"s": 14682,
"text": "X = pre.texts_to_sequences(X)y = pre.texts_to_sequences(y)"
},
{
"code": null,
"e": 14819,
"s": 14741,
"text": "Weβre done on preprocessing our input data. I had around 2 million instances."
},
{
"code": null,
"e": 14854,
"s": 14819,
"text": "Letβs move on into creating model."
},
{
"code": null,
"e": 15015,
"s": 14854,
"text": "Before we dive into the code and implementation, letβs recall what is Deep Learning, Dense Layer, RNN, LSTM layer, and activation function. We will recall them."
},
{
"code": null,
"e": 15346,
"s": 15015,
"text": "Deep Learning is a subset of Machine Learning technique. According to Yoshua Bengio, he said βDeep learning algorithms seek to exploit the unknown structure in the input distribution in order to discover good representations, often at multiple levels, with higher-level learned features defined in terms of lower-level featuresβ ."
},
{
"code": null,
"e": 15883,
"s": 15346,
"text": "Deep Learning will learn about the features representation from the data. We donβt have to extract feature from data. Itβs different from the others Machine Learning algorithm which need to extract features. It consists of several layers and network which mimics humanβs brain. It has many alias such as Deep Neural Network. The main part of the Deep Neural Network is backpropagation algorithm, which will update our modelβs weight to make the error become minimum with optimizer algorithm . If you want to learn more, visit this site."
},
{
"code": null,
"e": 16235,
"s": 15883,
"text": "Embedding is a technique which will make our instance in the dataset into a learned representation. In this tutorial we will use Word Embedding. Word embedding will represent our word into a learned representation as real-valued vector. It often consists of ten or hundreds dimensional vector. The vector usually will capture the meaning of the words."
},
{
"code": null,
"e": 16305,
"s": 16235,
"text": "There are several algorithms that can make Word Embedding. There are:"
},
{
"code": null,
"e": 16351,
"s": 16305,
"text": "Embedding LayerWord2vecGloVeFastexteLMo (NEW)"
},
{
"code": null,
"e": 16367,
"s": 16351,
"text": "Embedding Layer"
},
{
"code": null,
"e": 16376,
"s": 16367,
"text": "Word2vec"
},
{
"code": null,
"e": 16382,
"s": 16376,
"text": "GloVe"
},
{
"code": null,
"e": 16390,
"s": 16382,
"text": "Fastext"
},
{
"code": null,
"e": 16401,
"s": 16390,
"text": "eLMo (NEW)"
},
{
"code": null,
"e": 16494,
"s": 16401,
"text": "In our model, we will use Embedding Layer. It will update the vector according to our model."
},
{
"code": null,
"e": 16893,
"s": 16494,
"text": "Itβs an alias of Fully Connected Layer. Itβs a linear layer which propagate a linear function and backpropagate from neuron to neuron using the derivative of the function (gradient). To make it simpler, itβs a network which only take the input and multiply it with weight that is learned from backprogation. I found a medium article which can help you better on understanding Fully Connected Layer."
},
{
"code": null,
"e": 17174,
"s": 16893,
"text": "Recurrent Neural Network (RNN) is a layer which has a internal memory so it can remember the sequence information of inputs. The connection between neuron is a sequence of directed graph. It will remember previous neuronβs information (weight) and pass it into the present neuron."
},
{
"code": null,
"e": 17417,
"s": 17174,
"text": "There is several weakness in using RNN. It canβt learn βlong-term dependenciesβ. It will suffer a problem called βvanishing gradientβ . It wonβt update the neuronβs weight anymore. To solve this problem, Long Short Term Memory (LSTM) is used."
},
{
"code": null,
"e": 17769,
"s": 17417,
"text": "LSTM is a remedy on RNNβs problem. itβs capable to solve βlong-term dependenciesβ problem. LSTM has the ability to remove or add information to the new neuron with a structures called gates. There are 3 gates in the LSTM : forget gate, input gate, and output gate. They will control the neuron state. For further information, you can visit this site ."
},
{
"code": null,
"e": 18038,
"s": 17769,
"text": "Normalize the output values of the targeted layer. They will have a mean output activation of zero and standard deviation of one. It has several benefits such as speeding up our training speed. See this article if you want to know more detail about BatchNormalization."
},
{
"code": null,
"e": 18206,
"s": 18038,
"text": "It is used to determine the output of a layer is activated or not. It maps the output to the range of the activation function. To know more detail, visit this article."
},
{
"code": null,
"e": 18247,
"s": 18206,
"text": "Done recalling? letβs move into the code"
},
{
"code": null,
"e": 18507,
"s": 18247,
"text": "What we will build is a simple architecture Deep Network. It consists of Embedding Layer, LSTM Layer, and Dense Layer with categorical cross entropy and softmax activation as the output. Image 7 is the visualization of our architecture that we want to create."
},
{
"code": null,
"e": 19023,
"s": 18507,
"text": "model = Sequential()e = Embedding(vocab_size,100 ,input_length=max_length-1, trainable=True)model.add(e)model.add(keras.layers.BatchNormalization())model.add(keras.layers.Bidirectional(keras.layers.CuDNNLSTM(100)))model.add(keras.layers.BatchNormalization())model.add(Dense(100, activation='relu'))model.add(keras.layers.BatchNormalization())model.add(Dense(vocab_size+1, activation='softmax')) # vocab_size +1 to avoid out of bound# compile the modelmodel.compile(optimizer='adam', loss='categorical_crossentropy')"
},
{
"code": null,
"e": 19335,
"s": 19023,
"text": "In this article we will use the model with the stated hyperparameter. Of course, you can tweak the hyperparameter of our model. For simplicity, we will use only 1 bi-LSTM and 1 Dense Layer. We use BatchNormalization to speed up our learner. If we use GPU, we should use CuDNNLSTM to speed up our training speed."
},
{
"code": null,
"e": 19477,
"s": 19335,
"text": "I use adam optimizer because itβs a populer optimizer right now. Itβs fast and can adapt our modelβs learning rate on backpropagation nicely."
},
{
"code": null,
"e": 19931,
"s": 19477,
"text": "Before we fit or train our model. We have a problem to tackle. If we see our vocab_size, it has around 45.000 unique words. In keras, we should encode the train label into one hot encoding [0 0 0 ... 1 ... 0]. If we change all of our train label into one hot encoding, it will cause MemoryError (It need 45.000 * 2 milion * 4 byte memory. It is impossible to save it into the memory). So we need to change our train label to one hot encoding in a batch."
},
{
"code": null,
"e": 20455,
"s": 19931,
"text": "def batch_data(start,end): global X,y,y_input, X_input X_input = np.array(X)[start:end] y_input = np.array(y)[start:end] y_input = keras.utils.to_categorical(y_input,vocab_size+1)max_epoch = 40instance_max = len(X)batch_size = 10000for i in range(max_epoch): start_idx_counter = 0 while start_idx_counter < instance_max: batch_data(start_idx_counter, min(start_idx_counter+batch_size,instance_max)) model.fit(X_input, y_input, epochs=1, batch_size=64) start_idx_counter += batch_size"
},
{
"code": null,
"e": 20668,
"s": 20455,
"text": "We will define 10000 as our batch size. Feel free to decrease or increase the size as you wish. We fit our model with 40 epochs (iteration). Execute the code! The batch_size in the fit method can also be tweaked."
},
{
"code": null,
"e": 20682,
"s": 20668,
"text": "Wait for it!!"
},
{
"code": null,
"e": 20785,
"s": 20682,
"text": "It took 1 day to train my model with GPU. If you donβt want to wait that long, decrease the max_epoch."
},
{
"code": null,
"e": 20929,
"s": 20785,
"text": "Done? Donβt forget to save the model and the tokenizer. Do you want to wait another day to train our model? No? Donβt forget to save the model!"
},
{
"code": null,
"e": 20962,
"s": 20929,
"text": "model.save('lyric_gen_model.h5')"
},
{
"code": null,
"e": 21011,
"s": 20962,
"text": "We will use pickle library to save our tokenizer"
},
{
"code": null,
"e": 21082,
"s": 21011,
"text": "import picklepickle.dump( pre, open( \"tokenizer_pre_lyric.p\", \"wb\" ) )"
},
{
"code": null,
"e": 21122,
"s": 21082,
"text": "Weβre done. Letβs generate our lyric!!!"
},
{
"code": null,
"e": 21262,
"s": 21122,
"text": "Letβs use our model to generate lyric. Weβve trained our model and we will use it. Now to do that, we need to load our model and tokenizer."
},
{
"code": null,
"e": 21374,
"s": 21262,
"text": "model = keras.models.load_model('lyric_gen_model.h5')pre = pickle.load( open( \"tokenizer_pre_lyric.p\", \"rb\" ) )"
},
{
"code": null,
"e": 21418,
"s": 21374,
"text": "Then we need to preprocess our input first."
},
{
"code": null,
"e": 21490,
"s": 21418,
"text": "def preprocess_predict(X): X = pre.texts_to_sequences(X) return X"
},
{
"code": null,
"e": 21681,
"s": 21490,
"text": "In our article we have inserted β<start>β token into the start of the lyric. We do this to mark the start of the songβs lyric. If we want to generate without any start words. We can do this:"
},
{
"code": null,
"e": 21716,
"s": 21681,
"text": "seed = \"<start> \" * (max_length-1)"
},
{
"code": null,
"e": 21770,
"s": 21716,
"text": "Alternatively, you can also include some start words."
},
{
"code": null,
"e": 21824,
"s": 21770,
"text": "seed = \"<start> \" * (max_length-3)seed = \"<div> love\""
},
{
"code": null,
"e": 21882,
"s": 21824,
"text": "We should define the function to help us generating lyric"
},
{
"code": null,
"e": 22679,
"s": 21882,
"text": "def is_word_in_dict(words, word_idx): for word in words.split(): if word not in word_idx: return False return Truedef generate_song_by_model(model, idx_word, X_sent, word_idx, total_classes, word_generated=80): string_returned = X_sent if is_word_in_dict(X_sent, word_idx): X = np.array(preprocess_predict([X_sent])) counter = 1 for i in range(word_generated): y_pred = model.predict(X) rnd_choice = np.random.choice(range(0,total_classes),size=1,replace=False, p=y_pred[0]) word_predict = idx_word[rnd_choice[0]] string_returned += \" \" + word_predict X = ' '.join(string_returned.split()[counter:]) X = np.array(preprocess_predict([X])) counter += 1 return string_returned"
},
{
"code": null,
"e": 23198,
"s": 22679,
"text": "In this function, we will predict word based on our seed (X_sent variable in our generate function). We take window size length-1 tokens as a input of our model and the model will predict the next token. In the next loop, it will take the predicted output and size-length-2 tokens into the model. It will loop until the end that we set. We will get a random word based on the probability distribution produced by the output of softmax. If you are using Jupyter Notebook, use this command to display the generated lyric"
},
{
"code": null,
"e": 23377,
"s": 23198,
"text": "from IPython.display import HTMLgenerated_lyric = generate_song_by_model(model, pre.index_word, seed, max_length, pre.word_index, vocab_size+1,loop_count=50)HTML(generated_lyric)"
},
{
"code": null,
"e": 23649,
"s": 23377,
"text": "It will generate 50 new tokens/words (including tags). The generated lyric should have HTML tag <div> and <br> that serve as separator of rows and verses. We use HTML function in IPython.display to clean the tag in the display. Hereβs some example of our generated lyric."
},
{
"code": null,
"e": 23672,
"s": 23649,
"text": "i try to take you home"
},
{
"code": null,
"e": 23695,
"s": 23672,
"text": "i m a light of the one"
},
{
"code": null,
"e": 23725,
"s": 23695,
"text": "one day s erat a can fly away"
},
{
"code": null,
"e": 23755,
"s": 23725,
"text": "who have lookin my hands down"
},
{
"code": null,
"e": 23780,
"s": 23755,
"text": "and one if i didn t fine"
},
{
"code": null,
"e": 23799,
"s": 23780,
"text": "you start a way to"
},
{
"code": null,
"e": 24016,
"s": 23799,
"text": "In this generated lyric. Itβs very consistent to use english word. Itβs not bad although there are some confusing meaning. Our result is based on randomness. If your model has learnt less, it can generate bad lyrics!"
},
{
"code": null,
"e": 24156,
"s": 24016,
"text": "If you are wondering why it generate english word, sometimes Indonesian song contains mixed language. Some songs contain full english word."
},
{
"code": null,
"e": 24189,
"s": 24156,
"text": "Here is another generated lyric."
},
{
"code": null,
"e": 24220,
"s": 24189,
"text": "dara kau bertanya siapa namamu"
},
{
"code": null,
"e": 24241,
"s": 24220,
"text": "yang senyum tangismu"
},
{
"code": null,
"e": 24263,
"s": 24241,
"text": "pasti pahit di ayahku"
},
{
"code": null,
"e": 24298,
"s": 24263,
"text": "pada bermula dekat di pandang luka"
},
{
"code": null,
"e": 24323,
"s": 24298,
"text": "dan semua karena cintamu"
},
{
"code": null,
"e": 24374,
"s": 24323,
"text": "tersimpan nama jiwa ku masih ada di jendela hatimu"
},
{
"code": null,
"e": 24395,
"s": 24374,
"text": "ku tak ingin sendiri"
},
{
"code": null,
"e": 24615,
"s": 24395,
"text": "Translate it if you want to know the meaning of the lyric. Itβs also very consistent about using Indonesian language and talk about love. And again, its randomness will decide whether the generated lyric is good or not."
},
{
"code": null,
"e": 24862,
"s": 24615,
"text": "If you follow this article, weβve built a tool to generate Indonesian Lyric. Weβve utilized web crawler and deep learning library to build the generator. It can generate some good lyrics although it depend on our luck (randomness on probability)."
},
{
"code": null,
"e": 25035,
"s": 24862,
"text": "In this article, we skip some steps such as Exploratory Analysis. We should have tried another architecture or hyperparameter. We also need to evaluate the generated lyric."
},
{
"code": null,
"e": 25276,
"s": 25035,
"text": "Thank you for reading my first article about Artificial Intelligence. Since itβs my first and Iβm still not too expert in this area, I need some constructive feedback to make me better on writing and deep learning. Go easy on me please >_<!"
},
{
"code": null,
"e": 25338,
"s": 25276,
"text": "Sorry for any spelling mistake,grammar, and inefficient code."
},
{
"code": null,
"e": 25525,
"s": 25338,
"text": "Oh did I mention part 1? Yeah , I plan to make improvement on this lyric generator by making the architecture more complex (maybe using GAN), using another embedding, and hyperparameter."
},
{
"code": null,
"e": 25640,
"s": 25525,
"text": "For the next article, Iβm going to do some reinforcement learning from a game that will be developed from scratch."
}
] |
How to throw a C++ exception?
|
Exception handling is used to handle the exceptions. We can use try catch block to protect the code. Exception can be thrown anywhere within the code block. The keyword βthrowβ is used to throw an exception.
Here is an example of throw in C++ language,
Live Demo
#include <iostream>
using namespace std;
int display(int x, int y) {
if( y == 0 ) {
throw "Division by zero condition!";
}
return (x/y);
}
int main () {
int a = 50;
int b = 0;
int c = 0;
try {
c = display(a, b);
cout << c << endl;
} catch (const char* msg) {
cerr << msg << endl;
}
return 0;
}
Here is the output
Division by zero condition!
|
[
{
"code": null,
"e": 1270,
"s": 1062,
"text": "Exception handling is used to handle the exceptions. We can use try catch block to protect the code. Exception can be thrown anywhere within the code block. The keyword βthrowβ is used to throw an exception."
},
{
"code": null,
"e": 1315,
"s": 1270,
"text": "Here is an example of throw in C++ language,"
},
{
"code": null,
"e": 1326,
"s": 1315,
"text": " Live Demo"
},
{
"code": null,
"e": 1677,
"s": 1326,
"text": "#include <iostream>\nusing namespace std;\n\nint display(int x, int y) {\n if( y == 0 ) {\n throw \"Division by zero condition!\";\n }\n return (x/y);\n}\n\nint main () {\n int a = 50;\n int b = 0;\n int c = 0;\n\n try {\n c = display(a, b);\n cout << c << endl;\n } catch (const char* msg) {\n cerr << msg << endl;\n }\n return 0;\n}"
},
{
"code": null,
"e": 1696,
"s": 1677,
"text": "Here is the output"
},
{
"code": null,
"e": 1724,
"s": 1696,
"text": "Division by zero condition!"
}
] |
Stochastic Volatility Pricing in Python | by Roman Paolucci | Towards Data Science
|
There are a variety of methods used to price securities. I would argue that this topic is as much an art as it is a science. This article discusses the advantages of using simulations (mainly in the form of stochastic inputs) for pricing financial instruments. If you are unfamiliar with securities pricing I would suggest this progression of articles...
Martingales and Markov Processes
A gentle introduction to stochastic processes
Geometric Brownian Motion
The primary stochastic process used in the Black-Scholes model
Stochastic Integrals
The evaluation of stochastic integrals for deriving the Black-Scholes model
Deriving the Black-Scholes Model
Deriving the infamous European option pricing model step by step
Those articles will provide a strong foundation in pricing specific securities using a closed-form solution. Afterward, to get a grasp of basic simulation pricing, check out these articles...
Monte Carlo Pricing in Python
Simulating asset price paths to price financial instruments
Python for Pricing Exotics
Advanced simulation pricing specifically for exotic instruments
Having a strong understanding of these different pricing methodologies will reflect the aforementioned art aspect of this science. Each pricing method is different β from the initial assumptions to the actual means (numerical or analytical) of deriving the securityβs price. That doesnβt mean that any particular method is more correct or incorrect; which is precisely why understanding how each price is derived is so important. Knowing the assumptions of a Black-Scholes price (lognormally distributed stock prices and no transaction costs just to name two) against a Monte Carlo price (perhaps inclusive of transaction costs) will help guide your pricing needs. There is beauty in both the theoretical analytical solutions and the numerical solutions (which often converge to some theoretical solutions). In fact, some of my previous research has looked at amendments to the Black-Scholes model to better reflect generic market conditions...
papers.ssrn.com
I will now assume that you have a good foundation of securities pricing knowledge. Without further ado, letβs look at why simulation pricing is so powerful by allowing variation in model inputs.
Empirically observed heteroskedasticity in stock prices is not preserved in Geometric Brownian motion as volatility is held constant. Heston (1993) finds a quasi closed-form solution similar to Black-Scholes persisting the notion of stochastic volatility. However, the derivation of his solution is significantly more complicated than the derivation of the Black-Scholes model and is beyond the scope of this article. Nevertheless, the underlying processes he uses to derive his model can be easily implemented into a simulation for pricing capturing, in essence, the same result: stochastic volatility.
There are fundamentally two processes:
I. The stochastic process used to generate a new variance value
II. The stochastic process used to generate a new stock price value
First, letβs first get a good idea of the parameters we are working with...
S β Initial stock price
r β Risk-free rate of interest
v_t β Instantaneous variance
Ξ±, Ξ² β Mean reverting parameters
Ο_v β Varianceβs volatility
Ξ΅ βGenerated error
Ο β Error correlation
Ξt β Change in time
Now letβs take a look at the processes themselves...
Fundamentally, there is nothing particularly surprising about these processes. Each process can essentially be decomposed as an expectation in the first term, and a shock to that expectation in the second term.
The particularly keen reader will notice that by creating a separate stochastic process for volatility, we are once again fixing volatility. That is, we are fixing varianceβs volatility. This can become a circular argument. Should there be a separate stochastic process for the volatility of variance which is now its own stochastic process? There is research on this subject, and it is worth noting, but for the sake of this article, I digress.
Now letβs look to Python to implement these processes to price securities.
First, letβs import numpy and define the parameters of the stochastic variance process, along with some parameters to price a standard European option...
Next, we need to create the outer loop that is responsible for running the simulation n times...
There are a few parameters set within this loop that will become more clear within the next loop. First, at the start of each new simulation in the series of simulations we need to reset base parameters: St, inst_var_now, prev_inst_var, and step. These are synonymous with the input parameters defined in the first section of the article. Notice that the instantaneous variance is broken up into two variables, this is to allow us to use the appropriate error for each step in the stochastic process generating new variances. Letβs create the inner loop to step through a stock price path with a stochastic variance...
After each iteration of this while loop in the set of simulations, we will arrive at the final stock price value. This final stock price value can be used once again in the outer loop to generate a payoff based on the security we are pricing. In this example, I am pricing a European option, so based on the parameters I compute the appropriate payoff...
Notice that when appending the payoff to the payoffs list the payoff is discounted by the risk-free rate over time T. If the time value of money is a foreign concept see Quantitative Finance in Python.
To compute the simulated price of this European option we simply average the values appended to the payoffs list...
14.648492872411381
There we have it! We have arrived at the simulated price by a process with stochastic variance.
This article has shown how to simulate a securityβs price using a stochastic variance process. Again, donβt think of this price as more or less correct when compared to other pricing methodologies. Rather, understand the reason for differences in the final price. This notion can be extended to each parameter affecting a financial instrument and make them all stochastic processes.
Stochastic Variance Simulation Pricing Script:
|
[
{
"code": null,
"e": 402,
"s": 47,
"text": "There are a variety of methods used to price securities. I would argue that this topic is as much an art as it is a science. This article discusses the advantages of using simulations (mainly in the form of stochastic inputs) for pricing financial instruments. If you are unfamiliar with securities pricing I would suggest this progression of articles..."
},
{
"code": null,
"e": 435,
"s": 402,
"text": "Martingales and Markov Processes"
},
{
"code": null,
"e": 481,
"s": 435,
"text": "A gentle introduction to stochastic processes"
},
{
"code": null,
"e": 507,
"s": 481,
"text": "Geometric Brownian Motion"
},
{
"code": null,
"e": 570,
"s": 507,
"text": "The primary stochastic process used in the Black-Scholes model"
},
{
"code": null,
"e": 591,
"s": 570,
"text": "Stochastic Integrals"
},
{
"code": null,
"e": 667,
"s": 591,
"text": "The evaluation of stochastic integrals for deriving the Black-Scholes model"
},
{
"code": null,
"e": 700,
"s": 667,
"text": "Deriving the Black-Scholes Model"
},
{
"code": null,
"e": 765,
"s": 700,
"text": "Deriving the infamous European option pricing model step by step"
},
{
"code": null,
"e": 957,
"s": 765,
"text": "Those articles will provide a strong foundation in pricing specific securities using a closed-form solution. Afterward, to get a grasp of basic simulation pricing, check out these articles..."
},
{
"code": null,
"e": 987,
"s": 957,
"text": "Monte Carlo Pricing in Python"
},
{
"code": null,
"e": 1047,
"s": 987,
"text": "Simulating asset price paths to price financial instruments"
},
{
"code": null,
"e": 1074,
"s": 1047,
"text": "Python for Pricing Exotics"
},
{
"code": null,
"e": 1138,
"s": 1074,
"text": "Advanced simulation pricing specifically for exotic instruments"
},
{
"code": null,
"e": 2083,
"s": 1138,
"text": "Having a strong understanding of these different pricing methodologies will reflect the aforementioned art aspect of this science. Each pricing method is different β from the initial assumptions to the actual means (numerical or analytical) of deriving the securityβs price. That doesnβt mean that any particular method is more correct or incorrect; which is precisely why understanding how each price is derived is so important. Knowing the assumptions of a Black-Scholes price (lognormally distributed stock prices and no transaction costs just to name two) against a Monte Carlo price (perhaps inclusive of transaction costs) will help guide your pricing needs. There is beauty in both the theoretical analytical solutions and the numerical solutions (which often converge to some theoretical solutions). In fact, some of my previous research has looked at amendments to the Black-Scholes model to better reflect generic market conditions..."
},
{
"code": null,
"e": 2099,
"s": 2083,
"text": "papers.ssrn.com"
},
{
"code": null,
"e": 2294,
"s": 2099,
"text": "I will now assume that you have a good foundation of securities pricing knowledge. Without further ado, letβs look at why simulation pricing is so powerful by allowing variation in model inputs."
},
{
"code": null,
"e": 2898,
"s": 2294,
"text": "Empirically observed heteroskedasticity in stock prices is not preserved in Geometric Brownian motion as volatility is held constant. Heston (1993) finds a quasi closed-form solution similar to Black-Scholes persisting the notion of stochastic volatility. However, the derivation of his solution is significantly more complicated than the derivation of the Black-Scholes model and is beyond the scope of this article. Nevertheless, the underlying processes he uses to derive his model can be easily implemented into a simulation for pricing capturing, in essence, the same result: stochastic volatility."
},
{
"code": null,
"e": 2937,
"s": 2898,
"text": "There are fundamentally two processes:"
},
{
"code": null,
"e": 3001,
"s": 2937,
"text": "I. The stochastic process used to generate a new variance value"
},
{
"code": null,
"e": 3069,
"s": 3001,
"text": "II. The stochastic process used to generate a new stock price value"
},
{
"code": null,
"e": 3145,
"s": 3069,
"text": "First, letβs first get a good idea of the parameters we are working with..."
},
{
"code": null,
"e": 3169,
"s": 3145,
"text": "S β Initial stock price"
},
{
"code": null,
"e": 3200,
"s": 3169,
"text": "r β Risk-free rate of interest"
},
{
"code": null,
"e": 3229,
"s": 3200,
"text": "v_t β Instantaneous variance"
},
{
"code": null,
"e": 3262,
"s": 3229,
"text": "Ξ±, Ξ² β Mean reverting parameters"
},
{
"code": null,
"e": 3290,
"s": 3262,
"text": "Ο_v β Varianceβs volatility"
},
{
"code": null,
"e": 3309,
"s": 3290,
"text": "Ξ΅ βGenerated error"
},
{
"code": null,
"e": 3331,
"s": 3309,
"text": "Ο β Error correlation"
},
{
"code": null,
"e": 3351,
"s": 3331,
"text": "Ξt β Change in time"
},
{
"code": null,
"e": 3404,
"s": 3351,
"text": "Now letβs take a look at the processes themselves..."
},
{
"code": null,
"e": 3615,
"s": 3404,
"text": "Fundamentally, there is nothing particularly surprising about these processes. Each process can essentially be decomposed as an expectation in the first term, and a shock to that expectation in the second term."
},
{
"code": null,
"e": 4061,
"s": 3615,
"text": "The particularly keen reader will notice that by creating a separate stochastic process for volatility, we are once again fixing volatility. That is, we are fixing varianceβs volatility. This can become a circular argument. Should there be a separate stochastic process for the volatility of variance which is now its own stochastic process? There is research on this subject, and it is worth noting, but for the sake of this article, I digress."
},
{
"code": null,
"e": 4136,
"s": 4061,
"text": "Now letβs look to Python to implement these processes to price securities."
},
{
"code": null,
"e": 4290,
"s": 4136,
"text": "First, letβs import numpy and define the parameters of the stochastic variance process, along with some parameters to price a standard European option..."
},
{
"code": null,
"e": 4387,
"s": 4290,
"text": "Next, we need to create the outer loop that is responsible for running the simulation n times..."
},
{
"code": null,
"e": 5006,
"s": 4387,
"text": "There are a few parameters set within this loop that will become more clear within the next loop. First, at the start of each new simulation in the series of simulations we need to reset base parameters: St, inst_var_now, prev_inst_var, and step. These are synonymous with the input parameters defined in the first section of the article. Notice that the instantaneous variance is broken up into two variables, this is to allow us to use the appropriate error for each step in the stochastic process generating new variances. Letβs create the inner loop to step through a stock price path with a stochastic variance..."
},
{
"code": null,
"e": 5361,
"s": 5006,
"text": "After each iteration of this while loop in the set of simulations, we will arrive at the final stock price value. This final stock price value can be used once again in the outer loop to generate a payoff based on the security we are pricing. In this example, I am pricing a European option, so based on the parameters I compute the appropriate payoff..."
},
{
"code": null,
"e": 5563,
"s": 5361,
"text": "Notice that when appending the payoff to the payoffs list the payoff is discounted by the risk-free rate over time T. If the time value of money is a foreign concept see Quantitative Finance in Python."
},
{
"code": null,
"e": 5679,
"s": 5563,
"text": "To compute the simulated price of this European option we simply average the values appended to the payoffs list..."
},
{
"code": null,
"e": 5698,
"s": 5679,
"text": "14.648492872411381"
},
{
"code": null,
"e": 5794,
"s": 5698,
"text": "There we have it! We have arrived at the simulated price by a process with stochastic variance."
},
{
"code": null,
"e": 6177,
"s": 5794,
"text": "This article has shown how to simulate a securityβs price using a stochastic variance process. Again, donβt think of this price as more or less correct when compared to other pricing methodologies. Rather, understand the reason for differences in the final price. This notion can be extended to each parameter affecting a financial instrument and make them all stochastic processes."
}
] |
Sum of N-terms of geometric progression for larger values of N | Set 2 (Using recursion)
|
02 Mar, 2022
A Geometric series is a series with a constant ratio between successive terms. The first term of the series is denoted by a and the common ratio is denoted by r. The series looks like this:- The task is to find the sum of such a series, mod M.
Examples:
Input: a = 1, r = 2, N = 10000, M = 10000
Output: 8751
Input: a = 1, r = 4, N = 10000, M = 100000
Output: 12501
Approach:
To find the sum of series we can easily take a as common and find the sum of and multiply it with a.Steps to find the sum of the above series. Here, it can be resolved that:
To find the sum of series we can easily take a as common and find the sum of and multiply it with a.
Steps to find the sum of the above series. Here, it can be resolved that:
Here, it can be resolved that:
If we denote, then, and, This will work as our recursive case.
So, the base cases are:
Sum(r, 0) = 1.
Sum(r, 1) = 1 + r.
Below is the implementation of the above approach.
C++
Java
Python3
C#
Javascript
// C++ implementation to// illustrate the program#include <iostream>using namespace std; // Function to calculate the sum// recursivelyint SumGPUtil(long long int r, long long int n, long long int m){ // Base cases if (n == 0) return 1; if (n == 1) return (1 + r) % m; long long int ans; // If n is odd if (n % 2 == 1) { ans = (1 + r) * SumGPUtil((r * r) % m, (n - 1) / 2, m); } else { // If n is even ans = 1 + (r * (1 + r) * SumGPUtil((r * r) % m, (n / 2) - 1, m)); } return (ans % m);} // Function to print the long value of Sumvoid SumGP(long long int a, long long int r, long long int N, long long int M){ long long int answer; answer = a * SumGPUtil(r, N, M); answer = answer % M; cout << answer << endl;} // Driver Codeint main(){ // First element long long int a = 1; // Common difference long long int r = 4; // Number of elements long long int N = 10000; // Mod value long long int M = 100000; SumGP(a, r, N, M); return 0;} // This code is contributed by sanjoy_62
// Java implementation to// illustrate the programimport java.io.*; class GFG{ // Function to calculate the sum// recursivelystatic long SumGPUtil(long r, long n, long m){ // Base cases if (n == 0) return 1; if (n == 1) return (1 + r) % m; long ans; // If n is odd if (n % 2 == 1) { ans = (1 + r) * SumGPUtil((r * r) % m, (n - 1) / 2, m); } else { // If n is even ans = 1 + (r * (1 + r) * SumGPUtil((r * r) % m, (n / 2) - 1, m)); } return (ans % m);} // Function to print the value of Sumstatic void SumGP(long a, long r, long N, long M){ long answer; answer = a * SumGPUtil(r, N, M); answer = answer % M; System.out.println(answer);} // Driver Codepublic static void main (String[] args){ // First element long a = 1; // Common difference long r = 4; // Number of elements long N = 10000; // Mod value long M = 100000; SumGP(a, r, N, M);}} // This code is contributed by sanjoy_62
# Python3 implementation to illustrate the program # Function to calculate the sum# recursivelydef SumGPUtil (r, n, m): # Base cases if n == 0: return 1 if n == 1: return (1 + r) % m # If n is odd if n % 2 == 1: ans = (1 + r) * SumGPUtil(r * r % m, (n - 1)//2, m) else: #If n is even ans = 1 + r * (1 + r) * SumGPUtil(r * r % m, n//2 - 1, m) return ans % m # Function to print the value of Sumdef SumGP (a, r, N, M): answer = a * SumGPUtil(r, N, M) answer = answer % M print(answer) #Driver Programif __name__== '__main__': a = 1 # first element r = 4 # common difference N = 10000 # Number of elements M = 100000 # Mod value SumGP(a, r, N, M)
// C# implementation to// illustrate the programusing System; class GFG{ // Function to calculate the sum// recursivelystatic long SumGPUtil(long r, long n, long m){ // Base cases if (n == 0) return 1; if (n == 1) return (1 + r) % m; long ans; // If n is odd if (n % 2 == 1) { ans = (1 + r) * SumGPUtil((r * r) % m, (n - 1) / 2, m); } else { // If n is even ans = 1 + (r * (1 + r) * SumGPUtil((r * r) % m, (n / 2) - 1, m)); } return (ans % m);} // Function to print the value of Sumstatic void SumGP(long a, long r, long N, long M){ long answer; answer = a * SumGPUtil(r, N, M); answer = answer % M; Console.WriteLine(answer);} // Driver Codepublic static void Main(){ // First element long a = 1; // Common difference long r = 4; // Number of elements long N = 10000; // Mod value long M = 100000; SumGP(a, r, N, M);}} // This code is contributed by sanjoy_62
<script> // Javascript implementation to// illustrate the program // Function to calculate the sum// recursivelyfunction SumGPUtil(r, n, m){ // Base cases if (n == 0) return 1; if (n == 1) return (1 + r) % m; let ans; // If n is odd if (n % 2 == 1) { ans = (1 + r) * SumGPUtil((r * r) % m, (n - 1) / 2, m); } else { // If n is even ans = 1 + (r * (1 + r) * SumGPUtil((r * r) % m, (n / 2) - 1, m)); } return (ans % m);} // Function to print the value of Sumfunction SumGP(a, r, N, M){ let answer; answer = a * SumGPUtil(r, N, M); answer = answer % M; document.write(answer);} // Driver Code // First element let a = 1; // Common difference let r = 4; // Number of elements let N = 10000; // Mod value let M = 100000; SumGP(a, r, N, M); </script>
12501
Time complexity: O(log N)
Auxiliary Space: O(1)
sanjoy_62
splevel62
sumitgumber28
rishavmahato348
arorakashish0911
Algorithms
Analysis
Competitive Programming
Mathematical
Recursion
Mathematical
Recursion
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
SDE SHEET - A Complete Guide for SDE Preparation
What is Hashing | A Complete Tutorial
CPU Scheduling in Operating Systems
Understanding Time Complexity with Simple Examples
Understanding Time Complexity with Simple Examples
Time Complexity and Space Complexity
Practice Questions on Time Complexity Analysis
Analysis of Algorithms | Set 2 (Worst, Average and Best Cases)
Analysis of Algorithms | Set 3 (Asymptotic Notations)
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n02 Mar, 2022"
},
{
"code": null,
"e": 298,
"s": 54,
"text": "A Geometric series is a series with a constant ratio between successive terms. The first term of the series is denoted by a and the common ratio is denoted by r. The series looks like this:- The task is to find the sum of such a series, mod M."
},
{
"code": null,
"e": 310,
"s": 298,
"text": "Examples: "
},
{
"code": null,
"e": 428,
"s": 310,
"text": "Input: a = 1, r = 2, N = 10000, M = 10000\nOutput: 8751\n\nInput: a = 1, r = 4, N = 10000, M = 100000\nOutput: 12501 "
},
{
"code": null,
"e": 439,
"s": 428,
"text": "Approach: "
},
{
"code": null,
"e": 614,
"s": 439,
"text": "To find the sum of series we can easily take a as common and find the sum of and multiply it with a.Steps to find the sum of the above series. Here, it can be resolved that: "
},
{
"code": null,
"e": 715,
"s": 614,
"text": "To find the sum of series we can easily take a as common and find the sum of and multiply it with a."
},
{
"code": null,
"e": 790,
"s": 715,
"text": "Steps to find the sum of the above series. Here, it can be resolved that: "
},
{
"code": null,
"e": 822,
"s": 790,
"text": "Here, it can be resolved that: "
},
{
"code": null,
"e": 886,
"s": 822,
"text": "If we denote, then, and, This will work as our recursive case. "
},
{
"code": null,
"e": 910,
"s": 886,
"text": "So, the base cases are:"
},
{
"code": null,
"e": 944,
"s": 910,
"text": "Sum(r, 0) = 1.\nSum(r, 1) = 1 + r."
},
{
"code": null,
"e": 997,
"s": 944,
"text": "Below is the implementation of the above approach. "
},
{
"code": null,
"e": 1001,
"s": 997,
"text": "C++"
},
{
"code": null,
"e": 1006,
"s": 1001,
"text": "Java"
},
{
"code": null,
"e": 1014,
"s": 1006,
"text": "Python3"
},
{
"code": null,
"e": 1017,
"s": 1014,
"text": "C#"
},
{
"code": null,
"e": 1028,
"s": 1017,
"text": "Javascript"
},
{
"code": "// C++ implementation to// illustrate the program#include <iostream>using namespace std; // Function to calculate the sum// recursivelyint SumGPUtil(long long int r, long long int n, long long int m){ // Base cases if (n == 0) return 1; if (n == 1) return (1 + r) % m; long long int ans; // If n is odd if (n % 2 == 1) { ans = (1 + r) * SumGPUtil((r * r) % m, (n - 1) / 2, m); } else { // If n is even ans = 1 + (r * (1 + r) * SumGPUtil((r * r) % m, (n / 2) - 1, m)); } return (ans % m);} // Function to print the long value of Sumvoid SumGP(long long int a, long long int r, long long int N, long long int M){ long long int answer; answer = a * SumGPUtil(r, N, M); answer = answer % M; cout << answer << endl;} // Driver Codeint main(){ // First element long long int a = 1; // Common difference long long int r = 4; // Number of elements long long int N = 10000; // Mod value long long int M = 100000; SumGP(a, r, N, M); return 0;} // This code is contributed by sanjoy_62",
"e": 2293,
"s": 1028,
"text": null
},
{
"code": "// Java implementation to// illustrate the programimport java.io.*; class GFG{ // Function to calculate the sum// recursivelystatic long SumGPUtil(long r, long n, long m){ // Base cases if (n == 0) return 1; if (n == 1) return (1 + r) % m; long ans; // If n is odd if (n % 2 == 1) { ans = (1 + r) * SumGPUtil((r * r) % m, (n - 1) / 2, m); } else { // If n is even ans = 1 + (r * (1 + r) * SumGPUtil((r * r) % m, (n / 2) - 1, m)); } return (ans % m);} // Function to print the value of Sumstatic void SumGP(long a, long r, long N, long M){ long answer; answer = a * SumGPUtil(r, N, M); answer = answer % M; System.out.println(answer);} // Driver Codepublic static void main (String[] args){ // First element long a = 1; // Common difference long r = 4; // Number of elements long N = 10000; // Mod value long M = 100000; SumGP(a, r, N, M);}} // This code is contributed by sanjoy_62",
"e": 3439,
"s": 2293,
"text": null
},
{
"code": "# Python3 implementation to illustrate the program # Function to calculate the sum# recursivelydef SumGPUtil (r, n, m): # Base cases if n == 0: return 1 if n == 1: return (1 + r) % m # If n is odd if n % 2 == 1: ans = (1 + r) * SumGPUtil(r * r % m, (n - 1)//2, m) else: #If n is even ans = 1 + r * (1 + r) * SumGPUtil(r * r % m, n//2 - 1, m) return ans % m # Function to print the value of Sumdef SumGP (a, r, N, M): answer = a * SumGPUtil(r, N, M) answer = answer % M print(answer) #Driver Programif __name__== '__main__': a = 1 # first element r = 4 # common difference N = 10000 # Number of elements M = 100000 # Mod value SumGP(a, r, N, M)",
"e": 4315,
"s": 3439,
"text": null
},
{
"code": "// C# implementation to// illustrate the programusing System; class GFG{ // Function to calculate the sum// recursivelystatic long SumGPUtil(long r, long n, long m){ // Base cases if (n == 0) return 1; if (n == 1) return (1 + r) % m; long ans; // If n is odd if (n % 2 == 1) { ans = (1 + r) * SumGPUtil((r * r) % m, (n - 1) / 2, m); } else { // If n is even ans = 1 + (r * (1 + r) * SumGPUtil((r * r) % m, (n / 2) - 1, m)); } return (ans % m);} // Function to print the value of Sumstatic void SumGP(long a, long r, long N, long M){ long answer; answer = a * SumGPUtil(r, N, M); answer = answer % M; Console.WriteLine(answer);} // Driver Codepublic static void Main(){ // First element long a = 1; // Common difference long r = 4; // Number of elements long N = 10000; // Mod value long M = 100000; SumGP(a, r, N, M);}} // This code is contributed by sanjoy_62",
"e": 5444,
"s": 4315,
"text": null
},
{
"code": "<script> // Javascript implementation to// illustrate the program // Function to calculate the sum// recursivelyfunction SumGPUtil(r, n, m){ // Base cases if (n == 0) return 1; if (n == 1) return (1 + r) % m; let ans; // If n is odd if (n % 2 == 1) { ans = (1 + r) * SumGPUtil((r * r) % m, (n - 1) / 2, m); } else { // If n is even ans = 1 + (r * (1 + r) * SumGPUtil((r * r) % m, (n / 2) - 1, m)); } return (ans % m);} // Function to print the value of Sumfunction SumGP(a, r, N, M){ let answer; answer = a * SumGPUtil(r, N, M); answer = answer % M; document.write(answer);} // Driver Code // First element let a = 1; // Common difference let r = 4; // Number of elements let N = 10000; // Mod value let M = 100000; SumGP(a, r, N, M); </script>",
"e": 6460,
"s": 5444,
"text": null
},
{
"code": null,
"e": 6466,
"s": 6460,
"text": "12501"
},
{
"code": null,
"e": 6494,
"s": 6468,
"text": "Time complexity: O(log N)"
},
{
"code": null,
"e": 6517,
"s": 6494,
"text": "Auxiliary Space: O(1) "
},
{
"code": null,
"e": 6527,
"s": 6517,
"text": "sanjoy_62"
},
{
"code": null,
"e": 6537,
"s": 6527,
"text": "splevel62"
},
{
"code": null,
"e": 6551,
"s": 6537,
"text": "sumitgumber28"
},
{
"code": null,
"e": 6567,
"s": 6551,
"text": "rishavmahato348"
},
{
"code": null,
"e": 6584,
"s": 6567,
"text": "arorakashish0911"
},
{
"code": null,
"e": 6595,
"s": 6584,
"text": "Algorithms"
},
{
"code": null,
"e": 6604,
"s": 6595,
"text": "Analysis"
},
{
"code": null,
"e": 6628,
"s": 6604,
"text": "Competitive Programming"
},
{
"code": null,
"e": 6641,
"s": 6628,
"text": "Mathematical"
},
{
"code": null,
"e": 6651,
"s": 6641,
"text": "Recursion"
},
{
"code": null,
"e": 6664,
"s": 6651,
"text": "Mathematical"
},
{
"code": null,
"e": 6674,
"s": 6664,
"text": "Recursion"
},
{
"code": null,
"e": 6685,
"s": 6674,
"text": "Algorithms"
},
{
"code": null,
"e": 6783,
"s": 6685,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6808,
"s": 6783,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 6857,
"s": 6808,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 6895,
"s": 6857,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 6931,
"s": 6895,
"text": "CPU Scheduling in Operating Systems"
},
{
"code": null,
"e": 6982,
"s": 6931,
"text": "Understanding Time Complexity with Simple Examples"
},
{
"code": null,
"e": 7033,
"s": 6982,
"text": "Understanding Time Complexity with Simple Examples"
},
{
"code": null,
"e": 7070,
"s": 7033,
"text": "Time Complexity and Space Complexity"
},
{
"code": null,
"e": 7117,
"s": 7070,
"text": "Practice Questions on Time Complexity Analysis"
},
{
"code": null,
"e": 7180,
"s": 7117,
"text": "Analysis of Algorithms | Set 2 (Worst, Average and Best Cases)"
}
] |
OpenCV | Motion Blur in Python
|
26 Aug, 2019
This article explains how to add blur to an image using OpenCV. Motion blur is a specific type of blur used to lend a directed blur effect to images.
The Motion Blur FilterApplying motion blur to an image boils down to convolving a filter across the image. Sample 5*5 filter filters are given below.
Vertical:
Horizontal:
The greater the size of the filter, the greater will be the motion blur effect. Further, the direction of 1βs across the filter grid is the direction of the desired motion. To customize a motion blur in a specific vector direction, e.g. diagonally, simply place the 1βs along the vector to create the filter.
CodeConsider the following image of a car.
Code: Python code for applying a motion blur effect on the image.
# loading libraryimport cv2import numpy as np img = cv2.imread('car.jpg') # Specify the kernel size.# The greater the size, the more the motion.kernel_size = 30 # Create the vertical kernel.kernel_v = np.zeros((kernel_size, kernel_size)) # Create a copy of the same for creating the horizontal kernel.kernel_h = np.copy(kernel_v) # Fill the middle row with ones.kernel_v[:, int((kernel_size - 1)/2)] = np.ones(kernel_size)kernel_h[int((kernel_size - 1)/2), :] = np.ones(kernel_size) # Normalize.kernel_v /= kernel_sizekernel_h /= kernel_size # Apply the vertical kernel.vertical_mb = cv2.filter2D(img, -1, kernel_v) # Apply the horizontal kernel.horizonal_mb = cv2.filter2D(img, -1, kernel_h) # Save the outputs.cv2.imwrite('car_vertical.jpg', vertical_mb)cv2.imwrite('car_horizontal.jpg', horizonal_mb)
Output
Vertical Blur:
Horizontal Blur:
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
How to Install PIP on Windows ?
Python String | replace()
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Iterate over a list in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Aug, 2019"
},
{
"code": null,
"e": 178,
"s": 28,
"text": "This article explains how to add blur to an image using OpenCV. Motion blur is a specific type of blur used to lend a directed blur effect to images."
},
{
"code": null,
"e": 328,
"s": 178,
"text": "The Motion Blur FilterApplying motion blur to an image boils down to convolving a filter across the image. Sample 5*5 filter filters are given below."
},
{
"code": null,
"e": 338,
"s": 328,
"text": "Vertical:"
},
{
"code": null,
"e": 350,
"s": 338,
"text": "Horizontal:"
},
{
"code": null,
"e": 659,
"s": 350,
"text": "The greater the size of the filter, the greater will be the motion blur effect. Further, the direction of 1βs across the filter grid is the direction of the desired motion. To customize a motion blur in a specific vector direction, e.g. diagonally, simply place the 1βs along the vector to create the filter."
},
{
"code": null,
"e": 702,
"s": 659,
"text": "CodeConsider the following image of a car."
},
{
"code": null,
"e": 768,
"s": 702,
"text": "Code: Python code for applying a motion blur effect on the image."
},
{
"code": "# loading libraryimport cv2import numpy as np img = cv2.imread('car.jpg') # Specify the kernel size.# The greater the size, the more the motion.kernel_size = 30 # Create the vertical kernel.kernel_v = np.zeros((kernel_size, kernel_size)) # Create a copy of the same for creating the horizontal kernel.kernel_h = np.copy(kernel_v) # Fill the middle row with ones.kernel_v[:, int((kernel_size - 1)/2)] = np.ones(kernel_size)kernel_h[int((kernel_size - 1)/2), :] = np.ones(kernel_size) # Normalize.kernel_v /= kernel_sizekernel_h /= kernel_size # Apply the vertical kernel.vertical_mb = cv2.filter2D(img, -1, kernel_v) # Apply the horizontal kernel.horizonal_mb = cv2.filter2D(img, -1, kernel_h) # Save the outputs.cv2.imwrite('car_vertical.jpg', vertical_mb)cv2.imwrite('car_horizontal.jpg', horizonal_mb)",
"e": 1581,
"s": 768,
"text": null
},
{
"code": null,
"e": 1588,
"s": 1581,
"text": "Output"
},
{
"code": null,
"e": 1603,
"s": 1588,
"text": "Vertical Blur:"
},
{
"code": null,
"e": 1620,
"s": 1603,
"text": "Horizontal Blur:"
},
{
"code": null,
"e": 1627,
"s": 1620,
"text": "Python"
},
{
"code": null,
"e": 1725,
"s": 1627,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1743,
"s": 1725,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1785,
"s": 1743,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1807,
"s": 1785,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1842,
"s": 1807,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 1874,
"s": 1842,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1900,
"s": 1874,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1929,
"s": 1900,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 1956,
"s": 1929,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1977,
"s": 1956,
"text": "Python OOPs Concepts"
}
] |
PyQt5 β How to delete all the items in ComboBox ?
|
22 Apr, 2020
In this article we will see how we can clear all the items in the combo box. We know we can add items in the combo box with the help of addItem method to add single item and addItems method to add multiple items. In order to delete all the items in the combo box we will use clear method.
Syntax : combo_box.clear()
Argument : It takes no argument
Action performed : It will delete all the items of combo box
Steps for implementation:
1. Create a combo box2. Add items to combo box3. Create push button4. Add action to the push button5. Inside the action delete the items of combo box with the help of clear method
Below is the implementation β
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating a combo box widget self.combo_box = QComboBox(self) # setting geometry of combo box self.combo_box.setGeometry(200, 150, 120, 30) # geek list geek_list = ["Geek", "Geeky Geek", "Legend Geek", "Ultra Legend Geek"] # adding list of items to combo box self.combo_box.addItems(geek_list) # creating push button to clear the list button = QPushButton("Clear", self) # adding action to button button.pressed.connect(self.delete) def delete(self): # delete items of list self.combo_box.clear() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
Python PyQt5-ComboBox
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Apr, 2020"
},
{
"code": null,
"e": 317,
"s": 28,
"text": "In this article we will see how we can clear all the items in the combo box. We know we can add items in the combo box with the help of addItem method to add single item and addItems method to add multiple items. In order to delete all the items in the combo box we will use clear method."
},
{
"code": null,
"e": 344,
"s": 317,
"text": "Syntax : combo_box.clear()"
},
{
"code": null,
"e": 376,
"s": 344,
"text": "Argument : It takes no argument"
},
{
"code": null,
"e": 437,
"s": 376,
"text": "Action performed : It will delete all the items of combo box"
},
{
"code": null,
"e": 463,
"s": 437,
"text": "Steps for implementation:"
},
{
"code": null,
"e": 643,
"s": 463,
"text": "1. Create a combo box2. Add items to combo box3. Create push button4. Add action to the push button5. Inside the action delete the items of combo box with the help of clear method"
},
{
"code": null,
"e": 673,
"s": 643,
"text": "Below is the implementation β"
},
{
"code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating a combo box widget self.combo_box = QComboBox(self) # setting geometry of combo box self.combo_box.setGeometry(200, 150, 120, 30) # geek list geek_list = [\"Geek\", \"Geeky Geek\", \"Legend Geek\", \"Ultra Legend Geek\"] # adding list of items to combo box self.combo_box.addItems(geek_list) # creating push button to clear the list button = QPushButton(\"Clear\", self) # adding action to button button.pressed.connect(self.delete) def delete(self): # delete items of list self.combo_box.clear() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 1949,
"s": 673,
"text": null
},
{
"code": null,
"e": 1958,
"s": 1949,
"text": "Output :"
},
{
"code": null,
"e": 1980,
"s": 1958,
"text": "Python PyQt5-ComboBox"
},
{
"code": null,
"e": 1991,
"s": 1980,
"text": "Python-gui"
},
{
"code": null,
"e": 2003,
"s": 1991,
"text": "Python-PyQt"
},
{
"code": null,
"e": 2010,
"s": 2003,
"text": "Python"
}
] |
JavaFx | ColorPicker with examples
|
14 Nov, 2019
ColorPicker is a part of JavaFX. ColorPicker allows the user to choose a color from given set of colors or make their own custom color. An initial Color can be set using the setValue() function or defining it in a constructor and the color selected by the user can be found using the getValue() function.An Action event is generated when the user selects a color from the color picker. This event can be handled using an event handler.
ColorPicker appearance can be controlled in three ways:
A simple button mode
A menu button mode
A split menu button mode
Constructor of the class are:
ColorPicker():Creates a default ColorPicker instance with a selected color set to white.ColorPicker(Color c):Creates a ColorPicker instance and sets the selected color to the given color.
ColorPicker():Creates a default ColorPicker instance with a selected color set to white.
ColorPicker(Color c):Creates a ColorPicker instance and sets the selected color to the given color.
Commonly used methods:
Below programs will illustrate the use of color picker:
Program to create a color picker and add it to the stage: This program creates a ColorPicker indicated by the name cp. The color picker will be created inside a scene, which in turn will be hosted inside a stage (which is the top level JavaFX container). The function setTitle() is used to provide title to the stage.Then a tile-pane is created, on which addChildren() method is called to attach the color picker inside the scene, along with the resolution specified by (200, 200) in the code. Finally, the show() method is called to display the final results.// Java Program to create a color picker and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.collections.*;import javafx.stage.Stage;import javafx.scene.text.Text.*;import javafx.scene.paint.*;import javafx.scene.text.*;public class colorpicker extends Application { // labels Label l; // launch the application public void start(Stage s) { // set title for the stage s.setTitle("creating color picker"); // create a tile pane TilePane r = new TilePane(); // create a label l = new Label("This is a color picker example "); // create a color picker ColorPicker cp = new ColorPicker(Color.BLUE); // add label r.getChildren().add(l); r.getChildren().add(cp); // create a scene Scene sc = new Scene(r, 200, 200); // set the scene s.setScene(sc); s.show(); } public static void main(String args[]) { // launch the application launch(args); }}Output:Program to create color picker of three different appearance: This program creates a ColorPicker indicated by the name cp, cp1, cp2. cp will have the appearance of menu button, cp1 will have the appearance of button and cp2 will have the appearance of the split button. The color pickers will be created inside a scene, which in turn will be hosted inside a stage (which is the top level JavaFX container). The function setTitle() is used to provide title to the stage. Then a tile-pane is created, on which addChildren() method is called to attach the color picker inside the scene, along with the resolution specified by (200, 200) in the code. Finally, the show() method is called to display the final results.// Java Program to create color picker of three different appearanceimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.collections.*;import javafx.stage.Stage;import javafx.scene.text.Text.*;import javafx.scene.paint.*;import javafx.scene.text.*;public class colorpicker_1 extends Application { // labels Label l; // launch the application public void start(Stage s) { // set title for the stage s.setTitle("creating color picker"); // create a tile pane TilePane r = new TilePane(); // create a label l = new Label("This is a color picker example "); // create a color picker ColorPicker cp = new ColorPicker(Color.BLUE); // create a color picker ColorPicker cp1 = new ColorPicker(Color.BLUE); // set the appearance of color picker to button cp1.getStyleClass().add("button"); // create a color picker ColorPicker cp2 = new ColorPicker(Color.BLUE); // set the appearance of color picker to split button cp2.getStyleClass().add("split-button"); // add label r.getChildren().add(l); r.getChildren().add(cp); r.getChildren().add(cp1); r.getChildren().add(cp2); // create a scene Scene sc = new Scene(r, 200, 200); // set the scene s.setScene(sc); s.show(); } public static void main(String args[]) { // launch the application launch(args); }}Output:Program to create color picker and add a listener to it: This program creates a ColorPicker indicated by the name cp .we will create an event hab=ndler and a label l2 that will show the color selected by the user. The event handler will handle the events of the colorpicker and will set the text of the label l2 to the RGB value of the color selected. The event will be associated with the color picker using setOnAction() method. The color pickers will be created inside a scene, which in turn will be hosted inside a stage (which is the top level JavaFX container). The function setTitle() is used to provide title to the stage. Then a tile-pane is created, on which addChildren() method is called to attach the color picker inside the scene, along with the resolution specified by (200, 200) in the code. Finally, the show() method is called to display the final results.// Java Program to create color picker and add listener to itimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.collections.*;import javafx.stage.Stage;import javafx.scene.text.Text.*;import javafx.scene.paint.*;import javafx.scene.text.*;public class colorpicker_2 extends Application { // labels Label l; // launch the application public void start(Stage s) { // set title for the stage s.setTitle("creating color picker"); // create a tile pane TilePane r = new TilePane(); // create a label l = new Label("This is a color picker example "); Label l1 = new Label("no selected color "); // create a color picker ColorPicker cp = new ColorPicker(); // create a event handler EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { // color Color c = cp.getValue(); // set text of the label to RGB value of color l1.setText("Red = " + c.getRed() + ", Green = " + c.getGreen() + ", Blue = " + c.getBlue()); } }; // set listener cp.setOnAction(event); // add label r.getChildren().add(l); r.getChildren().add(cp); r.getChildren().add(l1); // create a scene Scene sc = new Scene(r, 500, 200); // set the scene s.setScene(sc); s.show(); } public static void main(String args[]) { // launch the application launch(args); }}Output:Note: The above programs might not run in an online IDE please use an offline compiler.Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/ColorPicker.htmlMy Personal Notes
arrow_drop_upSave
Program to create a color picker and add it to the stage: This program creates a ColorPicker indicated by the name cp. The color picker will be created inside a scene, which in turn will be hosted inside a stage (which is the top level JavaFX container). The function setTitle() is used to provide title to the stage.Then a tile-pane is created, on which addChildren() method is called to attach the color picker inside the scene, along with the resolution specified by (200, 200) in the code. Finally, the show() method is called to display the final results.// Java Program to create a color picker and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.collections.*;import javafx.stage.Stage;import javafx.scene.text.Text.*;import javafx.scene.paint.*;import javafx.scene.text.*;public class colorpicker extends Application { // labels Label l; // launch the application public void start(Stage s) { // set title for the stage s.setTitle("creating color picker"); // create a tile pane TilePane r = new TilePane(); // create a label l = new Label("This is a color picker example "); // create a color picker ColorPicker cp = new ColorPicker(Color.BLUE); // add label r.getChildren().add(l); r.getChildren().add(cp); // create a scene Scene sc = new Scene(r, 200, 200); // set the scene s.setScene(sc); s.show(); } public static void main(String args[]) { // launch the application launch(args); }}Output:
// Java Program to create a color picker and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.collections.*;import javafx.stage.Stage;import javafx.scene.text.Text.*;import javafx.scene.paint.*;import javafx.scene.text.*;public class colorpicker extends Application { // labels Label l; // launch the application public void start(Stage s) { // set title for the stage s.setTitle("creating color picker"); // create a tile pane TilePane r = new TilePane(); // create a label l = new Label("This is a color picker example "); // create a color picker ColorPicker cp = new ColorPicker(Color.BLUE); // add label r.getChildren().add(l); r.getChildren().add(cp); // create a scene Scene sc = new Scene(r, 200, 200); // set the scene s.setScene(sc); s.show(); } public static void main(String args[]) { // launch the application launch(args); }}
Output:
Program to create color picker of three different appearance: This program creates a ColorPicker indicated by the name cp, cp1, cp2. cp will have the appearance of menu button, cp1 will have the appearance of button and cp2 will have the appearance of the split button. The color pickers will be created inside a scene, which in turn will be hosted inside a stage (which is the top level JavaFX container). The function setTitle() is used to provide title to the stage. Then a tile-pane is created, on which addChildren() method is called to attach the color picker inside the scene, along with the resolution specified by (200, 200) in the code. Finally, the show() method is called to display the final results.// Java Program to create color picker of three different appearanceimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.collections.*;import javafx.stage.Stage;import javafx.scene.text.Text.*;import javafx.scene.paint.*;import javafx.scene.text.*;public class colorpicker_1 extends Application { // labels Label l; // launch the application public void start(Stage s) { // set title for the stage s.setTitle("creating color picker"); // create a tile pane TilePane r = new TilePane(); // create a label l = new Label("This is a color picker example "); // create a color picker ColorPicker cp = new ColorPicker(Color.BLUE); // create a color picker ColorPicker cp1 = new ColorPicker(Color.BLUE); // set the appearance of color picker to button cp1.getStyleClass().add("button"); // create a color picker ColorPicker cp2 = new ColorPicker(Color.BLUE); // set the appearance of color picker to split button cp2.getStyleClass().add("split-button"); // add label r.getChildren().add(l); r.getChildren().add(cp); r.getChildren().add(cp1); r.getChildren().add(cp2); // create a scene Scene sc = new Scene(r, 200, 200); // set the scene s.setScene(sc); s.show(); } public static void main(String args[]) { // launch the application launch(args); }}Output:
// Java Program to create color picker of three different appearanceimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.collections.*;import javafx.stage.Stage;import javafx.scene.text.Text.*;import javafx.scene.paint.*;import javafx.scene.text.*;public class colorpicker_1 extends Application { // labels Label l; // launch the application public void start(Stage s) { // set title for the stage s.setTitle("creating color picker"); // create a tile pane TilePane r = new TilePane(); // create a label l = new Label("This is a color picker example "); // create a color picker ColorPicker cp = new ColorPicker(Color.BLUE); // create a color picker ColorPicker cp1 = new ColorPicker(Color.BLUE); // set the appearance of color picker to button cp1.getStyleClass().add("button"); // create a color picker ColorPicker cp2 = new ColorPicker(Color.BLUE); // set the appearance of color picker to split button cp2.getStyleClass().add("split-button"); // add label r.getChildren().add(l); r.getChildren().add(cp); r.getChildren().add(cp1); r.getChildren().add(cp2); // create a scene Scene sc = new Scene(r, 200, 200); // set the scene s.setScene(sc); s.show(); } public static void main(String args[]) { // launch the application launch(args); }}
Output:
Program to create color picker and add a listener to it: This program creates a ColorPicker indicated by the name cp .we will create an event hab=ndler and a label l2 that will show the color selected by the user. The event handler will handle the events of the colorpicker and will set the text of the label l2 to the RGB value of the color selected. The event will be associated with the color picker using setOnAction() method. The color pickers will be created inside a scene, which in turn will be hosted inside a stage (which is the top level JavaFX container). The function setTitle() is used to provide title to the stage. Then a tile-pane is created, on which addChildren() method is called to attach the color picker inside the scene, along with the resolution specified by (200, 200) in the code. Finally, the show() method is called to display the final results.// Java Program to create color picker and add listener to itimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.collections.*;import javafx.stage.Stage;import javafx.scene.text.Text.*;import javafx.scene.paint.*;import javafx.scene.text.*;public class colorpicker_2 extends Application { // labels Label l; // launch the application public void start(Stage s) { // set title for the stage s.setTitle("creating color picker"); // create a tile pane TilePane r = new TilePane(); // create a label l = new Label("This is a color picker example "); Label l1 = new Label("no selected color "); // create a color picker ColorPicker cp = new ColorPicker(); // create a event handler EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { // color Color c = cp.getValue(); // set text of the label to RGB value of color l1.setText("Red = " + c.getRed() + ", Green = " + c.getGreen() + ", Blue = " + c.getBlue()); } }; // set listener cp.setOnAction(event); // add label r.getChildren().add(l); r.getChildren().add(cp); r.getChildren().add(l1); // create a scene Scene sc = new Scene(r, 500, 200); // set the scene s.setScene(sc); s.show(); } public static void main(String args[]) { // launch the application launch(args); }}Output:Note: The above programs might not run in an online IDE please use an offline compiler.Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/ColorPicker.htmlMy Personal Notes
arrow_drop_upSave
// Java Program to create color picker and add listener to itimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.collections.*;import javafx.stage.Stage;import javafx.scene.text.Text.*;import javafx.scene.paint.*;import javafx.scene.text.*;public class colorpicker_2 extends Application { // labels Label l; // launch the application public void start(Stage s) { // set title for the stage s.setTitle("creating color picker"); // create a tile pane TilePane r = new TilePane(); // create a label l = new Label("This is a color picker example "); Label l1 = new Label("no selected color "); // create a color picker ColorPicker cp = new ColorPicker(); // create a event handler EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { // color Color c = cp.getValue(); // set text of the label to RGB value of color l1.setText("Red = " + c.getRed() + ", Green = " + c.getGreen() + ", Blue = " + c.getBlue()); } }; // set listener cp.setOnAction(event); // add label r.getChildren().add(l); r.getChildren().add(cp); r.getChildren().add(l1); // create a scene Scene sc = new Scene(r, 500, 200); // set the scene s.setScene(sc); s.show(); } public static void main(String args[]) { // launch the application launch(args); }}
Output:
Note: The above programs might not run in an online IDE please use an offline compiler.Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/ColorPicker.html
ManasChhabra2
nidhi_biet
JavaFX
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
Stream In Java
ArrayList in Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
Stack Class in Java
Initialize an ArrayList in Java
Introduction to Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 Nov, 2019"
},
{
"code": null,
"e": 464,
"s": 28,
"text": "ColorPicker is a part of JavaFX. ColorPicker allows the user to choose a color from given set of colors or make their own custom color. An initial Color can be set using the setValue() function or defining it in a constructor and the color selected by the user can be found using the getValue() function.An Action event is generated when the user selects a color from the color picker. This event can be handled using an event handler."
},
{
"code": null,
"e": 520,
"s": 464,
"text": "ColorPicker appearance can be controlled in three ways:"
},
{
"code": null,
"e": 541,
"s": 520,
"text": "A simple button mode"
},
{
"code": null,
"e": 560,
"s": 541,
"text": "A menu button mode"
},
{
"code": null,
"e": 585,
"s": 560,
"text": "A split menu button mode"
},
{
"code": null,
"e": 615,
"s": 585,
"text": "Constructor of the class are:"
},
{
"code": null,
"e": 803,
"s": 615,
"text": "ColorPicker():Creates a default ColorPicker instance with a selected color set to white.ColorPicker(Color c):Creates a ColorPicker instance and sets the selected color to the given color."
},
{
"code": null,
"e": 892,
"s": 803,
"text": "ColorPicker():Creates a default ColorPicker instance with a selected color set to white."
},
{
"code": null,
"e": 992,
"s": 892,
"text": "ColorPicker(Color c):Creates a ColorPicker instance and sets the selected color to the given color."
},
{
"code": null,
"e": 1015,
"s": 992,
"text": "Commonly used methods:"
},
{
"code": null,
"e": 1071,
"s": 1015,
"text": "Below programs will illustrate the use of color picker:"
},
{
"code": null,
"e": 8063,
"s": 1071,
"text": "Program to create a color picker and add it to the stage: This program creates a ColorPicker indicated by the name cp. The color picker will be created inside a scene, which in turn will be hosted inside a stage (which is the top level JavaFX container). The function setTitle() is used to provide title to the stage.Then a tile-pane is created, on which addChildren() method is called to attach the color picker inside the scene, along with the resolution specified by (200, 200) in the code. Finally, the show() method is called to display the final results.// Java Program to create a color picker and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.collections.*;import javafx.stage.Stage;import javafx.scene.text.Text.*;import javafx.scene.paint.*;import javafx.scene.text.*;public class colorpicker extends Application { // labels Label l; // launch the application public void start(Stage s) { // set title for the stage s.setTitle(\"creating color picker\"); // create a tile pane TilePane r = new TilePane(); // create a label l = new Label(\"This is a color picker example \"); // create a color picker ColorPicker cp = new ColorPicker(Color.BLUE); // add label r.getChildren().add(l); r.getChildren().add(cp); // create a scene Scene sc = new Scene(r, 200, 200); // set the scene s.setScene(sc); s.show(); } public static void main(String args[]) { // launch the application launch(args); }}Output:Program to create color picker of three different appearance: This program creates a ColorPicker indicated by the name cp, cp1, cp2. cp will have the appearance of menu button, cp1 will have the appearance of button and cp2 will have the appearance of the split button. The color pickers will be created inside a scene, which in turn will be hosted inside a stage (which is the top level JavaFX container). The function setTitle() is used to provide title to the stage. Then a tile-pane is created, on which addChildren() method is called to attach the color picker inside the scene, along with the resolution specified by (200, 200) in the code. Finally, the show() method is called to display the final results.// Java Program to create color picker of three different appearanceimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.collections.*;import javafx.stage.Stage;import javafx.scene.text.Text.*;import javafx.scene.paint.*;import javafx.scene.text.*;public class colorpicker_1 extends Application { // labels Label l; // launch the application public void start(Stage s) { // set title for the stage s.setTitle(\"creating color picker\"); // create a tile pane TilePane r = new TilePane(); // create a label l = new Label(\"This is a color picker example \"); // create a color picker ColorPicker cp = new ColorPicker(Color.BLUE); // create a color picker ColorPicker cp1 = new ColorPicker(Color.BLUE); // set the appearance of color picker to button cp1.getStyleClass().add(\"button\"); // create a color picker ColorPicker cp2 = new ColorPicker(Color.BLUE); // set the appearance of color picker to split button cp2.getStyleClass().add(\"split-button\"); // add label r.getChildren().add(l); r.getChildren().add(cp); r.getChildren().add(cp1); r.getChildren().add(cp2); // create a scene Scene sc = new Scene(r, 200, 200); // set the scene s.setScene(sc); s.show(); } public static void main(String args[]) { // launch the application launch(args); }}Output:Program to create color picker and add a listener to it: This program creates a ColorPicker indicated by the name cp .we will create an event hab=ndler and a label l2 that will show the color selected by the user. The event handler will handle the events of the colorpicker and will set the text of the label l2 to the RGB value of the color selected. The event will be associated with the color picker using setOnAction() method. The color pickers will be created inside a scene, which in turn will be hosted inside a stage (which is the top level JavaFX container). The function setTitle() is used to provide title to the stage. Then a tile-pane is created, on which addChildren() method is called to attach the color picker inside the scene, along with the resolution specified by (200, 200) in the code. Finally, the show() method is called to display the final results.// Java Program to create color picker and add listener to itimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.collections.*;import javafx.stage.Stage;import javafx.scene.text.Text.*;import javafx.scene.paint.*;import javafx.scene.text.*;public class colorpicker_2 extends Application { // labels Label l; // launch the application public void start(Stage s) { // set title for the stage s.setTitle(\"creating color picker\"); // create a tile pane TilePane r = new TilePane(); // create a label l = new Label(\"This is a color picker example \"); Label l1 = new Label(\"no selected color \"); // create a color picker ColorPicker cp = new ColorPicker(); // create a event handler EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { // color Color c = cp.getValue(); // set text of the label to RGB value of color l1.setText(\"Red = \" + c.getRed() + \", Green = \" + c.getGreen() + \", Blue = \" + c.getBlue()); } }; // set listener cp.setOnAction(event); // add label r.getChildren().add(l); r.getChildren().add(cp); r.getChildren().add(l1); // create a scene Scene sc = new Scene(r, 500, 200); // set the scene s.setScene(sc); s.show(); } public static void main(String args[]) { // launch the application launch(args); }}Output:Note: The above programs might not run in an online IDE please use an offline compiler.Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/ColorPicker.htmlMy Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 9813,
"s": 8063,
"text": "Program to create a color picker and add it to the stage: This program creates a ColorPicker indicated by the name cp. The color picker will be created inside a scene, which in turn will be hosted inside a stage (which is the top level JavaFX container). The function setTitle() is used to provide title to the stage.Then a tile-pane is created, on which addChildren() method is called to attach the color picker inside the scene, along with the resolution specified by (200, 200) in the code. Finally, the show() method is called to display the final results.// Java Program to create a color picker and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.collections.*;import javafx.stage.Stage;import javafx.scene.text.Text.*;import javafx.scene.paint.*;import javafx.scene.text.*;public class colorpicker extends Application { // labels Label l; // launch the application public void start(Stage s) { // set title for the stage s.setTitle(\"creating color picker\"); // create a tile pane TilePane r = new TilePane(); // create a label l = new Label(\"This is a color picker example \"); // create a color picker ColorPicker cp = new ColorPicker(Color.BLUE); // add label r.getChildren().add(l); r.getChildren().add(cp); // create a scene Scene sc = new Scene(r, 200, 200); // set the scene s.setScene(sc); s.show(); } public static void main(String args[]) { // launch the application launch(args); }}Output:"
},
{
"code": "// Java Program to create a color picker and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.collections.*;import javafx.stage.Stage;import javafx.scene.text.Text.*;import javafx.scene.paint.*;import javafx.scene.text.*;public class colorpicker extends Application { // labels Label l; // launch the application public void start(Stage s) { // set title for the stage s.setTitle(\"creating color picker\"); // create a tile pane TilePane r = new TilePane(); // create a label l = new Label(\"This is a color picker example \"); // create a color picker ColorPicker cp = new ColorPicker(Color.BLUE); // add label r.getChildren().add(l); r.getChildren().add(cp); // create a scene Scene sc = new Scene(r, 200, 200); // set the scene s.setScene(sc); s.show(); } public static void main(String args[]) { // launch the application launch(args); }}",
"e": 10996,
"s": 9813,
"text": null
},
{
"code": null,
"e": 11004,
"s": 10996,
"text": "Output:"
},
{
"code": null,
"e": 13366,
"s": 11004,
"text": "Program to create color picker of three different appearance: This program creates a ColorPicker indicated by the name cp, cp1, cp2. cp will have the appearance of menu button, cp1 will have the appearance of button and cp2 will have the appearance of the split button. The color pickers will be created inside a scene, which in turn will be hosted inside a stage (which is the top level JavaFX container). The function setTitle() is used to provide title to the stage. Then a tile-pane is created, on which addChildren() method is called to attach the color picker inside the scene, along with the resolution specified by (200, 200) in the code. Finally, the show() method is called to display the final results.// Java Program to create color picker of three different appearanceimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.collections.*;import javafx.stage.Stage;import javafx.scene.text.Text.*;import javafx.scene.paint.*;import javafx.scene.text.*;public class colorpicker_1 extends Application { // labels Label l; // launch the application public void start(Stage s) { // set title for the stage s.setTitle(\"creating color picker\"); // create a tile pane TilePane r = new TilePane(); // create a label l = new Label(\"This is a color picker example \"); // create a color picker ColorPicker cp = new ColorPicker(Color.BLUE); // create a color picker ColorPicker cp1 = new ColorPicker(Color.BLUE); // set the appearance of color picker to button cp1.getStyleClass().add(\"button\"); // create a color picker ColorPicker cp2 = new ColorPicker(Color.BLUE); // set the appearance of color picker to split button cp2.getStyleClass().add(\"split-button\"); // add label r.getChildren().add(l); r.getChildren().add(cp); r.getChildren().add(cp1); r.getChildren().add(cp2); // create a scene Scene sc = new Scene(r, 200, 200); // set the scene s.setScene(sc); s.show(); } public static void main(String args[]) { // launch the application launch(args); }}Output:"
},
{
"code": "// Java Program to create color picker of three different appearanceimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.collections.*;import javafx.stage.Stage;import javafx.scene.text.Text.*;import javafx.scene.paint.*;import javafx.scene.text.*;public class colorpicker_1 extends Application { // labels Label l; // launch the application public void start(Stage s) { // set title for the stage s.setTitle(\"creating color picker\"); // create a tile pane TilePane r = new TilePane(); // create a label l = new Label(\"This is a color picker example \"); // create a color picker ColorPicker cp = new ColorPicker(Color.BLUE); // create a color picker ColorPicker cp1 = new ColorPicker(Color.BLUE); // set the appearance of color picker to button cp1.getStyleClass().add(\"button\"); // create a color picker ColorPicker cp2 = new ColorPicker(Color.BLUE); // set the appearance of color picker to split button cp2.getStyleClass().add(\"split-button\"); // add label r.getChildren().add(l); r.getChildren().add(cp); r.getChildren().add(cp1); r.getChildren().add(cp2); // create a scene Scene sc = new Scene(r, 200, 200); // set the scene s.setScene(sc); s.show(); } public static void main(String args[]) { // launch the application launch(args); }}",
"e": 15008,
"s": 13366,
"text": null
},
{
"code": null,
"e": 15016,
"s": 15008,
"text": "Output:"
},
{
"code": null,
"e": 17898,
"s": 15016,
"text": "Program to create color picker and add a listener to it: This program creates a ColorPicker indicated by the name cp .we will create an event hab=ndler and a label l2 that will show the color selected by the user. The event handler will handle the events of the colorpicker and will set the text of the label l2 to the RGB value of the color selected. The event will be associated with the color picker using setOnAction() method. The color pickers will be created inside a scene, which in turn will be hosted inside a stage (which is the top level JavaFX container). The function setTitle() is used to provide title to the stage. Then a tile-pane is created, on which addChildren() method is called to attach the color picker inside the scene, along with the resolution specified by (200, 200) in the code. Finally, the show() method is called to display the final results.// Java Program to create color picker and add listener to itimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.collections.*;import javafx.stage.Stage;import javafx.scene.text.Text.*;import javafx.scene.paint.*;import javafx.scene.text.*;public class colorpicker_2 extends Application { // labels Label l; // launch the application public void start(Stage s) { // set title for the stage s.setTitle(\"creating color picker\"); // create a tile pane TilePane r = new TilePane(); // create a label l = new Label(\"This is a color picker example \"); Label l1 = new Label(\"no selected color \"); // create a color picker ColorPicker cp = new ColorPicker(); // create a event handler EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { // color Color c = cp.getValue(); // set text of the label to RGB value of color l1.setText(\"Red = \" + c.getRed() + \", Green = \" + c.getGreen() + \", Blue = \" + c.getBlue()); } }; // set listener cp.setOnAction(event); // add label r.getChildren().add(l); r.getChildren().add(cp); r.getChildren().add(l1); // create a scene Scene sc = new Scene(r, 500, 200); // set the scene s.setScene(sc); s.show(); } public static void main(String args[]) { // launch the application launch(args); }}Output:Note: The above programs might not run in an online IDE please use an offline compiler.Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/ColorPicker.htmlMy Personal Notes\narrow_drop_upSave"
},
{
"code": "// Java Program to create color picker and add listener to itimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.collections.*;import javafx.stage.Stage;import javafx.scene.text.Text.*;import javafx.scene.paint.*;import javafx.scene.text.*;public class colorpicker_2 extends Application { // labels Label l; // launch the application public void start(Stage s) { // set title for the stage s.setTitle(\"creating color picker\"); // create a tile pane TilePane r = new TilePane(); // create a label l = new Label(\"This is a color picker example \"); Label l1 = new Label(\"no selected color \"); // create a color picker ColorPicker cp = new ColorPicker(); // create a event handler EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { // color Color c = cp.getValue(); // set text of the label to RGB value of color l1.setText(\"Red = \" + c.getRed() + \", Green = \" + c.getGreen() + \", Blue = \" + c.getBlue()); } }; // set listener cp.setOnAction(event); // add label r.getChildren().add(l); r.getChildren().add(cp); r.getChildren().add(l1); // create a scene Scene sc = new Scene(r, 500, 200); // set the scene s.setScene(sc); s.show(); } public static void main(String args[]) { // launch the application launch(args); }}",
"e": 19685,
"s": 17898,
"text": null
},
{
"code": null,
"e": 19693,
"s": 19685,
"text": "Output:"
},
{
"code": null,
"e": 19873,
"s": 19693,
"text": "Note: The above programs might not run in an online IDE please use an offline compiler.Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/ColorPicker.html"
},
{
"code": null,
"e": 19887,
"s": 19873,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 19898,
"s": 19887,
"text": "nidhi_biet"
},
{
"code": null,
"e": 19905,
"s": 19898,
"text": "JavaFX"
},
{
"code": null,
"e": 19910,
"s": 19905,
"text": "Java"
},
{
"code": null,
"e": 19915,
"s": 19910,
"text": "Java"
},
{
"code": null,
"e": 20013,
"s": 19915,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 20032,
"s": 20013,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 20047,
"s": 20032,
"text": "Stream In Java"
},
{
"code": null,
"e": 20065,
"s": 20047,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 20085,
"s": 20065,
"text": "Collections in Java"
},
{
"code": null,
"e": 20109,
"s": 20085,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 20141,
"s": 20109,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 20153,
"s": 20141,
"text": "Set in Java"
},
{
"code": null,
"e": 20173,
"s": 20153,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 20205,
"s": 20173,
"text": "Initialize an ArrayList in Java"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.