title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Python Program for compound interest
| 16 Jun, 2022
Let us prior discuss the formula for compound interest. The formula to calculate compound interest annually is given by:
A = P(1 + R/100) t
Compound Interest = A - P
Where, A is amount P is the principal amount R is the rate and T is the time span
Example:
Input : Principle (amount): 1200
Time: 2
Rate: 5.4
Output : Compound Interest = 133.099243
Example
Python3
# Python3 program to find compound
# interest for given values.
def compound_interest(principle, rate, time):
# Calculates compound interest
Amount = principle * (pow((1 + rate / 100), time))
CI = Amount - principle
print("Compound interest is", CI)
# Driver Code
compound_interest(10000, 10.25, 5)
Compound interest is 6288.946267774416
Method 2: Finding compound interest of given values without using pow() function.
Python3
# Python code
# To find compound interest
# inputs
p= 1200 # principle amount
t= 2 # time
r= 5.4 # rate
# calculates the compound interest
a=p*(1+(r/100))**t # formula for calculating amount
ci=a-p # compound interest = amount - principal amount
# printing compound interest value
print(ci)
133.0992000000001
Time complexity: O(1)
Auxiliary Space: O(1)
Please refer complete article on Program to find compound interest for more details!
shivikapriya
wrestlemania(wwe)
laxmigangarajula03
hasani
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 57,
"s": 26,
"text": " \n16 Jun, 2022\n"
},
{
"code": null,
"e": 179,
"s": 57,
"text": "Let us prior discuss the formula for compound interest. The formula to calculate compound interest annually is given by: "
},
{
"code": null,
"e": 226,
"s": 179,
"text": "A = P(1 + R/100) t \nCompound Interest = A - P "
},
{
"code": null,
"e": 308,
"s": 226,
"text": "Where, A is amount P is the principal amount R is the rate and T is the time span"
},
{
"code": null,
"e": 318,
"s": 308,
"text": "Example: "
},
{
"code": null,
"e": 425,
"s": 318,
"text": "Input : Principle (amount): 1200\n Time: 2\n Rate: 5.4\nOutput : Compound Interest = 133.099243"
},
{
"code": null,
"e": 433,
"s": 425,
"text": "Example"
},
{
"code": null,
"e": 441,
"s": 433,
"text": "Python3"
},
{
"code": "\n\n\n\n\n\n\n# Python3 program to find compound\n# interest for given values.\n \n \ndef compound_interest(principle, rate, time):\n \n # Calculates compound interest\n Amount = principle * (pow((1 + rate / 100), time))\n CI = Amount - principle\n print(\"Compound interest is\", CI)\n \n \n# Driver Code\ncompound_interest(10000, 10.25, 5)\n\n\n\n\n\n",
"e": 789,
"s": 451,
"text": null
},
{
"code": null,
"e": 828,
"s": 789,
"text": "Compound interest is 6288.946267774416"
},
{
"code": null,
"e": 911,
"s": 828,
"text": "Method 2: Finding compound interest of given values without using pow() function."
},
{
"code": null,
"e": 919,
"s": 911,
"text": "Python3"
},
{
"code": "\n\n\n\n\n\n\n# Python code\n# To find compound interest \n \n# inputs \np= 1200 # principle amount \nt= 2 # time \nr= 5.4 # rate \n# calculates the compound interest\na=p*(1+(r/100))**t # formula for calculating amount \nci=a-p # compound interest = amount - principal amount\n# printing compound interest value\nprint(ci)\n\n\n\n\n\n",
"e": 1253,
"s": 929,
"text": null
},
{
"code": null,
"e": 1271,
"s": 1253,
"text": "133.0992000000001"
},
{
"code": null,
"e": 1293,
"s": 1271,
"text": "Time complexity: O(1)"
},
{
"code": null,
"e": 1315,
"s": 1293,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 1400,
"s": 1315,
"text": "Please refer complete article on Program to find compound interest for more details!"
},
{
"code": null,
"e": 1413,
"s": 1400,
"text": "shivikapriya"
},
{
"code": null,
"e": 1431,
"s": 1413,
"text": "wrestlemania(wwe)"
},
{
"code": null,
"e": 1450,
"s": 1431,
"text": "laxmigangarajula03"
},
{
"code": null,
"e": 1457,
"s": 1450,
"text": "hasani"
},
{
"code": null,
"e": 1475,
"s": 1457,
"text": "\nPython Programs\n"
}
] |
Python | Finding frequency in list of tuples | 28 Feb, 2019
In python we need to handle various forms of data and one among them is list of tuples in which we may have to perform any kind of operation. This particular article discusses the ways of finding the frequency of the 1st element in list of tuple which can be extended to any index. Let’s discuss certain ways in which this can be performed.
Method #1 : Using map() + count()The map function can be used to accumulate the indices of all the tuples in a list and the task of counting the frequency can be done using the generic count function of python library.
# Python3 code to demonstrate# finding frequency in list of tuples# using map() + count() # initializing list of tuplestest_list = [('Geeks', 1), ('for', 2), ('Geeks', 3)] # printing the original listprint ("The original list is : " + str(test_list)) # using map() + count()# finding frequency in list of tuples res = list(map(lambda i : i[0], test_list)).count('Geeks') # printing resultprint ("The frequency of element is : " + str(res))
The original list is : [('Geeks', 1), ('for', 2), ('Geeks', 3)]
The frequency of element is : 2
Method #2 : Using Counter() + list comprehensionList comprehension performs the task of getting the first element of the tuples and the counting part is handled by Counter function of collection library.
# Python3 code to demonstrate# finding frequency in list of tuples# using Counter() + list comprehensionfrom collections import Counter # initializing list of tuplestest_list = [('Geeks', 1), ('for', 2), ('Geeks', 3)] # printing the original listprint ("The original list is : " + str(test_list)) # using Counter() + list comprehension# finding frequency in list of tuples res = Counter(i[0] for i in test_list) # printing resultprint ("The frequency of element is : " + str(res['Geeks']))
The original list is : [('Geeks', 1), ('for', 2), ('Geeks', 3)]
The frequency of element is : 2
Python list-programs
Python tuple-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Feb, 2019"
},
{
"code": null,
"e": 369,
"s": 28,
"text": "In python we need to handle various forms of data and one among them is list of tuples in which we may have to perform any kind of operation. This particular article discusses the ways of finding the frequency of the 1st element in list of tuple which can be extended to any index. Let’s discuss certain ways in which this can be performed."
},
{
"code": null,
"e": 588,
"s": 369,
"text": "Method #1 : Using map() + count()The map function can be used to accumulate the indices of all the tuples in a list and the task of counting the frequency can be done using the generic count function of python library."
},
{
"code": "# Python3 code to demonstrate# finding frequency in list of tuples# using map() + count() # initializing list of tuplestest_list = [('Geeks', 1), ('for', 2), ('Geeks', 3)] # printing the original listprint (\"The original list is : \" + str(test_list)) # using map() + count()# finding frequency in list of tuples res = list(map(lambda i : i[0], test_list)).count('Geeks') # printing resultprint (\"The frequency of element is : \" + str(res))",
"e": 1032,
"s": 588,
"text": null
},
{
"code": null,
"e": 1129,
"s": 1032,
"text": "The original list is : [('Geeks', 1), ('for', 2), ('Geeks', 3)]\nThe frequency of element is : 2\n"
},
{
"code": null,
"e": 1334,
"s": 1129,
"text": " Method #2 : Using Counter() + list comprehensionList comprehension performs the task of getting the first element of the tuples and the counting part is handled by Counter function of collection library."
},
{
"code": "# Python3 code to demonstrate# finding frequency in list of tuples# using Counter() + list comprehensionfrom collections import Counter # initializing list of tuplestest_list = [('Geeks', 1), ('for', 2), ('Geeks', 3)] # printing the original listprint (\"The original list is : \" + str(test_list)) # using Counter() + list comprehension# finding frequency in list of tuples res = Counter(i[0] for i in test_list) # printing resultprint (\"The frequency of element is : \" + str(res['Geeks']))",
"e": 1828,
"s": 1334,
"text": null
},
{
"code": null,
"e": 1925,
"s": 1828,
"text": "The original list is : [('Geeks', 1), ('for', 2), ('Geeks', 3)]\nThe frequency of element is : 2\n"
},
{
"code": null,
"e": 1946,
"s": 1925,
"text": "Python list-programs"
},
{
"code": null,
"e": 1968,
"s": 1946,
"text": "Python tuple-programs"
},
{
"code": null,
"e": 1975,
"s": 1968,
"text": "Python"
},
{
"code": null,
"e": 1991,
"s": 1975,
"text": "Python Programs"
}
] |
MongoDB – Increment Operator ( $inc ) | 19 Apr, 2020
MongoDB provides different types of field update operators to update the values of the fields of the documents and $inc operator is one of them. This operator is used to increase the values of the fields to the specified amount or to increase the field by the given value.
You can also use this operator in embedded/nested documents. You can use this operator in methods like update(), updateOne() etc. according to your requirements.
This operator accepts positive and negative values.
If the given field does not exist, then this operator will create field and set the value of that field.
This operator will generate an error, if you use this operator with null value field.
It is an atomic operation in a single document.
Syntax:
{ $inc: { field1: amount1, field2: amount2, ... } }
In the following examples, we are working with:
Database: GeeksforGeeksCollection: contributorDocument: three documents that contain the details of the contributors in the form of field-value pairs.
In this example, we are updating the fields of an employee’s document whose name is Mohit by incrementing the value of publish articles field to 10 and decreasing the value of the salary field to -100.
db.contributor.update({name: "Mohit"}, {$inc: {publisharticles: 10, salary: -100}})
In this example, we are updating the field of an employee’s document whose name is Mohit by incrementing the value of a field to 10.
db.contributor.update({name: "Priya", "points._id": "g_1"}, {$inc: {"points.$.a":10}})
In this example, we are updating the field of an employee’s document whose name is Mohit by incrementing the value of a rank to 2.
db.contributor.update({name: "Amu"}, {$inc: {"personal.rank": 2}})
MongoDB
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": "\n19 Apr, 2020"
},
{
"code": null,
"e": 327,
"s": 54,
"text": "MongoDB provides different types of field update operators to update the values of the fields of the documents and $inc operator is one of them. This operator is used to increase the values of the fields to the specified amount or to increase the field by the given value."
},
{
"code": null,
"e": 489,
"s": 327,
"text": "You can also use this operator in embedded/nested documents. You can use this operator in methods like update(), updateOne() etc. according to your requirements."
},
{
"code": null,
"e": 541,
"s": 489,
"text": "This operator accepts positive and negative values."
},
{
"code": null,
"e": 646,
"s": 541,
"text": "If the given field does not exist, then this operator will create field and set the value of that field."
},
{
"code": null,
"e": 732,
"s": 646,
"text": "This operator will generate an error, if you use this operator with null value field."
},
{
"code": null,
"e": 780,
"s": 732,
"text": "It is an atomic operation in a single document."
},
{
"code": null,
"e": 788,
"s": 780,
"text": "Syntax:"
},
{
"code": null,
"e": 840,
"s": 788,
"text": "{ $inc: { field1: amount1, field2: amount2, ... } }"
},
{
"code": null,
"e": 888,
"s": 840,
"text": "In the following examples, we are working with:"
},
{
"code": null,
"e": 1039,
"s": 888,
"text": "Database: GeeksforGeeksCollection: contributorDocument: three documents that contain the details of the contributors in the form of field-value pairs."
},
{
"code": null,
"e": 1241,
"s": 1039,
"text": "In this example, we are updating the fields of an employee’s document whose name is Mohit by incrementing the value of publish articles field to 10 and decreasing the value of the salary field to -100."
},
{
"code": "db.contributor.update({name: \"Mohit\"}, {$inc: {publisharticles: 10, salary: -100}})",
"e": 1325,
"s": 1241,
"text": null
},
{
"code": null,
"e": 1458,
"s": 1325,
"text": "In this example, we are updating the field of an employee’s document whose name is Mohit by incrementing the value of a field to 10."
},
{
"code": "db.contributor.update({name: \"Priya\", \"points._id\": \"g_1\"}, {$inc: {\"points.$.a\":10}})",
"e": 1545,
"s": 1458,
"text": null
},
{
"code": null,
"e": 1676,
"s": 1545,
"text": "In this example, we are updating the field of an employee’s document whose name is Mohit by incrementing the value of a rank to 2."
},
{
"code": "db.contributor.update({name: \"Amu\"}, {$inc: {\"personal.rank\": 2}})",
"e": 1743,
"s": 1676,
"text": null
},
{
"code": null,
"e": 1751,
"s": 1743,
"text": "MongoDB"
},
{
"code": null,
"e": 1777,
"s": 1751,
"text": "Advanced Computer Subject"
}
] |
Iterate through List in Java | 08 Feb, 2022
Lists in java allow us to maintain an ordered collection of objects. Duplicate elements as well as null elements can also be stored in a List in Java. The List interface is a part of java.util package and it inherits the Collection interface. It preserves the order of insertion.
There are several ways to iterate over List in Java. They are discussed below:
Methods:
Using loops (Naive Approach)For loopFor-each loopWhile loopUsing IteratorUsing List iteratorUsing lambda expressionUsing stream.forEach()
Using loops (Naive Approach)For loopFor-each loopWhile loop
For loop
For-each loop
While loop
Using Iterator
Using List iterator
Using lambda expression
Using stream.forEach()
Method 1-A: Simple for loop
Each element can be accessed by iteration using a simple for loop. The index can be accessed using the index as a loop variable.
Syntax:
for (i = 0; i < list_name.size(); i++)
{
// code block to be executed
}
Example
Java
// Java Program to iterate over List// Using simple for loop // Importing all classes of// java.util packageimport java.util.*; // CLassclass GFG { // Main driver method public static void main(String args[]) { // Creating a ArrayList List<String> myList = new ArrayList<String>(); // Adding elements to the list // Custom inputs myList.add("A"); myList.add("B"); myList.add("C"); myList.add("D"); // For loop for iterating over the List for (int i = 0; i < myList.size(); i++) { // Print all elements of List System.out.println(myList.get(i)); } }}
A
B
C
D
Method 1-B: Enhanced for loop
Each element can be accessed by iteration using an enhanced for loop. This loop was introduced in J2SE 5.0. It is an alternative approach to traverse the for a loop. It makes the code more readable.
Syntax:
for(data_type variable : List_name)
{
// Body of the loop.
// Each element can be accessed using variable.
}
Java
// Java Program to Iterate over a List// using enhanced for loop (for-each) // Importing all classes of// java.util packageimport java.util.*; // Classclass GFG { // Main driver method public static void main(String args[]) { // Creating an Arraylist List<String> myList = new ArrayList<String>(); // Adding elements to the List // Custom inputs myList.add("A"); myList.add("B"); myList.add("C"); myList.add("D"); // Using enhanced for loop(for-each) for iteration for (String i : myList) { // Print all elements of ArrayList System.out.println(i); } }}
A
B
C
D
Method 1-C: Using a while loop
Iterating over a list can also be achieved using a while loop. The block of code inside the loop executes until the condition is true. A loop variable can be used as an index to access each element.
Syntax:
while(variable<list_name.size())
{
// Block of code to be executed
}
Java
// Java Program to iterate over a List// using while loop // Importing all classes of// java.util packageimport java.util.*; // Classclass GFG { // Main driver method public static void main(String args[]) { // Creating an ArrayList List<String> myList = new ArrayList<String>(); // Adding elements to the List // Custom inputs myList.add("A"); myList.add("B"); myList.add("C"); myList.add("D"); // Initializing any variable to 0 int i = 0; // If variable value is lesser than // value indicating size of List while (i < myList.size()) { // Print element of list System.out.println(myList.get(i)); // Increase variable count by 1 i++; } }}
A
B
C
D
Method 2: Using iterator
An iterator is an object in Java that allows iterating over elements of a collection. Each element in the list can be accessed using iterator with a while loop.
Syntax:
Iterator<data_type> variable = list_name.iterator();
Example
Java
// Java Program to iterate over the list// using iterator // Importing all classes of// java.util packageimport java.util.*; // Classclass GFG { // Main driver method public static void main(String args[]) { // Creating an ArrayList List<String> myList = new ArrayList<String>(); // Adding elements to the List // Custom inputs myList.add("A"); myList.add("B"); myList.add("C"); myList.add("D"); // Iterator Iterator<String> it = myList.iterator(); // Condition check for elements in List // using hasNext() method returning true till // there i single element in a List while (it.hasNext()) { // Print all elements of List System.out.println(it.next()); } }}
A
B
C
D
Method 3: Using List iterator
ListIterator is an iterator is a java which is available since the 1.2 version. It allows us to iterate elements one-by-one from a List implemented object. It is used to iterator over a list using while loop.
Syntax
ListIterator<data_type> variable = list_name.listIterator();
Java
// Java program to iterate over a list// using ListIteratorimport java.util.*; // Classclass GFG { // Main driver method public static void main(String args[]) { // Creating an ArrayList List<String> myList = new ArrayList<String>(); // Adding elements to the List // Custom inputs myList.add("A"); myList.add("B"); myList.add("C"); myList.add("D"); // List iterator ListIterator<String> it = myList.listIterator(); // Condition check whether there is element in List // using hasNext() which holds true till // there is single element in List while (it.hasNext()) { // Print all elements of List System.out.println(it.next()); } }}
A
B
C
D
Method 4: Using Iterable.forEach()
This feature is available since Java 8. It can also be used to iterate over a List. Iteration can be done using a lambda expression.
Syntax:
list_name.forEach(variable->{//block of code})
Java
// Java Program to iterate over a List// using forEach() // Importing all classes of// java.util methodimport java.util.*; // Classclass GFG { // Main driver method public static void main(String args[]) { // Creating an ArrayList List<String> myList = new ArrayList<String>(); // Adding elements to the List // Custom inputs myList.add("A"); myList.add("B"); myList.add("C"); myList.add("D"); // Lambda expression printing all elements in a List myList.forEach( (temp) -> { System.out.println(temp); }); }}
A
B
C
D
Method 5: Using Stream.forEach()
The processing order of stream().forEach() is undefined while in case of forEach(), it is defined. Both can be used to iterate over a List.
Syntax:
list_name.stream.forEach(variable->{//block of code})
Java
// Java Program iterating over a List// using stream.forEach() method // Importing all classes of// java.util methodimport java.util.*; // Classclass GFG { // Main driver method public static void main(String args[]) { // Creating an ArrayList List<String> myList = new ArrayList<String>(); // Adding elements to the List // Custom inputs myList.add("A"); myList.add("B"); myList.add("C"); myList.add("D"); // stream.forEach() method prints // all elements inside a List myList.stream().forEach( (temp) -> System.out.println(temp)); }}
A
B
C
D
surinderdawra388
singghakshay
rkbhola5
Java-Collections
java-list
Picked
Java
Java Programs
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Feb, 2022"
},
{
"code": null,
"e": 308,
"s": 28,
"text": "Lists in java allow us to maintain an ordered collection of objects. Duplicate elements as well as null elements can also be stored in a List in Java. The List interface is a part of java.util package and it inherits the Collection interface. It preserves the order of insertion."
},
{
"code": null,
"e": 387,
"s": 308,
"text": "There are several ways to iterate over List in Java. They are discussed below:"
},
{
"code": null,
"e": 396,
"s": 387,
"text": "Methods:"
},
{
"code": null,
"e": 534,
"s": 396,
"text": "Using loops (Naive Approach)For loopFor-each loopWhile loopUsing IteratorUsing List iteratorUsing lambda expressionUsing stream.forEach()"
},
{
"code": null,
"e": 594,
"s": 534,
"text": "Using loops (Naive Approach)For loopFor-each loopWhile loop"
},
{
"code": null,
"e": 603,
"s": 594,
"text": "For loop"
},
{
"code": null,
"e": 617,
"s": 603,
"text": "For-each loop"
},
{
"code": null,
"e": 628,
"s": 617,
"text": "While loop"
},
{
"code": null,
"e": 643,
"s": 628,
"text": "Using Iterator"
},
{
"code": null,
"e": 663,
"s": 643,
"text": "Using List iterator"
},
{
"code": null,
"e": 687,
"s": 663,
"text": "Using lambda expression"
},
{
"code": null,
"e": 710,
"s": 687,
"text": "Using stream.forEach()"
},
{
"code": null,
"e": 738,
"s": 710,
"text": "Method 1-A: Simple for loop"
},
{
"code": null,
"e": 867,
"s": 738,
"text": "Each element can be accessed by iteration using a simple for loop. The index can be accessed using the index as a loop variable."
},
{
"code": null,
"e": 875,
"s": 867,
"text": "Syntax:"
},
{
"code": null,
"e": 950,
"s": 875,
"text": "for (i = 0; i < list_name.size(); i++) \n{\n // code block to be executed\n}"
},
{
"code": null,
"e": 958,
"s": 950,
"text": "Example"
},
{
"code": null,
"e": 963,
"s": 958,
"text": "Java"
},
{
"code": "// Java Program to iterate over List// Using simple for loop // Importing all classes of// java.util packageimport java.util.*; // CLassclass GFG { // Main driver method public static void main(String args[]) { // Creating a ArrayList List<String> myList = new ArrayList<String>(); // Adding elements to the list // Custom inputs myList.add(\"A\"); myList.add(\"B\"); myList.add(\"C\"); myList.add(\"D\"); // For loop for iterating over the List for (int i = 0; i < myList.size(); i++) { // Print all elements of List System.out.println(myList.get(i)); } }}",
"e": 1628,
"s": 963,
"text": null
},
{
"code": null,
"e": 1636,
"s": 1628,
"text": "A\nB\nC\nD"
},
{
"code": null,
"e": 1666,
"s": 1636,
"text": "Method 1-B: Enhanced for loop"
},
{
"code": null,
"e": 1865,
"s": 1666,
"text": "Each element can be accessed by iteration using an enhanced for loop. This loop was introduced in J2SE 5.0. It is an alternative approach to traverse the for a loop. It makes the code more readable."
},
{
"code": null,
"e": 1873,
"s": 1865,
"text": "Syntax:"
},
{
"code": null,
"e": 1989,
"s": 1873,
"text": "for(data_type variable : List_name)\n{ \n // Body of the loop. \n // Each element can be accessed using variable. \n}"
},
{
"code": null,
"e": 1994,
"s": 1989,
"text": "Java"
},
{
"code": "// Java Program to Iterate over a List// using enhanced for loop (for-each) // Importing all classes of// java.util packageimport java.util.*; // Classclass GFG { // Main driver method public static void main(String args[]) { // Creating an Arraylist List<String> myList = new ArrayList<String>(); // Adding elements to the List // Custom inputs myList.add(\"A\"); myList.add(\"B\"); myList.add(\"C\"); myList.add(\"D\"); // Using enhanced for loop(for-each) for iteration for (String i : myList) { // Print all elements of ArrayList System.out.println(i); } }}",
"e": 2663,
"s": 1994,
"text": null
},
{
"code": null,
"e": 2671,
"s": 2663,
"text": "A\nB\nC\nD"
},
{
"code": null,
"e": 2702,
"s": 2671,
"text": "Method 1-C: Using a while loop"
},
{
"code": null,
"e": 2901,
"s": 2702,
"text": "Iterating over a list can also be achieved using a while loop. The block of code inside the loop executes until the condition is true. A loop variable can be used as an index to access each element."
},
{
"code": null,
"e": 2909,
"s": 2901,
"text": "Syntax:"
},
{
"code": null,
"e": 2982,
"s": 2909,
"text": "while(variable<list_name.size())\n{\n // Block of code to be executed \n}"
},
{
"code": null,
"e": 2987,
"s": 2982,
"text": "Java"
},
{
"code": "// Java Program to iterate over a List// using while loop // Importing all classes of// java.util packageimport java.util.*; // Classclass GFG { // Main driver method public static void main(String args[]) { // Creating an ArrayList List<String> myList = new ArrayList<String>(); // Adding elements to the List // Custom inputs myList.add(\"A\"); myList.add(\"B\"); myList.add(\"C\"); myList.add(\"D\"); // Initializing any variable to 0 int i = 0; // If variable value is lesser than // value indicating size of List while (i < myList.size()) { // Print element of list System.out.println(myList.get(i)); // Increase variable count by 1 i++; } }}",
"e": 3787,
"s": 2987,
"text": null
},
{
"code": null,
"e": 3795,
"s": 3787,
"text": "A\nB\nC\nD"
},
{
"code": null,
"e": 3820,
"s": 3795,
"text": "Method 2: Using iterator"
},
{
"code": null,
"e": 3981,
"s": 3820,
"text": "An iterator is an object in Java that allows iterating over elements of a collection. Each element in the list can be accessed using iterator with a while loop."
},
{
"code": null,
"e": 3989,
"s": 3981,
"text": "Syntax:"
},
{
"code": null,
"e": 4042,
"s": 3989,
"text": "Iterator<data_type> variable = list_name.iterator();"
},
{
"code": null,
"e": 4050,
"s": 4042,
"text": "Example"
},
{
"code": null,
"e": 4055,
"s": 4050,
"text": "Java"
},
{
"code": "// Java Program to iterate over the list// using iterator // Importing all classes of// java.util packageimport java.util.*; // Classclass GFG { // Main driver method public static void main(String args[]) { // Creating an ArrayList List<String> myList = new ArrayList<String>(); // Adding elements to the List // Custom inputs myList.add(\"A\"); myList.add(\"B\"); myList.add(\"C\"); myList.add(\"D\"); // Iterator Iterator<String> it = myList.iterator(); // Condition check for elements in List // using hasNext() method returning true till // there i single element in a List while (it.hasNext()) { // Print all elements of List System.out.println(it.next()); } }}",
"e": 4859,
"s": 4055,
"text": null
},
{
"code": null,
"e": 4867,
"s": 4859,
"text": "A\nB\nC\nD"
},
{
"code": null,
"e": 4897,
"s": 4867,
"text": "Method 3: Using List iterator"
},
{
"code": null,
"e": 5106,
"s": 4897,
"text": "ListIterator is an iterator is a java which is available since the 1.2 version. It allows us to iterate elements one-by-one from a List implemented object. It is used to iterator over a list using while loop."
},
{
"code": null,
"e": 5113,
"s": 5106,
"text": "Syntax"
},
{
"code": null,
"e": 5174,
"s": 5113,
"text": "ListIterator<data_type> variable = list_name.listIterator();"
},
{
"code": null,
"e": 5179,
"s": 5174,
"text": "Java"
},
{
"code": "// Java program to iterate over a list// using ListIteratorimport java.util.*; // Classclass GFG { // Main driver method public static void main(String args[]) { // Creating an ArrayList List<String> myList = new ArrayList<String>(); // Adding elements to the List // Custom inputs myList.add(\"A\"); myList.add(\"B\"); myList.add(\"C\"); myList.add(\"D\"); // List iterator ListIterator<String> it = myList.listIterator(); // Condition check whether there is element in List // using hasNext() which holds true till // there is single element in List while (it.hasNext()) { // Print all elements of List System.out.println(it.next()); } }}",
"e": 5956,
"s": 5179,
"text": null
},
{
"code": null,
"e": 5964,
"s": 5956,
"text": "A\nB\nC\nD"
},
{
"code": null,
"e": 5999,
"s": 5964,
"text": "Method 4: Using Iterable.forEach()"
},
{
"code": null,
"e": 6132,
"s": 5999,
"text": "This feature is available since Java 8. It can also be used to iterate over a List. Iteration can be done using a lambda expression."
},
{
"code": null,
"e": 6140,
"s": 6132,
"text": "Syntax:"
},
{
"code": null,
"e": 6187,
"s": 6140,
"text": "list_name.forEach(variable->{//block of code})"
},
{
"code": null,
"e": 6192,
"s": 6187,
"text": "Java"
},
{
"code": "// Java Program to iterate over a List// using forEach() // Importing all classes of// java.util methodimport java.util.*; // Classclass GFG { // Main driver method public static void main(String args[]) { // Creating an ArrayList List<String> myList = new ArrayList<String>(); // Adding elements to the List // Custom inputs myList.add(\"A\"); myList.add(\"B\"); myList.add(\"C\"); myList.add(\"D\"); // Lambda expression printing all elements in a List myList.forEach( (temp) -> { System.out.println(temp); }); }}",
"e": 6796,
"s": 6192,
"text": null
},
{
"code": null,
"e": 6804,
"s": 6796,
"text": "A\nB\nC\nD"
},
{
"code": null,
"e": 6837,
"s": 6804,
"text": "Method 5: Using Stream.forEach()"
},
{
"code": null,
"e": 6977,
"s": 6837,
"text": "The processing order of stream().forEach() is undefined while in case of forEach(), it is defined. Both can be used to iterate over a List."
},
{
"code": null,
"e": 6985,
"s": 6977,
"text": "Syntax:"
},
{
"code": null,
"e": 7039,
"s": 6985,
"text": "list_name.stream.forEach(variable->{//block of code})"
},
{
"code": null,
"e": 7044,
"s": 7039,
"text": "Java"
},
{
"code": "// Java Program iterating over a List// using stream.forEach() method // Importing all classes of// java.util methodimport java.util.*; // Classclass GFG { // Main driver method public static void main(String args[]) { // Creating an ArrayList List<String> myList = new ArrayList<String>(); // Adding elements to the List // Custom inputs myList.add(\"A\"); myList.add(\"B\"); myList.add(\"C\"); myList.add(\"D\"); // stream.forEach() method prints // all elements inside a List myList.stream().forEach( (temp) -> System.out.println(temp)); }}",
"e": 7683,
"s": 7044,
"text": null
},
{
"code": null,
"e": 7691,
"s": 7683,
"text": "A\nB\nC\nD"
},
{
"code": null,
"e": 7708,
"s": 7691,
"text": "surinderdawra388"
},
{
"code": null,
"e": 7721,
"s": 7708,
"text": "singghakshay"
},
{
"code": null,
"e": 7730,
"s": 7721,
"text": "rkbhola5"
},
{
"code": null,
"e": 7747,
"s": 7730,
"text": "Java-Collections"
},
{
"code": null,
"e": 7757,
"s": 7747,
"text": "java-list"
},
{
"code": null,
"e": 7764,
"s": 7757,
"text": "Picked"
},
{
"code": null,
"e": 7769,
"s": 7764,
"text": "Java"
},
{
"code": null,
"e": 7783,
"s": 7769,
"text": "Java Programs"
},
{
"code": null,
"e": 7788,
"s": 7783,
"text": "Java"
},
{
"code": null,
"e": 7805,
"s": 7788,
"text": "Java-Collections"
}
] |
Difference between Static and Dynamic Hazard | 04 May, 2020
1. Static Hazard :Static hazard occur in combinational circuits and can be eliminated by using redundant gates. Static hazard is further classified as:
1. Static-1 hazard
2. Static-0 hazard
2. Dynamic hazard :When the output changes several times then it should change from 1 to 0 or 0 to 1 only once, it is called dynamic hazard. Dynamic hazard occur when the output changes for two adjacent input combinations while changing, the output should change only once. But it may change three or more times in short intervals because of different delays in several paths. Dynamic hazards occur only in multilevel circuit.
Difference between Static and Dynamic Hazard :
Difference Between
Digital Electronics & Logic Design
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n04 May, 2020"
},
{
"code": null,
"e": 180,
"s": 28,
"text": "1. Static Hazard :Static hazard occur in combinational circuits and can be eliminated by using redundant gates. Static hazard is further classified as:"
},
{
"code": null,
"e": 219,
"s": 180,
"text": "1. Static-1 hazard\n2. Static-0 hazard "
},
{
"code": null,
"e": 646,
"s": 219,
"text": "2. Dynamic hazard :When the output changes several times then it should change from 1 to 0 or 0 to 1 only once, it is called dynamic hazard. Dynamic hazard occur when the output changes for two adjacent input combinations while changing, the output should change only once. But it may change three or more times in short intervals because of different delays in several paths. Dynamic hazards occur only in multilevel circuit."
},
{
"code": null,
"e": 693,
"s": 646,
"text": "Difference between Static and Dynamic Hazard :"
},
{
"code": null,
"e": 712,
"s": 693,
"text": "Difference Between"
},
{
"code": null,
"e": 747,
"s": 712,
"text": "Digital Electronics & Logic Design"
},
{
"code": null,
"e": 755,
"s": 747,
"text": "GATE CS"
}
] |
SQL | Views | 09 Jun, 2022
Views in SQL are kind of virtual tables. A view also has rows and columns as they are in a real table in the database. We can create a view by selecting fields from one or more tables present in the database. A View can either have all the rows of a table or specific rows based on certain condition.
In this article we will learn about creating , deleting and updating Views.Sample Tables:
StudentDetails
StudentMarks
CREATING VIEWS
We can create View using CREATE VIEW statement. A View can be created from a single table or multiple tables.
Syntax:
CREATE VIEW view_name AS
SELECT column1, column2.....
FROM table_name
WHERE condition;
view_name: Name for the View
table_name: Name of the table
condition: Condition to select rows
Examples:
Creating View from a single table:In this example we will create a View named DetailsView from the table StudentDetails.Query:CREATE VIEW DetailsView AS
SELECT NAME, ADDRESS
FROM StudentDetails
WHERE S_ID < 5;
To see the data in the View, we can query the view in the same manner as we query a table.SELECT * FROM DetailsView;
Output:In this example, we will create a view named StudentNames from the table StudentDetails.Query:CREATE VIEW StudentNames AS
SELECT S_ID, NAME
FROM StudentDetails
ORDER BY NAME;
If we now query the view as,SELECT * FROM StudentNames;
Output:
In this example we will create a View named DetailsView from the table StudentDetails.Query:CREATE VIEW DetailsView AS
SELECT NAME, ADDRESS
FROM StudentDetails
WHERE S_ID < 5;
To see the data in the View, we can query the view in the same manner as we query a table.SELECT * FROM DetailsView;
Output:
CREATE VIEW DetailsView AS
SELECT NAME, ADDRESS
FROM StudentDetails
WHERE S_ID < 5;
To see the data in the View, we can query the view in the same manner as we query a table.
SELECT * FROM DetailsView;
Output:
In this example, we will create a view named StudentNames from the table StudentDetails.Query:CREATE VIEW StudentNames AS
SELECT S_ID, NAME
FROM StudentDetails
ORDER BY NAME;
If we now query the view as,SELECT * FROM StudentNames;
Output:
CREATE VIEW StudentNames AS
SELECT S_ID, NAME
FROM StudentDetails
ORDER BY NAME;
If we now query the view as,
SELECT * FROM StudentNames;
Output:
Creating View from multiple tables: In this example we will create a View named MarksView from two tables StudentDetails and StudentMarks. To create a View from multiple tables we can simply include multiple tables in the SELECT statement. Query:CREATE VIEW MarksView AS
SELECT StudentDetails.NAME, StudentDetails.ADDRESS, StudentMarks.MARKS
FROM StudentDetails, StudentMarks
WHERE StudentDetails.NAME = StudentMarks.NAME;
To display data of View MarksView:SELECT * FROM MarksView;
Output:
CREATE VIEW MarksView AS
SELECT StudentDetails.NAME, StudentDetails.ADDRESS, StudentMarks.MARKS
FROM StudentDetails, StudentMarks
WHERE StudentDetails.NAME = StudentMarks.NAME;
To display data of View MarksView:
SELECT * FROM MarksView;
Output:
DELETING VIEWS
We have learned about creating a View, but what if a created View is not needed any more? Obviously we will want to delete it. SQL allows us to delete an existing View. We can delete or drop a View using the DROP statement.
Syntax:
DROP VIEW view_name;
view_name: Name of the View which we want to delete.
For example, if we want to delete the View MarksView, we can do this as:
DROP VIEW MarksView;
UPDATING VIEWS
There are certain conditions needed to be satisfied to update a view. If any one of these conditions is not met, then we will not be allowed to update the view.
The SELECT statement which is used to create the view should not include GROUP BY clause or ORDER BY clause.The SELECT statement should not have the DISTINCT keyword.The View should have all NOT NULL values.The view should not be created using nested queries or complex queries.The view should be created from a single table. If the view is created using multiple tables then we will not be allowed to update the view.
The SELECT statement which is used to create the view should not include GROUP BY clause or ORDER BY clause.
The SELECT statement should not have the DISTINCT keyword.
The View should have all NOT NULL values.
The view should not be created using nested queries or complex queries.
The view should be created from a single table. If the view is created using multiple tables then we will not be allowed to update the view.
We can use the CREATE OR REPLACE VIEW statement to add or remove fields from a view.Syntax:CREATE OR REPLACE VIEW view_name AS
SELECT column1,coulmn2,..
FROM table_name
WHERE condition;
For example, if we want to update the view MarksView and add the field AGE to this View from StudentMarks Table, we can do this as:CREATE OR REPLACE VIEW MarksView AS
SELECT StudentDetails.NAME, StudentDetails.ADDRESS, StudentMarks.MARKS, StudentMarks.AGE
FROM StudentDetails, StudentMarks
WHERE StudentDetails.NAME = StudentMarks.NAME;
If we fetch all the data from MarksView now as:SELECT * FROM MarksView;
Output:
CREATE OR REPLACE VIEW view_name AS
SELECT column1,coulmn2,..
FROM table_name
WHERE condition;
For example, if we want to update the view MarksView and add the field AGE to this View from StudentMarks Table, we can do this as:
CREATE OR REPLACE VIEW MarksView AS
SELECT StudentDetails.NAME, StudentDetails.ADDRESS, StudentMarks.MARKS, StudentMarks.AGE
FROM StudentDetails, StudentMarks
WHERE StudentDetails.NAME = StudentMarks.NAME;
If we fetch all the data from MarksView now as:
SELECT * FROM MarksView;
Output:
Inserting a row in a view:We can insert a row in a View in a same way as we do in a table. We can use the INSERT INTO statement of SQL to insert a row in a View.Syntax:INSERT INTO view_name(column1, column2 , column3,..)
VALUES(value1, value2, value3..);
view_name: Name of the View
Example:In the below example we will insert a new row in the View DetailsView which we have created above in the example of “creating views from a single table”.INSERT INTO DetailsView(NAME, ADDRESS)
VALUES("Suresh","Gurgaon");
If we fetch all the data from DetailsView now as,SELECT * FROM DetailsView;
Output:
INSERT INTO view_name(column1, column2 , column3,..)
VALUES(value1, value2, value3..);
view_name: Name of the View
Example:In the below example we will insert a new row in the View DetailsView which we have created above in the example of “creating views from a single table”.
INSERT INTO DetailsView(NAME, ADDRESS)
VALUES("Suresh","Gurgaon");
If we fetch all the data from DetailsView now as,
SELECT * FROM DetailsView;
Output:
Deleting a row from a View:Deleting rows from a view is also as simple as deleting rows from a table. We can use the DELETE statement of SQL to delete rows from a view. Also deleting a row from a view first delete the row from the actual table and the change is then reflected in the view.Syntax:DELETE FROM view_name
WHERE condition;
view_name:Name of view from where we want to delete rows
condition: Condition to select rows
Example:In this example we will delete the last row from the view DetailsView which we just added in the above example of inserting rows.DELETE FROM DetailsView
WHERE NAME="Suresh";
If we fetch all the data from DetailsView now as,SELECT * FROM DetailsView;
Output:
DELETE FROM view_name
WHERE condition;
view_name:Name of view from where we want to delete rows
condition: Condition to select rows
Example:In this example we will delete the last row from the view DetailsView which we just added in the above example of inserting rows.
DELETE FROM DetailsView
WHERE NAME="Suresh";
If we fetch all the data from DetailsView now as,
SELECT * FROM DetailsView;
Output:
WITH CHECK OPTION
The WITH CHECK OPTION clause in SQL is a very useful clause for views. It is applicable to a updatable view. If the view is not updatable, then there is no meaning of including this clause in the CREATE VIEW statement.
The WITH CHECK OPTION clause is used to prevent the insertion of rows in the view where the condition in the WHERE clause in CREATE VIEW statement is not satisfied.
If we have used the WITH CHECK OPTION clause in the CREATE VIEW statement, and if the UPDATE or INSERT clause does not satisfy the conditions then they will return an error.
Example:In the below example we are creating a View SampleView from StudentDetails Table with WITH CHECK OPTION clause.
CREATE VIEW SampleView AS
SELECT S_ID, NAME
FROM StudentDetails
WHERE NAME IS NOT NULL
WITH CHECK OPTION;
In this View if we now try to insert a new row with null value in the NAME column then it will give an error because the view is created with the condition for NAME column as NOT NULL.For example,though the View is updatable but then also the below query for this View is not valid:
INSERT INTO SampleView(S_ID)
VALUES(6);
NOTE: The default value of NAME column is null.
Uses of a View :A good database should contain views due to the given reasons:
Restricting data access –Views provide an additional level of table security by restricting access to a predetermined set of rows and columns of a table.Hiding data complexity –A view can hide the complexity that exists in a multiple table join.Simplify commands for the user –Views allows the user to select information from multiple tables without requiring the users to actually know how to perform a join.Store complex queries –Views can be used to store complex queries.Rename Columns –Views can also be used to rename the columns without affecting the base tables provided the number of columns in view must match the number of columns specified in select statement. Thus, renaming helps to hide the names of the columns of the base tables.Multiple view facility –Different views can be created on the same table for different users.
Restricting data access –Views provide an additional level of table security by restricting access to a predetermined set of rows and columns of a table.
Hiding data complexity –A view can hide the complexity that exists in a multiple table join.
Simplify commands for the user –Views allows the user to select information from multiple tables without requiring the users to actually know how to perform a join.
Store complex queries –Views can be used to store complex queries.
Rename Columns –Views can also be used to rename the columns without affecting the base tables provided the number of columns in view must match the number of columns specified in select statement. Thus, renaming helps to hide the names of the columns of the base tables.
Multiple view facility –Different views can be created on the same table for different users.
This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Geek_Dev
itskawal2000
amritagg2137
SQL-basics
Articles
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n09 Jun, 2022"
},
{
"code": null,
"e": 353,
"s": 52,
"text": "Views in SQL are kind of virtual tables. A view also has rows and columns as they are in a real table in the database. We can create a view by selecting fields from one or more tables present in the database. A View can either have all the rows of a table or specific rows based on certain condition."
},
{
"code": null,
"e": 443,
"s": 353,
"text": "In this article we will learn about creating , deleting and updating Views.Sample Tables:"
},
{
"code": null,
"e": 458,
"s": 443,
"text": "StudentDetails"
},
{
"code": null,
"e": 471,
"s": 458,
"text": "StudentMarks"
},
{
"code": null,
"e": 486,
"s": 471,
"text": "CREATING VIEWS"
},
{
"code": null,
"e": 596,
"s": 486,
"text": "We can create View using CREATE VIEW statement. A View can be created from a single table or multiple tables."
},
{
"code": null,
"e": 604,
"s": 596,
"text": "Syntax:"
},
{
"code": null,
"e": 788,
"s": 604,
"text": "CREATE VIEW view_name AS\nSELECT column1, column2.....\nFROM table_name\nWHERE condition;\n\nview_name: Name for the View\ntable_name: Name of the table\ncondition: Condition to select rows\n"
},
{
"code": null,
"e": 798,
"s": 788,
"text": "Examples:"
},
{
"code": null,
"e": 1371,
"s": 798,
"text": "Creating View from a single table:In this example we will create a View named DetailsView from the table StudentDetails.Query:CREATE VIEW DetailsView AS\nSELECT NAME, ADDRESS\nFROM StudentDetails\nWHERE S_ID < 5;\nTo see the data in the View, we can query the view in the same manner as we query a table.SELECT * FROM DetailsView;\nOutput:In this example, we will create a view named StudentNames from the table StudentDetails.Query:CREATE VIEW StudentNames AS\nSELECT S_ID, NAME\nFROM StudentDetails\nORDER BY NAME;\nIf we now query the view as,SELECT * FROM StudentNames;\nOutput:"
},
{
"code": null,
"e": 1672,
"s": 1371,
"text": "In this example we will create a View named DetailsView from the table StudentDetails.Query:CREATE VIEW DetailsView AS\nSELECT NAME, ADDRESS\nFROM StudentDetails\nWHERE S_ID < 5;\nTo see the data in the View, we can query the view in the same manner as we query a table.SELECT * FROM DetailsView;\nOutput:"
},
{
"code": null,
"e": 1757,
"s": 1672,
"text": "CREATE VIEW DetailsView AS\nSELECT NAME, ADDRESS\nFROM StudentDetails\nWHERE S_ID < 5;\n"
},
{
"code": null,
"e": 1848,
"s": 1757,
"text": "To see the data in the View, we can query the view in the same manner as we query a table."
},
{
"code": null,
"e": 1876,
"s": 1848,
"text": "SELECT * FROM DetailsView;\n"
},
{
"code": null,
"e": 1884,
"s": 1876,
"text": "Output:"
},
{
"code": null,
"e": 2123,
"s": 1884,
"text": "In this example, we will create a view named StudentNames from the table StudentDetails.Query:CREATE VIEW StudentNames AS\nSELECT S_ID, NAME\nFROM StudentDetails\nORDER BY NAME;\nIf we now query the view as,SELECT * FROM StudentNames;\nOutput:"
},
{
"code": null,
"e": 2205,
"s": 2123,
"text": "CREATE VIEW StudentNames AS\nSELECT S_ID, NAME\nFROM StudentDetails\nORDER BY NAME;\n"
},
{
"code": null,
"e": 2234,
"s": 2205,
"text": "If we now query the view as,"
},
{
"code": null,
"e": 2263,
"s": 2234,
"text": "SELECT * FROM StudentNames;\n"
},
{
"code": null,
"e": 2271,
"s": 2263,
"text": "Output:"
},
{
"code": null,
"e": 2761,
"s": 2271,
"text": "Creating View from multiple tables: In this example we will create a View named MarksView from two tables StudentDetails and StudentMarks. To create a View from multiple tables we can simply include multiple tables in the SELECT statement. Query:CREATE VIEW MarksView AS\nSELECT StudentDetails.NAME, StudentDetails.ADDRESS, StudentMarks.MARKS\nFROM StudentDetails, StudentMarks\nWHERE StudentDetails.NAME = StudentMarks.NAME;\nTo display data of View MarksView:SELECT * FROM MarksView;\nOutput:"
},
{
"code": null,
"e": 2939,
"s": 2761,
"text": "CREATE VIEW MarksView AS\nSELECT StudentDetails.NAME, StudentDetails.ADDRESS, StudentMarks.MARKS\nFROM StudentDetails, StudentMarks\nWHERE StudentDetails.NAME = StudentMarks.NAME;\n"
},
{
"code": null,
"e": 2974,
"s": 2939,
"text": "To display data of View MarksView:"
},
{
"code": null,
"e": 3000,
"s": 2974,
"text": "SELECT * FROM MarksView;\n"
},
{
"code": null,
"e": 3008,
"s": 3000,
"text": "Output:"
},
{
"code": null,
"e": 3023,
"s": 3008,
"text": "DELETING VIEWS"
},
{
"code": null,
"e": 3247,
"s": 3023,
"text": "We have learned about creating a View, but what if a created View is not needed any more? Obviously we will want to delete it. SQL allows us to delete an existing View. We can delete or drop a View using the DROP statement."
},
{
"code": null,
"e": 3255,
"s": 3247,
"text": "Syntax:"
},
{
"code": null,
"e": 3331,
"s": 3255,
"text": "DROP VIEW view_name;\n\nview_name: Name of the View which we want to delete.\n"
},
{
"code": null,
"e": 3404,
"s": 3331,
"text": "For example, if we want to delete the View MarksView, we can do this as:"
},
{
"code": null,
"e": 3426,
"s": 3404,
"text": "DROP VIEW MarksView;\n"
},
{
"code": null,
"e": 3441,
"s": 3426,
"text": "UPDATING VIEWS"
},
{
"code": null,
"e": 3602,
"s": 3441,
"text": "There are certain conditions needed to be satisfied to update a view. If any one of these conditions is not met, then we will not be allowed to update the view."
},
{
"code": null,
"e": 4021,
"s": 3602,
"text": "The SELECT statement which is used to create the view should not include GROUP BY clause or ORDER BY clause.The SELECT statement should not have the DISTINCT keyword.The View should have all NOT NULL values.The view should not be created using nested queries or complex queries.The view should be created from a single table. If the view is created using multiple tables then we will not be allowed to update the view."
},
{
"code": null,
"e": 4130,
"s": 4021,
"text": "The SELECT statement which is used to create the view should not include GROUP BY clause or ORDER BY clause."
},
{
"code": null,
"e": 4189,
"s": 4130,
"text": "The SELECT statement should not have the DISTINCT keyword."
},
{
"code": null,
"e": 4231,
"s": 4189,
"text": "The View should have all NOT NULL values."
},
{
"code": null,
"e": 4303,
"s": 4231,
"text": "The view should not be created using nested queries or complex queries."
},
{
"code": null,
"e": 4444,
"s": 4303,
"text": "The view should be created from a single table. If the view is created using multiple tables then we will not be allowed to update the view."
},
{
"code": null,
"e": 5047,
"s": 4444,
"text": "We can use the CREATE OR REPLACE VIEW statement to add or remove fields from a view.Syntax:CREATE OR REPLACE VIEW view_name AS\nSELECT column1,coulmn2,..\nFROM table_name\nWHERE condition;\nFor example, if we want to update the view MarksView and add the field AGE to this View from StudentMarks Table, we can do this as:CREATE OR REPLACE VIEW MarksView AS\nSELECT StudentDetails.NAME, StudentDetails.ADDRESS, StudentMarks.MARKS, StudentMarks.AGE\nFROM StudentDetails, StudentMarks\nWHERE StudentDetails.NAME = StudentMarks.NAME;\nIf we fetch all the data from MarksView now as:SELECT * FROM MarksView;\nOutput:"
},
{
"code": null,
"e": 5143,
"s": 5047,
"text": "CREATE OR REPLACE VIEW view_name AS\nSELECT column1,coulmn2,..\nFROM table_name\nWHERE condition;\n"
},
{
"code": null,
"e": 5275,
"s": 5143,
"text": "For example, if we want to update the view MarksView and add the field AGE to this View from StudentMarks Table, we can do this as:"
},
{
"code": null,
"e": 5482,
"s": 5275,
"text": "CREATE OR REPLACE VIEW MarksView AS\nSELECT StudentDetails.NAME, StudentDetails.ADDRESS, StudentMarks.MARKS, StudentMarks.AGE\nFROM StudentDetails, StudentMarks\nWHERE StudentDetails.NAME = StudentMarks.NAME;\n"
},
{
"code": null,
"e": 5530,
"s": 5482,
"text": "If we fetch all the data from MarksView now as:"
},
{
"code": null,
"e": 5556,
"s": 5530,
"text": "SELECT * FROM MarksView;\n"
},
{
"code": null,
"e": 5564,
"s": 5556,
"text": "Output:"
},
{
"code": null,
"e": 6161,
"s": 5564,
"text": "Inserting a row in a view:We can insert a row in a View in a same way as we do in a table. We can use the INSERT INTO statement of SQL to insert a row in a View.Syntax:INSERT INTO view_name(column1, column2 , column3,..) \nVALUES(value1, value2, value3..);\n\nview_name: Name of the View\nExample:In the below example we will insert a new row in the View DetailsView which we have created above in the example of “creating views from a single table”.INSERT INTO DetailsView(NAME, ADDRESS)\nVALUES(\"Suresh\",\"Gurgaon\");\nIf we fetch all the data from DetailsView now as,SELECT * FROM DetailsView;\nOutput:"
},
{
"code": null,
"e": 6279,
"s": 6161,
"text": "INSERT INTO view_name(column1, column2 , column3,..) \nVALUES(value1, value2, value3..);\n\nview_name: Name of the View\n"
},
{
"code": null,
"e": 6441,
"s": 6279,
"text": "Example:In the below example we will insert a new row in the View DetailsView which we have created above in the example of “creating views from a single table”."
},
{
"code": null,
"e": 6509,
"s": 6441,
"text": "INSERT INTO DetailsView(NAME, ADDRESS)\nVALUES(\"Suresh\",\"Gurgaon\");\n"
},
{
"code": null,
"e": 6559,
"s": 6509,
"text": "If we fetch all the data from DetailsView now as,"
},
{
"code": null,
"e": 6587,
"s": 6559,
"text": "SELECT * FROM DetailsView;\n"
},
{
"code": null,
"e": 6595,
"s": 6587,
"text": "Output:"
},
{
"code": null,
"e": 7291,
"s": 6595,
"text": "Deleting a row from a View:Deleting rows from a view is also as simple as deleting rows from a table. We can use the DELETE statement of SQL to delete rows from a view. Also deleting a row from a view first delete the row from the actual table and the change is then reflected in the view.Syntax:DELETE FROM view_name\nWHERE condition;\n\nview_name:Name of view from where we want to delete rows\ncondition: Condition to select rows \nExample:In this example we will delete the last row from the view DetailsView which we just added in the above example of inserting rows.DELETE FROM DetailsView\nWHERE NAME=\"Suresh\";\nIf we fetch all the data from DetailsView now as,SELECT * FROM DetailsView;\nOutput:"
},
{
"code": null,
"e": 7426,
"s": 7291,
"text": "DELETE FROM view_name\nWHERE condition;\n\nview_name:Name of view from where we want to delete rows\ncondition: Condition to select rows \n"
},
{
"code": null,
"e": 7564,
"s": 7426,
"text": "Example:In this example we will delete the last row from the view DetailsView which we just added in the above example of inserting rows."
},
{
"code": null,
"e": 7610,
"s": 7564,
"text": "DELETE FROM DetailsView\nWHERE NAME=\"Suresh\";\n"
},
{
"code": null,
"e": 7660,
"s": 7610,
"text": "If we fetch all the data from DetailsView now as,"
},
{
"code": null,
"e": 7688,
"s": 7660,
"text": "SELECT * FROM DetailsView;\n"
},
{
"code": null,
"e": 7696,
"s": 7688,
"text": "Output:"
},
{
"code": null,
"e": 7714,
"s": 7696,
"text": "WITH CHECK OPTION"
},
{
"code": null,
"e": 7933,
"s": 7714,
"text": "The WITH CHECK OPTION clause in SQL is a very useful clause for views. It is applicable to a updatable view. If the view is not updatable, then there is no meaning of including this clause in the CREATE VIEW statement."
},
{
"code": null,
"e": 8098,
"s": 7933,
"text": "The WITH CHECK OPTION clause is used to prevent the insertion of rows in the view where the condition in the WHERE clause in CREATE VIEW statement is not satisfied."
},
{
"code": null,
"e": 8272,
"s": 8098,
"text": "If we have used the WITH CHECK OPTION clause in the CREATE VIEW statement, and if the UPDATE or INSERT clause does not satisfy the conditions then they will return an error."
},
{
"code": null,
"e": 8392,
"s": 8272,
"text": "Example:In the below example we are creating a View SampleView from StudentDetails Table with WITH CHECK OPTION clause."
},
{
"code": null,
"e": 8500,
"s": 8392,
"text": "CREATE VIEW SampleView AS\nSELECT S_ID, NAME\nFROM StudentDetails\nWHERE NAME IS NOT NULL\nWITH CHECK OPTION;\n"
},
{
"code": null,
"e": 8783,
"s": 8500,
"text": "In this View if we now try to insert a new row with null value in the NAME column then it will give an error because the view is created with the condition for NAME column as NOT NULL.For example,though the View is updatable but then also the below query for this View is not valid:"
},
{
"code": null,
"e": 8824,
"s": 8783,
"text": "INSERT INTO SampleView(S_ID)\nVALUES(6);\n"
},
{
"code": null,
"e": 8872,
"s": 8824,
"text": "NOTE: The default value of NAME column is null."
},
{
"code": null,
"e": 8951,
"s": 8872,
"text": "Uses of a View :A good database should contain views due to the given reasons:"
},
{
"code": null,
"e": 9791,
"s": 8951,
"text": "Restricting data access –Views provide an additional level of table security by restricting access to a predetermined set of rows and columns of a table.Hiding data complexity –A view can hide the complexity that exists in a multiple table join.Simplify commands for the user –Views allows the user to select information from multiple tables without requiring the users to actually know how to perform a join.Store complex queries –Views can be used to store complex queries.Rename Columns –Views can also be used to rename the columns without affecting the base tables provided the number of columns in view must match the number of columns specified in select statement. Thus, renaming helps to hide the names of the columns of the base tables.Multiple view facility –Different views can be created on the same table for different users."
},
{
"code": null,
"e": 9945,
"s": 9791,
"text": "Restricting data access –Views provide an additional level of table security by restricting access to a predetermined set of rows and columns of a table."
},
{
"code": null,
"e": 10038,
"s": 9945,
"text": "Hiding data complexity –A view can hide the complexity that exists in a multiple table join."
},
{
"code": null,
"e": 10203,
"s": 10038,
"text": "Simplify commands for the user –Views allows the user to select information from multiple tables without requiring the users to actually know how to perform a join."
},
{
"code": null,
"e": 10270,
"s": 10203,
"text": "Store complex queries –Views can be used to store complex queries."
},
{
"code": null,
"e": 10542,
"s": 10270,
"text": "Rename Columns –Views can also be used to rename the columns without affecting the base tables provided the number of columns in view must match the number of columns specified in select statement. Thus, renaming helps to hide the names of the columns of the base tables."
},
{
"code": null,
"e": 10636,
"s": 10542,
"text": "Multiple view facility –Different views can be created on the same table for different users."
},
{
"code": null,
"e": 10937,
"s": 10636,
"text": "This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 11062,
"s": 10937,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 11071,
"s": 11062,
"text": "Geek_Dev"
},
{
"code": null,
"e": 11084,
"s": 11071,
"text": "itskawal2000"
},
{
"code": null,
"e": 11097,
"s": 11084,
"text": "amritagg2137"
},
{
"code": null,
"e": 11108,
"s": 11097,
"text": "SQL-basics"
},
{
"code": null,
"e": 11117,
"s": 11108,
"text": "Articles"
},
{
"code": null,
"e": 11122,
"s": 11117,
"text": "DBMS"
},
{
"code": null,
"e": 11126,
"s": 11122,
"text": "SQL"
},
{
"code": null,
"e": 11131,
"s": 11126,
"text": "DBMS"
},
{
"code": null,
"e": 11135,
"s": 11131,
"text": "SQL"
}
] |
Find k-cores of an undirected graph | 30 Jun, 2022
Given a graph G and an integer K, K-cores of the graph are connected components that are left after all vertices of degree less than k have been removed (Source wiki)
Example:
Input : Adjacency list representation of graph shown
on left side of below diagram
Output: K-Cores :
[2] -> 3 -> 4 -> 6
[3] -> 2 -> 4 -> 6 -> 7
[4] -> 2 -> 3 -> 6 -> 7
[6] -> 2 -> 3 -> 4 -> 7
[7] -> 3 -> 4 -> 6
We strongly recommend you to minimize your browser and try this yourself first.The standard algorithm to find a k-core graph is to remove all the vertices that have degree less than- ‘K’ from the input graph. We must be careful that removing a vertex reduces the degree of all the vertices adjacent to it, hence the degree of adjacent vertices can also drop below-‘K’. And thus, we may have to remove those vertices also. This process may/may not go until there are no vertices left in the graph.
To implement above algorithm, we do a modified DFS on the input graph and delete all the vertices having degree less than ‘K’, then update degrees of all the adjacent vertices, and if their degree falls below ‘K’ we will delete them too.
Below is implementation of above idea. Note that the below program only prints vertices of k cores, but it can be easily extended to print the complete k cores as we have modified adjacency list.
C++14
Java
Python3
C#
// C++ program to find K-Cores of a graph#include<bits/stdc++.h>using namespace std; // This class represents a undirected graph using adjacency// list representationclass Graph{ int V; // No. of vertices // Pointer to an array containing adjacency lists list<int> *adj;public: Graph(int V); // Constructor // function to add an edge to graph void addEdge(int u, int v); // A recursive function to print DFS starting from v bool DFSUtil(int, vector<bool> &, vector<int> &, int k); // prints k-Cores of given graph void printKCores(int k);}; // A recursive function to print DFS starting from v.// It returns true if degree of v after processing is less// than k else false// It also updates degree of adjacent if degree of v// is less than k. And if degree of a processed adjacent// becomes less than k, then it reduces of degree of v also,bool Graph::DFSUtil(int v, vector<bool> &visited, vector<int> &vDegree, int k){ // Mark the current node as visited and print it visited[v] = true; // Recur for all the vertices adjacent to this vertex list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) { // degree of v is less than k, then degree of adjacent // must be reduced if (vDegree[v] < k) vDegree[*i]--; // If adjacent is not processed, process it if (!visited[*i]) { // If degree of adjacent after processing becomes // less than k, then reduce degree of v also. DFSUtil(*i, visited, vDegree, k); } } // Return true if degree of v is less than k return (vDegree[v] < k);} Graph::Graph(int V){ this->V = V; adj = new list<int>[V];} void Graph::addEdge(int u, int v){ adj[u].push_back(v); adj[v].push_back(u);} // Prints k cores of an undirected graphvoid Graph::printKCores(int k){ // INITIALIZATION // Mark all the vertices as not visited and not // processed. vector<bool> visited(V, false); vector<bool> processed(V, false); int mindeg = INT_MAX; int startvertex; // Store degrees of all vertices vector<int> vDegree(V); for (int i=0; i<V; i++) { vDegree[i] = adj[i].size(); if (vDegree[i] < mindeg) { mindeg = vDegree[i]; startvertex=i; } } DFSUtil(startvertex, visited, vDegree, k); // If Graph is disconnected. for (int i=0; i<V; i++) if (visited[i] == false) DFSUtil(i, visited, vDegree, k); // Considering Edge Case (Example 3 in main() function) for (int v=0; v<V; v++){ if (vDegree[v] >= k){ int cnt = 0; list<int>::iterator itr; for (itr = adj[v].begin(); itr != adj[v].end(); ++itr) if (vDegree[*itr] >= k) cnt++; if(cnt < k) vDegree[v] = cnt; } } // PRINTING K CORES cout << "K-Cores : \n"; for (int v=0; v<V; v++) { // Only considering those vertices which have degree // >= K after DFS if (vDegree[v] >= k) { cout << "\n[" << v << "]"; // Traverse adjacency list of v and print only // those adjacent which have vDegree >= k after // DFS. list<int>::iterator itr; for (itr = adj[v].begin(); itr != adj[v].end(); ++itr) if (vDegree[*itr] >= k) cout << " -> " << *itr; } }} // Driver program to test methods of graph classint main(){ // Create a graph given in the above diagram int k = 3; Graph g1(9); g1.addEdge(0, 1); g1.addEdge(0, 2); g1.addEdge(1, 2); g1.addEdge(1, 5); g1.addEdge(2, 3); g1.addEdge(2, 4); g1.addEdge(2, 5); g1.addEdge(2, 6); g1.addEdge(3, 4); g1.addEdge(3, 6); g1.addEdge(3, 7); g1.addEdge(4, 6); g1.addEdge(4, 7); g1.addEdge(5, 6); g1.addEdge(5, 8); g1.addEdge(6, 7); g1.addEdge(6, 8); g1.printKCores(k); cout << endl << endl; Graph g2(13); g2.addEdge(0, 1); g2.addEdge(0, 2); g2.addEdge(0, 3); g2.addEdge(1, 4); g2.addEdge(1, 5); g2.addEdge(1, 6); g2.addEdge(2, 7); g2.addEdge(2, 8); g2.addEdge(2, 9); g2.addEdge(3, 10); g2.addEdge(3, 11); g2.addEdge(3, 12); g2.printKCores(k); Graph gr(9); gr.addEdge(0, 1); gr.addEdge(0, 2); gr.addEdge(1, 2); gr.addEdge(2, 5); gr.addEdge(2, 4); gr.addEdge(2, 3); gr.addEdge(2, 6); gr.addEdge(3, 4); gr.addEdge(3, 6); gr.addEdge(3, 7); gr.addEdge(4, 6); gr.addEdge(5, 6); gr.addEdge(5, 7); gr.addEdge(5, 8); gr.addEdge(8, 7); gr.printKCores(k); return 0;}
// Java program to find K-Cores of a graphimport java.util.*; class GFG{ // This class represents a undirected graph using adjacency // list representation static class Graph { int V; // No. of vertices // Pointer to an array containing adjacency lists Vector<Integer>[] adj; @SuppressWarnings("unchecked") Graph(int V) { this.V = V; this.adj = new Vector[V]; for (int i = 0; i < V; i++) adj[i] = new Vector<>(); } // function to add an edge to graph void addEdge(int u, int v) { this.adj[u].add(v); this.adj[v].add(u); } // A recursive function to print DFS starting from v. // It returns true if degree of v after processing is less // than k else false // It also updates degree of adjacent if degree of v // is less than k. And if degree of a processed adjacent // becomes less than k, then it reduces of degree of v also, boolean DFSUtil(int v, boolean[] visited, int[] vDegree, int k) { // Mark the current node as visited and print it visited[v] = true; // Recur for all the vertices adjacent to this vertex for (int i : adj[v]) { // degree of v is less than k, then degree of adjacent // must be reduced if (vDegree[v] < k) vDegree[i]--; // If adjacent is not processed, process it if (!visited[i]) { // If degree of adjacent after processing becomes // less than k, then reduce degree of v also. DFSUtil(i, visited, vDegree, k); } } // Return true if degree of v is less than k return (vDegree[v] < k); } // Prints k cores of an undirected graph void printKCores(int k) { // INITIALIZATION // Mark all the vertices as not visited and not // processed. boolean[] visited = new boolean[V]; boolean[] processed = new boolean[V]; Arrays.fill(visited, false); Arrays.fill(processed, false); int mindeg = Integer.MAX_VALUE; int startvertex = 0; // Store degrees of all vertices int[] vDegree = new int[V]; for (int i = 0; i < V; i++) { vDegree[i] = adj[i].size(); if (vDegree[i] < mindeg) { mindeg = vDegree[i]; startvertex = i; } } DFSUtil(startvertex, visited, vDegree, k); // DFS traversal to update degrees of all // vertices. for (int i = 0; i < V; i++) if (!visited[i]) DFSUtil(i, visited, vDegree, k); // PRINTING K CORES System.out.println("K-Cores : "); for (int v = 0; v < V; v++) { // Only considering those vertices which have degree // >= K after BFS if (vDegree[v] >= k) { System.out.printf("\n[%d]", v); // Traverse adjacency list of v and print only // those adjacent which have vDegree >= k after // DFS. for (int i : adj[v]) if (vDegree[i] >= k) System.out.printf(" -> %d", i); } } } } // Driver Code public static void main(String[] args) { // Create a graph given in the above diagram int k = 3; Graph g1 = new Graph(9); g1.addEdge(0, 1); g1.addEdge(0, 2); g1.addEdge(1, 2); g1.addEdge(1, 5); g1.addEdge(2, 3); g1.addEdge(2, 4); g1.addEdge(2, 5); g1.addEdge(2, 6); g1.addEdge(3, 4); g1.addEdge(3, 6); g1.addEdge(3, 7); g1.addEdge(4, 6); g1.addEdge(4, 7); g1.addEdge(5, 6); g1.addEdge(5, 8); g1.addEdge(6, 7); g1.addEdge(6, 8); g1.printKCores(k); System.out.println(); Graph g2 = new Graph(13); g2.addEdge(0, 1); g2.addEdge(0, 2); g2.addEdge(0, 3); g2.addEdge(1, 4); g2.addEdge(1, 5); g2.addEdge(1, 6); g2.addEdge(2, 7); g2.addEdge(2, 8); g2.addEdge(2, 9); g2.addEdge(3, 10); g2.addEdge(3, 11); g2.addEdge(3, 12); g2.printKCores(k); }} // This code is contributed by// sanjeev2552
#saurabh_jain861# Python program to find K-Cores of a graphfrom collections import defaultdict # This class represents a undirected graph using adjacency# list representation class Graph: def __init__(self): # default dictionary to store graph self.graph = defaultdict(list) # function to add an edge to undirected graph def addEdge(self, u, v): self.graph[u].append(v) self.graph[v].append(u) # A recursive function to call DFS starting from v. # It returns true if vDegree of v after processing is less # than k else false # It also updates vDegree of adjacent if vDegree of v # is less than k. And if vDegree of a processed adjacent # becomes less than k, then it reduces of vDegree of v also, def DFSUtil(self, v, visited, vDegree, k): # Mark the current node as visited visited.add(v) # Recur for all the vertices adjacent to this vertex for i in self.graph[v]: # vDegree of v is less than k, then vDegree of # adjacent must be reduced if vDegree[v] < k: vDegree[i] = vDegree[i] - 1 # If adjacent is not processed, process it if i not in visited: # If vDegree of adjacent after processing becomes # less than k, then reduce vDegree of v also self.DFSUtil(i, visited, vDegree, k) def PrintKCores(self, k): visit = set() degree = defaultdict(lambda: 0) for i in list(self.graph): degree[i] = len(self.graph[i]) for i in list(self.graph): if i not in visit: self.DFSUtil(i, visit, degree, k) # print(degree) # print(self.graph) for i in list(self.graph): if degree[i] >= k: print(str("\n [ ") + str(i) + str(" ]"), end=" ") for j in self.graph[i]: if degree[j] >= k: print("-> " + str(j), end=" ") print() k = 3g1 = Graph()g1.addEdge(0, 1)g1.addEdge(0, 2)g1.addEdge(1, 2)g1.addEdge(1, 5)g1.addEdge(2, 3)g1.addEdge(2, 4)g1.addEdge(2, 5)g1.addEdge(2, 6)g1.addEdge(3, 4)g1.addEdge(3, 6)g1.addEdge(3, 7)g1.addEdge(4, 6)g1.addEdge(4, 7)g1.addEdge(5, 6)g1.addEdge(5, 8)g1.addEdge(6, 7)g1.addEdge(6, 8)g1.PrintKCores(k)
// C# program to find K-Cores of a graphusing System;using System.Collections.Generic; class GFG{ // This class represents a undirected// graph using adjacency list// representationpublic class Graph{ // No. of vertices int V; // Pointer to an array containing // adjacency lists List<int>[] adj; public Graph(int V) { this.V = V; this.adj = new List<int>[V]; for(int i = 0; i < V; i++) adj[i] = new List<int>(); } // Function to add an edge to graph public void addEdge(int u, int v) { this.adj[u].Add(v); this.adj[v].Add(u); } // A recursive function to print DFS // starting from v. It returns true // if degree of v after processing // is less than k else false // It also updates degree of adjacent // if degree of v is less than k. And // if degree of a processed adjacent // becomes less than k, then it reduces // of degree of v also, bool DFSUtil(int v, bool[] visited, int[] vDegree, int k) { // Mark the current node as // visited and print it visited[v] = true; // Recur for all the vertices // adjacent to this vertex foreach (int i in adj[v]) { // Degree of v is less than k, // then degree of adjacent // must be reduced if (vDegree[v] < k) vDegree[i]--; // If adjacent is not // processed, process it if (!visited[i]) { // If degree of adjacent after // processing becomes less than // k, then reduce degree of v also. DFSUtil(i, visited, vDegree, k); } } // Return true if degree of // v is less than k return (vDegree[v] < k); } // Prints k cores of an undirected graph public void printKCores(int k) { // INITIALIZATION // Mark all the vertices as not // visited and not processed. bool[] visited = new bool[V]; //bool[] processed = new bool[V]; int mindeg = int.MaxValue; int startvertex = 0; // Store degrees of all vertices int[] vDegree = new int[V]; for(int i = 0; i < V; i++) { vDegree[i] = adj[i].Count; if (vDegree[i] < mindeg) { mindeg = vDegree[i]; startvertex = i; } } DFSUtil(startvertex, visited, vDegree, k); // DFS traversal to update degrees of all // vertices. for(int i = 0; i < V; i++) if (!visited[i]) DFSUtil(i, visited, vDegree, k); // PRINTING K CORES Console.WriteLine("K-Cores : "); for(int v = 0; v < V; v++) { // Only considering those vertices // which have degree >= K after BFS if (vDegree[v] >= k) { Console.Write("\n " + v); // Traverse adjacency list of v // and print only those adjacent // which have vDegree >= k after // DFS. foreach(int i in adj[v]) if (vDegree[i] >= k) Console.Write(" -> " + i); } } }} // Driver Codepublic static void Main(String[] args){ // Create a graph given in the // above diagram int k = 3; Graph g1 = new Graph(9); g1.addEdge(0, 1); g1.addEdge(0, 2); g1.addEdge(1, 2); g1.addEdge(1, 5); g1.addEdge(2, 3); g1.addEdge(2, 4); g1.addEdge(2, 5); g1.addEdge(2, 6); g1.addEdge(3, 4); g1.addEdge(3, 6); g1.addEdge(3, 7); g1.addEdge(4, 6); g1.addEdge(4, 7); g1.addEdge(5, 6); g1.addEdge(5, 8); g1.addEdge(6, 7); g1.addEdge(6, 8); g1.printKCores(k); Console.WriteLine(); Graph g2 = new Graph(13); g2.addEdge(0, 1); g2.addEdge(0, 2); g2.addEdge(0, 3); g2.addEdge(1, 4); g2.addEdge(1, 5); g2.addEdge(1, 6); g2.addEdge(2, 7); g2.addEdge(2, 8); g2.addEdge(2, 9); g2.addEdge(3, 10); g2.addEdge(3, 11); g2.addEdge(3, 12); g2.printKCores(k);}} // This code is contributed by Princi Singh
Output :
K-Cores :
[2] -> 3 -> 4 -> 6
[3] -> 2 -> 4 -> 6 -> 7
[4] -> 2 -> 3 -> 6 -> 7
[6] -> 2 -> 3 -> 4 -> 7
[7] -> 3 -> 4 -> 6
K-Cores :
K-Cores :
[2] -> 4 -> 3 -> 6
[3] -> 2 -> 4 -> 6
[4] -> 2 -> 3 -> 6
[6] -> 2 -> 3 -> 4
Time complexity of the above solution is O(V + E) where V is number of vertices and E is number of edges.
Related Concepts : Degeneracy : Degeneracy of a graph is the largest value k such that the graph has a k-core. For example, the above shown graph has a 3-Cores and doesn’t have 4 or higher cores. Therefore, above graph is 3-degenerate. Degeneracy of a graph is used to measure how sparse graph is.
Reference : https://en.wikipedia.org/wiki/Degeneracy_%28graph_theory%29This article is contributed by Rachit Belwariar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
brainiac
sanjeev2552
princi singh
harish garg
saurabhjain17
vineetmalik06
amartyaniel20
anuragupadhyay319
idubeyofficial
graph-connectivity
Graph
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Find if there is a path between two vertices in a directed graph
Topological Sorting
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Detect Cycle in a Directed Graph
Find if there is a path between two vertices in an undirected graph
Introduction to Data Structures
Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)
Floyd Warshall Algorithm | DP-16
Bellman–Ford Algorithm | DP-23
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n30 Jun, 2022"
},
{
"code": null,
"e": 219,
"s": 52,
"text": "Given a graph G and an integer K, K-cores of the graph are connected components that are left after all vertices of degree less than k have been removed (Source wiki)"
},
{
"code": null,
"e": 229,
"s": 219,
"text": "Example: "
},
{
"code": null,
"e": 449,
"s": 229,
"text": "Input : Adjacency list representation of graph shown\n on left side of below diagram\nOutput: K-Cores : \n[2] -> 3 -> 4 -> 6\n[3] -> 2 -> 4 -> 6 -> 7\n[4] -> 2 -> 3 -> 6 -> 7\n[6] -> 2 -> 3 -> 4 -> 7\n[7] -> 3 -> 4 -> 6"
},
{
"code": null,
"e": 947,
"s": 449,
"text": " We strongly recommend you to minimize your browser and try this yourself first.The standard algorithm to find a k-core graph is to remove all the vertices that have degree less than- ‘K’ from the input graph. We must be careful that removing a vertex reduces the degree of all the vertices adjacent to it, hence the degree of adjacent vertices can also drop below-‘K’. And thus, we may have to remove those vertices also. This process may/may not go until there are no vertices left in the graph."
},
{
"code": null,
"e": 1185,
"s": 947,
"text": "To implement above algorithm, we do a modified DFS on the input graph and delete all the vertices having degree less than ‘K’, then update degrees of all the adjacent vertices, and if their degree falls below ‘K’ we will delete them too."
},
{
"code": null,
"e": 1382,
"s": 1185,
"text": "Below is implementation of above idea. Note that the below program only prints vertices of k cores, but it can be easily extended to print the complete k cores as we have modified adjacency list. "
},
{
"code": null,
"e": 1388,
"s": 1382,
"text": "C++14"
},
{
"code": null,
"e": 1393,
"s": 1388,
"text": "Java"
},
{
"code": null,
"e": 1401,
"s": 1393,
"text": "Python3"
},
{
"code": null,
"e": 1404,
"s": 1401,
"text": "C#"
},
{
"code": "// C++ program to find K-Cores of a graph#include<bits/stdc++.h>using namespace std; // This class represents a undirected graph using adjacency// list representationclass Graph{ int V; // No. of vertices // Pointer to an array containing adjacency lists list<int> *adj;public: Graph(int V); // Constructor // function to add an edge to graph void addEdge(int u, int v); // A recursive function to print DFS starting from v bool DFSUtil(int, vector<bool> &, vector<int> &, int k); // prints k-Cores of given graph void printKCores(int k);}; // A recursive function to print DFS starting from v.// It returns true if degree of v after processing is less// than k else false// It also updates degree of adjacent if degree of v// is less than k. And if degree of a processed adjacent// becomes less than k, then it reduces of degree of v also,bool Graph::DFSUtil(int v, vector<bool> &visited, vector<int> &vDegree, int k){ // Mark the current node as visited and print it visited[v] = true; // Recur for all the vertices adjacent to this vertex list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) { // degree of v is less than k, then degree of adjacent // must be reduced if (vDegree[v] < k) vDegree[*i]--; // If adjacent is not processed, process it if (!visited[*i]) { // If degree of adjacent after processing becomes // less than k, then reduce degree of v also. DFSUtil(*i, visited, vDegree, k); } } // Return true if degree of v is less than k return (vDegree[v] < k);} Graph::Graph(int V){ this->V = V; adj = new list<int>[V];} void Graph::addEdge(int u, int v){ adj[u].push_back(v); adj[v].push_back(u);} // Prints k cores of an undirected graphvoid Graph::printKCores(int k){ // INITIALIZATION // Mark all the vertices as not visited and not // processed. vector<bool> visited(V, false); vector<bool> processed(V, false); int mindeg = INT_MAX; int startvertex; // Store degrees of all vertices vector<int> vDegree(V); for (int i=0; i<V; i++) { vDegree[i] = adj[i].size(); if (vDegree[i] < mindeg) { mindeg = vDegree[i]; startvertex=i; } } DFSUtil(startvertex, visited, vDegree, k); // If Graph is disconnected. for (int i=0; i<V; i++) if (visited[i] == false) DFSUtil(i, visited, vDegree, k); // Considering Edge Case (Example 3 in main() function) for (int v=0; v<V; v++){ if (vDegree[v] >= k){ int cnt = 0; list<int>::iterator itr; for (itr = adj[v].begin(); itr != adj[v].end(); ++itr) if (vDegree[*itr] >= k) cnt++; if(cnt < k) vDegree[v] = cnt; } } // PRINTING K CORES cout << \"K-Cores : \\n\"; for (int v=0; v<V; v++) { // Only considering those vertices which have degree // >= K after DFS if (vDegree[v] >= k) { cout << \"\\n[\" << v << \"]\"; // Traverse adjacency list of v and print only // those adjacent which have vDegree >= k after // DFS. list<int>::iterator itr; for (itr = adj[v].begin(); itr != adj[v].end(); ++itr) if (vDegree[*itr] >= k) cout << \" -> \" << *itr; } }} // Driver program to test methods of graph classint main(){ // Create a graph given in the above diagram int k = 3; Graph g1(9); g1.addEdge(0, 1); g1.addEdge(0, 2); g1.addEdge(1, 2); g1.addEdge(1, 5); g1.addEdge(2, 3); g1.addEdge(2, 4); g1.addEdge(2, 5); g1.addEdge(2, 6); g1.addEdge(3, 4); g1.addEdge(3, 6); g1.addEdge(3, 7); g1.addEdge(4, 6); g1.addEdge(4, 7); g1.addEdge(5, 6); g1.addEdge(5, 8); g1.addEdge(6, 7); g1.addEdge(6, 8); g1.printKCores(k); cout << endl << endl; Graph g2(13); g2.addEdge(0, 1); g2.addEdge(0, 2); g2.addEdge(0, 3); g2.addEdge(1, 4); g2.addEdge(1, 5); g2.addEdge(1, 6); g2.addEdge(2, 7); g2.addEdge(2, 8); g2.addEdge(2, 9); g2.addEdge(3, 10); g2.addEdge(3, 11); g2.addEdge(3, 12); g2.printKCores(k); Graph gr(9); gr.addEdge(0, 1); gr.addEdge(0, 2); gr.addEdge(1, 2); gr.addEdge(2, 5); gr.addEdge(2, 4); gr.addEdge(2, 3); gr.addEdge(2, 6); gr.addEdge(3, 4); gr.addEdge(3, 6); gr.addEdge(3, 7); gr.addEdge(4, 6); gr.addEdge(5, 6); gr.addEdge(5, 7); gr.addEdge(5, 8); gr.addEdge(8, 7); gr.printKCores(k); return 0;}",
"e": 6104,
"s": 1404,
"text": null
},
{
"code": "// Java program to find K-Cores of a graphimport java.util.*; class GFG{ // This class represents a undirected graph using adjacency // list representation static class Graph { int V; // No. of vertices // Pointer to an array containing adjacency lists Vector<Integer>[] adj; @SuppressWarnings(\"unchecked\") Graph(int V) { this.V = V; this.adj = new Vector[V]; for (int i = 0; i < V; i++) adj[i] = new Vector<>(); } // function to add an edge to graph void addEdge(int u, int v) { this.adj[u].add(v); this.adj[v].add(u); } // A recursive function to print DFS starting from v. // It returns true if degree of v after processing is less // than k else false // It also updates degree of adjacent if degree of v // is less than k. And if degree of a processed adjacent // becomes less than k, then it reduces of degree of v also, boolean DFSUtil(int v, boolean[] visited, int[] vDegree, int k) { // Mark the current node as visited and print it visited[v] = true; // Recur for all the vertices adjacent to this vertex for (int i : adj[v]) { // degree of v is less than k, then degree of adjacent // must be reduced if (vDegree[v] < k) vDegree[i]--; // If adjacent is not processed, process it if (!visited[i]) { // If degree of adjacent after processing becomes // less than k, then reduce degree of v also. DFSUtil(i, visited, vDegree, k); } } // Return true if degree of v is less than k return (vDegree[v] < k); } // Prints k cores of an undirected graph void printKCores(int k) { // INITIALIZATION // Mark all the vertices as not visited and not // processed. boolean[] visited = new boolean[V]; boolean[] processed = new boolean[V]; Arrays.fill(visited, false); Arrays.fill(processed, false); int mindeg = Integer.MAX_VALUE; int startvertex = 0; // Store degrees of all vertices int[] vDegree = new int[V]; for (int i = 0; i < V; i++) { vDegree[i] = adj[i].size(); if (vDegree[i] < mindeg) { mindeg = vDegree[i]; startvertex = i; } } DFSUtil(startvertex, visited, vDegree, k); // DFS traversal to update degrees of all // vertices. for (int i = 0; i < V; i++) if (!visited[i]) DFSUtil(i, visited, vDegree, k); // PRINTING K CORES System.out.println(\"K-Cores : \"); for (int v = 0; v < V; v++) { // Only considering those vertices which have degree // >= K after BFS if (vDegree[v] >= k) { System.out.printf(\"\\n[%d]\", v); // Traverse adjacency list of v and print only // those adjacent which have vDegree >= k after // DFS. for (int i : adj[v]) if (vDegree[i] >= k) System.out.printf(\" -> %d\", i); } } } } // Driver Code public static void main(String[] args) { // Create a graph given in the above diagram int k = 3; Graph g1 = new Graph(9); g1.addEdge(0, 1); g1.addEdge(0, 2); g1.addEdge(1, 2); g1.addEdge(1, 5); g1.addEdge(2, 3); g1.addEdge(2, 4); g1.addEdge(2, 5); g1.addEdge(2, 6); g1.addEdge(3, 4); g1.addEdge(3, 6); g1.addEdge(3, 7); g1.addEdge(4, 6); g1.addEdge(4, 7); g1.addEdge(5, 6); g1.addEdge(5, 8); g1.addEdge(6, 7); g1.addEdge(6, 8); g1.printKCores(k); System.out.println(); Graph g2 = new Graph(13); g2.addEdge(0, 1); g2.addEdge(0, 2); g2.addEdge(0, 3); g2.addEdge(1, 4); g2.addEdge(1, 5); g2.addEdge(1, 6); g2.addEdge(2, 7); g2.addEdge(2, 8); g2.addEdge(2, 9); g2.addEdge(3, 10); g2.addEdge(3, 11); g2.addEdge(3, 12); g2.printKCores(k); }} // This code is contributed by// sanjeev2552",
"e": 10823,
"s": 6104,
"text": null
},
{
"code": "#saurabh_jain861# Python program to find K-Cores of a graphfrom collections import defaultdict # This class represents a undirected graph using adjacency# list representation class Graph: def __init__(self): # default dictionary to store graph self.graph = defaultdict(list) # function to add an edge to undirected graph def addEdge(self, u, v): self.graph[u].append(v) self.graph[v].append(u) # A recursive function to call DFS starting from v. # It returns true if vDegree of v after processing is less # than k else false # It also updates vDegree of adjacent if vDegree of v # is less than k. And if vDegree of a processed adjacent # becomes less than k, then it reduces of vDegree of v also, def DFSUtil(self, v, visited, vDegree, k): # Mark the current node as visited visited.add(v) # Recur for all the vertices adjacent to this vertex for i in self.graph[v]: # vDegree of v is less than k, then vDegree of # adjacent must be reduced if vDegree[v] < k: vDegree[i] = vDegree[i] - 1 # If adjacent is not processed, process it if i not in visited: # If vDegree of adjacent after processing becomes # less than k, then reduce vDegree of v also self.DFSUtil(i, visited, vDegree, k) def PrintKCores(self, k): visit = set() degree = defaultdict(lambda: 0) for i in list(self.graph): degree[i] = len(self.graph[i]) for i in list(self.graph): if i not in visit: self.DFSUtil(i, visit, degree, k) # print(degree) # print(self.graph) for i in list(self.graph): if degree[i] >= k: print(str(\"\\n [ \") + str(i) + str(\" ]\"), end=\" \") for j in self.graph[i]: if degree[j] >= k: print(\"-> \" + str(j), end=\" \") print() k = 3g1 = Graph()g1.addEdge(0, 1)g1.addEdge(0, 2)g1.addEdge(1, 2)g1.addEdge(1, 5)g1.addEdge(2, 3)g1.addEdge(2, 4)g1.addEdge(2, 5)g1.addEdge(2, 6)g1.addEdge(3, 4)g1.addEdge(3, 6)g1.addEdge(3, 7)g1.addEdge(4, 6)g1.addEdge(4, 7)g1.addEdge(5, 6)g1.addEdge(5, 8)g1.addEdge(6, 7)g1.addEdge(6, 8)g1.PrintKCores(k)",
"e": 13147,
"s": 10823,
"text": null
},
{
"code": "// C# program to find K-Cores of a graphusing System;using System.Collections.Generic; class GFG{ // This class represents a undirected// graph using adjacency list// representationpublic class Graph{ // No. of vertices int V; // Pointer to an array containing // adjacency lists List<int>[] adj; public Graph(int V) { this.V = V; this.adj = new List<int>[V]; for(int i = 0; i < V; i++) adj[i] = new List<int>(); } // Function to add an edge to graph public void addEdge(int u, int v) { this.adj[u].Add(v); this.adj[v].Add(u); } // A recursive function to print DFS // starting from v. It returns true // if degree of v after processing // is less than k else false // It also updates degree of adjacent // if degree of v is less than k. And // if degree of a processed adjacent // becomes less than k, then it reduces // of degree of v also, bool DFSUtil(int v, bool[] visited, int[] vDegree, int k) { // Mark the current node as // visited and print it visited[v] = true; // Recur for all the vertices // adjacent to this vertex foreach (int i in adj[v]) { // Degree of v is less than k, // then degree of adjacent // must be reduced if (vDegree[v] < k) vDegree[i]--; // If adjacent is not // processed, process it if (!visited[i]) { // If degree of adjacent after // processing becomes less than // k, then reduce degree of v also. DFSUtil(i, visited, vDegree, k); } } // Return true if degree of // v is less than k return (vDegree[v] < k); } // Prints k cores of an undirected graph public void printKCores(int k) { // INITIALIZATION // Mark all the vertices as not // visited and not processed. bool[] visited = new bool[V]; //bool[] processed = new bool[V]; int mindeg = int.MaxValue; int startvertex = 0; // Store degrees of all vertices int[] vDegree = new int[V]; for(int i = 0; i < V; i++) { vDegree[i] = adj[i].Count; if (vDegree[i] < mindeg) { mindeg = vDegree[i]; startvertex = i; } } DFSUtil(startvertex, visited, vDegree, k); // DFS traversal to update degrees of all // vertices. for(int i = 0; i < V; i++) if (!visited[i]) DFSUtil(i, visited, vDegree, k); // PRINTING K CORES Console.WriteLine(\"K-Cores : \"); for(int v = 0; v < V; v++) { // Only considering those vertices // which have degree >= K after BFS if (vDegree[v] >= k) { Console.Write(\"\\n \" + v); // Traverse adjacency list of v // and print only those adjacent // which have vDegree >= k after // DFS. foreach(int i in adj[v]) if (vDegree[i] >= k) Console.Write(\" -> \" + i); } } }} // Driver Codepublic static void Main(String[] args){ // Create a graph given in the // above diagram int k = 3; Graph g1 = new Graph(9); g1.addEdge(0, 1); g1.addEdge(0, 2); g1.addEdge(1, 2); g1.addEdge(1, 5); g1.addEdge(2, 3); g1.addEdge(2, 4); g1.addEdge(2, 5); g1.addEdge(2, 6); g1.addEdge(3, 4); g1.addEdge(3, 6); g1.addEdge(3, 7); g1.addEdge(4, 6); g1.addEdge(4, 7); g1.addEdge(5, 6); g1.addEdge(5, 8); g1.addEdge(6, 7); g1.addEdge(6, 8); g1.printKCores(k); Console.WriteLine(); Graph g2 = new Graph(13); g2.addEdge(0, 1); g2.addEdge(0, 2); g2.addEdge(0, 3); g2.addEdge(1, 4); g2.addEdge(1, 5); g2.addEdge(1, 6); g2.addEdge(2, 7); g2.addEdge(2, 8); g2.addEdge(2, 9); g2.addEdge(3, 10); g2.addEdge(3, 11); g2.addEdge(3, 12); g2.printKCores(k);}} // This code is contributed by Princi Singh",
"e": 17475,
"s": 13147,
"text": null
},
{
"code": null,
"e": 17484,
"s": 17475,
"text": "Output :"
},
{
"code": null,
"e": 17706,
"s": 17484,
"text": "K-Cores : \n\n[2] -> 3 -> 4 -> 6\n[3] -> 2 -> 4 -> 6 -> 7\n[4] -> 2 -> 3 -> 6 -> 7\n[6] -> 2 -> 3 -> 4 -> 7\n[7] -> 3 -> 4 -> 6\n\nK-Cores : \nK-Cores : \n\n[2] -> 4 -> 3 -> 6\n[3] -> 2 -> 4 -> 6\n[4] -> 2 -> 3 -> 6\n[6] -> 2 -> 3 -> 4"
},
{
"code": null,
"e": 17812,
"s": 17706,
"text": "Time complexity of the above solution is O(V + E) where V is number of vertices and E is number of edges."
},
{
"code": null,
"e": 18110,
"s": 17812,
"text": "Related Concepts : Degeneracy : Degeneracy of a graph is the largest value k such that the graph has a k-core. For example, the above shown graph has a 3-Cores and doesn’t have 4 or higher cores. Therefore, above graph is 3-degenerate. Degeneracy of a graph is used to measure how sparse graph is."
},
{
"code": null,
"e": 18355,
"s": 18110,
"text": "Reference : https://en.wikipedia.org/wiki/Degeneracy_%28graph_theory%29This article is contributed by Rachit Belwariar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 18364,
"s": 18355,
"text": "brainiac"
},
{
"code": null,
"e": 18376,
"s": 18364,
"text": "sanjeev2552"
},
{
"code": null,
"e": 18389,
"s": 18376,
"text": "princi singh"
},
{
"code": null,
"e": 18401,
"s": 18389,
"text": "harish garg"
},
{
"code": null,
"e": 18415,
"s": 18401,
"text": "saurabhjain17"
},
{
"code": null,
"e": 18429,
"s": 18415,
"text": "vineetmalik06"
},
{
"code": null,
"e": 18443,
"s": 18429,
"text": "amartyaniel20"
},
{
"code": null,
"e": 18461,
"s": 18443,
"text": "anuragupadhyay319"
},
{
"code": null,
"e": 18476,
"s": 18461,
"text": "idubeyofficial"
},
{
"code": null,
"e": 18495,
"s": 18476,
"text": "graph-connectivity"
},
{
"code": null,
"e": 18501,
"s": 18495,
"text": "Graph"
},
{
"code": null,
"e": 18507,
"s": 18501,
"text": "Graph"
},
{
"code": null,
"e": 18605,
"s": 18507,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 18670,
"s": 18605,
"text": "Find if there is a path between two vertices in a directed graph"
},
{
"code": null,
"e": 18690,
"s": 18670,
"text": "Topological Sorting"
},
{
"code": null,
"e": 18748,
"s": 18690,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
},
{
"code": null,
"e": 18781,
"s": 18748,
"text": "Detect Cycle in a Directed Graph"
},
{
"code": null,
"e": 18849,
"s": 18781,
"text": "Find if there is a path between two vertices in an undirected graph"
},
{
"code": null,
"e": 18881,
"s": 18849,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 18956,
"s": 18881,
"text": "Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)"
},
{
"code": null,
"e": 18989,
"s": 18956,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 19020,
"s": 18989,
"text": "Bellman–Ford Algorithm | DP-23"
}
] |
Hardware Synchronization Algorithms : Unlock and Lock, Test and Set, Swap | 25 Aug, 2021
Process Synchronization problems occur when two processes running concurrently share the same data or same variable. The value of that variable may not be updated correctly before its being used by a second process. Such a condition is known as Race Around Condition. There are software as well as hardware solutions to this problem. In this article, we will talk about the most efficient hardware solution to process synchronization problems and its implementation.
There are three algorithms in the hardware approach of solving Process Synchronization problem:
Test and Set Swap Unlock and Lock
Test and Set
Swap
Unlock and Lock
Hardware instructions in many operating systems help in effective solution of critical section problems.
1. Test and Set : Here, the shared variable is lock which is initialized to false. TestAndSet(lock) algorithm works in this way – it always returns whatever value is sent to it and sets lock to true. The first process will enter the critical section at once as TestAndSet(lock) will return false and it’ll break out of the while loop. The other processes cannot enter now as lock is set to true and so the while loop continues to be true. Mutual exclusion is ensured. Once the first process gets out of the critical section, lock is changed to false. So, now the other processes can enter one by one. Progress is also ensured. However, after the first process any process can go in. There is no queue maintained, so any new process that finds the lock to be false again, can enter. So bounded waiting is not ensured.
Test and Set Pseudocode –
//Shared variable lock initialized to false
boolean lock;
boolean TestAndSet (boolean &target){
boolean rv = target;
target = true;
return rv;
}
while(1){
while (TestAndSet(lock));
critical section
lock = false;
remainder section
}
2. Swap : Swap algorithm is a lot like the TestAndSet algorithm. Instead of directly setting lock to true in the swap function, key is set to true and then swapped with lock. So, again, when a process is in the critical section, no other process gets to enter it as the value of lock is true. Mutual exclusion is ensured. Again, out of the critical section, lock is changed to false, so any process finding it gets t enter the critical section. Progress is ensured. However, again bounded waiting is not ensured for the very same reason.
Swap Pseudocode –
// Shared variable lock initialized to false
// and individual key initialized to false;
boolean lock;
Individual key;
void swap(boolean &a, boolean &b){
boolean temp = a;
a = b;
b = temp;
}
while (1){
key = true;
while(key)
swap(lock,key);
critical section
lock = false;
remainder section
}
3. Unlock and Lock : Unlock and Lock Algorithm uses TestAndSet to regulate the value of lock but it adds another value, waiting[i], for each process which checks whether or not a process has been waiting. A ready queue is maintained with respect to the process in the critical section. All the processes coming in next are added to the ready queue with respect to their process number, not necessarily sequentially. Once the ith process gets out of the critical section, it does not turn lock to false so that any process can avail the critical section now, which was the problem with the previous algorithms. Instead, it checks if there is any process waiting in the queue. The queue is taken to be a circular queue. j is considered to be the next process in line and the while loop checks from jth process to the last process and again from 0 to (i-1)th process if there is any process waiting to access the critical section. If there is no process waiting then the lock value is changed to false and any process which comes next can enter the critical section. If there is, then that process’ waiting value is turned to false, so that the first while loop becomes false and it can enter the critical section. This ensures bounded waiting. So the problem of process synchronization can be solved through this algorithm.
Unlock and Lock Pseudocode –
// Shared variable lock initialized to false
// and individual key initialized to false
boolean lock;
Individual key;
Individual waiting[i];
while(1){
waiting[i] = true;
key = true;
while(waiting[i] && key)
key = TestAndSet(lock);
critical section
j = (i+1) % n;
while(j != i && !waiting[j])
j = (j+1) % n;
if(j == i)
lock = false;
else
waiting[j] = false;
remainder section
}
surindertarika1234
Process Synchronization
GATE CS
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n25 Aug, 2021"
},
{
"code": null,
"e": 520,
"s": 52,
"text": "Process Synchronization problems occur when two processes running concurrently share the same data or same variable. The value of that variable may not be updated correctly before its being used by a second process. Such a condition is known as Race Around Condition. There are software as well as hardware solutions to this problem. In this article, we will talk about the most efficient hardware solution to process synchronization problems and its implementation. "
},
{
"code": null,
"e": 617,
"s": 520,
"text": "There are three algorithms in the hardware approach of solving Process Synchronization problem: "
},
{
"code": null,
"e": 652,
"s": 617,
"text": "Test and Set Swap Unlock and Lock "
},
{
"code": null,
"e": 666,
"s": 652,
"text": "Test and Set "
},
{
"code": null,
"e": 672,
"s": 666,
"text": "Swap "
},
{
"code": null,
"e": 689,
"s": 672,
"text": "Unlock and Lock "
},
{
"code": null,
"e": 795,
"s": 689,
"text": "Hardware instructions in many operating systems help in effective solution of critical section problems. "
},
{
"code": null,
"e": 1613,
"s": 795,
"text": "1. Test and Set : Here, the shared variable is lock which is initialized to false. TestAndSet(lock) algorithm works in this way – it always returns whatever value is sent to it and sets lock to true. The first process will enter the critical section at once as TestAndSet(lock) will return false and it’ll break out of the while loop. The other processes cannot enter now as lock is set to true and so the while loop continues to be true. Mutual exclusion is ensured. Once the first process gets out of the critical section, lock is changed to false. So, now the other processes can enter one by one. Progress is also ensured. However, after the first process any process can go in. There is no queue maintained, so any new process that finds the lock to be false again, can enter. So bounded waiting is not ensured. "
},
{
"code": null,
"e": 1640,
"s": 1613,
"text": "Test and Set Pseudocode – "
},
{
"code": null,
"e": 1904,
"s": 1640,
"text": "//Shared variable lock initialized to false\nboolean lock;\n\nboolean TestAndSet (boolean &target){\n boolean rv = target;\n target = true;\n return rv;\n}\n\nwhile(1){\n while (TestAndSet(lock));\n critical section\n lock = false;\n remainder section\n}\n "
},
{
"code": null,
"e": 2443,
"s": 1904,
"text": "2. Swap : Swap algorithm is a lot like the TestAndSet algorithm. Instead of directly setting lock to true in the swap function, key is set to true and then swapped with lock. So, again, when a process is in the critical section, no other process gets to enter it as the value of lock is true. Mutual exclusion is ensured. Again, out of the critical section, lock is changed to false, so any process finding it gets t enter the critical section. Progress is ensured. However, again bounded waiting is not ensured for the very same reason. "
},
{
"code": null,
"e": 2462,
"s": 2443,
"text": "Swap Pseudocode – "
},
{
"code": null,
"e": 2800,
"s": 2462,
"text": "// Shared variable lock initialized to false \n// and individual key initialized to false;\n\nboolean lock;\nIndividual key;\n\nvoid swap(boolean &a, boolean &b){\n boolean temp = a;\n a = b;\n b = temp;\n}\n\nwhile (1){\n key = true;\n while(key)\n swap(lock,key);\n critical section\n lock = false;\n remainder section\n} "
},
{
"code": null,
"e": 4123,
"s": 2800,
"text": "3. Unlock and Lock : Unlock and Lock Algorithm uses TestAndSet to regulate the value of lock but it adds another value, waiting[i], for each process which checks whether or not a process has been waiting. A ready queue is maintained with respect to the process in the critical section. All the processes coming in next are added to the ready queue with respect to their process number, not necessarily sequentially. Once the ith process gets out of the critical section, it does not turn lock to false so that any process can avail the critical section now, which was the problem with the previous algorithms. Instead, it checks if there is any process waiting in the queue. The queue is taken to be a circular queue. j is considered to be the next process in line and the while loop checks from jth process to the last process and again from 0 to (i-1)th process if there is any process waiting to access the critical section. If there is no process waiting then the lock value is changed to false and any process which comes next can enter the critical section. If there is, then that process’ waiting value is turned to false, so that the first while loop becomes false and it can enter the critical section. This ensures bounded waiting. So the problem of process synchronization can be solved through this algorithm. "
},
{
"code": null,
"e": 4153,
"s": 4123,
"text": "Unlock and Lock Pseudocode – "
},
{
"code": null,
"e": 4605,
"s": 4153,
"text": "// Shared variable lock initialized to false \n// and individual key initialized to false\n\nboolean lock;\nIndividual key;\nIndividual waiting[i];\n\nwhile(1){\n waiting[i] = true;\n key = true;\n while(waiting[i] && key)\n key = TestAndSet(lock);\n critical section\n j = (i+1) % n;\n while(j != i && !waiting[j])\n j = (j+1) % n;\n if(j == i)\n lock = false;\n else\n waiting[j] = false;\n remainder section\n} "
},
{
"code": null,
"e": 4626,
"s": 4607,
"text": "surindertarika1234"
},
{
"code": null,
"e": 4650,
"s": 4626,
"text": "Process Synchronization"
},
{
"code": null,
"e": 4658,
"s": 4650,
"text": "GATE CS"
},
{
"code": null,
"e": 4676,
"s": 4658,
"text": "Operating Systems"
},
{
"code": null,
"e": 4694,
"s": 4676,
"text": "Operating Systems"
}
] |
Mathematics | Conditional Probability | 28 Jun, 2021
Conditional probability P(A | B) indicates the probability of event ‘A’ happening given that event B happened.
We can easily understand the above formula using the below diagram. Since B has already happened, the sample space reduces to B. So the probability of A happening becomes divided by P(B)
Example:In a batch, there are 80% C programmers, and 40% are Java and C programmers. What is the probability that a C programmer is also Java programmer?
Let A --> Event that a student is Java programmer
B --> Event that a student is C programmer
P(A|B) = P(A ∩ B) / P(B)
= (0.4) / (0.8)
= 0.5
So there are 50% chances that student that knows C also
knows Java
Product Rule:Derived from above definition of conditional probability by multiplying both sides with P(B)
P(A ∩ B) = P(B) * P(A|B)
Understanding Conditional probability through tree:Computation for Conditional Probability can be done using tree, This method is very handy as well as fast when for many problems.
Example: In a certain library, twenty percent of the fiction books are worn and need replacement. Ten percent of the non-fiction books are worn and need replacement. Forty percent of the library’s books are fiction and sixty percent are non-fiction. What is the probability that a book chosen at random are worn? Draw a tree diagram representing the data.
Solution: Let F represents fiction books and N represents non-fiction books. Let W represents worn books and G represents non-worn books.
P(worn)= P(N)*P(W | N) + P(F)*P(W | F)
= 0.6*0.1 + 0.4* 0.2
= 0.14
Exercise:1) What is the value of P(A|A)?
2) Let P(E) denote the probability of the event E. Given P(A) = 1, P(B) = 1/2, the values of P(A | B) and P(B | A) respectively are (GATE CS 2003)(A) 1/4, 1/2(B) 1/2, 1/14(C) 1/2, 1(D) 1, 1/2See this for solution.
References:http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-042j-mathematics-for-computer-science-fall-2010/video-lectures/lecture-19-conditional-probability/
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
VaibhavRai3
Tushar512
Engineering Mathematics
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 163,
"s": 52,
"text": "Conditional probability P(A | B) indicates the probability of event ‘A’ happening given that event B happened."
},
{
"code": null,
"e": 357,
"s": 169,
"text": "We can easily understand the above formula using the below diagram. Since B has already happened, the sample space reduces to B. So the probability of A happening becomes divided by P(B)"
},
{
"code": null,
"e": 511,
"s": 357,
"text": "Example:In a batch, there are 80% C programmers, and 40% are Java and C programmers. What is the probability that a C programmer is also Java programmer?"
},
{
"code": null,
"e": 750,
"s": 511,
"text": "Let A --> Event that a student is Java programmer\n B --> Event that a student is C programmer\n P(A|B) = P(A ∩ B) / P(B)\n = (0.4) / (0.8)\n = 0.5\nSo there are 50% chances that student that knows C also \nknows Java "
},
{
"code": null,
"e": 856,
"s": 750,
"text": "Product Rule:Derived from above definition of conditional probability by multiplying both sides with P(B)"
},
{
"code": null,
"e": 886,
"s": 856,
"text": "\n P(A ∩ B) = P(B) * P(A|B) "
},
{
"code": null,
"e": 1067,
"s": 886,
"text": "Understanding Conditional probability through tree:Computation for Conditional Probability can be done using tree, This method is very handy as well as fast when for many problems."
},
{
"code": null,
"e": 1423,
"s": 1067,
"text": "Example: In a certain library, twenty percent of the fiction books are worn and need replacement. Ten percent of the non-fiction books are worn and need replacement. Forty percent of the library’s books are fiction and sixty percent are non-fiction. What is the probability that a book chosen at random are worn? Draw a tree diagram representing the data."
},
{
"code": null,
"e": 1561,
"s": 1423,
"text": "Solution: Let F represents fiction books and N represents non-fiction books. Let W represents worn books and G represents non-worn books."
},
{
"code": null,
"e": 1675,
"s": 1561,
"text": "P(worn)= P(N)*P(W | N) + P(F)*P(W | F)\n \n = 0.6*0.1 + 0.4* 0.2 \n = 0.14\n\n"
},
{
"code": null,
"e": 1716,
"s": 1675,
"text": "Exercise:1) What is the value of P(A|A)?"
},
{
"code": null,
"e": 1930,
"s": 1716,
"text": "2) Let P(E) denote the probability of the event E. Given P(A) = 1, P(B) = 1/2, the values of P(A | B) and P(B | A) respectively are (GATE CS 2003)(A) 1/4, 1/2(B) 1/2, 1/14(C) 1/2, 1(D) 1, 1/2See this for solution."
},
{
"code": null,
"e": 2113,
"s": 1930,
"text": "References:http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-042j-mathematics-for-computer-science-fall-2010/video-lectures/lecture-19-conditional-probability/"
},
{
"code": null,
"e": 2237,
"s": 2113,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 2249,
"s": 2237,
"text": "VaibhavRai3"
},
{
"code": null,
"e": 2259,
"s": 2249,
"text": "Tushar512"
},
{
"code": null,
"e": 2283,
"s": 2259,
"text": "Engineering Mathematics"
},
{
"code": null,
"e": 2291,
"s": 2283,
"text": "GATE CS"
}
] |
Python | Permutation of a given string using inbuilt function | 03 Aug, 2020
A permutation, also called an “arrangement number” or “order”, is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself. A string of length n has n! permutation.
Examples:
Input : str = 'ABC'
Output : ABC
ACB
BAC
BCA
CAB
CBA
We have existing solution for this problem please refer Permutations of a given string using STL link. We can also solve this problem in python using inbuilt function permutations(iterable).
# Function to find permutations of a given stringfrom itertools import permutations def allPermutations(str): # Get all permutations of string 'ABC' permList = permutations(str) # print all permutations for perm in list(permList): print (''.join(perm)) # Driver programif __name__ == "__main__": str = 'ABC' allPermutations(str)
ABC
ACB
BAC
BCA
CAB
CBA
Permutation and Combination in Python
Permutations of a given string with repeating charactersThe idea is to use dictionary to avoid printing duplicates.
from itertools import permutationsimport string s = "GEEK"a = string.ascii_lettersp = permutations(s) # Create a dictionaryd = []for i in list(p): # Print only if not in dictionary if (i not in d): d.append(i) print(''.join(i))
GEEK
GEKE
GKEE
EGEK
EGKE
EEGK
EEKG
EKGE
EKEG
KGEE
KEGE
KEEG
Divyu_Pandey
Python string-programs
Python-Built-in-functions
python-string
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Enumerate() in Python
Different ways to create Pandas Dataframe
How to Install PIP on Windows ?
Python String | replace()
Python OOPs Concepts
Python Classes and Objects
*args and **kwargs in Python
Introduction To PYTHON
Create a Pandas DataFrame from Lists | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n03 Aug, 2020"
},
{
"code": null,
"e": 260,
"s": 52,
"text": "A permutation, also called an “arrangement number” or “order”, is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself. A string of length n has n! permutation."
},
{
"code": null,
"e": 270,
"s": 260,
"text": "Examples:"
},
{
"code": null,
"e": 374,
"s": 270,
"text": "Input : str = 'ABC'\nOutput : ABC \n ACB \n BAC \n BCA \n CAB \n CBA"
},
{
"code": null,
"e": 565,
"s": 374,
"text": "We have existing solution for this problem please refer Permutations of a given string using STL link. We can also solve this problem in python using inbuilt function permutations(iterable)."
},
{
"code": "# Function to find permutations of a given stringfrom itertools import permutations def allPermutations(str): # Get all permutations of string 'ABC' permList = permutations(str) # print all permutations for perm in list(permList): print (''.join(perm)) # Driver programif __name__ == \"__main__\": str = 'ABC' allPermutations(str)",
"e": 941,
"s": 565,
"text": null
},
{
"code": null,
"e": 966,
"s": 941,
"text": "ABC\nACB\nBAC\nBCA\nCAB\nCBA\n"
},
{
"code": null,
"e": 1004,
"s": 966,
"text": "Permutation and Combination in Python"
},
{
"code": null,
"e": 1120,
"s": 1004,
"text": "Permutations of a given string with repeating charactersThe idea is to use dictionary to avoid printing duplicates."
},
{
"code": "from itertools import permutationsimport string s = \"GEEK\"a = string.ascii_lettersp = permutations(s) # Create a dictionaryd = []for i in list(p): # Print only if not in dictionary if (i not in d): d.append(i) print(''.join(i))",
"e": 1372,
"s": 1120,
"text": null
},
{
"code": null,
"e": 1433,
"s": 1372,
"text": "GEEK\nGEKE\nGKEE\nEGEK\nEGKE\nEEGK\nEEKG\nEKGE\nEKEG\nKGEE\nKEGE\nKEEG\n"
},
{
"code": null,
"e": 1446,
"s": 1433,
"text": "Divyu_Pandey"
},
{
"code": null,
"e": 1469,
"s": 1446,
"text": "Python string-programs"
},
{
"code": null,
"e": 1495,
"s": 1469,
"text": "Python-Built-in-functions"
},
{
"code": null,
"e": 1509,
"s": 1495,
"text": "python-string"
},
{
"code": null,
"e": 1516,
"s": 1509,
"text": "Python"
},
{
"code": null,
"e": 1614,
"s": 1516,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1632,
"s": 1614,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1654,
"s": 1632,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1696,
"s": 1654,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1728,
"s": 1696,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1754,
"s": 1728,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1775,
"s": 1754,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1802,
"s": 1775,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1831,
"s": 1802,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 1854,
"s": 1831,
"text": "Introduction To PYTHON"
}
] |
DateTime.CompareTo() Method in C# | The DateTime.CompareTo() method in C# is used to compare the value of this instance to a specified DateTime value.
Following is the syntax −
public int CompareTo (DateTime val);
Above, Val is the date to be compared.
It returns an integer value,
<0 − If this instance is earlier than Val
0 − If this instance is the same as Val
>0 − If this instance is later than Val
Let us now see an example to implement the DateTime.CompareTo() method −
using System;
public class Demo {
public static void Main(){
DateTime date1 = new DateTime(2019, 05, 20, 6, 20, 40);
DateTime date2 = new DateTime(2019, 05, 20, 6, 20, 40);
Console.WriteLine("DateTime 1 = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", date1);
Console.WriteLine("DateTime 2 = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", date2);
int res = date1.CompareTo(date2);
// returns equal to 0 since date1 is equal to date2
Console.WriteLine(res);
}
}
This will produce the following output −
DateTime 1 = 20 November 2019, 06:20:40
DateTime 2 = 20 November 2019, 06:20:40
0
Let us now see another example to implement the DateTime.CompareTo() method −
using System;
public class Demo {
public static void Main(){
DateTime date1 = new DateTime(2019, 08, 20, 6, 20, 40);
DateTime date2 = new DateTime(2019, 05, 20, 6, 20, 40);
Console.WriteLine("DateTime 1 = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", date1);
Console.WriteLine("DateTime 2 = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", date2);
int res = date1.CompareTo(date2);
// returns >0 since date1 is later than date2
Console.WriteLine(res);
}
}
This will produce the following output −
DateTime 1 = 20 August 2019, 06:20:40
DateTime 2 = 20 May 2019, 06:20:40
1 | [
{
"code": null,
"e": 1177,
"s": 1062,
"text": "The DateTime.CompareTo() method in C# is used to compare the value of this instance to a specified DateTime value."
},
{
"code": null,
"e": 1203,
"s": 1177,
"text": "Following is the syntax −"
},
{
"code": null,
"e": 1240,
"s": 1203,
"text": "public int CompareTo (DateTime val);"
},
{
"code": null,
"e": 1279,
"s": 1240,
"text": "Above, Val is the date to be compared."
},
{
"code": null,
"e": 1308,
"s": 1279,
"text": "It returns an integer value,"
},
{
"code": null,
"e": 1350,
"s": 1308,
"text": "<0 − If this instance is earlier than Val"
},
{
"code": null,
"e": 1390,
"s": 1350,
"text": "0 − If this instance is the same as Val"
},
{
"code": null,
"e": 1430,
"s": 1390,
"text": ">0 − If this instance is later than Val"
},
{
"code": null,
"e": 1503,
"s": 1430,
"text": "Let us now see an example to implement the DateTime.CompareTo() method −"
},
{
"code": null,
"e": 1994,
"s": 1503,
"text": "using System;\npublic class Demo {\n public static void Main(){\n DateTime date1 = new DateTime(2019, 05, 20, 6, 20, 40);\n DateTime date2 = new DateTime(2019, 05, 20, 6, 20, 40);\n Console.WriteLine(\"DateTime 1 = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} \", date1);\n Console.WriteLine(\"DateTime 2 = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} \", date2);\n int res = date1.CompareTo(date2);\n // returns equal to 0 since date1 is equal to date2\n Console.WriteLine(res);\n }\n}"
},
{
"code": null,
"e": 2035,
"s": 1994,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2117,
"s": 2035,
"text": "DateTime 1 = 20 November 2019, 06:20:40\nDateTime 2 = 20 November 2019, 06:20:40\n0"
},
{
"code": null,
"e": 2195,
"s": 2117,
"text": "Let us now see another example to implement the DateTime.CompareTo() method −"
},
{
"code": null,
"e": 2680,
"s": 2195,
"text": "using System;\npublic class Demo {\n public static void Main(){\n DateTime date1 = new DateTime(2019, 08, 20, 6, 20, 40);\n DateTime date2 = new DateTime(2019, 05, 20, 6, 20, 40);\n Console.WriteLine(\"DateTime 1 = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} \", date1);\n Console.WriteLine(\"DateTime 2 = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} \", date2);\n int res = date1.CompareTo(date2);\n // returns >0 since date1 is later than date2\n Console.WriteLine(res);\n }\n}"
},
{
"code": null,
"e": 2721,
"s": 2680,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2796,
"s": 2721,
"text": "DateTime 1 = 20 August 2019, 06:20:40\nDateTime 2 = 20 May 2019, 06:20:40\n1"
}
] |
How to position horizontal scroll bar at center of DIV? | To position horizontal scroll bar at center of div, use the scrollleft. You can try to run the following code to position horizontal scroll bar in div.
The scroll bar is positioned at center of div:
Live Demo
<html>
<head>
<title>jQuery Scroll</title>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(document).ready(function(){
var outerContent = $('.demo');
var innerContent = $('.demo > div');
outerContent.scrollLeft( (innerContent.width() - outerContent.width()) / 2);
});
});
</script>
<style>
html, body, div {
margin:0;
padding:0;
}
.demo {
width:400px;
overflow-x:scroll;
}
#viewContainer {
height:120px;
width:1000px;
display:table;
}
.myclass {
width:250px;
height:100%;
display:table-cell;
border:2px solid blue;
}
</style>
</head>
<body>
<div class="demo">
<div id="viewContainer">
<div class="myclass" id="farLeft">Far left</div>
<div class="myclass" id="left">left</div>
<div class="myclass" id="center">center</div>
<div class="myclass" id="right">right</div>
<div class="myclass" id="farRight">Far right</div>
</div>
</div>
</body>
</html> | [
{
"code": null,
"e": 1214,
"s": 1062,
"text": "To position horizontal scroll bar at center of div, use the scrollleft. You can try to run the following code to position horizontal scroll bar in div."
},
{
"code": null,
"e": 1261,
"s": 1214,
"text": "The scroll bar is positioned at center of div:"
},
{
"code": null,
"e": 1271,
"s": 1261,
"text": "Live Demo"
},
{
"code": null,
"e": 2633,
"s": 1271,
"text": "<html>\n <head>\n \n <title>jQuery Scroll</title>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n \n <script>\n $(document).ready(function(){\n \n $(document).ready(function(){\n var outerContent = $('.demo');\n var innerContent = $('.demo > div');\n \n outerContent.scrollLeft( (innerContent.width() - outerContent.width()) / 2);\n \n });\n \n });\n </script>\n \n <style>\n html, body, div {\n margin:0;\n padding:0;\n }\n .demo {\n width:400px;\n overflow-x:scroll;\n }\n \n #viewContainer {\n height:120px;\n width:1000px;\n display:table;\n }\n .myclass {\n width:250px;\n height:100%;\n display:table-cell;\n border:2px solid blue;\n }\n </style>\n </head> \n<body>\n \n<div class=\"demo\">\n <div id=\"viewContainer\">\n <div class=\"myclass\" id=\"farLeft\">Far left</div>\n <div class=\"myclass\" id=\"left\">left</div>\n <div class=\"myclass\" id=\"center\">center</div>\n <div class=\"myclass\" id=\"right\">right</div>\n <div class=\"myclass\" id=\"farRight\">Far right</div>\n </div>\n</div> \n\n</body>\n</html>"
}
] |
Latent Semantic Analysis: intuition, math, implementation | by Ioana | Towards Data Science | TL;DR — Text data suffers heavily from high-dimensionality. Latent Semantic Analysis (LSA) is a popular, dimensionality-reduction techniques that follows the same method as Singular Value Decomposition. LSA ultimately reformulates text data in terms of r latent (i.e. hidden) features, where r is less than m, the number of terms in the data. I’ll explain the conceptual and mathematical intuition and run a basic implementation in Scikit-Learn using the 20 newsgroups dataset.
Language is more than the collection of words in front of you. When you read a text your mind conjures up images and notions. When you read many texts, themes begin to emerge, even if they’re never stated explicitly. Our innate ability to understand and process language defies an algorithmic expression (for the moment). LSA is one of the most popular Natural Language Processing (NLP) techniques for trying to determine themes within text mathematically. LSA is an unsupervised learning technique that rests on two pillars:
The distributional hypothesis, which states that words with similar meanings appear frequently together. This is best summarised by JR Firth’s quote “You shall know a word by the company it keeps” [1, p106]
Singular Value Decomposition (SVD — Figure 1) a mathematical technique that we’ll be looking at in greater depth.
Note that LSA is an unsupervised learning technique — there is no ground truth. The latent concepts might or might not be there! In the dataset we’ll use later we know there are 20 news categories and we can perform classification on them, but that’s only for illustrative purposes. It’ll often be the case that we’ll use LSA on unstructured, unlabelled data.
Like all Machine Learning concepts, LSA can be broken down into 3 parts: the intuition, the maths and the code. Feel free to use the links in Contents to skip to the part most relevant to you. The full code is available in this Github repo.
A note on terminology: generally when decomposition of this kind is done on text data, the terms SVD and LSA (or LSI) are used interchangeably. From now on I’ll be using LSA, for simplicity’s sake.
This article assumes some understanding of basic NLP preprocessing and of word vectorisation (specifically tf-idf vectorisation).
Intuition: explanation with political news topicsThe Math: SVD as a weighted, ordered sum of matrices or as a set of 3 linear transformationsThe code implementation: in Python3 with Scikit-Learn and 20Newsgroups dataReferences
Intuition: explanation with political news topics
The Math: SVD as a weighted, ordered sum of matrices or as a set of 3 linear transformations
The code implementation: in Python3 with Scikit-Learn and 20Newsgroups data
References
(return to Contents)
In simple terms: LSA takes meaningful text documents and recreates them in n different parts where each part expresses a different way of looking at meaning in the text. If you imagine the text data as a an idea, there would be n different ways of looking at that idea, or n different ways of conceptualising the whole text. LSA reduces our table of data to a table of latent (hidden) concepts.
Suppose that we have some table of data, in this case text data, where each row is one document, and each column represents a term (which can be a word or a group of words, like “baker’s dozen” or “Downing Street”). This is the standard way to represent text data (in a document-term matrix, as shown in Figure 2). The numbers in the table reflect how important that word is in the document. If the number is zero then that word simply doesn’t appear in that document.
Different documents will be about different topics. Let’s say all the documents are politics articles and there are 3 topics: foreign policy (F.P.), elections and reform.
Let’s say that there are articles strongly belonging to each category, some that are in two and some that belong to all 3 categories. We could plot a table where each row is a different document (a news article) and each column is a different topic. In the cells we would have a different numbers that indicated how strongly that document belonged to the particular topic (see Figure 3).
Now if we shift our attention conceptually to the topics themselves, we should ask ourselves the following question: do we expect certain words to turn up more often in either of these topics?
If we’re looking at foreign policy, we might see terms like “Middle East”, “EU”, “embassies”. For elections it might be “ballot”, “candidates”, “party”; and for reform we might see “bill”, “amendment” or “corruption”. So, if we plotted these topics and these terms in a different table, where the rows are the terms, we would see scores plotted for each term according to which topic it most strongly belonged. Naturally there will be terms that feature in all three documents (“prime minister”, “Parliament”, “decision”) and these terms will have scores across all 3 columns that reflect how much they belong to either category — the higher the number, the greater its affiliation to that topic. So, our second table (Figure 4) consists of terms and topics.
Now the last component is a bit trickier to explain as a table. It’s actually a set of numbers, one for each of our topics. What do the numbers represent? They represent how much each of the topics explains our data.
How do they “explain” the data? Well, suppose that actually, “reform” wasn’t really a salient topic across our articles, and the majority of the articles fit in far more comfortably in the “foreign policy” and “elections”. Thus “reform” would get a really low number in this set, lower than the other two. An alternative is that maybe all three numbers are actually quite low and we actually should have had four or more topics — we find out later that a lot of our articles were actually concerned with economics! By sticking to just three topics we’ve been denying ourselves the chance to get a more detailed and precise look at our data. The technical name for this array of numbers is the “singular values”.
So that’s the intuition so far. You’ll notice that our two tables have one thing in common (the documents / articles) and all three of them have one thing in common — the topics, or some representation of them.
Now let’s explain how this is a dimensionality reduction technique. It’s easier to see the merits if we specify a number of documents and topics. Suppose we had 100 articles and 10,000 different terms (just think of how many unique words there would be all those articles, from “amendment” to “zealous”!). In our original document-term matrix that’s 100 rows and 10,000 columns. When we start to break our data down into the 3 components, we can actually choose the number of topics — we could choose to have 10,000 different topics, if we genuinely thought that was reasonable. However, we could probably represent the data with far fewer topics, let’s say the 3 we originally talked about. That means that in our document-topic table, we’d slash about 99,997 columns, and in our term-topic table, we’d do the same. The columns and rows we’re discarding from our tables are shown as hashed rectangles in Figure 6. M is the original document-term table; U is the document-topic table, Σ (sigma) is the array of singular values and V-transpose (the superscript T means that the original matrix T has been flipped along its diagonal) is the document-topic table, but flipped on its diagonal (I’ll explain why in the math section).
As for the set of numbers denoting topic importance, from a set of 10,000 numbers, each number getting smaller and smaller as it corresponds to a less important topic, we cut down to only 3 numbers, for our 3 remaining topics. This is why the Python implementation for LSA is called Truncated SVD by the way: we’re cutting off part of our table, but we’ll get to the code later. It’s also worth noting that we don’t know what the 3 topics are in advance, we merely hypothesised that there would be 3 and, once we’ve gotten our components, we can explore them and see what the terms are.
Of course, we don’t just want to return to the original dataset: we now have 3 lower-dimensional components we can use. In the code and maths parts we’ll go through which one we actually take forward. In brief, once we’ve truncated the tables (matrices), the product we’ll be getting out is the document-topic table (U) times the singular values (Σ). This can be interpreted as the documents (all our news articles) along with how much they belong to each topic then weighted by the relative importance of each topic. You’ll notice that in that case something’s been left out of this final table — the words. Yes, we’ve gone beyond the words, we’re discarding them but keeping the themes, which is a much more compact way to express our text.
(return to Contents)
For the maths, I’ll be going through two different interpretations of SVD: first the general geometric decomposition that you can use with a real square matrix M and second the separable-models decomposition which is more pertinent to our example. SVD is also used in model-based recommendation systems. It is very similar to Principal Component Analysis (PCA), but it operates better on sparse data than PCA does (and text data is almost always sparse). Whereas PCA performs decomposition on the correlation matrix of a dataset, SVD/LSA performs decomposition directly on the dataset as it is.
We will be factorising this matrix into constituent matrices. When I say factorising this is essentially the same as when we’re taking a number and representing it its factors, which when multiplied together, give us the original number, e.g. A = B * C * D .
This is also why it’s called Singular Value Decomposition — we’re decomposing it into its constituent parts.
The extra dimension that wasn’t available to us in our original matrix, the r dimension, is the amount of latent concepts. Generally we’re trying to represent our matrix as other matrices that have one of their axes being this set of components. You will also note that, based on dimensions, the multiplication of the 3 matrices (when V is transposed) will lead us back to the shape of our original matrix, the r dimension effectively disappearing.
What matters in understanding the math is not the algebraic algorithm by which each number in U, V and Σ is determined, but the mathematical properties of these products and how they relate to each other.
First of all, it’s important to consider first what a matrix actually is and what it can be thought of — a transformation of vector space. In the top left corner of Figure 7 we have two perpendicular vectors. If we have only two variables to start with then the feature space (the data that we’re looking at) can be plotted anywhere in this space that is described by these two basis vectors. Now moving to the right in our diagram, the matrix M is applied to this vector space and this transforms it into the new, transformed space in our top right corner. In the diagram below the geometric effect of M would be referred to as “shearing” the vector space; the two vectors σ1 and σ2 are actually our singular values plotted in this space.
Now, just like with geometric transformations of points that you may remember from school, we can reconsider this transformation M as three separate transformations:
The rotation (or reflection) caused by V*. Note that V* = V-transpose as V is a real unitary matrix, so the complex conjugate of V is the same as its transpose. In vector terms, the transformation by V or V* keeps the length of the basis vectors the same;Σ has the effect of stretching or compressing all coordinate points along the values of its singular values. Imagine our disc in the bottom left corner as we squeeze it vertically down in the direction of σ2 and stretch it horizontally along the direction of σ1. These two singular values now can be pictured as the major and minor semi-axes of an ellipse. You can of course generalise this to n-dimensions.Lastly, applying U rotates (or reflects) our feature space. We’ve arrived at the same output as a transformation directly from M.
The rotation (or reflection) caused by V*. Note that V* = V-transpose as V is a real unitary matrix, so the complex conjugate of V is the same as its transpose. In vector terms, the transformation by V or V* keeps the length of the basis vectors the same;
Σ has the effect of stretching or compressing all coordinate points along the values of its singular values. Imagine our disc in the bottom left corner as we squeeze it vertically down in the direction of σ2 and stretch it horizontally along the direction of σ1. These two singular values now can be pictured as the major and minor semi-axes of an ellipse. You can of course generalise this to n-dimensions.
Lastly, applying U rotates (or reflects) our feature space. We’ve arrived at the same output as a transformation directly from M.
I also recommend the excellent Wikipedia entry on SVD as it has a particularly good explanation and GIF of the process.
So, in other words, where x is any column vector:
One of the properties of the matrices U and V* is that they’re unitary, so we can say that the columns of both of these matrices form two sets of orthonormal basis vectors. In other words, the column vectors you can get from U would form their own coordinate space, such that if there were two columns U1 and U2, you could write out all of the coordinates of the space as combinations of U1 and U2. The same applies to the columns of V, V1 and V2, and this would generalise to n-dimensions (you’d have n-columns).
We can arrive at the same understanding of PCA if we imagine that our matrix M can be broken down into a weighted sum of separable matrices, as shown below.
The matrices Ai are said to be separable because they can be decomposed into the outer product of two vectors, weighted by the singular value σi. Calculating the outer product of two vectors with shapes (m,) and (n,) would give us a matrix with a shape (m,n). In other words, every possible product of any two numbers in the two vectors is computed and placed in the new matrix. The singular value not only weights the sum but orders it, since the values are arranged in descending order, so that the first singular value is always the highest one.
In Figure 8 you can see how you could visualise this. Previously we had the tall U, the square Σ and the long V-transpose matrices. Now you can picture taking the first vertical slice from U, weighting (multiplying) all its values by the first singular value and then, by doing an outer product with the first horizontal slice of V-transpose, creating a new matrix with the dimensions of those slices. Then we add those products together and we get M. Or, if we don’t do the full sum but only complete it partially, we get the truncated version.
So, for our data:
where M is our original (m, n) data matrix — m rows, n columns; m documents, n terms
U is a (m, r) matrix — m documents and r concepts
Σ is a diagonal (r , r) matrix — all values except those in the diagonal are zero. (But what do the non-zero values represent?
V is a (n, r) matrix — n terms, r concepts
The values in Σ represent how much each latent concept explains the variance in our data. When these are multiplied by the u column vector for that latent concept, it will effectively weigh that vector.
If we were to decompose this to 5 components, this would look something like this:
where there would be originally r number of u vectors; 5 singular values and n number of v-transpose vectors.
(return to Contents)
In this last section we’ll see how we can implement basic LSA using Scikit-Learn.
from sklearn.datasets import fetch_20newsgroupsX_train, y_train = fetch_20newsgroups(subset='train', return_X_y=True)X_test, y_test = fetch_20newsgroups(subset='test', return_X_y=True)
The cleaning of text data is often a very different beast from cleaning of numerical data. You’ll often find yourself having prepared your vectoriser, you model and you’re ready to Gridsearch and then extract features, only to find that the most important features in cluster x is the string “___” ... so you go back...and do more cleaning. The code block below came about as a result of me realizing that I needed to remove website URLs, numbers and emails from the dataset.
from nltk.corpus import stopwordsfrom nltk.tokenize import RegexpTokenizerimport retokenizer = RegexpTokenizer(r'\b\w{3,}\b')stop_words = list(set(stopwords.words("english")))stop_words += list(string.punctuation)stop_words += ['__', '___']# Uncomment and run the 3 lines below if you haven't got these packages already# nltk.download('stopwords')# nltk.download('punkt')# nltk.download('wordnet')def rmv_emails_websites(string): """Function removes emails, websites and numbers""" new_str = re.sub(r"\S+@\S+", '', string) new_str = re.sub(r"\S+.co\S+", '', new_str) new_str = re.sub(r"\S+.ed\S+", '', new_str) new_str = re.sub(r"[0-9]+", '', new_str) return new_strX_train = list(map(rmv_emails_websites, X_train))X_test = list(map(rmv_emails_websites, X_test))
Our models work on numbers, not string! So we tokenise the text (turning all documents into smaller observational entities — in this case words) and then turn them into numbers using Sklearn’s TF-IDF vectoriser. I recommend with any transformation process (especially ones that take time to run) you do them on the first 10 rows of your data and inspect results: are they what you expected to see? Is the shape of the dataframe what you hoped for? Once you’re feeling confident of your code, feed in the whole corpus.
tfidf = TfidfVectorizer(lowercase=True, stop_words=stop_words, tokenizer=tokenizer.tokenize, max_df=0.2, min_df=0.02 )tfidf_train_sparse = tfidf.fit_transform(X_train)tfidf_train_df = pd.DataFrame(tfidf_train_sparse.toarray(), columns=tfidf.get_feature_names())tfidf_train_df.head()
This should give you your vectorised text data — the document-term matrix. Repeat the steps above for the test set as well, but only using transform, not fit_transform.
Just for the purpose of visualisation and EDA of our decomposed data, let’s fit our LSA object (which in Sklearn is the TruncatedSVD class) to our train data and specifying only 20 components.
from sklearn.decomposition import TruncatedSVDlsa_obj = TruncatedSVD(n_components=20, n_iter=100, random_state=42)tfidf_lsa_data = lsa_obj.fit_transform(tfidf_train_df)Sigma = lsa_obj.singular_values_V_T = lsa_obj.components_.T
Now let’s visualise the singular values — is the barplot below showing us what we expected of them?
sns.barplot(x=list(range(len(Sigma))), y = Sigma)
Let’s explore our reduced data through the term-topic matrix, V-tranpose. TruncatedSVD will return it to as a numpy array of shape (num_documents, num_components), so we’ll turn it into a Pandas dataframe for ease of manipulation.
term_topic_matrix = pd.DataFrame(data=lsa_term_topic, index = eda_train.columns, columns = [f'Latent_concept_{r}' for r in range(0,V_T.shape[1])])
Let’s slice our term-topic matrix into Pandas Series (single column data-frames), sort them by value and plot them. The code below plots this for our 2nd latent component (recall that in python we start counting from 0) and returns the plot in Figure 10:
data = term_topic_matrix[f'Latent_concept_1']data = data.sort_values(ascending=False)top_10 = data[:10]plt.title('Top terms along the axis of Latent concept 1')fig = sns.barplot(x= top_10.values, y=top_10.index)
These are the words that rank highly along our 2nd latent component. What about the words at the other end of this axis (see Fig 11)?
You can make your own mind up about that this semantic divergence signifies. Adding more preprocessing steps would help us cleave through the noise that words like “say” and “said” are creating, but we’ll press on for now. Let’s do one more pair of visualisations for the 6th latent concept (Figures 12 and 13).
At this point it’s up to us to infer some meaning from these plots. The negative end of concept 5’s axis seems to correlate very strongly with technological and scientific themes (‘space’, ‘science’, ‘computer’), but so does the positive end, albeit more focused on computer related terms (‘hard’, ‘drive’, ‘system’).
Now just to be clear, determining the right amount of components will require tuning, so I didn’t leave the argument set to 20, but changed it to 100. You might think that’s still a large number of dimensions, but our original was 220 (and that was with constraints on our minimum document frequency!), so we’ve reduced a sizeable chunk of the data. I’ll explore in another post how to choose the optimal number of singular values. For now we’ll just go forward with what we have.
Although LSA is an unsupervised technique often used to find patterns in unlabelled data, we’re using it here to reduce the dimensions of labelled data before feeing it into a model. We’ll compare our accuracy on the LSA data with the accuracy on our standard TF-IDF data to gauge how much useful information the LSA has captured from the original dataset. We now have a train dataset of shape (11314, 100). The number of documents is preserved and we have created 100 latent concepts. Now let’s run a model on this and on our standard TF-IDF data. The aim of the implementation below isn’t to get a great model, but to compare the two very different datasets. I’ve included basic cross validation through GridSearchCV and performed a tiny amount of tuning for the tolerance hyperparameter. If you were to do this for the sake of building an actual model, you would go much farther than what’s written below. This is just to help you get a basic implementation going:
logreg_lsa = LogisticRegression()logreg = LogisticRegression()logreg_param_grid = [{'penalty':['l1', 'l2']}, {'tol':[0.0001, 0.0005, 0.001]}]grid_lsa_log = GridSearchCV(estimator=logreg_lsa, param_grid=logreg_param_grid, scoring='accuracy', cv=5, n_jobs=-1)grid_log = GridSearchCV(estimator=logreg, param_grid=logreg_param_grid, scoring='accuracy', cv=5, n_jobs=-1)best_lsa_logreg = grid_lsa_log.fit(tfidf_lsa_data, y_train).best_estimator_best_reg_logreg = grid_log.fit(tfidf_train_df, y_train).best_estimator_print("Accuracy of Logistic Regression on LSA train data is :", best_lsa_logreg.score(tfidf_lsa_data, y_train))print("Accuracy of Logistic Regression with standard train data is :", best_reg_logreg.score(tfidf_train_df, y_train))
Which returns:
Accuracy of Logistic Regression on LSA train data is : 0.45Accuracy of Logistic Regression with standard train data is : 0.52
The drop in performance is significant, but you can work this into an optimisation pipeline and tweak the number of latent components. How does this perform on our test data (7532 documents) though?
Accuracy of Logistic Regression on LSA test data is : 0.35Accuracy of Logistic Regression on standard test data is : 0.37
Accuracy has dropped greatly for both, but notice how small the gap between the models is! Our LSA model is able to capture about as much information from our test data as our standard model did, with less than half the dimensions! Since this is a multi-label classification it would be best to visualise this with a confusion matrix (Figure 14). Our results look significantly better when you consider the random classification probability given 20 news categories. If you’re not familiar with a confusion matrix, as a rule of thumb, we want to maximise the numbers down the diagonal and minimise them everywhere else.
And that concludes our implementation of LSA in Scikit-Learn. We’ve covered the intuition, mathematics and coding of this technique.
I hope you’ve enjoyed this post and would appreciate any amount of claps. Feel free to leave any feedback (positive or constructive) in the comments, especially about the math section, since I found that the most challenging to articulate.
(return to Contents)
[1] L. Hobson, H. Cole, H. Hapke, Natural Language Processing in Action (2019), https://www.manning.com/books/natural-language-processing-in-action
[2] Pedregosa et al., Scikit-learn: Machine Learning in Python (2011), JMLR 12, pp. 2825–2830.
[3] Hamdaoui Y, TF(Term Frequency)-IDF(Inverse Document Frequency) from scratch in python (2019), Towards Data Science
[4] Wikipedia contributers, Singular Value Decomposition, https://en.wikipedia.org/wiki/Singular_value_decomposition | [
{
"code": null,
"e": 650,
"s": 172,
"text": "TL;DR — Text data suffers heavily from high-dimensionality. Latent Semantic Analysis (LSA) is a popular, dimensionality-reduction techniques that follows the same method as Singular Value Decomposition. LSA ultimately reformulates text data in terms of r latent (i.e. hidden) features, where r is less than m, the number of terms in the data. I’ll explain the conceptual and mathematical intuition and run a basic implementation in Scikit-Learn using the 20 newsgroups dataset."
},
{
"code": null,
"e": 1176,
"s": 650,
"text": "Language is more than the collection of words in front of you. When you read a text your mind conjures up images and notions. When you read many texts, themes begin to emerge, even if they’re never stated explicitly. Our innate ability to understand and process language defies an algorithmic expression (for the moment). LSA is one of the most popular Natural Language Processing (NLP) techniques for trying to determine themes within text mathematically. LSA is an unsupervised learning technique that rests on two pillars:"
},
{
"code": null,
"e": 1383,
"s": 1176,
"text": "The distributional hypothesis, which states that words with similar meanings appear frequently together. This is best summarised by JR Firth’s quote “You shall know a word by the company it keeps” [1, p106]"
},
{
"code": null,
"e": 1497,
"s": 1383,
"text": "Singular Value Decomposition (SVD — Figure 1) a mathematical technique that we’ll be looking at in greater depth."
},
{
"code": null,
"e": 1857,
"s": 1497,
"text": "Note that LSA is an unsupervised learning technique — there is no ground truth. The latent concepts might or might not be there! In the dataset we’ll use later we know there are 20 news categories and we can perform classification on them, but that’s only for illustrative purposes. It’ll often be the case that we’ll use LSA on unstructured, unlabelled data."
},
{
"code": null,
"e": 2098,
"s": 1857,
"text": "Like all Machine Learning concepts, LSA can be broken down into 3 parts: the intuition, the maths and the code. Feel free to use the links in Contents to skip to the part most relevant to you. The full code is available in this Github repo."
},
{
"code": null,
"e": 2296,
"s": 2098,
"text": "A note on terminology: generally when decomposition of this kind is done on text data, the terms SVD and LSA (or LSI) are used interchangeably. From now on I’ll be using LSA, for simplicity’s sake."
},
{
"code": null,
"e": 2426,
"s": 2296,
"text": "This article assumes some understanding of basic NLP preprocessing and of word vectorisation (specifically tf-idf vectorisation)."
},
{
"code": null,
"e": 2653,
"s": 2426,
"text": "Intuition: explanation with political news topicsThe Math: SVD as a weighted, ordered sum of matrices or as a set of 3 linear transformationsThe code implementation: in Python3 with Scikit-Learn and 20Newsgroups dataReferences"
},
{
"code": null,
"e": 2703,
"s": 2653,
"text": "Intuition: explanation with political news topics"
},
{
"code": null,
"e": 2796,
"s": 2703,
"text": "The Math: SVD as a weighted, ordered sum of matrices or as a set of 3 linear transformations"
},
{
"code": null,
"e": 2872,
"s": 2796,
"text": "The code implementation: in Python3 with Scikit-Learn and 20Newsgroups data"
},
{
"code": null,
"e": 2883,
"s": 2872,
"text": "References"
},
{
"code": null,
"e": 2904,
"s": 2883,
"text": "(return to Contents)"
},
{
"code": null,
"e": 3299,
"s": 2904,
"text": "In simple terms: LSA takes meaningful text documents and recreates them in n different parts where each part expresses a different way of looking at meaning in the text. If you imagine the text data as a an idea, there would be n different ways of looking at that idea, or n different ways of conceptualising the whole text. LSA reduces our table of data to a table of latent (hidden) concepts."
},
{
"code": null,
"e": 3768,
"s": 3299,
"text": "Suppose that we have some table of data, in this case text data, where each row is one document, and each column represents a term (which can be a word or a group of words, like “baker’s dozen” or “Downing Street”). This is the standard way to represent text data (in a document-term matrix, as shown in Figure 2). The numbers in the table reflect how important that word is in the document. If the number is zero then that word simply doesn’t appear in that document."
},
{
"code": null,
"e": 3939,
"s": 3768,
"text": "Different documents will be about different topics. Let’s say all the documents are politics articles and there are 3 topics: foreign policy (F.P.), elections and reform."
},
{
"code": null,
"e": 4327,
"s": 3939,
"text": "Let’s say that there are articles strongly belonging to each category, some that are in two and some that belong to all 3 categories. We could plot a table where each row is a different document (a news article) and each column is a different topic. In the cells we would have a different numbers that indicated how strongly that document belonged to the particular topic (see Figure 3)."
},
{
"code": null,
"e": 4520,
"s": 4327,
"text": "Now if we shift our attention conceptually to the topics themselves, we should ask ourselves the following question: do we expect certain words to turn up more often in either of these topics?"
},
{
"code": null,
"e": 5279,
"s": 4520,
"text": "If we’re looking at foreign policy, we might see terms like “Middle East”, “EU”, “embassies”. For elections it might be “ballot”, “candidates”, “party”; and for reform we might see “bill”, “amendment” or “corruption”. So, if we plotted these topics and these terms in a different table, where the rows are the terms, we would see scores plotted for each term according to which topic it most strongly belonged. Naturally there will be terms that feature in all three documents (“prime minister”, “Parliament”, “decision”) and these terms will have scores across all 3 columns that reflect how much they belong to either category — the higher the number, the greater its affiliation to that topic. So, our second table (Figure 4) consists of terms and topics."
},
{
"code": null,
"e": 5496,
"s": 5279,
"text": "Now the last component is a bit trickier to explain as a table. It’s actually a set of numbers, one for each of our topics. What do the numbers represent? They represent how much each of the topics explains our data."
},
{
"code": null,
"e": 6208,
"s": 5496,
"text": "How do they “explain” the data? Well, suppose that actually, “reform” wasn’t really a salient topic across our articles, and the majority of the articles fit in far more comfortably in the “foreign policy” and “elections”. Thus “reform” would get a really low number in this set, lower than the other two. An alternative is that maybe all three numbers are actually quite low and we actually should have had four or more topics — we find out later that a lot of our articles were actually concerned with economics! By sticking to just three topics we’ve been denying ourselves the chance to get a more detailed and precise look at our data. The technical name for this array of numbers is the “singular values”."
},
{
"code": null,
"e": 6419,
"s": 6208,
"text": "So that’s the intuition so far. You’ll notice that our two tables have one thing in common (the documents / articles) and all three of them have one thing in common — the topics, or some representation of them."
},
{
"code": null,
"e": 7648,
"s": 6419,
"text": "Now let’s explain how this is a dimensionality reduction technique. It’s easier to see the merits if we specify a number of documents and topics. Suppose we had 100 articles and 10,000 different terms (just think of how many unique words there would be all those articles, from “amendment” to “zealous”!). In our original document-term matrix that’s 100 rows and 10,000 columns. When we start to break our data down into the 3 components, we can actually choose the number of topics — we could choose to have 10,000 different topics, if we genuinely thought that was reasonable. However, we could probably represent the data with far fewer topics, let’s say the 3 we originally talked about. That means that in our document-topic table, we’d slash about 99,997 columns, and in our term-topic table, we’d do the same. The columns and rows we’re discarding from our tables are shown as hashed rectangles in Figure 6. M is the original document-term table; U is the document-topic table, Σ (sigma) is the array of singular values and V-transpose (the superscript T means that the original matrix T has been flipped along its diagonal) is the document-topic table, but flipped on its diagonal (I’ll explain why in the math section)."
},
{
"code": null,
"e": 8235,
"s": 7648,
"text": "As for the set of numbers denoting topic importance, from a set of 10,000 numbers, each number getting smaller and smaller as it corresponds to a less important topic, we cut down to only 3 numbers, for our 3 remaining topics. This is why the Python implementation for LSA is called Truncated SVD by the way: we’re cutting off part of our table, but we’ll get to the code later. It’s also worth noting that we don’t know what the 3 topics are in advance, we merely hypothesised that there would be 3 and, once we’ve gotten our components, we can explore them and see what the terms are."
},
{
"code": null,
"e": 8978,
"s": 8235,
"text": "Of course, we don’t just want to return to the original dataset: we now have 3 lower-dimensional components we can use. In the code and maths parts we’ll go through which one we actually take forward. In brief, once we’ve truncated the tables (matrices), the product we’ll be getting out is the document-topic table (U) times the singular values (Σ). This can be interpreted as the documents (all our news articles) along with how much they belong to each topic then weighted by the relative importance of each topic. You’ll notice that in that case something’s been left out of this final table — the words. Yes, we’ve gone beyond the words, we’re discarding them but keeping the themes, which is a much more compact way to express our text."
},
{
"code": null,
"e": 8999,
"s": 8978,
"text": "(return to Contents)"
},
{
"code": null,
"e": 9594,
"s": 8999,
"text": "For the maths, I’ll be going through two different interpretations of SVD: first the general geometric decomposition that you can use with a real square matrix M and second the separable-models decomposition which is more pertinent to our example. SVD is also used in model-based recommendation systems. It is very similar to Principal Component Analysis (PCA), but it operates better on sparse data than PCA does (and text data is almost always sparse). Whereas PCA performs decomposition on the correlation matrix of a dataset, SVD/LSA performs decomposition directly on the dataset as it is."
},
{
"code": null,
"e": 9853,
"s": 9594,
"text": "We will be factorising this matrix into constituent matrices. When I say factorising this is essentially the same as when we’re taking a number and representing it its factors, which when multiplied together, give us the original number, e.g. A = B * C * D ."
},
{
"code": null,
"e": 9962,
"s": 9853,
"text": "This is also why it’s called Singular Value Decomposition — we’re decomposing it into its constituent parts."
},
{
"code": null,
"e": 10411,
"s": 9962,
"text": "The extra dimension that wasn’t available to us in our original matrix, the r dimension, is the amount of latent concepts. Generally we’re trying to represent our matrix as other matrices that have one of their axes being this set of components. You will also note that, based on dimensions, the multiplication of the 3 matrices (when V is transposed) will lead us back to the shape of our original matrix, the r dimension effectively disappearing."
},
{
"code": null,
"e": 10616,
"s": 10411,
"text": "What matters in understanding the math is not the algebraic algorithm by which each number in U, V and Σ is determined, but the mathematical properties of these products and how they relate to each other."
},
{
"code": null,
"e": 11356,
"s": 10616,
"text": "First of all, it’s important to consider first what a matrix actually is and what it can be thought of — a transformation of vector space. In the top left corner of Figure 7 we have two perpendicular vectors. If we have only two variables to start with then the feature space (the data that we’re looking at) can be plotted anywhere in this space that is described by these two basis vectors. Now moving to the right in our diagram, the matrix M is applied to this vector space and this transforms it into the new, transformed space in our top right corner. In the diagram below the geometric effect of M would be referred to as “shearing” the vector space; the two vectors σ1 and σ2 are actually our singular values plotted in this space."
},
{
"code": null,
"e": 11522,
"s": 11356,
"text": "Now, just like with geometric transformations of points that you may remember from school, we can reconsider this transformation M as three separate transformations:"
},
{
"code": null,
"e": 12314,
"s": 11522,
"text": "The rotation (or reflection) caused by V*. Note that V* = V-transpose as V is a real unitary matrix, so the complex conjugate of V is the same as its transpose. In vector terms, the transformation by V or V* keeps the length of the basis vectors the same;Σ has the effect of stretching or compressing all coordinate points along the values of its singular values. Imagine our disc in the bottom left corner as we squeeze it vertically down in the direction of σ2 and stretch it horizontally along the direction of σ1. These two singular values now can be pictured as the major and minor semi-axes of an ellipse. You can of course generalise this to n-dimensions.Lastly, applying U rotates (or reflects) our feature space. We’ve arrived at the same output as a transformation directly from M."
},
{
"code": null,
"e": 12570,
"s": 12314,
"text": "The rotation (or reflection) caused by V*. Note that V* = V-transpose as V is a real unitary matrix, so the complex conjugate of V is the same as its transpose. In vector terms, the transformation by V or V* keeps the length of the basis vectors the same;"
},
{
"code": null,
"e": 12978,
"s": 12570,
"text": "Σ has the effect of stretching or compressing all coordinate points along the values of its singular values. Imagine our disc in the bottom left corner as we squeeze it vertically down in the direction of σ2 and stretch it horizontally along the direction of σ1. These two singular values now can be pictured as the major and minor semi-axes of an ellipse. You can of course generalise this to n-dimensions."
},
{
"code": null,
"e": 13108,
"s": 12978,
"text": "Lastly, applying U rotates (or reflects) our feature space. We’ve arrived at the same output as a transformation directly from M."
},
{
"code": null,
"e": 13228,
"s": 13108,
"text": "I also recommend the excellent Wikipedia entry on SVD as it has a particularly good explanation and GIF of the process."
},
{
"code": null,
"e": 13278,
"s": 13228,
"text": "So, in other words, where x is any column vector:"
},
{
"code": null,
"e": 13792,
"s": 13278,
"text": "One of the properties of the matrices U and V* is that they’re unitary, so we can say that the columns of both of these matrices form two sets of orthonormal basis vectors. In other words, the column vectors you can get from U would form their own coordinate space, such that if there were two columns U1 and U2, you could write out all of the coordinates of the space as combinations of U1 and U2. The same applies to the columns of V, V1 and V2, and this would generalise to n-dimensions (you’d have n-columns)."
},
{
"code": null,
"e": 13949,
"s": 13792,
"text": "We can arrive at the same understanding of PCA if we imagine that our matrix M can be broken down into a weighted sum of separable matrices, as shown below."
},
{
"code": null,
"e": 14498,
"s": 13949,
"text": "The matrices Ai are said to be separable because they can be decomposed into the outer product of two vectors, weighted by the singular value σi. Calculating the outer product of two vectors with shapes (m,) and (n,) would give us a matrix with a shape (m,n). In other words, every possible product of any two numbers in the two vectors is computed and placed in the new matrix. The singular value not only weights the sum but orders it, since the values are arranged in descending order, so that the first singular value is always the highest one."
},
{
"code": null,
"e": 15044,
"s": 14498,
"text": "In Figure 8 you can see how you could visualise this. Previously we had the tall U, the square Σ and the long V-transpose matrices. Now you can picture taking the first vertical slice from U, weighting (multiplying) all its values by the first singular value and then, by doing an outer product with the first horizontal slice of V-transpose, creating a new matrix with the dimensions of those slices. Then we add those products together and we get M. Or, if we don’t do the full sum but only complete it partially, we get the truncated version."
},
{
"code": null,
"e": 15062,
"s": 15044,
"text": "So, for our data:"
},
{
"code": null,
"e": 15147,
"s": 15062,
"text": "where M is our original (m, n) data matrix — m rows, n columns; m documents, n terms"
},
{
"code": null,
"e": 15197,
"s": 15147,
"text": "U is a (m, r) matrix — m documents and r concepts"
},
{
"code": null,
"e": 15324,
"s": 15197,
"text": "Σ is a diagonal (r , r) matrix — all values except those in the diagonal are zero. (But what do the non-zero values represent?"
},
{
"code": null,
"e": 15367,
"s": 15324,
"text": "V is a (n, r) matrix — n terms, r concepts"
},
{
"code": null,
"e": 15570,
"s": 15367,
"text": "The values in Σ represent how much each latent concept explains the variance in our data. When these are multiplied by the u column vector for that latent concept, it will effectively weigh that vector."
},
{
"code": null,
"e": 15653,
"s": 15570,
"text": "If we were to decompose this to 5 components, this would look something like this:"
},
{
"code": null,
"e": 15763,
"s": 15653,
"text": "where there would be originally r number of u vectors; 5 singular values and n number of v-transpose vectors."
},
{
"code": null,
"e": 15784,
"s": 15763,
"text": "(return to Contents)"
},
{
"code": null,
"e": 15866,
"s": 15784,
"text": "In this last section we’ll see how we can implement basic LSA using Scikit-Learn."
},
{
"code": null,
"e": 16051,
"s": 15866,
"text": "from sklearn.datasets import fetch_20newsgroupsX_train, y_train = fetch_20newsgroups(subset='train', return_X_y=True)X_test, y_test = fetch_20newsgroups(subset='test', return_X_y=True)"
},
{
"code": null,
"e": 16527,
"s": 16051,
"text": "The cleaning of text data is often a very different beast from cleaning of numerical data. You’ll often find yourself having prepared your vectoriser, you model and you’re ready to Gridsearch and then extract features, only to find that the most important features in cluster x is the string “___” ... so you go back...and do more cleaning. The code block below came about as a result of me realizing that I needed to remove website URLs, numbers and emails from the dataset."
},
{
"code": null,
"e": 17309,
"s": 16527,
"text": "from nltk.corpus import stopwordsfrom nltk.tokenize import RegexpTokenizerimport retokenizer = RegexpTokenizer(r'\\b\\w{3,}\\b')stop_words = list(set(stopwords.words(\"english\")))stop_words += list(string.punctuation)stop_words += ['__', '___']# Uncomment and run the 3 lines below if you haven't got these packages already# nltk.download('stopwords')# nltk.download('punkt')# nltk.download('wordnet')def rmv_emails_websites(string): \"\"\"Function removes emails, websites and numbers\"\"\" new_str = re.sub(r\"\\S+@\\S+\", '', string) new_str = re.sub(r\"\\S+.co\\S+\", '', new_str) new_str = re.sub(r\"\\S+.ed\\S+\", '', new_str) new_str = re.sub(r\"[0-9]+\", '', new_str) return new_strX_train = list(map(rmv_emails_websites, X_train))X_test = list(map(rmv_emails_websites, X_test))"
},
{
"code": null,
"e": 17827,
"s": 17309,
"text": "Our models work on numbers, not string! So we tokenise the text (turning all documents into smaller observational entities — in this case words) and then turn them into numbers using Sklearn’s TF-IDF vectoriser. I recommend with any transformation process (especially ones that take time to run) you do them on the first 10 rows of your data and inspect results: are they what you expected to see? Is the shape of the dataframe what you hoped for? Once you’re feeling confident of your code, feed in the whole corpus."
},
{
"code": null,
"e": 18251,
"s": 17827,
"text": "tfidf = TfidfVectorizer(lowercase=True, stop_words=stop_words, tokenizer=tokenizer.tokenize, max_df=0.2, min_df=0.02 )tfidf_train_sparse = tfidf.fit_transform(X_train)tfidf_train_df = pd.DataFrame(tfidf_train_sparse.toarray(), columns=tfidf.get_feature_names())tfidf_train_df.head()"
},
{
"code": null,
"e": 18420,
"s": 18251,
"text": "This should give you your vectorised text data — the document-term matrix. Repeat the steps above for the test set as well, but only using transform, not fit_transform."
},
{
"code": null,
"e": 18613,
"s": 18420,
"text": "Just for the purpose of visualisation and EDA of our decomposed data, let’s fit our LSA object (which in Sklearn is the TruncatedSVD class) to our train data and specifying only 20 components."
},
{
"code": null,
"e": 18841,
"s": 18613,
"text": "from sklearn.decomposition import TruncatedSVDlsa_obj = TruncatedSVD(n_components=20, n_iter=100, random_state=42)tfidf_lsa_data = lsa_obj.fit_transform(tfidf_train_df)Sigma = lsa_obj.singular_values_V_T = lsa_obj.components_.T"
},
{
"code": null,
"e": 18941,
"s": 18841,
"text": "Now let’s visualise the singular values — is the barplot below showing us what we expected of them?"
},
{
"code": null,
"e": 18991,
"s": 18941,
"text": "sns.barplot(x=list(range(len(Sigma))), y = Sigma)"
},
{
"code": null,
"e": 19222,
"s": 18991,
"text": "Let’s explore our reduced data through the term-topic matrix, V-tranpose. TruncatedSVD will return it to as a numpy array of shape (num_documents, num_components), so we’ll turn it into a Pandas dataframe for ease of manipulation."
},
{
"code": null,
"e": 19435,
"s": 19222,
"text": "term_topic_matrix = pd.DataFrame(data=lsa_term_topic, index = eda_train.columns, columns = [f'Latent_concept_{r}' for r in range(0,V_T.shape[1])])"
},
{
"code": null,
"e": 19690,
"s": 19435,
"text": "Let’s slice our term-topic matrix into Pandas Series (single column data-frames), sort them by value and plot them. The code below plots this for our 2nd latent component (recall that in python we start counting from 0) and returns the plot in Figure 10:"
},
{
"code": null,
"e": 19902,
"s": 19690,
"text": "data = term_topic_matrix[f'Latent_concept_1']data = data.sort_values(ascending=False)top_10 = data[:10]plt.title('Top terms along the axis of Latent concept 1')fig = sns.barplot(x= top_10.values, y=top_10.index)"
},
{
"code": null,
"e": 20036,
"s": 19902,
"text": "These are the words that rank highly along our 2nd latent component. What about the words at the other end of this axis (see Fig 11)?"
},
{
"code": null,
"e": 20348,
"s": 20036,
"text": "You can make your own mind up about that this semantic divergence signifies. Adding more preprocessing steps would help us cleave through the noise that words like “say” and “said” are creating, but we’ll press on for now. Let’s do one more pair of visualisations for the 6th latent concept (Figures 12 and 13)."
},
{
"code": null,
"e": 20666,
"s": 20348,
"text": "At this point it’s up to us to infer some meaning from these plots. The negative end of concept 5’s axis seems to correlate very strongly with technological and scientific themes (‘space’, ‘science’, ‘computer’), but so does the positive end, albeit more focused on computer related terms (‘hard’, ‘drive’, ‘system’)."
},
{
"code": null,
"e": 21147,
"s": 20666,
"text": "Now just to be clear, determining the right amount of components will require tuning, so I didn’t leave the argument set to 20, but changed it to 100. You might think that’s still a large number of dimensions, but our original was 220 (and that was with constraints on our minimum document frequency!), so we’ve reduced a sizeable chunk of the data. I’ll explore in another post how to choose the optimal number of singular values. For now we’ll just go forward with what we have."
},
{
"code": null,
"e": 22115,
"s": 21147,
"text": "Although LSA is an unsupervised technique often used to find patterns in unlabelled data, we’re using it here to reduce the dimensions of labelled data before feeing it into a model. We’ll compare our accuracy on the LSA data with the accuracy on our standard TF-IDF data to gauge how much useful information the LSA has captured from the original dataset. We now have a train dataset of shape (11314, 100). The number of documents is preserved and we have created 100 latent concepts. Now let’s run a model on this and on our standard TF-IDF data. The aim of the implementation below isn’t to get a great model, but to compare the two very different datasets. I’ve included basic cross validation through GridSearchCV and performed a tiny amount of tuning for the tolerance hyperparameter. If you were to do this for the sake of building an actual model, you would go much farther than what’s written below. This is just to help you get a basic implementation going:"
},
{
"code": null,
"e": 23016,
"s": 22115,
"text": "logreg_lsa = LogisticRegression()logreg = LogisticRegression()logreg_param_grid = [{'penalty':['l1', 'l2']}, {'tol':[0.0001, 0.0005, 0.001]}]grid_lsa_log = GridSearchCV(estimator=logreg_lsa, param_grid=logreg_param_grid, scoring='accuracy', cv=5, n_jobs=-1)grid_log = GridSearchCV(estimator=logreg, param_grid=logreg_param_grid, scoring='accuracy', cv=5, n_jobs=-1)best_lsa_logreg = grid_lsa_log.fit(tfidf_lsa_data, y_train).best_estimator_best_reg_logreg = grid_log.fit(tfidf_train_df, y_train).best_estimator_print(\"Accuracy of Logistic Regression on LSA train data is :\", best_lsa_logreg.score(tfidf_lsa_data, y_train))print(\"Accuracy of Logistic Regression with standard train data is :\", best_reg_logreg.score(tfidf_train_df, y_train))"
},
{
"code": null,
"e": 23031,
"s": 23016,
"text": "Which returns:"
},
{
"code": null,
"e": 23157,
"s": 23031,
"text": "Accuracy of Logistic Regression on LSA train data is : 0.45Accuracy of Logistic Regression with standard train data is : 0.52"
},
{
"code": null,
"e": 23356,
"s": 23157,
"text": "The drop in performance is significant, but you can work this into an optimisation pipeline and tweak the number of latent components. How does this perform on our test data (7532 documents) though?"
},
{
"code": null,
"e": 23478,
"s": 23356,
"text": "Accuracy of Logistic Regression on LSA test data is : 0.35Accuracy of Logistic Regression on standard test data is : 0.37"
},
{
"code": null,
"e": 24098,
"s": 23478,
"text": "Accuracy has dropped greatly for both, but notice how small the gap between the models is! Our LSA model is able to capture about as much information from our test data as our standard model did, with less than half the dimensions! Since this is a multi-label classification it would be best to visualise this with a confusion matrix (Figure 14). Our results look significantly better when you consider the random classification probability given 20 news categories. If you’re not familiar with a confusion matrix, as a rule of thumb, we want to maximise the numbers down the diagonal and minimise them everywhere else."
},
{
"code": null,
"e": 24231,
"s": 24098,
"text": "And that concludes our implementation of LSA in Scikit-Learn. We’ve covered the intuition, mathematics and coding of this technique."
},
{
"code": null,
"e": 24471,
"s": 24231,
"text": "I hope you’ve enjoyed this post and would appreciate any amount of claps. Feel free to leave any feedback (positive or constructive) in the comments, especially about the math section, since I found that the most challenging to articulate."
},
{
"code": null,
"e": 24492,
"s": 24471,
"text": "(return to Contents)"
},
{
"code": null,
"e": 24640,
"s": 24492,
"text": "[1] L. Hobson, H. Cole, H. Hapke, Natural Language Processing in Action (2019), https://www.manning.com/books/natural-language-processing-in-action"
},
{
"code": null,
"e": 24735,
"s": 24640,
"text": "[2] Pedregosa et al., Scikit-learn: Machine Learning in Python (2011), JMLR 12, pp. 2825–2830."
},
{
"code": null,
"e": 24854,
"s": 24735,
"text": "[3] Hamdaoui Y, TF(Term Frequency)-IDF(Inverse Document Frequency) from scratch in python (2019), Towards Data Science"
}
] |
How to check if a variable is an integer in JavaScript? | To check if a variable is an integer, check the value using parseInt() and check with === operator.
You can try to run the following code to check the existence of an integer −
Live Demo
<html>
<head>
<script>
var a = 10;
if (a === parseInt(a, 10))
alert("Integer!")
else
alert("Not an integer!")
</script>
</head>
<body>
</body>
</html> | [
{
"code": null,
"e": 1162,
"s": 1062,
"text": "To check if a variable is an integer, check the value using parseInt() and check with === operator."
},
{
"code": null,
"e": 1239,
"s": 1162,
"text": "You can try to run the following code to check the existence of an integer −"
},
{
"code": null,
"e": 1249,
"s": 1239,
"text": "Live Demo"
},
{
"code": null,
"e": 1475,
"s": 1249,
"text": "<html>\n <head>\n <script>\n var a = 10;\n if (a === parseInt(a, 10))\n alert(\"Integer!\")\n else\n alert(\"Not an integer!\")\n </script>\n </head>\n <body>\n </body>\n</html> "
}
] |
Java - Thread Deadlock | Deadlock describes a situation where two or more threads are blocked forever, waiting for each other. Deadlock occurs when multiple threads need the same locks but obtain them in different order. A Java multithreaded program may suffer from the deadlock condition because the synchronized keyword causes the executing thread to block while waiting for the lock, or monitor, associated with the specified object. Here is an example.
public class TestThread {
public static Object Lock1 = new Object();
public static Object Lock2 = new Object();
public static void main(String args[]) {
ThreadDemo1 T1 = new ThreadDemo1();
ThreadDemo2 T2 = new ThreadDemo2();
T1.start();
T2.start();
}
private static class ThreadDemo1 extends Thread {
public void run() {
synchronized (Lock1) {
System.out.println("Thread 1: Holding lock 1...");
try { Thread.sleep(10); }
catch (InterruptedException e) {}
System.out.println("Thread 1: Waiting for lock 2...");
synchronized (Lock2) {
System.out.println("Thread 1: Holding lock 1 & 2...");
}
}
}
}
private static class ThreadDemo2 extends Thread {
public void run() {
synchronized (Lock2) {
System.out.println("Thread 2: Holding lock 2...");
try { Thread.sleep(10); }
catch (InterruptedException e) {}
System.out.println("Thread 2: Waiting for lock 1...");
synchronized (Lock1) {
System.out.println("Thread 2: Holding lock 1 & 2...");
}
}
}
}
}
When you compile and execute the above program, you find a deadlock situation and following is the output produced by the program −
Thread 1: Holding lock 1...
Thread 2: Holding lock 2...
Thread 1: Waiting for lock 2...
Thread 2: Waiting for lock 1...
The above program will hang forever because neither of the threads in position to proceed and waiting for each other to release the lock, so you can come out of the program by pressing CTRL+C.
Let's change the order of the lock and run of the same program to see if both the threads still wait for each other −
public class TestThread {
public static Object Lock1 = new Object();
public static Object Lock2 = new Object();
public static void main(String args[]) {
ThreadDemo1 T1 = new ThreadDemo1();
ThreadDemo2 T2 = new ThreadDemo2();
T1.start();
T2.start();
}
private static class ThreadDemo1 extends Thread {
public void run() {
synchronized (Lock1) {
System.out.println("Thread 1: Holding lock 1...");
try {
Thread.sleep(10);
} catch (InterruptedException e) {}
System.out.println("Thread 1: Waiting for lock 2...");
synchronized (Lock2) {
System.out.println("Thread 1: Holding lock 1 & 2...");
}
}
}
}
private static class ThreadDemo2 extends Thread {
public void run() {
synchronized (Lock1) {
System.out.println("Thread 2: Holding lock 1...");
try {
Thread.sleep(10);
} catch (InterruptedException e) {}
System.out.println("Thread 2: Waiting for lock 2...");
synchronized (Lock2) {
System.out.println("Thread 2: Holding lock 1 & 2...");
}
}
}
}
}
So just changing the order of the locks prevent the program in going into a deadlock situation and completes with the following result −
Thread 1: Holding lock 1...
Thread 1: Waiting for lock 2...
Thread 1: Holding lock 1 & 2...
Thread 2: Holding lock 1...
Thread 2: Waiting for lock 2...
Thread 2: Holding lock 1 & 2...
The above example is to just make the concept clear, however, it is a complex concept and you should deep dive into it before you develop your applications to deal with deadlock situations.
16 Lectures
2 hours
Malhar Lathkar
19 Lectures
5 hours
Malhar Lathkar
25 Lectures
2.5 hours
Anadi Sharma
126 Lectures
7 hours
Tushar Kale
119 Lectures
17.5 hours
Monica Mittal
76 Lectures
7 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2809,
"s": 2377,
"text": "Deadlock describes a situation where two or more threads are blocked forever, waiting for each other. Deadlock occurs when multiple threads need the same locks but obtain them in different order. A Java multithreaded program may suffer from the deadlock condition because the synchronized keyword causes the executing thread to block while waiting for the lock, or monitor, associated with the specified object. Here is an example."
},
{
"code": null,
"e": 4095,
"s": 2809,
"text": "public class TestThread {\n public static Object Lock1 = new Object();\n public static Object Lock2 = new Object();\n \n public static void main(String args[]) {\n ThreadDemo1 T1 = new ThreadDemo1();\n ThreadDemo2 T2 = new ThreadDemo2();\n T1.start();\n T2.start();\n }\n \n private static class ThreadDemo1 extends Thread {\n public void run() {\n synchronized (Lock1) {\n System.out.println(\"Thread 1: Holding lock 1...\");\n \n try { Thread.sleep(10); }\n catch (InterruptedException e) {}\n System.out.println(\"Thread 1: Waiting for lock 2...\");\n \n synchronized (Lock2) {\n System.out.println(\"Thread 1: Holding lock 1 & 2...\");\n }\n }\n }\n }\n private static class ThreadDemo2 extends Thread {\n public void run() {\n synchronized (Lock2) {\n System.out.println(\"Thread 2: Holding lock 2...\");\n \n try { Thread.sleep(10); }\n catch (InterruptedException e) {}\n System.out.println(\"Thread 2: Waiting for lock 1...\");\n \n synchronized (Lock1) {\n System.out.println(\"Thread 2: Holding lock 1 & 2...\");\n }\n }\n }\n } \n}"
},
{
"code": null,
"e": 4227,
"s": 4095,
"text": "When you compile and execute the above program, you find a deadlock situation and following is the output produced by the program −"
},
{
"code": null,
"e": 4348,
"s": 4227,
"text": "Thread 1: Holding lock 1...\nThread 2: Holding lock 2...\nThread 1: Waiting for lock 2...\nThread 2: Waiting for lock 1...\n"
},
{
"code": null,
"e": 4541,
"s": 4348,
"text": "The above program will hang forever because neither of the threads in position to proceed and waiting for each other to release the lock, so you can come out of the program by pressing CTRL+C."
},
{
"code": null,
"e": 4659,
"s": 4541,
"text": "Let's change the order of the lock and run of the same program to see if both the threads still wait for each other −"
},
{
"code": null,
"e": 5974,
"s": 4659,
"text": "public class TestThread {\n public static Object Lock1 = new Object();\n public static Object Lock2 = new Object();\n \n public static void main(String args[]) {\n ThreadDemo1 T1 = new ThreadDemo1();\n ThreadDemo2 T2 = new ThreadDemo2();\n T1.start();\n T2.start();\n }\n \n private static class ThreadDemo1 extends Thread {\n public void run() {\n synchronized (Lock1) {\n System.out.println(\"Thread 1: Holding lock 1...\");\n \n try {\n Thread.sleep(10);\n } catch (InterruptedException e) {}\n System.out.println(\"Thread 1: Waiting for lock 2...\");\n \n synchronized (Lock2) {\n System.out.println(\"Thread 1: Holding lock 1 & 2...\");\n }\n }\n }\n }\n private static class ThreadDemo2 extends Thread {\n public void run() {\n synchronized (Lock1) {\n System.out.println(\"Thread 2: Holding lock 1...\");\n \n try {\n Thread.sleep(10);\n } catch (InterruptedException e) {}\n System.out.println(\"Thread 2: Waiting for lock 2...\");\n \n synchronized (Lock2) {\n System.out.println(\"Thread 2: Holding lock 1 & 2...\");\n }\n }\n }\n } \n}"
},
{
"code": null,
"e": 6111,
"s": 5974,
"text": "So just changing the order of the locks prevent the program in going into a deadlock situation and completes with the following result −"
},
{
"code": null,
"e": 6296,
"s": 6111,
"text": "Thread 1: Holding lock 1...\nThread 1: Waiting for lock 2...\nThread 1: Holding lock 1 & 2...\nThread 2: Holding lock 1...\nThread 2: Waiting for lock 2...\nThread 2: Holding lock 1 & 2...\n"
},
{
"code": null,
"e": 6486,
"s": 6296,
"text": "The above example is to just make the concept clear, however, it is a complex concept and you should deep dive into it before you develop your applications to deal with deadlock situations."
},
{
"code": null,
"e": 6519,
"s": 6486,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 6535,
"s": 6519,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 6568,
"s": 6535,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 6584,
"s": 6568,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 6619,
"s": 6584,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6633,
"s": 6619,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 6667,
"s": 6633,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 6681,
"s": 6667,
"text": " Tushar Kale"
},
{
"code": null,
"e": 6718,
"s": 6681,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 6733,
"s": 6718,
"text": " Monica Mittal"
},
{
"code": null,
"e": 6766,
"s": 6733,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 6785,
"s": 6766,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6792,
"s": 6785,
"text": " Print"
},
{
"code": null,
"e": 6803,
"s": 6792,
"text": " Add Notes"
}
] |
cmp - Unix, Linux Command | cmp - Compare two files, and if they differ, tells the first byte and line number where they differ.
cmp options... FromFile [ToFile]
'cmp' reports the differences between two files character by character, instead of line by line. As a result, it is more useful than 'diff' for comparing binary files. For text files, 'cmp' is useful mainly when you want to know only whether two files are identical. For files that are identical, 'cmp' produces no output. When the files differ, by default, 'cmp' outputs the byte offset and line number where the first difference occurs. You can use the '-s' option to suppress that information, so that 'cmp' produces no output and reports whether the files differ using only its exit status. Unlike 'diff', 'cmp' cannot compare directories; it can only compare two files.
Compare two files
$ cat sample.txt
This is a sample text file
$ cat sample1.txt
This is another sample file
$ cmp sample.txt sample1.txt
sample.txt sample1.txt differ: byte 10, line 1
129 Lectures
23 hours
Eduonix Learning Solutions
5 Lectures
4.5 hours
Frahaan Hussain
35 Lectures
2 hours
Pradeep D
41 Lectures
2.5 hours
Musab Zayadneh
46 Lectures
4 hours
GUHARAJANM
6 Lectures
4 hours
Uplatz
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 10678,
"s": 10577,
"text": "cmp - Compare two files, and if they differ, tells the first byte and line number where they differ."
},
{
"code": null,
"e": 10711,
"s": 10678,
"text": "cmp options... FromFile [ToFile]"
},
{
"code": null,
"e": 11386,
"s": 10711,
"text": "'cmp' reports the differences between two files character by character, instead of line by line. As a result, it is more useful than 'diff' for comparing binary files. For text files, 'cmp' is useful mainly when you want to know only whether two files are identical. For files that are identical, 'cmp' produces no output. When the files differ, by default, 'cmp' outputs the byte offset and line number where the first difference occurs. You can use the '-s' option to suppress that information, so that 'cmp' produces no output and reports whether the files differ using only its exit status. Unlike 'diff', 'cmp' cannot compare directories; it can only compare two files."
},
{
"code": null,
"e": 11404,
"s": 11386,
"text": "Compare two files"
},
{
"code": null,
"e": 11571,
"s": 11404,
"text": "$ cat sample.txt\nThis is a sample text file\n$ cat sample1.txt\nThis is another sample file\n$ cmp sample.txt sample1.txt\nsample.txt sample1.txt differ: byte 10, line 1\n"
},
{
"code": null,
"e": 11606,
"s": 11571,
"text": "\n 129 Lectures \n 23 hours \n"
},
{
"code": null,
"e": 11634,
"s": 11606,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 11668,
"s": 11634,
"text": "\n 5 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 11685,
"s": 11668,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 11718,
"s": 11685,
"text": "\n 35 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 11729,
"s": 11718,
"text": " Pradeep D"
},
{
"code": null,
"e": 11764,
"s": 11729,
"text": "\n 41 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 11780,
"s": 11764,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 11813,
"s": 11780,
"text": "\n 46 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 11825,
"s": 11813,
"text": " GUHARAJANM"
},
{
"code": null,
"e": 11857,
"s": 11825,
"text": "\n 6 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 11865,
"s": 11857,
"text": " Uplatz"
},
{
"code": null,
"e": 11872,
"s": 11865,
"text": " Print"
},
{
"code": null,
"e": 11883,
"s": 11872,
"text": " Add Notes"
}
] |
Apache Commons Collections - Union | CollectionUtils class of Apache Commons Collections library provides various utility methods for common operations covering wide range of use cases. It helps avoid writing boilerplate code. This library is very useful prior to jdk 8 as similar functionalities are now provided in Java 8's Stream API.
union() method of CollectionUtils can be used to get the union of two collections.
Following is the declaration for org.apache.commons.collections4.CollectionUtils.union() method −
public static <O> Collection<O> union(Iterable<? extends O> a, Iterable<? extends O> b)
a − The first collection, must not be null.
a − The first collection, must not be null.
b − The second collection, must not be null.
b − The second collection, must not be null.
The union of the two collections.
The following example shows the usage of org.apache.commons.collections4.CollectionUtils.union() method. We'll get the union of two lists.
import java.util.Arrays;
import java.util.List;
import org.apache.commons.collections4.CollectionUtils;
public class CollectionUtilsTester {
public static void main(String[] args) {
//checking inclusion
List<String> list1 = Arrays.asList("A","A","A","C","B","B");
List<String> list2 = Arrays.asList("A","A","B","B");
System.out.println("List 1: " + list1);
System.out.println("List 2: " + list2);
System.out.println("Union of List 1 and List 2: "+ CollectionUtils.union(list1, list2));
}
}
This produces the following output −
List 1: [A, A, A, C, B, B]
List 2: [A, A, B, B]
Union of List 1 and List 2: [A, A, A, B, B, C]
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2501,
"s": 2200,
"text": "CollectionUtils class of Apache Commons Collections library provides various utility methods for common operations covering wide range of use cases. It helps avoid writing boilerplate code. This library is very useful prior to jdk 8 as similar functionalities are now provided in Java 8's Stream API."
},
{
"code": null,
"e": 2584,
"s": 2501,
"text": "union() method of CollectionUtils can be used to get the union of two collections."
},
{
"code": null,
"e": 2682,
"s": 2584,
"text": "Following is the declaration for org.apache.commons.collections4.CollectionUtils.union() method −"
},
{
"code": null,
"e": 2771,
"s": 2682,
"text": "public static <O> Collection<O> union(Iterable<? extends O> a, Iterable<? extends O> b)\n"
},
{
"code": null,
"e": 2815,
"s": 2771,
"text": "a − The first collection, must not be null."
},
{
"code": null,
"e": 2859,
"s": 2815,
"text": "a − The first collection, must not be null."
},
{
"code": null,
"e": 2904,
"s": 2859,
"text": "b − The second collection, must not be null."
},
{
"code": null,
"e": 2949,
"s": 2904,
"text": "b − The second collection, must not be null."
},
{
"code": null,
"e": 2983,
"s": 2949,
"text": "The union of the two collections."
},
{
"code": null,
"e": 3122,
"s": 2983,
"text": "The following example shows the usage of org.apache.commons.collections4.CollectionUtils.union() method. We'll get the union of two lists."
},
{
"code": null,
"e": 3662,
"s": 3122,
"text": "import java.util.Arrays;\nimport java.util.List;\nimport org.apache.commons.collections4.CollectionUtils;\n\npublic class CollectionUtilsTester {\n public static void main(String[] args) {\n //checking inclusion\n List<String> list1 = Arrays.asList(\"A\",\"A\",\"A\",\"C\",\"B\",\"B\");\n List<String> list2 = Arrays.asList(\"A\",\"A\",\"B\",\"B\");\n \n System.out.println(\"List 1: \" + list1);\n System.out.println(\"List 2: \" + list2);\n System.out.println(\"Union of List 1 and List 2: \"+ CollectionUtils.union(list1, list2));\n }\n}"
},
{
"code": null,
"e": 3699,
"s": 3662,
"text": "This produces the following output −"
},
{
"code": null,
"e": 3795,
"s": 3699,
"text": "List 1: [A, A, A, C, B, B]\nList 2: [A, A, B, B]\nUnion of List 1 and List 2: [A, A, A, B, B, C]\n"
},
{
"code": null,
"e": 3802,
"s": 3795,
"text": " Print"
},
{
"code": null,
"e": 3813,
"s": 3802,
"text": " Add Notes"
}
] |
SAP HANA - SQL Explain Plans | SQL explain plans are used to generate detail explanation of SQL statements. They are used to evaluate execution plan that SAP HANA database follows to execute the SQL statements.
The results of explain plan are stored into EXPLAIN_PLAN_TABLE for evaluation. To use Explain Plan, passed SQL query must be a data manipulation language (DML).
SELECT − retrieve data from the a database
SELECT − retrieve data from the a database
INSERT − insert data into a table
INSERT − insert data into a table
UPDATE − updates existing data within a table
UPDATE − updates existing data within a table
SQL Explain Plans cannot be used with DDL and DCL SQL statements.
EXPLAIN PLAN_TABLE in database consists of multiple columns. Few common column names − OPERATOR_NAME, OPERATOR_ID, PARENT_OPERATOR_ID, LEVEL and POSITION, etc.
COLUMN SEARCH value tells the starting position of column engine operators.
ROW SEARCH value tells the starting position of row engine operators.
EXPLAIN PLAN SET STATEMENT_NAME = ‘statement_name’ FOR <SQL DML statement>
SELECT Operator_Name, Operator_ID
FROM explain_plan_table
WHERE statement_name = 'statement_name';
DELETE FROM explain_plan_table WHERE statement_name = 'TPC-H Q10';
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": 3287,
"s": 3107,
"text": "SQL explain plans are used to generate detail explanation of SQL statements. They are used to evaluate execution plan that SAP HANA database follows to execute the SQL statements."
},
{
"code": null,
"e": 3448,
"s": 3287,
"text": "The results of explain plan are stored into EXPLAIN_PLAN_TABLE for evaluation. To use Explain Plan, passed SQL query must be a data manipulation language (DML)."
},
{
"code": null,
"e": 3491,
"s": 3448,
"text": "SELECT − retrieve data from the a database"
},
{
"code": null,
"e": 3534,
"s": 3491,
"text": "SELECT − retrieve data from the a database"
},
{
"code": null,
"e": 3568,
"s": 3534,
"text": "INSERT − insert data into a table"
},
{
"code": null,
"e": 3602,
"s": 3568,
"text": "INSERT − insert data into a table"
},
{
"code": null,
"e": 3648,
"s": 3602,
"text": "UPDATE − updates existing data within a table"
},
{
"code": null,
"e": 3694,
"s": 3648,
"text": "UPDATE − updates existing data within a table"
},
{
"code": null,
"e": 3760,
"s": 3694,
"text": "SQL Explain Plans cannot be used with DDL and DCL SQL statements."
},
{
"code": null,
"e": 3920,
"s": 3760,
"text": "EXPLAIN PLAN_TABLE in database consists of multiple columns. Few common column names − OPERATOR_NAME, OPERATOR_ID, PARENT_OPERATOR_ID, LEVEL and POSITION, etc."
},
{
"code": null,
"e": 3996,
"s": 3920,
"text": "COLUMN SEARCH value tells the starting position of column engine operators."
},
{
"code": null,
"e": 4066,
"s": 3996,
"text": "ROW SEARCH value tells the starting position of row engine operators."
},
{
"code": null,
"e": 4142,
"s": 4066,
"text": "EXPLAIN PLAN SET STATEMENT_NAME = ‘statement_name’ FOR <SQL DML statement>\n"
},
{
"code": null,
"e": 4241,
"s": 4142,
"text": "SELECT Operator_Name, Operator_ID\nFROM explain_plan_table\nWHERE statement_name = 'statement_name';"
},
{
"code": null,
"e": 4309,
"s": 4241,
"text": "DELETE FROM explain_plan_table WHERE statement_name = 'TPC-H Q10';\n"
},
{
"code": null,
"e": 4342,
"s": 4309,
"text": "\n 25 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 4356,
"s": 4342,
"text": " Sanjo Thomas"
},
{
"code": null,
"e": 4389,
"s": 4356,
"text": "\n 26 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4401,
"s": 4389,
"text": " Neha Gupta"
},
{
"code": null,
"e": 4436,
"s": 4401,
"text": "\n 30 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4451,
"s": 4436,
"text": " Sumit Agarwal"
},
{
"code": null,
"e": 4484,
"s": 4451,
"text": "\n 30 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4499,
"s": 4484,
"text": " Sumit Agarwal"
},
{
"code": null,
"e": 4534,
"s": 4499,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4546,
"s": 4534,
"text": " Neha Malik"
},
{
"code": null,
"e": 4581,
"s": 4546,
"text": "\n 13 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4593,
"s": 4581,
"text": " Neha Malik"
},
{
"code": null,
"e": 4600,
"s": 4593,
"text": " Print"
},
{
"code": null,
"e": 4611,
"s": 4600,
"text": " Add Notes"
}
] |
Facial expression detection using Deepface module in Python - GeeksforGeeks | 28 Jul, 2021
In this article, we are going to detect the facial expression of an already existing image using OpenCV, Deepface, and matplotlib modules in python.
OpenCV: OpenCV is an open-source library in python which is used for computer vision, machine learning, and image processing.
Matplotlib: Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python.
Deepface: Deepface was built by an artificial intelligence researchers group at Facebook. It is a framework in python for facial recognition and attributes analysis. Deepface’s core library components are used in Keras and TensorFlow.
pip install deepface
This is the most basic expression detection technique and there are several ways in which we can detect facial expression.
Step 1: Importing the required module.
Python3
#import the required modules
import cv2
import matplotlib.pyplot as plt
from deepface import DeepFace
Step 2: Copy the path of the picture of which expression detection is to be done, read the image using “imread()” method in cv2 providing the path within the bracket. imread() reads the image from the file and stores it in an array. Then use imshow() method of matplotlib. imshow() method converts data into image. Now plot the image using show method in order to ensure that the image has been correctly imported.
Python3
# read image
img = cv2.imread('img1.jpg')
# call imshow() using plt object
plt.imshow(img[:, :, : : -1])
# display that image
plt.show()
Output:
Output image
Step 3: Create a result variable that will store the result. Use Deepface analyze() method, Deepface analyze() method contains strong facial attribute analysis features such as age, gender, facial expressions. Facial expressions include anger, fear, neutral, sad, disgust, happy, and surprise. Print the result. The result shows the facial expressions percentage of the person.
Python3
# storing the result
result = DeepFace.analyze(img,
actions = ['emotion'])
# print result
print(result)
Output:
The result shows that person is 96% happy.
Below is the complete implementation:
Python3
# import the required modules
import cv2
import matplotlib.pyplot as plt
from deepface import DeepFace
# read image
img = cv2.imread('img.jpg')
# call imshow() using plt object
plt.imshow(img[:,:,::-1])
# display that image
plt.show()
# storing the result
result = DeepFace.analyze(img,actions=['emotion'])
# print result
print(result)
Output:
Picked
python-modules
Python-OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python | [
{
"code": null,
"e": 24001,
"s": 23970,
"text": " \n28 Jul, 2021\n"
},
{
"code": null,
"e": 24150,
"s": 24001,
"text": "In this article, we are going to detect the facial expression of an already existing image using OpenCV, Deepface, and matplotlib modules in python."
},
{
"code": null,
"e": 24276,
"s": 24150,
"text": "OpenCV: OpenCV is an open-source library in python which is used for computer vision, machine learning, and image processing."
},
{
"code": null,
"e": 24399,
"s": 24276,
"text": "Matplotlib: Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python."
},
{
"code": null,
"e": 24634,
"s": 24399,
"text": "Deepface: Deepface was built by an artificial intelligence researchers group at Facebook. It is a framework in python for facial recognition and attributes analysis. Deepface’s core library components are used in Keras and TensorFlow."
},
{
"code": null,
"e": 24655,
"s": 24634,
"text": "pip install deepface"
},
{
"code": null,
"e": 24779,
"s": 24655,
"text": "This is the most basic expression detection technique and there are several ways in which we can detect facial expression. "
},
{
"code": null,
"e": 24818,
"s": 24779,
"text": "Step 1: Importing the required module."
},
{
"code": null,
"e": 24826,
"s": 24818,
"text": "Python3"
},
{
"code": "\n\n\n\n\n\n\n#import the required modules \nimport cv2 \nimport matplotlib.pyplot as plt \nfrom deepface import DeepFace\n\n\n\n\n\n",
"e": 24954,
"s": 24836,
"text": null
},
{
"code": null,
"e": 25369,
"s": 24954,
"text": "Step 2: Copy the path of the picture of which expression detection is to be done, read the image using “imread()” method in cv2 providing the path within the bracket. imread() reads the image from the file and stores it in an array. Then use imshow() method of matplotlib. imshow() method converts data into image. Now plot the image using show method in order to ensure that the image has been correctly imported."
},
{
"code": null,
"e": 25377,
"s": 25369,
"text": "Python3"
},
{
"code": "\n\n\n\n\n\n\n# read image \nimg = cv2.imread('img1.jpg') \n \n# call imshow() using plt object \nplt.imshow(img[:, :, : : -1]) \n \n# display that image \nplt.show() \n\n\n\n\n\n",
"e": 25549,
"s": 25387,
"text": null
},
{
"code": null,
"e": 25557,
"s": 25549,
"text": "Output:"
},
{
"code": null,
"e": 25570,
"s": 25557,
"text": "Output image"
},
{
"code": null,
"e": 25948,
"s": 25570,
"text": "Step 3: Create a result variable that will store the result. Use Deepface analyze() method, Deepface analyze() method contains strong facial attribute analysis features such as age, gender, facial expressions. Facial expressions include anger, fear, neutral, sad, disgust, happy, and surprise. Print the result. The result shows the facial expressions percentage of the person."
},
{
"code": null,
"e": 25956,
"s": 25948,
"text": "Python3"
},
{
"code": "\n\n\n\n\n\n\n# storing the result \nresult = DeepFace.analyze(img, \n actions = ['emotion']) \n \n# print result \nprint(result)\n\n\n\n\n\n",
"e": 26116,
"s": 25966,
"text": null
},
{
"code": null,
"e": 26124,
"s": 26116,
"text": "Output:"
},
{
"code": null,
"e": 26167,
"s": 26124,
"text": "The result shows that person is 96% happy."
},
{
"code": null,
"e": 26205,
"s": 26167,
"text": "Below is the complete implementation:"
},
{
"code": null,
"e": 26213,
"s": 26205,
"text": "Python3"
},
{
"code": "\n\n\n\n\n\n\n# import the required modules \nimport cv2 \nimport matplotlib.pyplot as plt \nfrom deepface import DeepFace \n \n# read image \nimg = cv2.imread('img.jpg') \n \n# call imshow() using plt object \nplt.imshow(img[:,:,::-1]) \n \n# display that image \nplt.show() \n \n# storing the result \nresult = DeepFace.analyze(img,actions=['emotion']) \n \n# print result \nprint(result) \n\n\n\n\n\n",
"e": 26601,
"s": 26223,
"text": null
},
{
"code": null,
"e": 26609,
"s": 26601,
"text": "Output:"
},
{
"code": null,
"e": 26618,
"s": 26609,
"text": "\nPicked\n"
},
{
"code": null,
"e": 26635,
"s": 26618,
"text": "\npython-modules\n"
},
{
"code": null,
"e": 26651,
"s": 26635,
"text": "\nPython-OpenCV\n"
},
{
"code": null,
"e": 26660,
"s": 26651,
"text": "\nPython\n"
},
{
"code": null,
"e": 26865,
"s": 26660,
"text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n "
},
{
"code": null,
"e": 26897,
"s": 26865,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26953,
"s": 26897,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26995,
"s": 26953,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27037,
"s": 26995,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27073,
"s": 27037,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 27095,
"s": 27073,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27134,
"s": 27095,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27161,
"s": 27134,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27192,
"s": 27161,
"text": "Python | os.path.join() method"
}
] |
Bootstrap Panels | A panel in bootstrap is a bordered box with some padding around its content:
Panels are created with the .panel class, and content inside the panel has a
.panel-body class:
The .panel-default class is used to style the color of the
panel. See the last example on this page for more contextual classes.
The .panel-heading class adds a heading to the panel:
The .panel-footer class adds a footer to the panel:
To group many panels together, wrap a <div> with class
.panel-group around them.
The .panel-group class clears the bottom-margin of each panel:
To color the panel, use contextual classes (.panel-default, .panel-primary, .panel-success, .panel-info, .panel-warning, or .panel-danger):
Create a basic (default) Bootstrap Panel with the words: "Hello World".
<div class="">
<div class="">Hello World</div>
</div>
Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
[email protected]
Your message has been sent to W3Schools. | [
{
"code": null,
"e": 77,
"s": 0,
"text": "A panel in bootstrap is a bordered box with some padding around its content:"
},
{
"code": null,
"e": 174,
"s": 77,
"text": "Panels are created with the .panel class, and content inside the panel has a \n.panel-body class:"
},
{
"code": null,
"e": 304,
"s": 174,
"text": "The .panel-default class is used to style the color of the \npanel. See the last example on this page for more contextual classes."
},
{
"code": null,
"e": 358,
"s": 304,
"text": "The .panel-heading class adds a heading to the panel:"
},
{
"code": null,
"e": 410,
"s": 358,
"text": "The .panel-footer class adds a footer to the panel:"
},
{
"code": null,
"e": 492,
"s": 410,
"text": "To group many panels together, wrap a <div> with class \n.panel-group around them."
},
{
"code": null,
"e": 555,
"s": 492,
"text": "The .panel-group class clears the bottom-margin of each panel:"
},
{
"code": null,
"e": 695,
"s": 555,
"text": "To color the panel, use contextual classes (.panel-default, .panel-primary, .panel-success, .panel-info, .panel-warning, or .panel-danger):"
},
{
"code": null,
"e": 767,
"s": 695,
"text": "Create a basic (default) Bootstrap Panel with the words: \"Hello World\"."
},
{
"code": null,
"e": 824,
"s": 767,
"text": "<div class=\"\">\n <div class=\"\">Hello World</div>\n</div>\n"
},
{
"code": null,
"e": 843,
"s": 824,
"text": "Start the Exercise"
},
{
"code": null,
"e": 876,
"s": 843,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 918,
"s": 876,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 1025,
"s": 918,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 1044,
"s": 1025,
"text": "[email protected]"
}
] |
How to create a multilevel listView using Kotlin? | This example demonstrates how to create a multilevel listView using Kotlin Android.
Step 1 − Create a new project in Android Studio, go to File ⇉ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<ExpandableListView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/expandableListView"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
</ExpandableListView>
Step 3 − Add the following code to src/MainActivity.kt
package app.com.kotlinapp
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
private val header: MutableList<String> = ArrayList()
private val body: MutableList<MutableList<String>> = ArrayList()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val myFavCricketPlayers: MutableList<String> = ArrayList()
myFavCricketPlayers.add("MS.Dhoni");
myFavCricketPlayers.add("Sehwag");
myFavCricketPlayers.add("Shane Watson");
myFavCricketPlayers.add("Ricky Ponting");
myFavCricketPlayers.add("Shahid Afridi");
val myFavFootballPlayers: MutableList<String> = ArrayList()
myFavFootballPlayers.add("Cristiano Ronaldo")
myFavFootballPlayers.add("Lionel Messi")
myFavFootballPlayers.add("Gareth Bale")
myFavFootballPlayers.add("Neymar JR")
myFavFootballPlayers.add("David de Gea")
val myFavTennisPlayers: MutableList<String> = ArrayList()
myFavTennisPlayers.add("Roger Federer")
myFavTennisPlayers.add("Rafael Nadal")
myFavTennisPlayers.add("Andy Murray")
myFavTennisPlayers.add("Novak Jokovic")
myFavTennisPlayers.add("Sania Mirza")
header.add("myFavCricketPlayers")
header.add("myFavFootballPlayers")
header.add("myFavTennisPlayers")
body.add(myFavCricketPlayers)
body.add(myFavFootballPlayers)
body.add(myFavTennisPlayers)
expandableListView.setAdapter(CustomListAdapter(this, expandableListView, header, body))
}
}
Step 4 − Create a new Kotlin class and add the following code to src/CustomListAdapter.kt
package app.com.kotlinapp
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseExpandableListAdapter
import android.widget.ExpandableListView
import android.widget.TextView
import android.widget.Toast
class CustomListAdapter(
var context: Context,
var expandableListView: ExpandableListView,
var header: MutableList<String>,
var body: MutableList<MutableList<String>>
) :
BaseExpandableListAdapter() {
override fun getGroup(groupPosition: Int): String {
return header[groupPosition]
}
override fun isChildSelectable(groupPosition: Int, childPosition: Int): Boolean {
return true
}
override fun hasStableIds(): Boolean {
return false
}
override fun getGroupView(
groupPosition: Int,
isExpanded: Boolean,
convertView: View?,
parent: ViewGroup?
): View? {
var convertView = convertView
if (convertView == null) {
val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
convertView = inflater.inflate(R.layout.list_header, null)
}
val title = convertView?.findViewById<TextView>(R.id.textView)
title?.text = getGroup(groupPosition)
title?.setOnClickListener {
if (expandableListView.isGroupExpanded(groupPosition))
expandableListView.collapseGroup(groupPosition)
else
expandableListView.expandGroup(groupPosition)
Toast.makeText(context, getGroup(groupPosition), Toast.LENGTH_SHORT).show()
}
return convertView
}
override fun getChildrenCount(groupPosition: Int): Int {
return body[groupPosition].size
}
override fun getChild(groupPosition: Int, childPosition: Int): String {
return body[groupPosition][childPosition]
}
override fun getGroupId(groupPosition: Int): Long {
return groupPosition.toLong()
}
override fun getChildView(
groupPosition: Int,
childPosition: Int,
isLastChild: Boolean,
convertView: View?,
parent: ViewGroup?
): View? {
var convertView = convertView
if (convertView == null) {
val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
convertView = inflater.inflate(R.layout.list_body, null)
}
val title = convertView?.findViewById<TextView>(R.id.textView)
title?.text = getChild(groupPosition, childPosition)
return convertView
}
override fun getChildId(groupPosition: Int, childPosition: Int): Long {
return childPosition.toLong()
}
override fun getGroupCount(): Int {
return header.size
}
}
Step 5 − Create a Layout resource file (list_header.xml) and add the following code −
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingStart="?android:attr/expandableListPreferredItemPaddingLeft"
android:paddingTop="8dp"
android:paddingEnd="8dp"
android:paddingBottom="8dp"
android:textStyle="bold">
</TextView>
Step 6 − Create a Layout resource file (list_body.xml) and add the following code−
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingStart="?android:attr/expandableListPreferredItemPaddingLeft"
android:paddingTop="8dp"
android:paddingEnd="8dp"
android:paddingBottom="8dp">
</TextView>
Step 7 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="app.com.kotlinapp">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application&g;
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Click here to download the project code. | [
{
"code": null,
"e": 1146,
"s": 1062,
"text": "This example demonstrates how to create a multilevel listView using Kotlin Android."
},
{
"code": null,
"e": 1275,
"s": 1146,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇉ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1340,
"s": 1275,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1738,
"s": 1340,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<ExpandableListView xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:id=\"@+id/expandableListView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n</ExpandableListView>"
},
{
"code": null,
"e": 1793,
"s": 1738,
"text": "Step 3 − Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 3469,
"s": 1793,
"text": "package app.com.kotlinapp\nimport android.os.Bundle\nimport androidx.appcompat.app.AppCompatActivity\nimport kotlinx.android.synthetic.main.activity_main.*\nclass MainActivity : AppCompatActivity() {\n private val header: MutableList<String> = ArrayList()\n private val body: MutableList<MutableList<String>> = ArrayList()\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n val myFavCricketPlayers: MutableList<String> = ArrayList()\n myFavCricketPlayers.add(\"MS.Dhoni\");\n myFavCricketPlayers.add(\"Sehwag\");\n myFavCricketPlayers.add(\"Shane Watson\");\n myFavCricketPlayers.add(\"Ricky Ponting\");\n myFavCricketPlayers.add(\"Shahid Afridi\");\n val myFavFootballPlayers: MutableList<String> = ArrayList()\n myFavFootballPlayers.add(\"Cristiano Ronaldo\")\n myFavFootballPlayers.add(\"Lionel Messi\")\n myFavFootballPlayers.add(\"Gareth Bale\")\n myFavFootballPlayers.add(\"Neymar JR\")\n myFavFootballPlayers.add(\"David de Gea\")\n val myFavTennisPlayers: MutableList<String> = ArrayList()\n myFavTennisPlayers.add(\"Roger Federer\")\n myFavTennisPlayers.add(\"Rafael Nadal\")\n myFavTennisPlayers.add(\"Andy Murray\")\n myFavTennisPlayers.add(\"Novak Jokovic\")\n myFavTennisPlayers.add(\"Sania Mirza\")\n header.add(\"myFavCricketPlayers\")\n header.add(\"myFavFootballPlayers\")\n header.add(\"myFavTennisPlayers\")\n body.add(myFavCricketPlayers)\n body.add(myFavFootballPlayers)\n body.add(myFavTennisPlayers)\n expandableListView.setAdapter(CustomListAdapter(this, expandableListView, header, body))\n }\n}"
},
{
"code": null,
"e": 3559,
"s": 3469,
"text": "Step 4 − Create a new Kotlin class and add the following code to src/CustomListAdapter.kt"
},
{
"code": null,
"e": 6224,
"s": 3559,
"text": "package app.com.kotlinapp\nimport android.content.Context\nimport android.view.LayoutInflater\nimport android.view.View\nimport android.view.ViewGroup\nimport android.widget.BaseExpandableListAdapter\nimport android.widget.ExpandableListView\nimport android.widget.TextView\nimport android.widget.Toast\nclass CustomListAdapter(\n var context: Context,\n var expandableListView: ExpandableListView,\n var header: MutableList<String>,\n var body: MutableList<MutableList<String>>\n) :\n BaseExpandableListAdapter() {\n override fun getGroup(groupPosition: Int): String {\n return header[groupPosition]\n }\n override fun isChildSelectable(groupPosition: Int, childPosition: Int): Boolean {\n return true\n }\n override fun hasStableIds(): Boolean {\n return false\n }\n override fun getGroupView(\n groupPosition: Int,\n isExpanded: Boolean,\n convertView: View?,\n parent: ViewGroup?\n ): View? {\n var convertView = convertView\n if (convertView == null) {\n val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater\nconvertView = inflater.inflate(R.layout.list_header, null)\n }\n val title = convertView?.findViewById<TextView>(R.id.textView)\n title?.text = getGroup(groupPosition)\n title?.setOnClickListener {\n if (expandableListView.isGroupExpanded(groupPosition))\n expandableListView.collapseGroup(groupPosition)\n else\n expandableListView.expandGroup(groupPosition)\n Toast.makeText(context, getGroup(groupPosition), Toast.LENGTH_SHORT).show()\n }\n return convertView\n }\n override fun getChildrenCount(groupPosition: Int): Int {\n return body[groupPosition].size\n }\n override fun getChild(groupPosition: Int, childPosition: Int): String {\n return body[groupPosition][childPosition]\n }\n override fun getGroupId(groupPosition: Int): Long {\n return groupPosition.toLong()\n }\n override fun getChildView(\n groupPosition: Int,\n childPosition: Int,\n isLastChild: Boolean,\n convertView: View?,\n parent: ViewGroup?\n ): View? {\n var convertView = convertView\n if (convertView == null) {\n val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater\nconvertView = inflater.inflate(R.layout.list_body, null)\n }\n val title = convertView?.findViewById<TextView>(R.id.textView)\n title?.text = getChild(groupPosition, childPosition)\n return convertView\n}\n override fun getChildId(groupPosition: Int, childPosition: Int): Long {\n return childPosition.toLong()\n }\n override fun getGroupCount(): Int {\n return header.size\n }\n}"
},
{
"code": null,
"e": 6310,
"s": 6224,
"text": "Step 5 − Create a Layout resource file (list_header.xml) and add the following code −"
},
{
"code": null,
"e": 6734,
"s": 6310,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<TextView xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:id=\"@+id/textView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:paddingStart=\"?android:attr/expandableListPreferredItemPaddingLeft\"\n android:paddingTop=\"8dp\"\n android:paddingEnd=\"8dp\"\n android:paddingBottom=\"8dp\"\n android:textStyle=\"bold\">\n</TextView>"
},
{
"code": null,
"e": 6817,
"s": 6734,
"text": "Step 6 − Create a Layout resource file (list_body.xml) and add the following code−"
},
{
"code": null,
"e": 7213,
"s": 6817,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<TextView xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:id=\"@+id/textView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:paddingStart=\"?android:attr/expandableListPreferredItemPaddingLeft\"\n android:paddingTop=\"8dp\"\n android:paddingEnd=\"8dp\"\n android:paddingBottom=\"8dp\">\n</TextView>"
},
{
"code": null,
"e": 7268,
"s": 7213,
"text": "Step 7 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 7946,
"s": 7268,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.kotlinapp\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application&g;\n</manifest>"
},
{
"code": null,
"e": 8297,
"s": 7946,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –"
},
{
"code": null,
"e": 8338,
"s": 8297,
"text": "Click here to download the project code."
}
] |
How to clone an array using spread operator in JavaScript? | Cloning is nothing but copying an array into another array. In olden days, the slice() method is used to clone an array, but ES6 has provided spread operator(...) to make our task easy. Lets' discuss both the methods.
In the following example slice() method is used to copy the array. slice() is used to slice the array from one index to another index. Since there is are no indexes provided the slice() method would slice the whole array. After slicing, the sliced part is copied into another array using assignment operator(=).
Live Demo
<html>
<body>
<script>
const games = ['cricket', 'hockey', 'football','kabaddi'];
const clonegames = games.slice();
document.write(clonegames);
</script>
</body>
</html>
cricket,hockey,football,kabaddi
Es6 has brought many new features in which spread operator is a predominant one. This operator has many uses and cloning is one of those uses.
Live Demo
<html>
<body>
<script>
const games = ['cricket', 'hockey', 'football','kabaddi'];
const clonegames = [...games];
document.write(clonegames);
</script>
</body>
</html>
cricket,hockey,football,kabaddi | [
{
"code": null,
"e": 1280,
"s": 1062,
"text": "Cloning is nothing but copying an array into another array. In olden days, the slice() method is used to clone an array, but ES6 has provided spread operator(...) to make our task easy. Lets' discuss both the methods."
},
{
"code": null,
"e": 1593,
"s": 1280,
"text": "In the following example slice() method is used to copy the array. slice() is used to slice the array from one index to another index. Since there is are no indexes provided the slice() method would slice the whole array. After slicing, the sliced part is copied into another array using assignment operator(=). "
},
{
"code": null,
"e": 1604,
"s": 1593,
"text": " Live Demo"
},
{
"code": null,
"e": 1798,
"s": 1604,
"text": "<html>\n<body>\n <script>\n const games = ['cricket', 'hockey', 'football','kabaddi'];\n const clonegames = games.slice();\n document.write(clonegames);\n </script>\n</body>\n</html>"
},
{
"code": null,
"e": 1830,
"s": 1798,
"text": "cricket,hockey,football,kabaddi"
},
{
"code": null,
"e": 1974,
"s": 1830,
"text": "Es6 has brought many new features in which spread operator is a predominant one. This operator has many uses and cloning is one of those uses. "
},
{
"code": null,
"e": 1984,
"s": 1974,
"text": "Live Demo"
},
{
"code": null,
"e": 2175,
"s": 1984,
"text": "<html>\n<body>\n <script>\n const games = ['cricket', 'hockey', 'football','kabaddi'];\n const clonegames = [...games];\n document.write(clonegames);\n </script>\n</body>\n</html>"
},
{
"code": null,
"e": 2207,
"s": 2175,
"text": "cricket,hockey,football,kabaddi"
}
] |
Create array from JSON object JavaScript | Suppose, we have the following JSON object −
const obj = {
"test1": [{
"1": {
"rssi": -25,
}
}, {
"2": {
"rssi": -25,
}
}],
"test2": [{
"15": {
"rssi": -10,
} }, {
"19": {
"rssi": -21,
}
}]
};
We are required to write a JavaScript function that takes in an object like this −
The function should then map the "rssi" property of all the nested objects to a corresponding nested array of arrays.
Therefore, for the above array, the output should look like this −
const output = [[-25, -25], [-10, -21]];
const obj = {
"test1": [{
"1": {
"rssi": -25,
}
}, {
"2": {
"rssi": -25,
}
}],
"test2": [
{
"15":
{ "rssi": -10,
}
}, {
"19": {
"rssi": -21,
}
}]
};
const mapToValues = (object = {}) => {
const res = [];
for (let key in object) {
let obj = object[key];
let aux = [];
for (let i = 0; i < obj.length; i++) {
for (x in obj[i]) {
aux.push(obj[i][x].rssi);
}
}
res.push(aux);
}
return res;
};
console.log(mapToValues(obj));
And the output in the console will be −
[ [ -25, -25 ], [ -10, -21 ] ] | [
{
"code": null,
"e": 1107,
"s": 1062,
"text": "Suppose, we have the following JSON object −"
},
{
"code": null,
"e": 1351,
"s": 1107,
"text": "const obj = {\n \"test1\": [{\n \"1\": {\n \"rssi\": -25,\n }\n }, {\n \"2\": {\n \"rssi\": -25,\n }\n }],\n \"test2\": [{\n \"15\": {\n \"rssi\": -10,\n } }, {\n \"19\": {\n \"rssi\": -21,\n }\n }]\n};"
},
{
"code": null,
"e": 1434,
"s": 1351,
"text": "We are required to write a JavaScript function that takes in an object like this −"
},
{
"code": null,
"e": 1552,
"s": 1434,
"text": "The function should then map the \"rssi\" property of all the nested objects to a corresponding nested array of arrays."
},
{
"code": null,
"e": 1619,
"s": 1552,
"text": "Therefore, for the above array, the output should look like this −"
},
{
"code": null,
"e": 1660,
"s": 1619,
"text": "const output = [[-25, -25], [-10, -21]];"
},
{
"code": null,
"e": 2247,
"s": 1660,
"text": "const obj = {\n \"test1\": [{\n \"1\": {\n \"rssi\": -25,\n }\n }, {\n \"2\": {\n \"rssi\": -25,\n }\n}],\n\"test2\": [\n {\n \"15\":\n { \"rssi\": -10,\n }\n }, {\n \"19\": {\n \"rssi\": -21,\n }\n }]\n};\nconst mapToValues = (object = {}) => {\n const res = [];\n for (let key in object) {\n let obj = object[key];\n let aux = [];\n for (let i = 0; i < obj.length; i++) {\n for (x in obj[i]) {\n aux.push(obj[i][x].rssi);\n }\n }\n res.push(aux);\n }\n return res;\n};\nconsole.log(mapToValues(obj));"
},
{
"code": null,
"e": 2287,
"s": 2247,
"text": "And the output in the console will be −"
},
{
"code": null,
"e": 2318,
"s": 2287,
"text": "[ [ -25, -25 ], [ -10, -21 ] ]"
}
] |
Python SQLite - Delete Data | To delete records from a SQLite table, you need to use the DELETE FROM statement. To remove specific records, you need to use WHERE clause along with it.
To update specific rows, you need to use the WHERE clause along with it.
Following is the syntax of the DELETE query in SQLite −
DELETE FROM table_name [WHERE Clause]
Assume we have created a table with name CRICKETERS using the following query −
sqlite> CREATE TABLE CRICKETERS (
First_Name VARCHAR(255),
Last_Name VARCHAR(255),
Age int,
Place_Of_Birth VARCHAR(255),
Country VARCHAR(255)
);
sqlite>
And if we have inserted 5 records in to it using INSERT statements as −
sqlite> insert into CRICKETERS values('Shikhar', 'Dhawan', 33, 'Delhi', 'India');
sqlite> insert into CRICKETERS values('Jonathan', 'Trott', 38, 'CapeTown', 'SouthAfrica');
sqlite> insert into CRICKETERS values('Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka');
sqlite> insert into CRICKETERS values('Virat', 'Kohli', 30, 'Delhi', 'India');
sqlite> insert into CRICKETERS values('Rohit', 'Sharma', 32, 'Nagpur', 'India');
sqlite>
Following statement deletes the record of the cricketer whose last name is 'Sangakkara'.
sqlite> DELETE FROM CRICKETERS WHERE LAST_NAME = 'Sangakkara';
sqlite>
If you retrieve the contents of the table using the SELECT statement, you can see only 4 records since we have deleted one.
sqlite> SELECT * FROM CRICKETERS;
First_Name Last_Name Age Place_Of_B Country
---------- ---------- ---- ---------- -------------
Shikhar Dhawan 46 Delhi India
Jonathan Trott 39 CapeTown SouthAfrica
Virat Kohli 31 Delhi India
Rohit Sharma 33 Nagpur India
sqlite>
If you execute the DELETE FROM statement without the WHERE clause, all the records from the specified table will be deleted.
sqlite> DELETE FROM CRICKETERS;
sqlite>
Since you have deleted all the records, if you try to retrieve the contents of the CRICKETERS table, using SELECT statement you will get an empty result set as shown below −
sqlite> SELECT * FROM CRICKETERS;
sqlite>
To add records to an existing table in SQLite database −
Import sqlite3 package.
Import sqlite3 package.
Create a connection object using the connect() method by passing the name of the database as a parameter to it.
Create a connection object using the connect() method by passing the name of the database as a parameter to it.
The cursor() method returns a cursor object using which you can communicate with SQLite3 . Create a cursor object by invoking the cursor() object on the (above created) Connection object.
The cursor() method returns a cursor object using which you can communicate with SQLite3 . Create a cursor object by invoking the cursor() object on the (above created) Connection object.
Then, invoke the execute() method on the cursor object, by passing an DELETE statement as a parameter to it.
Then, invoke the execute() method on the cursor object, by passing an DELETE statement as a parameter to it.
Following python example deletes the records from EMPLOYEE table with age value greater than 25.
import sqlite3
#Connecting to sqlite
conn = sqlite3.connect('example.db')
#Creating a cursor object using the cursor() method
cursor = conn.cursor()
#Retrieving contents of the table
print("Contents of the table: ")
cursor.execute('''SELECT * from EMPLOYEE''')
print(cursor.fetchall())
#Deleting records
cursor.execute('''DELETE FROM EMPLOYEE WHERE AGE > 25''')
#Retrieving data after delete
print("Contents of the table after delete operation ")
cursor.execute("SELECT * from EMPLOYEE")
print(cursor.fetchall())
#Commit your changes in the database
conn.commit()
#Closing the connection
conn.close()
Contents of the table:
[('Ramya', 'Rama priya', 27, 'F', 9000.0),
('Vinay', 'Battacharya', 21, 'M', 6000.0),
('Sharukh', 'Sheik', 26, 'M', 8300.0),
('Sarmista', 'Sharma', 26, 'F', 10000.0),
('Tripthi', 'Mishra', 24, 'F', 6000.0)]
Contents of the table after delete operation
[('Vinay', 'Battacharya', 21, 'M', 6000.0),
('Tripthi', 'Mishra', 24, 'F', 6000.0)]
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 3359,
"s": 3205,
"text": "To delete records from a SQLite table, you need to use the DELETE FROM statement. To remove specific records, you need to use WHERE clause along with it."
},
{
"code": null,
"e": 3432,
"s": 3359,
"text": "To update specific rows, you need to use the WHERE clause along with it."
},
{
"code": null,
"e": 3488,
"s": 3432,
"text": "Following is the syntax of the DELETE query in SQLite −"
},
{
"code": null,
"e": 3527,
"s": 3488,
"text": "DELETE FROM table_name [WHERE Clause]\n"
},
{
"code": null,
"e": 3607,
"s": 3527,
"text": "Assume we have created a table with name CRICKETERS using the following query −"
},
{
"code": null,
"e": 3775,
"s": 3607,
"text": "sqlite> CREATE TABLE CRICKETERS (\n First_Name VARCHAR(255),\n Last_Name VARCHAR(255),\n Age int,\n Place_Of_Birth VARCHAR(255),\n Country VARCHAR(255)\n);\nsqlite>"
},
{
"code": null,
"e": 3847,
"s": 3775,
"text": "And if we have inserted 5 records in to it using INSERT statements as −"
},
{
"code": null,
"e": 4277,
"s": 3847,
"text": "sqlite> insert into CRICKETERS values('Shikhar', 'Dhawan', 33, 'Delhi', 'India');\nsqlite> insert into CRICKETERS values('Jonathan', 'Trott', 38, 'CapeTown', 'SouthAfrica');\nsqlite> insert into CRICKETERS values('Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka');\nsqlite> insert into CRICKETERS values('Virat', 'Kohli', 30, 'Delhi', 'India');\nsqlite> insert into CRICKETERS values('Rohit', 'Sharma', 32, 'Nagpur', 'India');\nsqlite>"
},
{
"code": null,
"e": 4366,
"s": 4277,
"text": "Following statement deletes the record of the cricketer whose last name is 'Sangakkara'."
},
{
"code": null,
"e": 4438,
"s": 4366,
"text": "sqlite> DELETE FROM CRICKETERS WHERE LAST_NAME = 'Sangakkara';\nsqlite>\n"
},
{
"code": null,
"e": 4562,
"s": 4438,
"text": "If you retrieve the contents of the table using the SELECT statement, you can see only 4 records since we have deleted one."
},
{
"code": null,
"e": 4885,
"s": 4562,
"text": "sqlite> SELECT * FROM CRICKETERS;\nFirst_Name Last_Name Age Place_Of_B Country\n---------- ---------- ---- ---------- -------------\nShikhar Dhawan 46 Delhi India\nJonathan Trott 39 CapeTown SouthAfrica\nVirat Kohli 31 Delhi India\nRohit Sharma 33 Nagpur India\nsqlite>\n"
},
{
"code": null,
"e": 5010,
"s": 4885,
"text": "If you execute the DELETE FROM statement without the WHERE clause, all the records from the specified table will be deleted."
},
{
"code": null,
"e": 5051,
"s": 5010,
"text": "sqlite> DELETE FROM CRICKETERS;\nsqlite>\n"
},
{
"code": null,
"e": 5225,
"s": 5051,
"text": "Since you have deleted all the records, if you try to retrieve the contents of the CRICKETERS table, using SELECT statement you will get an empty result set as shown below −"
},
{
"code": null,
"e": 5268,
"s": 5225,
"text": "sqlite> SELECT * FROM CRICKETERS;\nsqlite>\n"
},
{
"code": null,
"e": 5325,
"s": 5268,
"text": "To add records to an existing table in SQLite database −"
},
{
"code": null,
"e": 5349,
"s": 5325,
"text": "Import sqlite3 package."
},
{
"code": null,
"e": 5373,
"s": 5349,
"text": "Import sqlite3 package."
},
{
"code": null,
"e": 5485,
"s": 5373,
"text": "Create a connection object using the connect() method by passing the name of the database as a parameter to it."
},
{
"code": null,
"e": 5597,
"s": 5485,
"text": "Create a connection object using the connect() method by passing the name of the database as a parameter to it."
},
{
"code": null,
"e": 5785,
"s": 5597,
"text": "The cursor() method returns a cursor object using which you can communicate with SQLite3 . Create a cursor object by invoking the cursor() object on the (above created) Connection object."
},
{
"code": null,
"e": 5973,
"s": 5785,
"text": "The cursor() method returns a cursor object using which you can communicate with SQLite3 . Create a cursor object by invoking the cursor() object on the (above created) Connection object."
},
{
"code": null,
"e": 6082,
"s": 5973,
"text": "Then, invoke the execute() method on the cursor object, by passing an DELETE statement as a parameter to it."
},
{
"code": null,
"e": 6191,
"s": 6082,
"text": "Then, invoke the execute() method on the cursor object, by passing an DELETE statement as a parameter to it."
},
{
"code": null,
"e": 6288,
"s": 6191,
"text": "Following python example deletes the records from EMPLOYEE table with age value greater than 25."
},
{
"code": null,
"e": 6896,
"s": 6288,
"text": "import sqlite3\n\n#Connecting to sqlite\nconn = sqlite3.connect('example.db')\n\n#Creating a cursor object using the cursor() method\ncursor = conn.cursor()\n\n#Retrieving contents of the table\nprint(\"Contents of the table: \")\ncursor.execute('''SELECT * from EMPLOYEE''')\nprint(cursor.fetchall())\n\n#Deleting records\ncursor.execute('''DELETE FROM EMPLOYEE WHERE AGE > 25''')\n\n#Retrieving data after delete\nprint(\"Contents of the table after delete operation \")\ncursor.execute(\"SELECT * from EMPLOYEE\")\nprint(cursor.fetchall())\n\n#Commit your changes in the database\nconn.commit()\n\n#Closing the connection\nconn.close()"
},
{
"code": null,
"e": 7276,
"s": 6896,
"text": "Contents of the table:\n[('Ramya', 'Rama priya', 27, 'F', 9000.0), \n ('Vinay', 'Battacharya', 21, 'M', 6000.0), \n ('Sharukh', 'Sheik', 26, 'M', 8300.0), \n ('Sarmista', 'Sharma', 26, 'F', 10000.0), \n ('Tripthi', 'Mishra', 24, 'F', 6000.0)]\nContents of the table after delete operation\n[('Vinay', 'Battacharya', 21, 'M', 6000.0), \n ('Tripthi', 'Mishra', 24, 'F', 6000.0)]\n"
},
{
"code": null,
"e": 7313,
"s": 7276,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 7329,
"s": 7313,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 7362,
"s": 7329,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 7381,
"s": 7362,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 7416,
"s": 7381,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 7438,
"s": 7416,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 7472,
"s": 7438,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 7500,
"s": 7472,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 7535,
"s": 7500,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 7549,
"s": 7535,
"text": " Lets Kode It"
},
{
"code": null,
"e": 7582,
"s": 7549,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 7599,
"s": 7582,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 7606,
"s": 7599,
"text": " Print"
},
{
"code": null,
"e": 7617,
"s": 7606,
"text": " Add Notes"
}
] |
ReactJS UI Ant Design Drawer Component - GeeksforGeeks | 01 Jun, 2021
Ant Design Library has this component pre-built, and it is very easy to integrate as well. The Drawer component is a panel that slides in from the edge of the screen. We can use the following approach in ReactJS to use the Ant Design Drawer Component.
Drawer Props:
afterVisibleChange: It is a callback function that is triggered after the animation ends when switching drawers.
bodyStyle: It is used for the style of the drawer content part.
className: It is used to pass the class name of the container of the Drawer dialog.
closable: It is used to indicate whether a close button is visible on the top right of the Drawer dialog or not
closeIcon: It is used for the custom close icon.
contentWrapperStyle: It is used for the style of the drawer wrapper of the content part.
destroyOnClose: It is used to indicate whether to unmount child components on the closing drawer or not.
drawerStyle: It is used for the style of the popup layer element.
footer: It is used to denote the footer for Drawer.
footerStyle: It is used for the style of the drawer footer part.
forceRender: It is used to forcefully pre-render the Drawer component.
getContainer: It is used to return the mounted node for Drawer.
headerStyle: It is used for the style of the drawer header part.
height: It is used to denote the height of the Drawer dialog.
keyboard: It is used to indicate whether to support press ESC to close or not.
mask: It is used to indicate whether to show mask or not.
maskClosable: It is used to indicate whether to close the Drawer or not while clicking on the mask.
maskStyle: It is used for the style for Drawer’s mask element.
placement: It is used for the placement of the Drawer.
push: It is the nested drawers’ push behavior.
style: It is used for the style of wrapper element.
title: It is used to denote the title for Drawer.
visible: It is used to indicate whether the Drawer dialog is visible or not.
width: It is used to denote the width of the Drawer dialog.
zIndex: It is used to denote the z-index of the Drawer.
onClose: It is a callback function that will be triggered when a user clicks the mask, close button, or Cancel button.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:npx create-react-app foldername
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Step 3: After creating the ReactJS application, Install the required module using the following command:npm install antd
Step 3: After creating the ReactJS application, Install the required module using the following command:
npm install antd
Project Structure: It will look like the following.
Project Structure
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React, { useState } from 'react'import "antd/dist/antd.css";import { Drawer, Button } from 'antd'; export default function App() { const [visible, setVisible] = useState(false); return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>ReactJS Ant-Design Drawer Component</h4> <> <Button type="primary" onClick={() => { setVisible(true); }}>Open</Button> <Drawer title="Drawer Demo" placement="left" closable={false} visible={visible} onClose={() => { setVisible(false) }} > <p>Item One</p> <p>Item Two</p> <p>Item Three</p> <p>Item Four</p> <p>Item Five</p> </Drawer> </> </div> );}
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Reference: https://ant.design/components/drawer/
ReactJS-Ant Design
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to redirect to another page in ReactJS ?
How to fetch data from an API in ReactJS ?
How to pass data from child component to its parent in ReactJS ?
How to navigate on path by button click in react router ?
How to set background images in ReactJS ?
Express.js express.Router() Function
Installation of Node.js on Linux
How to create footer to stay at the bottom of a Web page?
Convert a string to an integer in JavaScript
How to set input type date in dd-mm-yyyy format using HTML ? | [
{
"code": null,
"e": 33847,
"s": 33819,
"text": "\n01 Jun, 2021"
},
{
"code": null,
"e": 34099,
"s": 33847,
"text": "Ant Design Library has this component pre-built, and it is very easy to integrate as well. The Drawer component is a panel that slides in from the edge of the screen. We can use the following approach in ReactJS to use the Ant Design Drawer Component."
},
{
"code": null,
"e": 34113,
"s": 34099,
"text": "Drawer Props:"
},
{
"code": null,
"e": 34226,
"s": 34113,
"text": "afterVisibleChange: It is a callback function that is triggered after the animation ends when switching drawers."
},
{
"code": null,
"e": 34290,
"s": 34226,
"text": "bodyStyle: It is used for the style of the drawer content part."
},
{
"code": null,
"e": 34374,
"s": 34290,
"text": "className: It is used to pass the class name of the container of the Drawer dialog."
},
{
"code": null,
"e": 34486,
"s": 34374,
"text": "closable: It is used to indicate whether a close button is visible on the top right of the Drawer dialog or not"
},
{
"code": null,
"e": 34535,
"s": 34486,
"text": "closeIcon: It is used for the custom close icon."
},
{
"code": null,
"e": 34624,
"s": 34535,
"text": "contentWrapperStyle: It is used for the style of the drawer wrapper of the content part."
},
{
"code": null,
"e": 34729,
"s": 34624,
"text": "destroyOnClose: It is used to indicate whether to unmount child components on the closing drawer or not."
},
{
"code": null,
"e": 34795,
"s": 34729,
"text": "drawerStyle: It is used for the style of the popup layer element."
},
{
"code": null,
"e": 34847,
"s": 34795,
"text": "footer: It is used to denote the footer for Drawer."
},
{
"code": null,
"e": 34912,
"s": 34847,
"text": "footerStyle: It is used for the style of the drawer footer part."
},
{
"code": null,
"e": 34983,
"s": 34912,
"text": "forceRender: It is used to forcefully pre-render the Drawer component."
},
{
"code": null,
"e": 35047,
"s": 34983,
"text": "getContainer: It is used to return the mounted node for Drawer."
},
{
"code": null,
"e": 35112,
"s": 35047,
"text": "headerStyle: It is used for the style of the drawer header part."
},
{
"code": null,
"e": 35174,
"s": 35112,
"text": "height: It is used to denote the height of the Drawer dialog."
},
{
"code": null,
"e": 35253,
"s": 35174,
"text": "keyboard: It is used to indicate whether to support press ESC to close or not."
},
{
"code": null,
"e": 35311,
"s": 35253,
"text": "mask: It is used to indicate whether to show mask or not."
},
{
"code": null,
"e": 35411,
"s": 35311,
"text": "maskClosable: It is used to indicate whether to close the Drawer or not while clicking on the mask."
},
{
"code": null,
"e": 35474,
"s": 35411,
"text": "maskStyle: It is used for the style for Drawer’s mask element."
},
{
"code": null,
"e": 35529,
"s": 35474,
"text": "placement: It is used for the placement of the Drawer."
},
{
"code": null,
"e": 35576,
"s": 35529,
"text": "push: It is the nested drawers’ push behavior."
},
{
"code": null,
"e": 35628,
"s": 35576,
"text": "style: It is used for the style of wrapper element."
},
{
"code": null,
"e": 35678,
"s": 35628,
"text": "title: It is used to denote the title for Drawer."
},
{
"code": null,
"e": 35755,
"s": 35678,
"text": "visible: It is used to indicate whether the Drawer dialog is visible or not."
},
{
"code": null,
"e": 35815,
"s": 35755,
"text": "width: It is used to denote the width of the Drawer dialog."
},
{
"code": null,
"e": 35871,
"s": 35815,
"text": "zIndex: It is used to denote the z-index of the Drawer."
},
{
"code": null,
"e": 35990,
"s": 35871,
"text": "onClose: It is a callback function that will be triggered when a user clicks the mask, close button, or Cancel button."
},
{
"code": null,
"e": 36040,
"s": 35990,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 36135,
"s": 36040,
"text": "Step 1: Create a React application using the following command:npx create-react-app foldername"
},
{
"code": null,
"e": 36199,
"s": 36135,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 36231,
"s": 36199,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 36344,
"s": 36231,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername"
},
{
"code": null,
"e": 36444,
"s": 36344,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:"
},
{
"code": null,
"e": 36458,
"s": 36444,
"text": "cd foldername"
},
{
"code": null,
"e": 36579,
"s": 36458,
"text": "Step 3: After creating the ReactJS application, Install the required module using the following command:npm install antd"
},
{
"code": null,
"e": 36684,
"s": 36579,
"text": "Step 3: After creating the ReactJS application, Install the required module using the following command:"
},
{
"code": null,
"e": 36701,
"s": 36684,
"text": "npm install antd"
},
{
"code": null,
"e": 36753,
"s": 36701,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 36771,
"s": 36753,
"text": "Project Structure"
},
{
"code": null,
"e": 36901,
"s": 36771,
"text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code."
},
{
"code": null,
"e": 36908,
"s": 36901,
"text": "App.js"
},
{
"code": "import React, { useState } from 'react'import \"antd/dist/antd.css\";import { Drawer, Button } from 'antd'; export default function App() { const [visible, setVisible] = useState(false); return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>ReactJS Ant-Design Drawer Component</h4> <> <Button type=\"primary\" onClick={() => { setVisible(true); }}>Open</Button> <Drawer title=\"Drawer Demo\" placement=\"left\" closable={false} visible={visible} onClose={() => { setVisible(false) }} > <p>Item One</p> <p>Item Two</p> <p>Item Three</p> <p>Item Four</p> <p>Item Five</p> </Drawer> </> </div> );}",
"e": 37718,
"s": 36908,
"text": null
},
{
"code": null,
"e": 37831,
"s": 37718,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 37841,
"s": 37831,
"text": "npm start"
},
{
"code": null,
"e": 37940,
"s": 37841,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:"
},
{
"code": null,
"e": 37989,
"s": 37940,
"text": "Reference: https://ant.design/components/drawer/"
},
{
"code": null,
"e": 38008,
"s": 37989,
"text": "ReactJS-Ant Design"
},
{
"code": null,
"e": 38016,
"s": 38008,
"text": "ReactJS"
},
{
"code": null,
"e": 38033,
"s": 38016,
"text": "Web Technologies"
},
{
"code": null,
"e": 38131,
"s": 38033,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38140,
"s": 38131,
"text": "Comments"
},
{
"code": null,
"e": 38153,
"s": 38140,
"text": "Old Comments"
},
{
"code": null,
"e": 38198,
"s": 38153,
"text": "How to redirect to another page in ReactJS ?"
},
{
"code": null,
"e": 38241,
"s": 38198,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 38306,
"s": 38241,
"text": "How to pass data from child component to its parent in ReactJS ?"
},
{
"code": null,
"e": 38364,
"s": 38306,
"text": "How to navigate on path by button click in react router ?"
},
{
"code": null,
"e": 38406,
"s": 38364,
"text": "How to set background images in ReactJS ?"
},
{
"code": null,
"e": 38443,
"s": 38406,
"text": "Express.js express.Router() Function"
},
{
"code": null,
"e": 38476,
"s": 38443,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 38534,
"s": 38476,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 38579,
"s": 38534,
"text": "Convert a string to an integer in JavaScript"
}
] |
Convert Docx to Pdf using docx2pdf Module in Python - GeeksforGeeks | 03 Aug, 2021
Tired of having to use online docx to PDF converters with crappy interfaces and conversion limits? Then, look no further than your friendly neighborhood language python’s docx2pdf module. This module is a hidden gem among the many modules for the python language.
This module can be used to convert files singly or in bulk using the command line or a python program.
This module does not come built-in with Python. To install this module type the below command in the terminal.
pip install docx2pdf
The basic structure of the docx2pdf command line usage is:
docx2pdf [input] [output]
If only the input file is specified, it generates a pdf from the docx and stores it in the same folder.
Example:
docx2pdf usage using the command line
GeeksforGeeks folder containing both the original GFG.docx and the converted GFG.pdf
Original GFG.docx on the left and GFG.pdf on the right
For the bulk conversion, you can specify the folder containing all the Docx files. The converted pdfs will get stored in the same folder.
docx2pdf GeeksForGeeks_Folder/
You can also explicitly specify the input and output file or folder by specifying the path.
An endless number of useful applications can be made using this module.
Python3
# Python3 program to convert docx to pdf# using docx2pdf module # Import the convert method from the# docx2pdf modulefrom docx2pdf import convert # Converting docx present in the same folder# as the python fileconvert("GFG.docx") # Converting docx specifying both the input# and output pathsconvert("GeeksForGeeks\GFG_1.docx", "Other_Folder\Mine.pdf") # Notice that the output filename need not be# the same as the docx # Bulk Conversionconvert("GeeksForGeeks\")
Output:
simranarora5sos
python-modules
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?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Defaultdict in Python
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n03 Aug, 2021"
},
{
"code": null,
"e": 24556,
"s": 24292,
"text": "Tired of having to use online docx to PDF converters with crappy interfaces and conversion limits? Then, look no further than your friendly neighborhood language python’s docx2pdf module. This module is a hidden gem among the many modules for the python language."
},
{
"code": null,
"e": 24659,
"s": 24556,
"text": "This module can be used to convert files singly or in bulk using the command line or a python program."
},
{
"code": null,
"e": 24770,
"s": 24659,
"text": "This module does not come built-in with Python. To install this module type the below command in the terminal."
},
{
"code": null,
"e": 24791,
"s": 24770,
"text": "pip install docx2pdf"
},
{
"code": null,
"e": 24850,
"s": 24791,
"text": "The basic structure of the docx2pdf command line usage is:"
},
{
"code": null,
"e": 24876,
"s": 24850,
"text": "docx2pdf [input] [output]"
},
{
"code": null,
"e": 24980,
"s": 24876,
"text": "If only the input file is specified, it generates a pdf from the docx and stores it in the same folder."
},
{
"code": null,
"e": 24989,
"s": 24980,
"text": "Example:"
},
{
"code": null,
"e": 25027,
"s": 24989,
"text": "docx2pdf usage using the command line"
},
{
"code": null,
"e": 25112,
"s": 25027,
"text": "GeeksforGeeks folder containing both the original GFG.docx and the converted GFG.pdf"
},
{
"code": null,
"e": 25167,
"s": 25112,
"text": "Original GFG.docx on the left and GFG.pdf on the right"
},
{
"code": null,
"e": 25305,
"s": 25167,
"text": "For the bulk conversion, you can specify the folder containing all the Docx files. The converted pdfs will get stored in the same folder."
},
{
"code": null,
"e": 25336,
"s": 25305,
"text": "docx2pdf GeeksForGeeks_Folder/"
},
{
"code": null,
"e": 25428,
"s": 25336,
"text": "You can also explicitly specify the input and output file or folder by specifying the path."
},
{
"code": null,
"e": 25500,
"s": 25428,
"text": "An endless number of useful applications can be made using this module."
},
{
"code": null,
"e": 25508,
"s": 25500,
"text": "Python3"
},
{
"code": "# Python3 program to convert docx to pdf# using docx2pdf module # Import the convert method from the# docx2pdf modulefrom docx2pdf import convert # Converting docx present in the same folder# as the python fileconvert(\"GFG.docx\") # Converting docx specifying both the input# and output pathsconvert(\"GeeksForGeeks\\GFG_1.docx\", \"Other_Folder\\Mine.pdf\") # Notice that the output filename need not be# the same as the docx # Bulk Conversionconvert(\"GeeksForGeeks\\\")",
"e": 25971,
"s": 25508,
"text": null
},
{
"code": null,
"e": 25979,
"s": 25971,
"text": "Output:"
},
{
"code": null,
"e": 25995,
"s": 25979,
"text": "simranarora5sos"
},
{
"code": null,
"e": 26010,
"s": 25995,
"text": "python-modules"
},
{
"code": null,
"e": 26025,
"s": 26010,
"text": "python-utility"
},
{
"code": null,
"e": 26032,
"s": 26025,
"text": "Python"
},
{
"code": null,
"e": 26130,
"s": 26032,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26162,
"s": 26130,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26204,
"s": 26162,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26260,
"s": 26204,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26302,
"s": 26260,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26333,
"s": 26302,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 26388,
"s": 26333,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 26410,
"s": 26388,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26449,
"s": 26410,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26478,
"s": 26449,
"text": "Create a directory in Python"
}
] |
Java Program for GCD of more than two (or array) numbers | Following is the Java program for GCD of more than two numbers −
Live Demo
public class Demo{
static int gcd_of_nums(int val_1, int val_2){
if (val_1 == 0)
return val_2;
return gcd_of_nums(val_2 % val_1, val_1);
}
static int find_gcd(int arr[], int no){
int result = arr[0];
for (int i = 1; i < no; i++){
result = gcd_of_nums(arr[i], result);
if(result == 1){
return 1;
}
}
return result;
}
public static void main(String[] args){
int my_arr[] = { 7, 49, 177, 105, 119, 42};
int no = my_arr.length;
System.out.println("The GCD of the elements in the array is ");
System.out.println(find_gcd(my_arr, no));
}
}
The GCD of the elements in the array is
1
A class named Demo contains a main function that takes in two values. If the first value is 0, the second value is returned as output. Otherwise, a recursive function is written that computes the greatest common divisor of the two elements.
Next, another static function is defined that takes an array and another integer value as parameter. The first element of the array is assigned to a variable named ‘result’ and a ‘for’ loop iterates over elements from 1 to the integer value that was passed as a parameter to the function. The greatest common divisor function is called on this array elements and a result. This output is assigned to ‘result’ variable itself. If the value of ‘result’ is 1, then the output is 1, otherwise the value of ‘result’ is returned.
In the main function, an array integer is defined and the length of the array is assigned to a specific value. The greatest common divisor function is called on the array elements and length. Relevant data is displayed on the console. | [
{
"code": null,
"e": 1127,
"s": 1062,
"text": "Following is the Java program for GCD of more than two numbers −"
},
{
"code": null,
"e": 1138,
"s": 1127,
"text": " Live Demo"
},
{
"code": null,
"e": 1795,
"s": 1138,
"text": "public class Demo{\n static int gcd_of_nums(int val_1, int val_2){\n if (val_1 == 0)\n return val_2;\n return gcd_of_nums(val_2 % val_1, val_1);\n }\n static int find_gcd(int arr[], int no){\n int result = arr[0];\n for (int i = 1; i < no; i++){\n result = gcd_of_nums(arr[i], result);\n if(result == 1){\n return 1;\n }\n }\n return result;\n }\n public static void main(String[] args){\n int my_arr[] = { 7, 49, 177, 105, 119, 42};\n int no = my_arr.length;\n System.out.println(\"The GCD of the elements in the array is \");\n System.out.println(find_gcd(my_arr, no));\n }\n}"
},
{
"code": null,
"e": 1837,
"s": 1795,
"text": "The GCD of the elements in the array is\n1"
},
{
"code": null,
"e": 2078,
"s": 1837,
"text": "A class named Demo contains a main function that takes in two values. If the first value is 0, the second value is returned as output. Otherwise, a recursive function is written that computes the greatest common divisor of the two elements."
},
{
"code": null,
"e": 2602,
"s": 2078,
"text": "Next, another static function is defined that takes an array and another integer value as parameter. The first element of the array is assigned to a variable named ‘result’ and a ‘for’ loop iterates over elements from 1 to the integer value that was passed as a parameter to the function. The greatest common divisor function is called on this array elements and a result. This output is assigned to ‘result’ variable itself. If the value of ‘result’ is 1, then the output is 1, otherwise the value of ‘result’ is returned."
},
{
"code": null,
"e": 2837,
"s": 2602,
"text": "In the main function, an array integer is defined and the length of the array is assigned to a specific value. The greatest common divisor function is called on the array elements and length. Relevant data is displayed on the console."
}
] |
Kotlin Output (Print Text) | The println() function is used to output values/print text:
fun main() {
println("Hello World")
}
You can add as many println() functions as you want. Note that it will add a new line for each function:
fun main() {
println("Hello World!")
println("I am learning Kotlin.")
println("It is awesome!")
}
You can also print numbers, and perform mathematical calculations:
fun main() {
println(3 + 3)
}
There is also a print() function, which is similar to println(). The only difference is that it does not insert a new line at the end of the output:
fun main() {
print("Hello World! ")
print("I am learning Kotlin. ")
print("It is awesome!")
}
Note that we have added a space character to create a space between the sentences.
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
[email protected]
Your message has been sent to W3Schools. | [
{
"code": null,
"e": 60,
"s": 0,
"text": "The println() function is used to output values/print text:"
},
{
"code": null,
"e": 100,
"s": 60,
"text": "fun main() {\n println(\"Hello World\")\n}"
},
{
"code": null,
"e": 205,
"s": 100,
"text": "You can add as many println() functions as you want. Note that it will add a new line for each function:"
},
{
"code": null,
"e": 309,
"s": 205,
"text": "fun main() {\n println(\"Hello World!\")\n println(\"I am learning Kotlin.\")\n println(\"It is awesome!\")\n}"
},
{
"code": null,
"e": 376,
"s": 309,
"text": "You can also print numbers, and perform mathematical calculations:"
},
{
"code": null,
"e": 408,
"s": 376,
"text": "fun main() {\n println(3 + 3)\n}"
},
{
"code": null,
"e": 557,
"s": 408,
"text": "There is also a print() function, which is similar to println(). The only difference is that it does not insert a new line at the end of the output:"
},
{
"code": null,
"e": 657,
"s": 557,
"text": "fun main() {\n print(\"Hello World! \")\n print(\"I am learning Kotlin. \")\n print(\"It is awesome!\")\n}"
},
{
"code": null,
"e": 740,
"s": 657,
"text": "Note that we have added a space character to create a space between the sentences."
},
{
"code": null,
"e": 773,
"s": 740,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 815,
"s": 773,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 922,
"s": 815,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 941,
"s": 922,
"text": "[email protected]"
}
] |
Creating Charts in Google Slides with Python | by Mikey Gracie | Towards Data Science | A common gap data scientists run up against is how to programmatically create simple, elegantly formatted and company-branded visualizations in a slide deck.
Leveraging Google APIs and the package gslides you can easily create charts and tables in Google Slides that will impress your audience, all with Python!
Whether you are a data scientist wanting to level up your presentations or an analyst that’s looking to automate their manual work in Slides & Sheets, this tutorial will walk you through how you can integrate gslides into your workflow.
A data scientist performs analysis in a Jupyter notebook using a plotting package (matplotlib, plotly, ggplot2). To share their results, they copy an image from their notebook into a slide deck.
While their analysis may be excellent, non-technical stakeholders who are comfortable in Sheets & Slides have to adjust their mental model to interpret those visualizations created in python with non-standard formatting. Questions arise such as:
Can I view the underlying data in your chart?
We want to share this material out to senior stakeholders, can you format the chart according to company brand guidelines?
A data analyst has to update a deck each month for monitoring purposes. They have to fetch data from the data warehouse, export the result, copy it into a Google Sheet and update the necessary charts.
This workflow is highly manual and repetitive which makes the work tedious and demotivating for an analyst.
To create charts in Google slides, we can pass data from pandas to the Google Slides & Sheets API using python. What do these APIs do? A large majority of the actions you can perform manually in these platforms you can replicate through creating requests and passing them to the appropriate API.
Where this becomes complex is that there are many requests that you need to familiarize yourself with and to create those requests you typically have to write json that is hundreds of lines of long. To avoid directly working with complicated Google API requests we can use gslides, a wrapper around the Google APIs that creates and executes requests. By configuring those requests for the user, glides enables the user to manipulate Google Sheets & Slides through simple python commands as opposed to a lengthy json request.
gslides is object oriented, where each class represents a object in Google Sheets or Slides.
Spreadsheet represents a google sheet
Frame represents a range of data within a google sheet
Series represents a series or multiple series in a chart
Chart represents a chart that will be created in google sheets then moved to google slides
Table represents a table that will be created in google slides
Presentation represents a google slides presentation.
The initialization methods get() or create() for the Spreadsheet, Frame and Presentation classes allows the user to either get existing objects or create new ones.
For more info about the package consult the documentation here.
Using gslides relies on creating a project and credentials in the Google Cloud Platform. Here are the steps you will have to follow.
Create a project in the Google Cloud Platform enabling the Slides & Sheets API.Create either Service Account or OAuth 2.0 credentials. The key difference here is if you use OAuth 2.0 any command you run will run as if your personal google account is the creator & editor. If you use a Service Account, an account with the domain <project>.iam.gserviceaccount.com will be the creator & editor. More commentary around the tradeoffs of using a Service Account can be found here.Establish your credentials
Create a project in the Google Cloud Platform enabling the Slides & Sheets API.
Create either Service Account or OAuth 2.0 credentials. The key difference here is if you use OAuth 2.0 any command you run will run as if your personal google account is the creator & editor. If you use a Service Account, an account with the domain <project>.iam.gserviceaccount.com will be the creator & editor. More commentary around the tradeoffs of using a Service Account can be found here.
Establish your credentials
For OAuth 2.0 you will run:
import os.pathfrom googleapiclient.discovery import buildfrom google_auth_oauthlib.flow import InstalledAppFlowfrom google.auth.transport.requests import Requestfrom google.oauth2.credentials import Credentials# These scopes are read & write permissions. Necessary to run gslidesSCOPES = ['https://www.googleapis.com/auth/presentations', 'https://www.googleapis.com/auth/spreadsheets']creds = None# The file token.json stores the user's access and refresh tokens, and is# created automatically when the authorization flow completes for the first# time.if os.path.exists('token.json'): creds = Credentials.from_authorized_user_file('token.json', SCOPES)# If there are no (valid) credentials available, let the user log in.if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( '<PATH_TO_CREDS>', SCOPES) creds = flow.run_local_server() # Save the credentials for the next run with open('token.json', 'w') as token: token.write(creds.to_json())
For a Service Account:
from google.oauth2 import service_accountSCOPES = ['https://www.googleapis.com/auth/presentations', 'https://www.googleapis.com/auth/spreadsheets']credentials = service_account.Credentials.from_service_account_file( '<PATH_TO_CREDS>')creds = credentials.with_scopes(SCOPES)
4. Download gslides
pip install gslides
In the most basic usage, gslides passes data from a pandas dataframe to Google Sheets then uses that data in Google Sheets to create a chart or table in Sheets & Slides. See this flow below, with the full notebook here.
1. Initialize the connection to the Google APIs
import gslidesfrom gslides import ( Frame, Presentation, Spreadsheet, Table, Series, Chart)gslides.initialize_credentials(creds) #BringYourOwnCredentials
2. Create a presentation
prs = Presentation.create( name = 'demo pres')
3. Create a spreadsheet
spr = Spreadsheet.create( title = 'demo spreadsheet', sheet_names = ['demo sheet'])
4. Load the data to the spreadsheet
plt_df = #Pandas DataFrame with Iris dataframe = Frame.create( df = plt_df, spreadsheet_id = spr.spreadsheet_id, sheet_id = sp.sheet_names['demo sheet'], sheet_name = 'demo sheet', overwrite_data = True)
5. Create a scatterplot
sc = Series.scatter()ch = Chart( data = frame.data, #Passing the data from the frame x_axis_column = 'sepal length (cm)', series = [sc], #Passing the series object title = 'Demo Chart', x_axis_label = 'Sepal Length', y_axis_label = 'Petal Width', legend_position = 'RIGHT_LEGEND',)
6. Create a table
tbl = Table( data = plt_df.head())
7. Create a slide with the scatterplot & table
prs.add_slide( objects = [ch, tbl], layout = (1,2), #1 row by 2 columns title = "Investigation into Fischer's Iris dataset", notes = "Data from 1936")
The result is this slide:
With the package users can:
Create a new presentation
Create a new slide with charts or tables
Delete a slide
Create a new spreadsheet
Add or delete a tab in a spreadsheet
Add data from to pandas data frame to a spreadsheet
Get data from a spreadsheet to a pandas DataFrame
Template text into a presentation similar to Jinja
Force update all linked charts in a presentation with refreshed underlying data
Where gslides shines is the flexibility offered in numerous configurable parameters. Full details of that configurability can be found here, but see below for a snapshot of what is feasible.
gslides enables analysts to easily create charts & tables in Google Slides. Based on this tutorial hopefully you have a good sense of what’s possible with gslides and how it can be implemented into your workflow. Be sure to check out the documentation here for any questions you may have. | [
{
"code": null,
"e": 205,
"s": 47,
"text": "A common gap data scientists run up against is how to programmatically create simple, elegantly formatted and company-branded visualizations in a slide deck."
},
{
"code": null,
"e": 359,
"s": 205,
"text": "Leveraging Google APIs and the package gslides you can easily create charts and tables in Google Slides that will impress your audience, all with Python!"
},
{
"code": null,
"e": 596,
"s": 359,
"text": "Whether you are a data scientist wanting to level up your presentations or an analyst that’s looking to automate their manual work in Slides & Sheets, this tutorial will walk you through how you can integrate gslides into your workflow."
},
{
"code": null,
"e": 791,
"s": 596,
"text": "A data scientist performs analysis in a Jupyter notebook using a plotting package (matplotlib, plotly, ggplot2). To share their results, they copy an image from their notebook into a slide deck."
},
{
"code": null,
"e": 1037,
"s": 791,
"text": "While their analysis may be excellent, non-technical stakeholders who are comfortable in Sheets & Slides have to adjust their mental model to interpret those visualizations created in python with non-standard formatting. Questions arise such as:"
},
{
"code": null,
"e": 1083,
"s": 1037,
"text": "Can I view the underlying data in your chart?"
},
{
"code": null,
"e": 1206,
"s": 1083,
"text": "We want to share this material out to senior stakeholders, can you format the chart according to company brand guidelines?"
},
{
"code": null,
"e": 1407,
"s": 1206,
"text": "A data analyst has to update a deck each month for monitoring purposes. They have to fetch data from the data warehouse, export the result, copy it into a Google Sheet and update the necessary charts."
},
{
"code": null,
"e": 1515,
"s": 1407,
"text": "This workflow is highly manual and repetitive which makes the work tedious and demotivating for an analyst."
},
{
"code": null,
"e": 1811,
"s": 1515,
"text": "To create charts in Google slides, we can pass data from pandas to the Google Slides & Sheets API using python. What do these APIs do? A large majority of the actions you can perform manually in these platforms you can replicate through creating requests and passing them to the appropriate API."
},
{
"code": null,
"e": 2336,
"s": 1811,
"text": "Where this becomes complex is that there are many requests that you need to familiarize yourself with and to create those requests you typically have to write json that is hundreds of lines of long. To avoid directly working with complicated Google API requests we can use gslides, a wrapper around the Google APIs that creates and executes requests. By configuring those requests for the user, glides enables the user to manipulate Google Sheets & Slides through simple python commands as opposed to a lengthy json request."
},
{
"code": null,
"e": 2429,
"s": 2336,
"text": "gslides is object oriented, where each class represents a object in Google Sheets or Slides."
},
{
"code": null,
"e": 2467,
"s": 2429,
"text": "Spreadsheet represents a google sheet"
},
{
"code": null,
"e": 2522,
"s": 2467,
"text": "Frame represents a range of data within a google sheet"
},
{
"code": null,
"e": 2579,
"s": 2522,
"text": "Series represents a series or multiple series in a chart"
},
{
"code": null,
"e": 2670,
"s": 2579,
"text": "Chart represents a chart that will be created in google sheets then moved to google slides"
},
{
"code": null,
"e": 2733,
"s": 2670,
"text": "Table represents a table that will be created in google slides"
},
{
"code": null,
"e": 2787,
"s": 2733,
"text": "Presentation represents a google slides presentation."
},
{
"code": null,
"e": 2951,
"s": 2787,
"text": "The initialization methods get() or create() for the Spreadsheet, Frame and Presentation classes allows the user to either get existing objects or create new ones."
},
{
"code": null,
"e": 3015,
"s": 2951,
"text": "For more info about the package consult the documentation here."
},
{
"code": null,
"e": 3148,
"s": 3015,
"text": "Using gslides relies on creating a project and credentials in the Google Cloud Platform. Here are the steps you will have to follow."
},
{
"code": null,
"e": 3650,
"s": 3148,
"text": "Create a project in the Google Cloud Platform enabling the Slides & Sheets API.Create either Service Account or OAuth 2.0 credentials. The key difference here is if you use OAuth 2.0 any command you run will run as if your personal google account is the creator & editor. If you use a Service Account, an account with the domain <project>.iam.gserviceaccount.com will be the creator & editor. More commentary around the tradeoffs of using a Service Account can be found here.Establish your credentials"
},
{
"code": null,
"e": 3730,
"s": 3650,
"text": "Create a project in the Google Cloud Platform enabling the Slides & Sheets API."
},
{
"code": null,
"e": 4127,
"s": 3730,
"text": "Create either Service Account or OAuth 2.0 credentials. The key difference here is if you use OAuth 2.0 any command you run will run as if your personal google account is the creator & editor. If you use a Service Account, an account with the domain <project>.iam.gserviceaccount.com will be the creator & editor. More commentary around the tradeoffs of using a Service Account can be found here."
},
{
"code": null,
"e": 4154,
"s": 4127,
"text": "Establish your credentials"
},
{
"code": null,
"e": 4182,
"s": 4154,
"text": "For OAuth 2.0 you will run:"
},
{
"code": null,
"e": 5298,
"s": 4182,
"text": "import os.pathfrom googleapiclient.discovery import buildfrom google_auth_oauthlib.flow import InstalledAppFlowfrom google.auth.transport.requests import Requestfrom google.oauth2.credentials import Credentials# These scopes are read & write permissions. Necessary to run gslidesSCOPES = ['https://www.googleapis.com/auth/presentations', 'https://www.googleapis.com/auth/spreadsheets']creds = None# The file token.json stores the user's access and refresh tokens, and is# created automatically when the authorization flow completes for the first# time.if os.path.exists('token.json'): creds = Credentials.from_authorized_user_file('token.json', SCOPES)# If there are no (valid) credentials available, let the user log in.if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( '<PATH_TO_CREDS>', SCOPES) creds = flow.run_local_server() # Save the credentials for the next run with open('token.json', 'w') as token: token.write(creds.to_json())"
},
{
"code": null,
"e": 5321,
"s": 5298,
"text": "For a Service Account:"
},
{
"code": null,
"e": 5606,
"s": 5321,
"text": "from google.oauth2 import service_accountSCOPES = ['https://www.googleapis.com/auth/presentations', 'https://www.googleapis.com/auth/spreadsheets']credentials = service_account.Credentials.from_service_account_file( '<PATH_TO_CREDS>')creds = credentials.with_scopes(SCOPES)"
},
{
"code": null,
"e": 5626,
"s": 5606,
"text": "4. Download gslides"
},
{
"code": null,
"e": 5646,
"s": 5626,
"text": "pip install gslides"
},
{
"code": null,
"e": 5866,
"s": 5646,
"text": "In the most basic usage, gslides passes data from a pandas dataframe to Google Sheets then uses that data in Google Sheets to create a chart or table in Sheets & Slides. See this flow below, with the full notebook here."
},
{
"code": null,
"e": 5914,
"s": 5866,
"text": "1. Initialize the connection to the Google APIs"
},
{
"code": null,
"e": 6083,
"s": 5914,
"text": "import gslidesfrom gslides import ( Frame, Presentation, Spreadsheet, Table, Series, Chart)gslides.initialize_credentials(creds) #BringYourOwnCredentials"
},
{
"code": null,
"e": 6108,
"s": 6083,
"text": "2. Create a presentation"
},
{
"code": null,
"e": 6158,
"s": 6108,
"text": "prs = Presentation.create( name = 'demo pres')"
},
{
"code": null,
"e": 6182,
"s": 6158,
"text": "3. Create a spreadsheet"
},
{
"code": null,
"e": 6272,
"s": 6182,
"text": "spr = Spreadsheet.create( title = 'demo spreadsheet', sheet_names = ['demo sheet'])"
},
{
"code": null,
"e": 6308,
"s": 6272,
"text": "4. Load the data to the spreadsheet"
},
{
"code": null,
"e": 6530,
"s": 6308,
"text": "plt_df = #Pandas DataFrame with Iris dataframe = Frame.create( df = plt_df, spreadsheet_id = spr.spreadsheet_id, sheet_id = sp.sheet_names['demo sheet'], sheet_name = 'demo sheet', overwrite_data = True)"
},
{
"code": null,
"e": 6554,
"s": 6530,
"text": "5. Create a scatterplot"
},
{
"code": null,
"e": 6873,
"s": 6554,
"text": "sc = Series.scatter()ch = Chart( data = frame.data, #Passing the data from the frame x_axis_column = 'sepal length (cm)', series = [sc], #Passing the series object title = 'Demo Chart', x_axis_label = 'Sepal Length', y_axis_label = 'Petal Width', legend_position = 'RIGHT_LEGEND',)"
},
{
"code": null,
"e": 6891,
"s": 6873,
"text": "6. Create a table"
},
{
"code": null,
"e": 6929,
"s": 6891,
"text": "tbl = Table( data = plt_df.head())"
},
{
"code": null,
"e": 6976,
"s": 6929,
"text": "7. Create a slide with the scatterplot & table"
},
{
"code": null,
"e": 7151,
"s": 6976,
"text": "prs.add_slide( objects = [ch, tbl], layout = (1,2), #1 row by 2 columns title = \"Investigation into Fischer's Iris dataset\", notes = \"Data from 1936\")"
},
{
"code": null,
"e": 7177,
"s": 7151,
"text": "The result is this slide:"
},
{
"code": null,
"e": 7205,
"s": 7177,
"text": "With the package users can:"
},
{
"code": null,
"e": 7231,
"s": 7205,
"text": "Create a new presentation"
},
{
"code": null,
"e": 7272,
"s": 7231,
"text": "Create a new slide with charts or tables"
},
{
"code": null,
"e": 7287,
"s": 7272,
"text": "Delete a slide"
},
{
"code": null,
"e": 7312,
"s": 7287,
"text": "Create a new spreadsheet"
},
{
"code": null,
"e": 7349,
"s": 7312,
"text": "Add or delete a tab in a spreadsheet"
},
{
"code": null,
"e": 7401,
"s": 7349,
"text": "Add data from to pandas data frame to a spreadsheet"
},
{
"code": null,
"e": 7451,
"s": 7401,
"text": "Get data from a spreadsheet to a pandas DataFrame"
},
{
"code": null,
"e": 7502,
"s": 7451,
"text": "Template text into a presentation similar to Jinja"
},
{
"code": null,
"e": 7582,
"s": 7502,
"text": "Force update all linked charts in a presentation with refreshed underlying data"
},
{
"code": null,
"e": 7773,
"s": 7582,
"text": "Where gslides shines is the flexibility offered in numerous configurable parameters. Full details of that configurability can be found here, but see below for a snapshot of what is feasible."
}
] |
MySQL query to select the values having multiple occurrence and display their count | For this, use GROUP BY HAVING clause. Let us first create a table −
mysql> create table DemoTable673(
Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
Value int
);
Query OK, 0 rows affected (0.59 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable673(Value) values(10);
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable673(Value) values(20);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable673(Value) values(10);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable673(Value) values(30);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable673(Value) values(20);
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable673(Value) values(10);
Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable673(Value) values(10);
Query OK, 1 row affected (0.28 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable673;
This will produce the following output −
+----+-------+
| Id | Value |
+----+-------+
| 1 | 10 |
| 2 | 20 |
| 3 | 10 |
| 4 | 30 |
| 5 | 20 |
| 6 | 10 |
| 7 | 10 |
+----+-------+
7 rows in set (0.00 sec)
Following is the query to display only the values having multiple occurrences −
mysql> select Id,count(*) as myValue from DemoTable673 group by Value having count(*) > 1;
This will produce the following output −
+----+---------+
| Id | myValue |
+----+---------+
| 1 | 4 |
| 2 | 2 |
+----+---------+
2 rows in set (0.00 sec) | [
{
"code": null,
"e": 1130,
"s": 1062,
"text": "For this, use GROUP BY HAVING clause. Let us first create a table −"
},
{
"code": null,
"e": 1264,
"s": 1130,
"text": "mysql> create table DemoTable673(\n Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n Value int\n);\nQuery OK, 0 rows affected (0.59 sec)"
},
{
"code": null,
"e": 1320,
"s": 1264,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1929,
"s": 1320,
"text": "mysql> insert into DemoTable673(Value) values(10);\nQuery OK, 1 row affected (0.21 sec)\nmysql> insert into DemoTable673(Value) values(20);\nQuery OK, 1 row affected (0.18 sec)\nmysql> insert into DemoTable673(Value) values(10);\nQuery OK, 1 row affected (0.10 sec)\nmysql> insert into DemoTable673(Value) values(30);\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into DemoTable673(Value) values(20);\nQuery OK, 1 row affected (0.09 sec)\nmysql> insert into DemoTable673(Value) values(10);\nQuery OK, 1 row affected (0.08 sec)\nmysql> insert into DemoTable673(Value) values(10);\nQuery OK, 1 row affected (0.28 sec)"
},
{
"code": null,
"e": 1989,
"s": 1929,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 2023,
"s": 1989,
"text": "mysql> select *from DemoTable673;"
},
{
"code": null,
"e": 2064,
"s": 2023,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2254,
"s": 2064,
"text": "+----+-------+\n| Id | Value |\n+----+-------+\n| 1 | 10 |\n| 2 | 20 |\n| 3 | 10 |\n| 4 | 30 |\n| 5 | 20 |\n| 6 | 10 |\n| 7 | 10 |\n+----+-------+\n7 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2334,
"s": 2254,
"text": "Following is the query to display only the values having multiple occurrences −"
},
{
"code": null,
"e": 2425,
"s": 2334,
"text": "mysql> select Id,count(*) as myValue from DemoTable673 group by Value having count(*) > 1;"
},
{
"code": null,
"e": 2466,
"s": 2425,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2593,
"s": 2466,
"text": "+----+---------+\n| Id | myValue |\n+----+---------+\n| 1 | 4 |\n| 2 | 2 |\n+----+---------+\n2 rows in set (0.00 sec)"
}
] |
How to request Location Permission at runtime on Kotlin? | This example demonstrates how to request Location Permission at runtime on Kotlin.
Step 1 − Create a new project in Android Studio, go to File? New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:padding="8dp"
android:text="Tutorials Point"
android:textColor="@android:color/holo_green_dark"
android:textSize="48sp"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:padding="4dp"
android:textColor="@android:color/background_dark"
android:text="Request Location permission at Run time!"
android:textAlignment="center"
android:textSize="36sp"
android:textStyle="bold" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.content.pm.PackageManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
if (ContextCompat.checkSelfPermission(this@MainActivity,
Manifest.permission.ACCESS_FINE_LOCATION) !==
PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this@MainActivity,
Manifest.permission.ACCESS_FINE_LOCATION)) {
ActivityCompat.requestPermissions(this@MainActivity,
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), 1)
} else {
ActivityCompat.requestPermissions(this@MainActivity,
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), 1)
}
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>,
grantResults: IntArray) {
when (requestCode) {
1 -> {
if (grantResults.isNotEmpty() && grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
if ((ContextCompat.checkSelfPermission(this@MainActivity,
Manifest.permission.ACCESS_FINE_LOCATION) ===
PackageManager.PERMISSION_GRANTED)) {
Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show()
}
} else {
Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show()
}
return
}
}
}
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.myapplication">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen | [
{
"code": null,
"e": 1145,
"s": 1062,
"text": "This example demonstrates how to request Location Permission at runtime on Kotlin."
},
{
"code": null,
"e": 1273,
"s": 1145,
"text": "Step 1 − Create a new project in Android Studio, go to File? New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1338,
"s": 1273,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2422,
"s": 1338,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"50dp\"\n android:padding=\"8dp\"\n android:text=\"Tutorials Point\"\n android:textColor=\"@android:color/holo_green_dark\"\n android:textSize=\"48sp\"\n android:textStyle=\"bold\" />\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:padding=\"4dp\"\n android:textColor=\"@android:color/background_dark\"\n android:text=\"Request Location permission at Run time!\"\n android:textAlignment=\"center\"\n android:textSize=\"36sp\"\n android:textStyle=\"bold\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 2477,
"s": 2422,
"text": "Step 3 − Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 4243,
"s": 2477,
"text": "import android.content.pm.PackageManager\nimport androidx.appcompat.app.AppCompatActivity\nimport android.os.Bundle\nimport android.widget.Toast\nimport androidx.core.app.ActivityCompat\nimport androidx.core.content.ContextCompat\nclass MainActivity : AppCompatActivity() {\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n if (ContextCompat.checkSelfPermission(this@MainActivity,\n Manifest.permission.ACCESS_FINE_LOCATION) !==\n PackageManager.PERMISSION_GRANTED) {\n if (ActivityCompat.shouldShowRequestPermissionRationale(this@MainActivity,\n Manifest.permission.ACCESS_FINE_LOCATION)) {\n ActivityCompat.requestPermissions(this@MainActivity,\n arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), 1)\n } else {\n ActivityCompat.requestPermissions(this@MainActivity,\n arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), 1)\n }\n }\n }\n override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>,\n grantResults: IntArray) {\n when (requestCode) {\n 1 -> {\n if (grantResults.isNotEmpty() && grantResults[0] ==\n PackageManager.PERMISSION_GRANTED) {\n if ((ContextCompat.checkSelfPermission(this@MainActivity,\n Manifest.permission.ACCESS_FINE_LOCATION) ===\n PackageManager.PERMISSION_GRANTED)) {\n Toast.makeText(this, \"Permission Granted\", Toast.LENGTH_SHORT).show()\n }\n } else {\n Toast.makeText(this, \"Permission Denied\", Toast.LENGTH_SHORT).show()\n }\n return\n }\n }\n }\n}"
},
{
"code": null,
"e": 4298,
"s": 4243,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 5050,
"s": 4298,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.myapplication\">\n<uses-permission android:name=\"android.permission.ACCESS_FINE_LOCATION\" />\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 5398,
"s": 5050,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen"
}
] |
5 Must-Know SQL Functions For Manipulating Dates | by Soner Yıldırım | Towards Data Science | If you had asked about the most important skill for a data scientist before I got my first job, my answer would certainly be Python. No doubt!
I work as a data scientist now and if you ask me the same question, my answer is still Python. However, I have second thoughts. What makes me think twice is SQL.
SQL is a must-have skill for data scientists. It is mainly used for querying relational databases but it is able to perform much more. SQL is equipped with so many functionalities that make it a highly efficient data analysis and manipulation tool.
In this article, we will go over 5 SQL functions that are used for manipulating dates. They come in handy when working with data that involves date or time based information.
Note: SQL is used by many relational database management systems such as MySQL, SQL Server, PostgreSQL, and so on. Although they mostly adopt the same SQL syntax, there might be small differences. In this article, we will be using SQL Server.
As its name suggests, the getdate function gives us today’s date. Let’s do an example.
DECLARE @mydate DateSET @mydate = GETDATE()print @mydate'2021-08-22'
We create a variable called “mydate” and assign its value as today’s date.
The name of this function is even more self-explanatory than the previous one. The dateadd function is used for adding a time or date interval to a date.
As always, the syntax is easier to understand with examples.
DECLARE @mydate DateSET @mydate = GETDATE()SELECT DATEADD(MONTH, 1, @mydate) AS NextMonthNextMonth2021-09-22
The first parameter indicates the interval and second one is the number of intervals. The third parameter is the base value.
DATEADD(interval, number of intervals, date)
We can use other intervals as well.
DECLARE @mydate DateSET @mydate = GETDATE()SELECT DATEADD(WEEK, -2, @mydate) AS TwoWeeksBeforeTwoWeeksBefore2021-08-08
If you put a minus sign before the number of intervals, it subtracts the specified interval from the given date.
It is possible to add time-based intervals but we need to use a datetime variable.
DECLARE @mydate DateTimeSET @mydate = GETDATE()SELECT DATEADD(HOUR, 10, @mydate)'2021-08-23 00:10:17.287'
The datediff function is used for calculating the difference between two dates based on a given interval.
DECLARE @mydate DateSET @mydate = '2018-08-08'SELECT DATEDIFF(MONTH, @mydate, GETDATE())36
The mydate variable holds the value “2018–08–08”. In the select statement, we calculate the difference between this variable and the current date.
Just like the dateadd function, the datediff function accepts other intervals as well.
DECLARE @mydate DateSET @mydate = '2021-10-08'SELECT DATEDIFF(DAY, @mydate, GETDATE()) AS DayDifferenceDayDifference47
The datename function can be used for extracting the parts of a date. For instance, we can get the name of month and day from a date as follows:
DECLARE @mydate DateSET @mydate = '2021-10-08'SELECT DATENAME(MONTH, @mydate)OctoberSELECT DATENAME(WEEKDAY, @mydate)Friday
The year, month, and day are separate functions but I think it is better to cover them together.
We have covered the datename function which gives us month and day names. In some cases, we need this information as numbers. The year, month, and day functions allow for decomposing a date.
Let’s do an example that demonstrates how they can be used.
DECLARE @mydate DateSET @mydate = '2021-10-08'SELECT Date = @mydate, Year = YEAR(@mydate), Month = MONTH(@mydate), Day = DAY(@mydate)Date Year Month Day2021-10-08 2021 10 8
We now have access to each part of the given date.
Manipulating dates is important for data analysis especially when working with time series data. SQL provides several functions to make this process simple and efficient.
The functions in this article cover a substantial amount of operation that you will need to do with dates.
Thank you for reading. Please let me know if you have any feedback. | [
{
"code": null,
"e": 315,
"s": 172,
"text": "If you had asked about the most important skill for a data scientist before I got my first job, my answer would certainly be Python. No doubt!"
},
{
"code": null,
"e": 477,
"s": 315,
"text": "I work as a data scientist now and if you ask me the same question, my answer is still Python. However, I have second thoughts. What makes me think twice is SQL."
},
{
"code": null,
"e": 726,
"s": 477,
"text": "SQL is a must-have skill for data scientists. It is mainly used for querying relational databases but it is able to perform much more. SQL is equipped with so many functionalities that make it a highly efficient data analysis and manipulation tool."
},
{
"code": null,
"e": 901,
"s": 726,
"text": "In this article, we will go over 5 SQL functions that are used for manipulating dates. They come in handy when working with data that involves date or time based information."
},
{
"code": null,
"e": 1144,
"s": 901,
"text": "Note: SQL is used by many relational database management systems such as MySQL, SQL Server, PostgreSQL, and so on. Although they mostly adopt the same SQL syntax, there might be small differences. In this article, we will be using SQL Server."
},
{
"code": null,
"e": 1231,
"s": 1144,
"text": "As its name suggests, the getdate function gives us today’s date. Let’s do an example."
},
{
"code": null,
"e": 1300,
"s": 1231,
"text": "DECLARE @mydate DateSET @mydate = GETDATE()print @mydate'2021-08-22'"
},
{
"code": null,
"e": 1375,
"s": 1300,
"text": "We create a variable called “mydate” and assign its value as today’s date."
},
{
"code": null,
"e": 1529,
"s": 1375,
"text": "The name of this function is even more self-explanatory than the previous one. The dateadd function is used for adding a time or date interval to a date."
},
{
"code": null,
"e": 1590,
"s": 1529,
"text": "As always, the syntax is easier to understand with examples."
},
{
"code": null,
"e": 1699,
"s": 1590,
"text": "DECLARE @mydate DateSET @mydate = GETDATE()SELECT DATEADD(MONTH, 1, @mydate) AS NextMonthNextMonth2021-09-22"
},
{
"code": null,
"e": 1824,
"s": 1699,
"text": "The first parameter indicates the interval and second one is the number of intervals. The third parameter is the base value."
},
{
"code": null,
"e": 1869,
"s": 1824,
"text": "DATEADD(interval, number of intervals, date)"
},
{
"code": null,
"e": 1905,
"s": 1869,
"text": "We can use other intervals as well."
},
{
"code": null,
"e": 2024,
"s": 1905,
"text": "DECLARE @mydate DateSET @mydate = GETDATE()SELECT DATEADD(WEEK, -2, @mydate) AS TwoWeeksBeforeTwoWeeksBefore2021-08-08"
},
{
"code": null,
"e": 2137,
"s": 2024,
"text": "If you put a minus sign before the number of intervals, it subtracts the specified interval from the given date."
},
{
"code": null,
"e": 2220,
"s": 2137,
"text": "It is possible to add time-based intervals but we need to use a datetime variable."
},
{
"code": null,
"e": 2326,
"s": 2220,
"text": "DECLARE @mydate DateTimeSET @mydate = GETDATE()SELECT DATEADD(HOUR, 10, @mydate)'2021-08-23 00:10:17.287'"
},
{
"code": null,
"e": 2432,
"s": 2326,
"text": "The datediff function is used for calculating the difference between two dates based on a given interval."
},
{
"code": null,
"e": 2523,
"s": 2432,
"text": "DECLARE @mydate DateSET @mydate = '2018-08-08'SELECT DATEDIFF(MONTH, @mydate, GETDATE())36"
},
{
"code": null,
"e": 2670,
"s": 2523,
"text": "The mydate variable holds the value “2018–08–08”. In the select statement, we calculate the difference between this variable and the current date."
},
{
"code": null,
"e": 2757,
"s": 2670,
"text": "Just like the dateadd function, the datediff function accepts other intervals as well."
},
{
"code": null,
"e": 2876,
"s": 2757,
"text": "DECLARE @mydate DateSET @mydate = '2021-10-08'SELECT DATEDIFF(DAY, @mydate, GETDATE()) AS DayDifferenceDayDifference47"
},
{
"code": null,
"e": 3021,
"s": 2876,
"text": "The datename function can be used for extracting the parts of a date. For instance, we can get the name of month and day from a date as follows:"
},
{
"code": null,
"e": 3145,
"s": 3021,
"text": "DECLARE @mydate DateSET @mydate = '2021-10-08'SELECT DATENAME(MONTH, @mydate)OctoberSELECT DATENAME(WEEKDAY, @mydate)Friday"
},
{
"code": null,
"e": 3242,
"s": 3145,
"text": "The year, month, and day are separate functions but I think it is better to cover them together."
},
{
"code": null,
"e": 3433,
"s": 3242,
"text": "We have covered the datename function which gives us month and day names. In some cases, we need this information as numbers. The year, month, and day functions allow for decomposing a date."
},
{
"code": null,
"e": 3493,
"s": 3433,
"text": "Let’s do an example that demonstrates how they can be used."
},
{
"code": null,
"e": 3689,
"s": 3493,
"text": "DECLARE @mydate DateSET @mydate = '2021-10-08'SELECT Date = @mydate, Year = YEAR(@mydate), Month = MONTH(@mydate), Day = DAY(@mydate)Date Year Month Day2021-10-08 2021 10 8"
},
{
"code": null,
"e": 3740,
"s": 3689,
"text": "We now have access to each part of the given date."
},
{
"code": null,
"e": 3911,
"s": 3740,
"text": "Manipulating dates is important for data analysis especially when working with time series data. SQL provides several functions to make this process simple and efficient."
},
{
"code": null,
"e": 4018,
"s": 3911,
"text": "The functions in this article cover a substantial amount of operation that you will need to do with dates."
}
] |
Python – Ways to find Geometric Mean in List | 30 Jan, 2020
While working with Python, we can have a problem in which we need to find geometric mean of a list cumulative. This problem is common in Data Science domain. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using loop + formulaThe simpler manner to approach this problem is to employ the formula for finding geometric mean and perform using loop shorthands. This is the most basic approach to solve this problem.
# Python3 code to demonstrate working of # Geometric Mean of List # using loop + formula import math # initialize list test_list = [6, 7, 3, 9, 10, 15] # printing original list print("The original list is : " + str(test_list)) # Geometric Mean of List # using loop + formula temp = 1for i in range(0, len(test_list)) : temp = temp * test_list[i] temp2 = (float)(math.pow(temp, (1 / len(test_list)))) res = (float)(temp2) # printing result print("The geometric mean of list is : " + str(res))
The original list is : [6, 7, 3, 9, 10, 15]
The geometric mean of list is : 7.443617568993922
Method #2 : Using statistics.geometric_mean()This task can also be performed using inbuilt function of geometric_mean(). This is new in Python versions >= 3.8.
# Python3 code to demonstrate working of # Geometric Mean of List # using statistics.geometric_mean()import statistics # initialize list test_list = [6, 7, 3, 9, 10, 15] # printing original list print("The original list is : " + str(test_list)) # Geometric Mean of List # using statistics.geometric_mean() res = statistics.geometric_mean(test_list, 1) # printing result print("The geometric mean of list is : " + str(res))
The original list is : [6, 7, 3, 9, 10, 15]
The geometric mean of list is : 7.443617568993922
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Jan, 2020"
},
{
"code": null,
"e": 250,
"s": 28,
"text": "While working with Python, we can have a problem in which we need to find geometric mean of a list cumulative. This problem is common in Data Science domain. Let’s discuss certain ways in which this problem can be solved."
},
{
"code": null,
"e": 468,
"s": 250,
"text": "Method #1 : Using loop + formulaThe simpler manner to approach this problem is to employ the formula for finding geometric mean and perform using loop shorthands. This is the most basic approach to solve this problem."
},
{
"code": "# Python3 code to demonstrate working of # Geometric Mean of List # using loop + formula import math # initialize list test_list = [6, 7, 3, 9, 10, 15] # printing original list print(\"The original list is : \" + str(test_list)) # Geometric Mean of List # using loop + formula temp = 1for i in range(0, len(test_list)) : temp = temp * test_list[i] temp2 = (float)(math.pow(temp, (1 / len(test_list)))) res = (float)(temp2) # printing result print(\"The geometric mean of list is : \" + str(res)) ",
"e": 972,
"s": 468,
"text": null
},
{
"code": null,
"e": 1067,
"s": 972,
"text": "The original list is : [6, 7, 3, 9, 10, 15]\nThe geometric mean of list is : 7.443617568993922\n"
},
{
"code": null,
"e": 1229,
"s": 1069,
"text": "Method #2 : Using statistics.geometric_mean()This task can also be performed using inbuilt function of geometric_mean(). This is new in Python versions >= 3.8."
},
{
"code": "# Python3 code to demonstrate working of # Geometric Mean of List # using statistics.geometric_mean()import statistics # initialize list test_list = [6, 7, 3, 9, 10, 15] # printing original list print(\"The original list is : \" + str(test_list)) # Geometric Mean of List # using statistics.geometric_mean() res = statistics.geometric_mean(test_list, 1) # printing result print(\"The geometric mean of list is : \" + str(res))",
"e": 1660,
"s": 1229,
"text": null
},
{
"code": null,
"e": 1755,
"s": 1660,
"text": "The original list is : [6, 7, 3, 9, 10, 15]\nThe geometric mean of list is : 7.443617568993922\n"
},
{
"code": null,
"e": 1776,
"s": 1755,
"text": "Python list-programs"
},
{
"code": null,
"e": 1783,
"s": 1776,
"text": "Python"
},
{
"code": null,
"e": 1799,
"s": 1783,
"text": "Python Programs"
}
] |
Create Dataframe of Unequal Length in R | 16 May, 2021
In this article, we will be looking at the approach to create a data frame of unequal length using different functions in R Programming language.
To create a data frame of unequal length, we add the NA value at the end of the columns which are smaller in the lengths and makes them equal to the column which has the maximum length among all and with this process all the length becomes equal and the user is able to process operations on that data frame in R language.
rep() function is used to replicate the values in x. Here, this will be used to replicate NA value of the end of the columns of the data frames.
Syntax: rep(x, ...)
Parameters:
x:-a vector or a factor or a POSIXct or POSIXlt or Date object.
...:-further arguments to be passed to or from other methods
Example 1:
R
# Creating variablex=c(1,2,3,4,5)y=c(1,2,3) # Finding maximum lengthmax_ln <- max(c(length(x), length(y)))gfg_data<- data.frame(col1 = c(x,rep(NA, max_ln - length(x))), col2 = c(y,rep(NA, max_ln - length(y))))gfg_datais.data.frame((gfg_data))
Output:
Example 2:
R
# Creating variablea=c('a','b','c','d')b=c('g','e','e','k','s')c=c('f','o','r')d=c('g','e','e','k','s') # Finding maximum lengthmax_ln1 <- max(c(length(a), length(b)))max_ln2 <- max(c(length(c), length(d)))max_ln<-max(max_ln2,max_ln1)gfg_data<- data.frame(col1 = c(a,rep(NA, max_ln - length(a))), col2 = c(b,rep(NA, max_ln - length(b))), col3 = c(c,rep(NA, max_ln - length(c))), col4 = c(d,rep(NA, max_ln - length(d)))) gfg_datais.data.frame((gfg_data))
Output:
Picked
R DataFrame-Programs
R-DataFrame
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
Merge DataFrames by Column Names in R
How to Sort a DataFrame in R ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 May, 2021"
},
{
"code": null,
"e": 174,
"s": 28,
"text": "In this article, we will be looking at the approach to create a data frame of unequal length using different functions in R Programming language."
},
{
"code": null,
"e": 498,
"s": 174,
"text": "To create a data frame of unequal length, we add the NA value at the end of the columns which are smaller in the lengths and makes them equal to the column which has the maximum length among all and with this process all the length becomes equal and the user is able to process operations on that data frame in R language. "
},
{
"code": null,
"e": 643,
"s": 498,
"text": "rep() function is used to replicate the values in x. Here, this will be used to replicate NA value of the end of the columns of the data frames."
},
{
"code": null,
"e": 663,
"s": 643,
"text": "Syntax: rep(x, ...)"
},
{
"code": null,
"e": 675,
"s": 663,
"text": "Parameters:"
},
{
"code": null,
"e": 739,
"s": 675,
"text": "x:-a vector or a factor or a POSIXct or POSIXlt or Date object."
},
{
"code": null,
"e": 800,
"s": 739,
"text": "...:-further arguments to be passed to or from other methods"
},
{
"code": null,
"e": 811,
"s": 800,
"text": "Example 1:"
},
{
"code": null,
"e": 813,
"s": 811,
"text": "R"
},
{
"code": "# Creating variablex=c(1,2,3,4,5)y=c(1,2,3) # Finding maximum lengthmax_ln <- max(c(length(x), length(y)))gfg_data<- data.frame(col1 = c(x,rep(NA, max_ln - length(x))), col2 = c(y,rep(NA, max_ln - length(y))))gfg_datais.data.frame((gfg_data))",
"e": 1078,
"s": 813,
"text": null
},
{
"code": null,
"e": 1086,
"s": 1078,
"text": "Output:"
},
{
"code": null,
"e": 1097,
"s": 1086,
"text": "Example 2:"
},
{
"code": null,
"e": 1099,
"s": 1097,
"text": "R"
},
{
"code": "# Creating variablea=c('a','b','c','d')b=c('g','e','e','k','s')c=c('f','o','r')d=c('g','e','e','k','s') # Finding maximum lengthmax_ln1 <- max(c(length(a), length(b)))max_ln2 <- max(c(length(c), length(d)))max_ln<-max(max_ln2,max_ln1)gfg_data<- data.frame(col1 = c(a,rep(NA, max_ln - length(a))), col2 = c(b,rep(NA, max_ln - length(b))), col3 = c(c,rep(NA, max_ln - length(c))), col4 = c(d,rep(NA, max_ln - length(d)))) gfg_datais.data.frame((gfg_data))",
"e": 1618,
"s": 1099,
"text": null
},
{
"code": null,
"e": 1626,
"s": 1618,
"text": "Output:"
},
{
"code": null,
"e": 1633,
"s": 1626,
"text": "Picked"
},
{
"code": null,
"e": 1654,
"s": 1633,
"text": "R DataFrame-Programs"
},
{
"code": null,
"e": 1666,
"s": 1654,
"text": "R-DataFrame"
},
{
"code": null,
"e": 1677,
"s": 1666,
"text": "R Language"
},
{
"code": null,
"e": 1688,
"s": 1677,
"text": "R Programs"
},
{
"code": null,
"e": 1786,
"s": 1688,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1838,
"s": 1786,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 1896,
"s": 1838,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 1931,
"s": 1896,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 1969,
"s": 1931,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 2018,
"s": 1969,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 2076,
"s": 2018,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 2125,
"s": 2076,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 2168,
"s": 2125,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 2206,
"s": 2168,
"text": "Merge DataFrames by Column Names in R"
}
] |
How to replace missing values recorded with blank spaces in R with NA or any other value? | Sometimes when we read data in R, the missing values are recorded as blank spaces and it is difficult to replace them with any value. The reason behind this is we need to know how many spaces we have used in place of missing values. If we know that then assigning any value becomes easy.
Consider the below data frame of vectors x and y.
> x<-c("", 3,2,1,2,3,2,1," ", 43, "")
> y<-c(1,2,"", 43,2," ", 3,2,3,"", 7)
> df<-data.frame(x,y)
> df
x y
1 1
2 3 2
3 2
4 1 43
5 2 2
6 3
7 2 3
8 1 2
9 3
10 43
11 7
Here, we have missing values recorded as blank spaces as well simply with double inverted commas. Now let’s replace these missing values with NA as shown below −
> df[df==""]<-NA
> df
x y
1 <NA> 1
2 3 2
3 2 <NA>
4 1 43
5 2 2
6 3
7 2 3
8 1 2
9 3
10 43 <NA>
11 <NA> 7
Here, the nineth value in x and sixth value in y are not replaced because the number of blank spaces, so we need to specify them. First, read the number of spaces by looking at the vectors as follows −
> x
[1] "" "3" "2" "1" "2" "3" "2" "1" " " "43" ""
> y
[1] "1" "2" "" "43" "2" " " "3" "2"
[9] "3" "" "7"
There seems to be one blank space for nineth value in x and five blank spaces in sixth value of y. Now let’s change the df for x as follows −
> df[df==" "]<-NA
> df
x y
1 <NA> 1
2 3 2
3 2 <NA>
4 1 43
5 2 2
6 3
7 2 3
8 1 2
9 <NA> 3
10 43 <NA>
11 <NA> 7
Now we will the df for y as shown below −
> df[df==" "]<-NA
> df
x y
1 <NA> 1
2 3 2
3 2 <NA>
4 1 43
5 2 2
6 3 <NA>
7 2 3
8 1 2
9 <NA> 3
10 43 <NA>
11 <NA> 7
Now, we have our complete data frame with NA’s and other numbers. | [
{
"code": null,
"e": 1475,
"s": 1187,
"text": "Sometimes when we read data in R, the missing values are recorded as blank spaces and it is difficult to replace them with any value. The reason behind this is we need to know how many spaces we have used in place of missing values. If we know that then assigning any value becomes easy."
},
{
"code": null,
"e": 1525,
"s": 1475,
"text": "Consider the below data frame of vectors x and y."
},
{
"code": null,
"e": 1709,
"s": 1525,
"text": "> x<-c(\"\", 3,2,1,2,3,2,1,\" \", 43, \"\")\n> y<-c(1,2,\"\", 43,2,\" \", 3,2,3,\"\", 7)\n> df<-data.frame(x,y)\n> df\n x y\n1 1\n2 3 2\n3 2\n4 1 43\n5 2 2\n6 3\n7 2 3\n8 1 2\n9 3\n10 43\n11 7"
},
{
"code": null,
"e": 1871,
"s": 1709,
"text": "Here, we have missing values recorded as blank spaces as well simply with double inverted commas. Now let’s replace these missing values with NA as shown below −"
},
{
"code": null,
"e": 2015,
"s": 1871,
"text": "> df[df==\"\"]<-NA\n> df\n x y\n1 <NA> 1\n2 3 2\n3 2 <NA>\n4 1 43\n5 2 2\n6 3\n7 2 3\n8 1 2\n9 3\n10 43 <NA>\n11 <NA> 7"
},
{
"code": null,
"e": 2217,
"s": 2015,
"text": "Here, the nineth value in x and sixth value in y are not replaced because the number of blank spaces, so we need to specify them. First, read the number of spaces by looking at the vectors as follows −"
},
{
"code": null,
"e": 2344,
"s": 2217,
"text": "> x\n[1] \"\" \"3\" \"2\" \"1\" \"2\" \"3\" \"2\" \"1\" \" \" \"43\" \"\"\n> y\n[1] \"1\" \"2\" \"\" \"43\" \"2\" \" \" \"3\" \"2\"\n[9] \"3\" \"\" \"7\""
},
{
"code": null,
"e": 2486,
"s": 2344,
"text": "There seems to be one blank space for nineth value in x and five blank spaces in sixth value of y. Now let’s change the df for x as follows −"
},
{
"code": null,
"e": 2631,
"s": 2486,
"text": "> df[df==\" \"]<-NA\n> df\n x y\n1 <NA> 1\n2 3 2\n3 2 <NA>\n4 1 43\n5 2 2\n6 3\n7 2 3\n8 1 2\n9 <NA> 3\n10 43 <NA>\n11 <NA> 7"
},
{
"code": null,
"e": 2673,
"s": 2631,
"text": "Now we will the df for y as shown below −"
},
{
"code": null,
"e": 2819,
"s": 2673,
"text": "> df[df==\" \"]<-NA\n> df\n x y\n1 <NA> 1\n2 3 2\n3 2 <NA>\n4 1 43\n5 2 2\n6 3 <NA>\n7 2 3\n8 1 2\n9 <NA> 3\n10 43 <NA>\n11 <NA> 7"
},
{
"code": null,
"e": 2885,
"s": 2819,
"text": "Now, we have our complete data frame with NA’s and other numbers."
}
] |
TreeMap firstEntry() and firstKey() Method in Java with Examples | 20 Nov, 2021
There are two variants of first() in Java.util.TreeMap, both are discussed in this article.
It returns a key-value mapping associated with the least key in this map, or null if the map is empty.
Syntax:
public Map.Entry firstEntry()
Return Type: An entry with the least key and null if the map is empty.
Example:
Java
// Java Program to Illustrate Working of firstKey() Method// of TreeMap class // Importing required classesimport java.io.*;import java.util.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating an empty TreeMap by // declaring object of integer, strings pairs TreeMap<Integer, String> treemap = new TreeMap<Integer, String>(); // Populating values in the TreeMap // using put() method treemap.put(2, "two"); treemap.put(7, "seven"); treemap.put(3, "three"); treemap.put(1, "one"); treemap.put(6, "six"); treemap.put(9, "nine"); // Printing the lowest entry in TreeMap by // using firstEntry() method System.out.println("Lowest entry is: " + treemap.firstEntry()); }}
Output:
Lowest entry is: 1=one
It returns the first (lowest) key currently in the map.
Syntax:
public K firstKey()
Return Type: The first (lowest) key currently in this map.
Exception Thrown: NoSuchElementException is thrown if this map is empty.
Example:
Java
// Java Program to Demonstrate firstKey() Method// of TreeMap class // Importing required classesimport java.io.*;import java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an empty TreeMap by // declaring object of integer, strings pairs TreeMap<Integer, String> treemap = new TreeMap<Integer, String>(); // Populating values in the TreeMap // using put() method treemap.put(2, "two"); treemap.put(1, "one"); treemap.put(3, "three"); treemap.put(6, "six"); treemap.put(5, "five"); treemap.put(9, "nine"); // Printing the lowest entry in TreeMap by // using firstKey() method System.out.println("Lowest key is: " + treemap.firstKey()); }}
Output:
Lowest key is: 1
Implementation: These functions can be used to fetch the best-ranked person in the given list, or can be used to assign a winner in which person with the lowest time to finish a task wins. The latter one is discussed below.
Example: Practical Application
Java
// Java Program to Demonstrate Application Usage// of firstKey() and firstEntry() Methods// of TreeMap class // Importing required classesimport java.io.*;import java.util.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating an empty TreeMap // of Integer and String times of participants // In seconds TreeMap<Float, String> time = new TreeMap<Float, String>(); // Populating the time taken to complete task // using put() method time.put(2.32f, "Astha"); time.put(7.43f, "Manjeet"); time.put(1.3f, "Shambhavi"); time.put(5.63f, "Nikhil"); time.put(6.26f, "Vaishnavi"); // Printing person with least time // using of firstEntry() method System.out.println("Winner with lowest time is : " + time.firstEntry()); }}
Output:
Winner with lowest time is : 1.3=Shambhavi
This article is contributed by Shambhavi Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
solankimayank
Java - util package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Nov, 2021"
},
{
"code": null,
"e": 120,
"s": 28,
"text": "There are two variants of first() in Java.util.TreeMap, both are discussed in this article."
},
{
"code": null,
"e": 224,
"s": 120,
"text": "It returns a key-value mapping associated with the least key in this map, or null if the map is empty. "
},
{
"code": null,
"e": 233,
"s": 224,
"text": "Syntax: "
},
{
"code": null,
"e": 263,
"s": 233,
"text": "public Map.Entry firstEntry()"
},
{
"code": null,
"e": 334,
"s": 263,
"text": "Return Type: An entry with the least key and null if the map is empty."
},
{
"code": null,
"e": 343,
"s": 334,
"text": "Example:"
},
{
"code": null,
"e": 348,
"s": 343,
"text": "Java"
},
{
"code": "// Java Program to Illustrate Working of firstKey() Method// of TreeMap class // Importing required classesimport java.io.*;import java.util.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating an empty TreeMap by // declaring object of integer, strings pairs TreeMap<Integer, String> treemap = new TreeMap<Integer, String>(); // Populating values in the TreeMap // using put() method treemap.put(2, \"two\"); treemap.put(7, \"seven\"); treemap.put(3, \"three\"); treemap.put(1, \"one\"); treemap.put(6, \"six\"); treemap.put(9, \"nine\"); // Printing the lowest entry in TreeMap by // using firstEntry() method System.out.println(\"Lowest entry is: \" + treemap.firstEntry()); }}",
"e": 1229,
"s": 348,
"text": null
},
{
"code": null,
"e": 1238,
"s": 1229,
"text": "Output: "
},
{
"code": null,
"e": 1261,
"s": 1238,
"text": "Lowest entry is: 1=one"
},
{
"code": null,
"e": 1318,
"s": 1261,
"text": "It returns the first (lowest) key currently in the map. "
},
{
"code": null,
"e": 1327,
"s": 1318,
"text": "Syntax: "
},
{
"code": null,
"e": 1347,
"s": 1327,
"text": "public K firstKey()"
},
{
"code": null,
"e": 1406,
"s": 1347,
"text": "Return Type: The first (lowest) key currently in this map."
},
{
"code": null,
"e": 1479,
"s": 1406,
"text": "Exception Thrown: NoSuchElementException is thrown if this map is empty."
},
{
"code": null,
"e": 1488,
"s": 1479,
"text": "Example:"
},
{
"code": null,
"e": 1493,
"s": 1488,
"text": "Java"
},
{
"code": "// Java Program to Demonstrate firstKey() Method// of TreeMap class // Importing required classesimport java.io.*;import java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an empty TreeMap by // declaring object of integer, strings pairs TreeMap<Integer, String> treemap = new TreeMap<Integer, String>(); // Populating values in the TreeMap // using put() method treemap.put(2, \"two\"); treemap.put(1, \"one\"); treemap.put(3, \"three\"); treemap.put(6, \"six\"); treemap.put(5, \"five\"); treemap.put(9, \"nine\"); // Printing the lowest entry in TreeMap by // using firstKey() method System.out.println(\"Lowest key is: \" + treemap.firstKey()); }}",
"e": 2350,
"s": 1493,
"text": null
},
{
"code": null,
"e": 2359,
"s": 2350,
"text": "Output: "
},
{
"code": null,
"e": 2376,
"s": 2359,
"text": "Lowest key is: 1"
},
{
"code": null,
"e": 2601,
"s": 2376,
"text": "Implementation: These functions can be used to fetch the best-ranked person in the given list, or can be used to assign a winner in which person with the lowest time to finish a task wins. The latter one is discussed below. "
},
{
"code": null,
"e": 2633,
"s": 2601,
"text": "Example: Practical Application "
},
{
"code": null,
"e": 2638,
"s": 2633,
"text": "Java"
},
{
"code": "// Java Program to Demonstrate Application Usage// of firstKey() and firstEntry() Methods// of TreeMap class // Importing required classesimport java.io.*;import java.util.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating an empty TreeMap // of Integer and String times of participants // In seconds TreeMap<Float, String> time = new TreeMap<Float, String>(); // Populating the time taken to complete task // using put() method time.put(2.32f, \"Astha\"); time.put(7.43f, \"Manjeet\"); time.put(1.3f, \"Shambhavi\"); time.put(5.63f, \"Nikhil\"); time.put(6.26f, \"Vaishnavi\"); // Printing person with least time // using of firstEntry() method System.out.println(\"Winner with lowest time is : \" + time.firstEntry()); }}",
"e": 3566,
"s": 2638,
"text": null
},
{
"code": null,
"e": 3575,
"s": 3566,
"text": "Output: "
},
{
"code": null,
"e": 3618,
"s": 3575,
"text": "Winner with lowest time is : 1.3=Shambhavi"
},
{
"code": null,
"e": 4042,
"s": 3618,
"text": "This article is contributed by Shambhavi Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 4056,
"s": 4042,
"text": "solankimayank"
},
{
"code": null,
"e": 4076,
"s": 4056,
"text": "Java - util package"
},
{
"code": null,
"e": 4081,
"s": 4076,
"text": "Java"
},
{
"code": null,
"e": 4086,
"s": 4081,
"text": "Java"
}
] |
Python | Pandas DataFrame.truncate | 21 Feb, 2019
Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Arithmetic operations align on both row and column labels. It can be thought of as a dict-like container for Series objects. This is the primary data structure of the Pandas.
Pandas DataFrame.truncate() function is used to truncate a Series or DataFrame before and after some index value. This is a useful shorthand for boolean indexing based on index values above or below certain thresholds.
Syntax: DataFrame.truncate(before=None, after=None, axis=None, copy=True)
Parameter :before : Truncate all rows before this index value.after : Truncate all rows after this index value.axis : Axis to truncate. Truncates the index (rows) by default.copy : Return a copy of the truncated section.
Returns : The truncated Series or DataFrame.
Example #1: Use DataFrame.truncate() function to truncate some entries before and after the passed labels of the given dataframe.
# importing pandas as pdimport pandas as pd # Creating the DataFramedf = pd.DataFrame({'Weight':[45, 88, 56, 15, 71], 'Name':['Sam', 'Andrea', 'Alex', 'Robin', 'Kia'], 'Age':[14, 25, 55, 8, 21]}) # Create the indexindex_ = pd.date_range('2010-10-09 08:45', periods = 5, freq ='H') # Set the indexdf.index = index_ # Print the DataFrameprint(df)
Output :
Now we will use DataFrame.truncate() function to truncate the entries before ‘2010-10-09 09:45:00’ and after ‘2010-10-09 11:45:00’ in the given dataframe.
# return the truncated dataframeresult = df.truncate(before = '2010-10-09 09:45:00', after = '2010-10-09 11:45:00') # Print the resultprint(result)
Output :
As we can see in the output, the DataFrame.truncate() function has successfully truncated the entries before and after the passed labels in the given dataframe. Example #2: Use DataFrame.truncate() function to truncate some entries before and after the passed labels of the given dataframe.
# importing pandas as pdimport pandas as pd # Creating the DataFramedf = pd.DataFrame({"A":[12, 4, 5, None, 1], "B":[7, 2, 54, 3, None], "C":[20, 16, 11, 3, 8], "D":[14, 3, None, 2, 6]}) # Create the indexindex_ = ['Row_1', 'Row_2', 'Row_3', 'Row_4', 'Row_5'] # Set the indexdf.index = index_ # Print the DataFrameprint(df)
Output :
Now we will use DataFrame.truncate() function to truncate the entries before ‘Row_3’ and after ‘Row_4’ in the given dataframe.
# return the truncated dataframeresult = df.truncate(before = 'Row_3', after = 'Row_4') # Print the resultprint(result)
Output :
As we can see in the output, the DataFrame.truncate() function has successfully truncated the entries before and after the passed labels in the given dataframe.
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate over a list in Python
How to iterate through Excel rows in Python?
Enumerate() in Python
Rotate axis tick labels in Seaborn and Matplotlib
Python Dictionary
Deque in Python
Stack in Python
Queue in Python
Read a file line by line in Python
Defaultdict in Python | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n21 Feb, 2019"
},
{
"code": null,
"e": 366,
"s": 52,
"text": "Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Arithmetic operations align on both row and column labels. It can be thought of as a dict-like container for Series objects. This is the primary data structure of the Pandas."
},
{
"code": null,
"e": 585,
"s": 366,
"text": "Pandas DataFrame.truncate() function is used to truncate a Series or DataFrame before and after some index value. This is a useful shorthand for boolean indexing based on index values above or below certain thresholds."
},
{
"code": null,
"e": 659,
"s": 585,
"text": "Syntax: DataFrame.truncate(before=None, after=None, axis=None, copy=True)"
},
{
"code": null,
"e": 880,
"s": 659,
"text": "Parameter :before : Truncate all rows before this index value.after : Truncate all rows after this index value.axis : Axis to truncate. Truncates the index (rows) by default.copy : Return a copy of the truncated section."
},
{
"code": null,
"e": 925,
"s": 880,
"text": "Returns : The truncated Series or DataFrame."
},
{
"code": null,
"e": 1055,
"s": 925,
"text": "Example #1: Use DataFrame.truncate() function to truncate some entries before and after the passed labels of the given dataframe."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the DataFramedf = pd.DataFrame({'Weight':[45, 88, 56, 15, 71], 'Name':['Sam', 'Andrea', 'Alex', 'Robin', 'Kia'], 'Age':[14, 25, 55, 8, 21]}) # Create the indexindex_ = pd.date_range('2010-10-09 08:45', periods = 5, freq ='H') # Set the indexdf.index = index_ # Print the DataFrameprint(df)",
"e": 1440,
"s": 1055,
"text": null
},
{
"code": null,
"e": 1449,
"s": 1440,
"text": "Output :"
},
{
"code": null,
"e": 1604,
"s": 1449,
"text": "Now we will use DataFrame.truncate() function to truncate the entries before ‘2010-10-09 09:45:00’ and after ‘2010-10-09 11:45:00’ in the given dataframe."
},
{
"code": "# return the truncated dataframeresult = df.truncate(before = '2010-10-09 09:45:00', after = '2010-10-09 11:45:00') # Print the resultprint(result)",
"e": 1753,
"s": 1604,
"text": null
},
{
"code": null,
"e": 1762,
"s": 1753,
"text": "Output :"
},
{
"code": null,
"e": 2053,
"s": 1762,
"text": "As we can see in the output, the DataFrame.truncate() function has successfully truncated the entries before and after the passed labels in the given dataframe. Example #2: Use DataFrame.truncate() function to truncate some entries before and after the passed labels of the given dataframe."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the DataFramedf = pd.DataFrame({\"A\":[12, 4, 5, None, 1], \"B\":[7, 2, 54, 3, None], \"C\":[20, 16, 11, 3, 8], \"D\":[14, 3, None, 2, 6]}) # Create the indexindex_ = ['Row_1', 'Row_2', 'Row_3', 'Row_4', 'Row_5'] # Set the indexdf.index = index_ # Print the DataFrameprint(df)",
"e": 2439,
"s": 2053,
"text": null
},
{
"code": null,
"e": 2448,
"s": 2439,
"text": "Output :"
},
{
"code": null,
"e": 2575,
"s": 2448,
"text": "Now we will use DataFrame.truncate() function to truncate the entries before ‘Row_3’ and after ‘Row_4’ in the given dataframe."
},
{
"code": "# return the truncated dataframeresult = df.truncate(before = 'Row_3', after = 'Row_4') # Print the resultprint(result)",
"e": 2696,
"s": 2575,
"text": null
},
{
"code": null,
"e": 2705,
"s": 2696,
"text": "Output :"
},
{
"code": null,
"e": 2866,
"s": 2705,
"text": "As we can see in the output, the DataFrame.truncate() function has successfully truncated the entries before and after the passed labels in the given dataframe."
},
{
"code": null,
"e": 2890,
"s": 2866,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 2922,
"s": 2890,
"text": "Python pandas-dataFrame-methods"
},
{
"code": null,
"e": 2936,
"s": 2922,
"text": "Python-pandas"
},
{
"code": null,
"e": 2943,
"s": 2936,
"text": "Python"
},
{
"code": null,
"e": 3041,
"s": 2943,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3071,
"s": 3041,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 3116,
"s": 3071,
"text": "How to iterate through Excel rows in Python?"
},
{
"code": null,
"e": 3138,
"s": 3116,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3188,
"s": 3138,
"text": "Rotate axis tick labels in Seaborn and Matplotlib"
},
{
"code": null,
"e": 3206,
"s": 3188,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3222,
"s": 3206,
"text": "Deque in Python"
},
{
"code": null,
"e": 3238,
"s": 3222,
"text": "Stack in Python"
},
{
"code": null,
"e": 3254,
"s": 3238,
"text": "Queue in Python"
},
{
"code": null,
"e": 3289,
"s": 3254,
"text": "Read a file line by line in Python"
}
] |
RxJava - Completable Observable | The Completable class represents deferred response. Completable observable can either indicate a successful completion or error.
Following is the declaration for io.reactivex.Completable class −
public abstract class Completable
extends Object
implements CompletableSource
Following is the sequential protocol that Completable Observable operates −
onSubscribe (onError | onComplete)?
Create the following Java program using any editor of your choice in, say, C:\> RxJava.
import java.util.concurrent.TimeUnit;
import io.reactivex.Completable;
import io.reactivex.disposables.Disposable;
import io.reactivex.observers.DisposableCompletableObserver;
import io.reactivex.schedulers.Schedulers;
public class ObservableTester {
public static void main(String[] args) throws InterruptedException {
//Create an observer
Disposable disposable = Completable.complete()
.delay(2, TimeUnit.SECONDS, Schedulers.io())
.subscribeWith(new DisposableCompletableObserver() {
@Override
public void onError(Throwable e) {
e.printStackTrace();
}
@Override
public void onStart() {
System.out.println("Started!");
}
@Override
public void onComplete() {
System.out.println("Done!");
}
});
Thread.sleep(3000);
//start observing
disposable.dispose();
}
}
Compile the class using javac compiler as follows −
C:\RxJava>javac ObservableTester.java
Now run the ObservableTester as follows −
C:\RxJava>java ObservableTester
It should produce the following output − | [
{
"code": null,
"e": 2664,
"s": 2535,
"text": "The Completable class represents deferred response. Completable observable can either indicate a successful completion or error."
},
{
"code": null,
"e": 2730,
"s": 2664,
"text": "Following is the declaration for io.reactivex.Completable class −"
},
{
"code": null,
"e": 2809,
"s": 2730,
"text": "public abstract class Completable\nextends Object\nimplements CompletableSource\n"
},
{
"code": null,
"e": 2885,
"s": 2809,
"text": "Following is the sequential protocol that Completable Observable operates −"
},
{
"code": null,
"e": 2922,
"s": 2885,
"text": "onSubscribe (onError | onComplete)?\n"
},
{
"code": null,
"e": 3010,
"s": 2922,
"text": "Create the following Java program using any editor of your choice in, say, C:\\> RxJava."
},
{
"code": null,
"e": 3950,
"s": 3010,
"text": "import java.util.concurrent.TimeUnit;\n\nimport io.reactivex.Completable;\nimport io.reactivex.disposables.Disposable;\nimport io.reactivex.observers.DisposableCompletableObserver;\nimport io.reactivex.schedulers.Schedulers;\n\npublic class ObservableTester {\n public static void main(String[] args) throws InterruptedException {\n\n //Create an observer\n Disposable disposable = Completable.complete()\n .delay(2, TimeUnit.SECONDS, Schedulers.io())\n .subscribeWith(new DisposableCompletableObserver() {\n @Override\n public void onError(Throwable e) { \n e.printStackTrace();\n }\n @Override\n public void onStart() {\n System.out.println(\"Started!\");\n }\n @Override\n public void onComplete() {\n System.out.println(\"Done!\");\n }\n }); \n Thread.sleep(3000);\n //start observing\n disposable.dispose();\n }\n}"
},
{
"code": null,
"e": 4002,
"s": 3950,
"text": "Compile the class using javac compiler as follows −"
},
{
"code": null,
"e": 4041,
"s": 4002,
"text": "C:\\RxJava>javac ObservableTester.java\n"
},
{
"code": null,
"e": 4083,
"s": 4041,
"text": "Now run the ObservableTester as follows −"
},
{
"code": null,
"e": 4116,
"s": 4083,
"text": "C:\\RxJava>java ObservableTester\n"
}
] |
MYSQLdb Connection in Python | 23 Nov, 2021
In this article, I have discussed how to connect to MySQL database remotely using python. For any application, it is very important to store the database on a server for easy data access. It is quite complicated to connect to the database remotely because every service provider doesn’t provide remote access to the MySQL database. Here I am using python’s MySQLdb module for connecting to our database which is at any server that provides remote access.
What is MYSQLdb?
MySQLdb is an interface for connecting to a MySQL database server from Python. It implements the Python Database API v2.0 and is built on top of the MySQL C API.
Packages to Install
mysql-connector-python
mysql-python
If using anaconda
conda install -c anaconda mysql-python
conda install -c anaconda mysql-connector-python
else
pip install MySQL-python
pip install MySQL-python-connector
Import-Package
import MYSQLdb
How to connect to a remote MySQL database using python?
Before we start you should know the basics of SQL. Now let us discuss the methods used in this code:
connect(): This method is used for creating a connection to our database it has four arguments:
Server NameDatabase User NameDatabase PasswordDatabase Name
Server Name
Database User Name
Database Password
Database Name
cursor(): This method creates a cursor object that is capable of executing SQL queries on the database.
execute(): This method is used for executing SQL queries on the database. It takes a sql query( as string) as an argument.
fetchone(): This method retrieves the next row of a query result set and returns a single sequence, or None if no more rows are available.
close() : This method close the database connection.
Free remote mysql database providers: 1.www.freemysqlhosting.net 2.www.heliohost.org
Python3
'''This code would not be run on geeksforgeeks IDEbecause required moduleare not installed on IDE. Also this code requiresa remote MySQL databaseconnection with validHostname, Dbusername Password and Dbname''' # Module For Connecting To MySQL databaseimport MySQLdb # Function for connecting to MySQL databasedef mysqlconnect(): #Trying to connect try: db_connection= MySQLdb.connect ("Hostname","dbusername","password","dbname") # If connection is not successful except: print("Can't connect to database") return 0 # If Connection Is Successful print("Connected") # Making Cursor Object For Query Execution cursor=db_connection.cursor() # Executing Query cursor.execute("SELECT CURDATE();") # Above Query Gives Us The Current Date # Fetching Data m = cursor.fetchone() # Printing Result Of Above print("Today's Date Is ",m[0]) # Closing Database Connection db_connection.close() # Function Call For Connecting To Our Databasemysqlconnect()
Connected
Today's Date Is 2017-11-14
Python3
# Python code to illustrate and create a# table in databaseimport mysql.connector as mysql # Open database connectiondb = mysql.connect(host="localhost",user="root",password="tiger",database="python") cursor = db.cursor() # Drop table if it already exist using execute()cursor.execute("DROP TABLE IF EXISTS EMPLOYEE") # Create table as per requirementsql = "CREATE TABLE EMPLOYEE ( FNAME CHAR(20) NOT NULL, LNAME CHAR(20), AGE INT )" cursor.execute(sql) #table created # disconnect from serverdb.close()
Output:
ysachin2314
vivekpisal12345
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n23 Nov, 2021"
},
{
"code": null,
"e": 510,
"s": 54,
"text": "In this article, I have discussed how to connect to MySQL database remotely using python. For any application, it is very important to store the database on a server for easy data access. It is quite complicated to connect to the database remotely because every service provider doesn’t provide remote access to the MySQL database. Here I am using python’s MySQLdb module for connecting to our database which is at any server that provides remote access. "
},
{
"code": null,
"e": 527,
"s": 510,
"text": "What is MYSQLdb?"
},
{
"code": null,
"e": 690,
"s": 527,
"text": "MySQLdb is an interface for connecting to a MySQL database server from Python. It implements the Python Database API v2.0 and is built on top of the MySQL C API. "
},
{
"code": null,
"e": 711,
"s": 690,
"text": "Packages to Install "
},
{
"code": null,
"e": 747,
"s": 711,
"text": "mysql-connector-python\nmysql-python"
},
{
"code": null,
"e": 766,
"s": 747,
"text": "If using anaconda "
},
{
"code": null,
"e": 854,
"s": 766,
"text": "conda install -c anaconda mysql-python\nconda install -c anaconda mysql-connector-python"
},
{
"code": null,
"e": 860,
"s": 854,
"text": "else "
},
{
"code": null,
"e": 920,
"s": 860,
"text": "pip install MySQL-python\npip install MySQL-python-connector"
},
{
"code": null,
"e": 936,
"s": 920,
"text": "Import-Package "
},
{
"code": null,
"e": 951,
"s": 936,
"text": "import MYSQLdb"
},
{
"code": null,
"e": 1008,
"s": 951,
"text": " How to connect to a remote MySQL database using python?"
},
{
"code": null,
"e": 1110,
"s": 1008,
"text": "Before we start you should know the basics of SQL. Now let us discuss the methods used in this code: "
},
{
"code": null,
"e": 1206,
"s": 1110,
"text": "connect(): This method is used for creating a connection to our database it has four arguments:"
},
{
"code": null,
"e": 1266,
"s": 1206,
"text": "Server NameDatabase User NameDatabase PasswordDatabase Name"
},
{
"code": null,
"e": 1278,
"s": 1266,
"text": "Server Name"
},
{
"code": null,
"e": 1297,
"s": 1278,
"text": "Database User Name"
},
{
"code": null,
"e": 1315,
"s": 1297,
"text": "Database Password"
},
{
"code": null,
"e": 1329,
"s": 1315,
"text": "Database Name"
},
{
"code": null,
"e": 1433,
"s": 1329,
"text": "cursor(): This method creates a cursor object that is capable of executing SQL queries on the database."
},
{
"code": null,
"e": 1556,
"s": 1433,
"text": "execute(): This method is used for executing SQL queries on the database. It takes a sql query( as string) as an argument."
},
{
"code": null,
"e": 1695,
"s": 1556,
"text": "fetchone(): This method retrieves the next row of a query result set and returns a single sequence, or None if no more rows are available."
},
{
"code": null,
"e": 1749,
"s": 1695,
"text": "close() : This method close the database connection. "
},
{
"code": null,
"e": 1836,
"s": 1749,
"text": "Free remote mysql database providers: 1.www.freemysqlhosting.net 2.www.heliohost.org "
},
{
"code": null,
"e": 1844,
"s": 1836,
"text": "Python3"
},
{
"code": "'''This code would not be run on geeksforgeeks IDEbecause required moduleare not installed on IDE. Also this code requiresa remote MySQL databaseconnection with validHostname, Dbusername Password and Dbname''' # Module For Connecting To MySQL databaseimport MySQLdb # Function for connecting to MySQL databasedef mysqlconnect(): #Trying to connect try: db_connection= MySQLdb.connect (\"Hostname\",\"dbusername\",\"password\",\"dbname\") # If connection is not successful except: print(\"Can't connect to database\") return 0 # If Connection Is Successful print(\"Connected\") # Making Cursor Object For Query Execution cursor=db_connection.cursor() # Executing Query cursor.execute(\"SELECT CURDATE();\") # Above Query Gives Us The Current Date # Fetching Data m = cursor.fetchone() # Printing Result Of Above print(\"Today's Date Is \",m[0]) # Closing Database Connection db_connection.close() # Function Call For Connecting To Our Databasemysqlconnect()",
"e": 2870,
"s": 1844,
"text": null
},
{
"code": null,
"e": 2908,
"s": 2870,
"text": "Connected\nToday's Date Is 2017-11-14"
},
{
"code": null,
"e": 2916,
"s": 2908,
"text": "Python3"
},
{
"code": "# Python code to illustrate and create a# table in databaseimport mysql.connector as mysql # Open database connectiondb = mysql.connect(host=\"localhost\",user=\"root\",password=\"tiger\",database=\"python\") cursor = db.cursor() # Drop table if it already exist using execute()cursor.execute(\"DROP TABLE IF EXISTS EMPLOYEE\") # Create table as per requirementsql = \"CREATE TABLE EMPLOYEE ( FNAME CHAR(20) NOT NULL, LNAME CHAR(20), AGE INT )\" cursor.execute(sql) #table created # disconnect from serverdb.close()",
"e": 3420,
"s": 2916,
"text": null
},
{
"code": null,
"e": 3428,
"s": 3420,
"text": "Output:"
},
{
"code": null,
"e": 3440,
"s": 3428,
"text": "ysachin2314"
},
{
"code": null,
"e": 3456,
"s": 3440,
"text": "vivekpisal12345"
},
{
"code": null,
"e": 3463,
"s": 3456,
"text": "Python"
},
{
"code": null,
"e": 3561,
"s": 3463,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3603,
"s": 3561,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3625,
"s": 3603,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3651,
"s": 3625,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3683,
"s": 3651,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3712,
"s": 3683,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3739,
"s": 3712,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3760,
"s": 3739,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3796,
"s": 3760,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 3819,
"s": 3796,
"text": "Introduction To PYTHON"
}
] |
Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive) | 26 May, 2022
The shortest job first (SJF) or shortest job next, is a scheduling policy that selects the waiting process with the smallest execution time to execute next. SJN, also known as Shortest Job Next (SJN), can be preemptive or non-preemptive.
Characteristics of SJF Scheduling:
Shortest Job first has the advantage of having a minimum average waiting time among all scheduling algorithms.
It is a Greedy Algorithm.
It may cause starvation if shorter processes keep coming. This problem can be solved using the concept of ageing.
It is practically infeasible as Operating System may not know burst times and therefore may not sort them. While it is not possible to predict execution time, several methods can be used to estimate the execution time for a job, such as a weighted average of previous execution times.
SJF can be used in specialized environments where accurate estimates of running time are available.
Algorithm:
Sort all the processes according to the arrival time.
Then select that process that has minimum arrival time and minimum Burst time.
After completion of the process make a pool of processes that arrives afterward till the completion of the previous process and select that process among the pool which is having minimum Burst time.
How to compute below times in SJF using a program?
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Completion Time: Time at which process completes its execution.
Turn Around Time: Time Difference between completion time and arrival time. Turn Around Time = Completion Time – Arrival Time
Waiting Time(W.T): Time Difference between turn around time and burst time. Waiting Time = Turn Around Time – Burst Time
Non-Preemptive Shortest Job First algorithm can be implemented using Segment Trees data structure. For detailed implementation of Non-Preemptive Shortest Job First scheduling algorithm, please refer: Program for Non-Preemptive Shortest Job First CPU Scheduling.
In this post, we have assumed arrival times as 0, so turn around and completion times are same.
Example-1: Consider the following table of arrival time and burst time for five processes P1, P2, P3, P4 and P5.
The Shortest Job First CPU Scheduling Algorithm will work on the basis of steps as mentioned below:
At time = 0,
Process P4 arrives and starts executing
At time= 1,
Process P3 arrives.
But, as P4 still needs 2 execution units to complete.
Thus, P3 will wait till P4 gets executed.
At time =2,
Process P1 arrives and is added to the waiting table
P4 will continue its execution.
At time = 3,
Process P4 will finish its execution.
Then, the burst time of P3 and P1 is compared.
Process P1 is executed because its burst time is less as compared to P3.
At time = 4,
Process P5 arrives and is added to the waiting Table.
P1 will continue execution.
At time = 5,
Process P2 arrives and is added to the waiting Table.
P1 will continue execution.
At time = 6,
Process P1 will finish its execution.
The burst time of P3, P5, and P2 is compared.
Process P2 is executed because its burst time is the lowest among all.
At time=9,
Process P2 is executing and P3 and P5 are in the waiting Table.
At time = 11,
The execution of Process P2 will be done.
The burst time of P3 and P5 is compared.
Process P5 is executed because its burst time is lower than P3.
At time = 15,
Process P5 will finish its execution.
At time = 23,
Process P3 will finish its execution.
The overall execution of the processes will be as shown below:
Gantt chart for above execution:
Gantt chart
Now, let’s calculate the average waiting time for above example:
P4 = 0 – 0 = 0
P1 = 3 – 2 = 1
P2 = 9 – 5 = 4
P5 = 11 – 4 = 7
P3 = 15 – 1 = 14
Average Waiting Time = 0 + 1 + 4 + 7 + 14/5 = 26/5 = 5.2
Advantages of SJF:
SJF is better than the First come first serve(FCFS) algorithm as it reduces the average waiting time.
SJF is generally used for long term scheduling
It is suitable for the jobs running in batches, where run times are already known.
SJF is probably optimal in terms of average turnaround time.
Disadvantages of SJF:
SJF may cause very long turn-around times or starvation.
In SJF job completion time must be known earlier, but sometimes it is hard to predict.
Sometimes, it is complicated to predict the length of the upcoming CPU request.
It leads to the starvation that does not reduce average turnaround time.
C
#include <stdio.h>int main(){ int A[100][4]; // Matrix for storing Process Id, Burst // Time, Average Waiting Time & Average // Turn Around Time. int i, j, n, total = 0, index, temp; float avg_wt, avg_tat; printf("Enter number of process: "); scanf("%d", &n); printf("Enter Burst Time:\n"); // User Input Burst Time and alloting Process Id. for (i = 0; i < n; i++) { printf("P%d: ", i + 1); scanf("%d", &A[i][1]); A[i][0] = i + 1; } // Sorting process according to their Burst Time. for (i = 0; i < n; i++) { index = i; for (j = i + 1; j < n; j++) if (A[j][1] < A[index][1]) index = j; temp = A[i][1]; A[i][1] = A[index][1]; A[index][1] = temp; temp = A[i][0]; A[i][0] = A[index][0]; A[index][0] = temp; } A[0][2] = 0; // Calculation of Waiting Times for (i = 1; i < n; i++) { A[i][2] = 0; for (j = 0; j < i; j++) A[i][2] += A[j][1]; total += A[i][2]; } avg_wt = (float)total / n; total = 0; printf("P BT WT TAT\n"); // Calculation of Turn Around Time and printing the // data. for (i = 0; i < n; i++) { A[i][3] = A[i][1] + A[i][2]; total += A[i][3]; printf("P%d %d %d %d\n", A[i][0], A[i][1], A[i][2], A[i][3]); } avg_tat = (float)total / n; printf("Average Waiting Time= %f", avg_wt); printf("\nAverage Turnaround Time= %f", avg_tat);}
Note: In this post, we have assumed arrival times as 0, so turn around and completion times are same.
In Set-2 we will discuss the preemptive version of SJF i.e. Shortest Remaining Time First
This article is contributed by Mahesh Kumar(NCE, Chandi). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
anish3007
msujawal
sanjeev2552
dharanendralv23
etcherlarevanthrao9402
tanvibugdani
kashishkumar2
amancselover
cpu-scheduling
Greedy
Operating Systems
Operating Systems
Greedy
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Dijkstra's shortest path algorithm | Greedy Algo-7
Program for array rotation
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Write a program to print all permutations of a given string
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Cache Memory in Computer Organization
LRU Cache Implementation
'crontab' in Linux with Examples
Cd cmd command
Memory Management in Operating System | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n26 May, 2022"
},
{
"code": null,
"e": 292,
"s": 52,
"text": "The shortest job first (SJF) or shortest job next, is a scheduling policy that selects the waiting process with the smallest execution time to execute next. SJN, also known as Shortest Job Next (SJN), can be preemptive or non-preemptive. "
},
{
"code": null,
"e": 327,
"s": 292,
"text": "Characteristics of SJF Scheduling:"
},
{
"code": null,
"e": 438,
"s": 327,
"text": "Shortest Job first has the advantage of having a minimum average waiting time among all scheduling algorithms."
},
{
"code": null,
"e": 464,
"s": 438,
"text": "It is a Greedy Algorithm."
},
{
"code": null,
"e": 578,
"s": 464,
"text": "It may cause starvation if shorter processes keep coming. This problem can be solved using the concept of ageing."
},
{
"code": null,
"e": 864,
"s": 578,
"text": "It is practically infeasible as Operating System may not know burst times and therefore may not sort them. While it is not possible to predict execution time, several methods can be used to estimate the execution time for a job, such as a weighted average of previous execution times. "
},
{
"code": null,
"e": 964,
"s": 864,
"text": "SJF can be used in specialized environments where accurate estimates of running time are available."
},
{
"code": null,
"e": 976,
"s": 964,
"text": "Algorithm: "
},
{
"code": null,
"e": 1031,
"s": 976,
"text": "Sort all the processes according to the arrival time. "
},
{
"code": null,
"e": 1111,
"s": 1031,
"text": "Then select that process that has minimum arrival time and minimum Burst time. "
},
{
"code": null,
"e": 1311,
"s": 1111,
"text": "After completion of the process make a pool of processes that arrives afterward till the completion of the previous process and select that process among the pool which is having minimum Burst time. "
},
{
"code": null,
"e": 1363,
"s": 1311,
"text": "How to compute below times in SJF using a program? "
},
{
"code": null,
"e": 1372,
"s": 1363,
"text": "Chapters"
},
{
"code": null,
"e": 1399,
"s": 1372,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 1449,
"s": 1399,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 1472,
"s": 1449,
"text": "captions off, selected"
},
{
"code": null,
"e": 1480,
"s": 1472,
"text": "English"
},
{
"code": null,
"e": 1504,
"s": 1480,
"text": "This is a modal window."
},
{
"code": null,
"e": 1573,
"s": 1504,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 1595,
"s": 1573,
"text": "End of dialog window."
},
{
"code": null,
"e": 1659,
"s": 1595,
"text": "Completion Time: Time at which process completes its execution."
},
{
"code": null,
"e": 1785,
"s": 1659,
"text": "Turn Around Time: Time Difference between completion time and arrival time. Turn Around Time = Completion Time – Arrival Time"
},
{
"code": null,
"e": 1906,
"s": 1785,
"text": "Waiting Time(W.T): Time Difference between turn around time and burst time. Waiting Time = Turn Around Time – Burst Time"
},
{
"code": null,
"e": 2169,
"s": 1906,
"text": "Non-Preemptive Shortest Job First algorithm can be implemented using Segment Trees data structure. For detailed implementation of Non-Preemptive Shortest Job First scheduling algorithm, please refer: Program for Non-Preemptive Shortest Job First CPU Scheduling. "
},
{
"code": null,
"e": 2265,
"s": 2169,
"text": "In this post, we have assumed arrival times as 0, so turn around and completion times are same."
},
{
"code": null,
"e": 2379,
"s": 2265,
"text": "Example-1: Consider the following table of arrival time and burst time for five processes P1, P2, P3, P4 and P5. "
},
{
"code": null,
"e": 2479,
"s": 2379,
"text": "The Shortest Job First CPU Scheduling Algorithm will work on the basis of steps as mentioned below:"
},
{
"code": null,
"e": 2492,
"s": 2479,
"text": "At time = 0,"
},
{
"code": null,
"e": 2532,
"s": 2492,
"text": "Process P4 arrives and starts executing"
},
{
"code": null,
"e": 2545,
"s": 2532,
"text": "At time= 1, "
},
{
"code": null,
"e": 2566,
"s": 2545,
"text": "Process P3 arrives. "
},
{
"code": null,
"e": 2621,
"s": 2566,
"text": "But, as P4 still needs 2 execution units to complete. "
},
{
"code": null,
"e": 2663,
"s": 2621,
"text": "Thus, P3 will wait till P4 gets executed."
},
{
"code": null,
"e": 2676,
"s": 2663,
"text": "At time =2, "
},
{
"code": null,
"e": 2730,
"s": 2676,
"text": "Process P1 arrives and is added to the waiting table "
},
{
"code": null,
"e": 2762,
"s": 2730,
"text": "P4 will continue its execution."
},
{
"code": null,
"e": 2776,
"s": 2762,
"text": "At time = 3, "
},
{
"code": null,
"e": 2815,
"s": 2776,
"text": "Process P4 will finish its execution. "
},
{
"code": null,
"e": 2863,
"s": 2815,
"text": "Then, the burst time of P3 and P1 is compared. "
},
{
"code": null,
"e": 2936,
"s": 2863,
"text": "Process P1 is executed because its burst time is less as compared to P3."
},
{
"code": null,
"e": 2950,
"s": 2936,
"text": "At time = 4, "
},
{
"code": null,
"e": 3004,
"s": 2950,
"text": "Process P5 arrives and is added to the waiting Table."
},
{
"code": null,
"e": 3032,
"s": 3004,
"text": "P1 will continue execution."
},
{
"code": null,
"e": 3046,
"s": 3032,
"text": "At time = 5, "
},
{
"code": null,
"e": 3101,
"s": 3046,
"text": "Process P2 arrives and is added to the waiting Table. "
},
{
"code": null,
"e": 3129,
"s": 3101,
"text": "P1 will continue execution."
},
{
"code": null,
"e": 3143,
"s": 3129,
"text": "At time = 6, "
},
{
"code": null,
"e": 3182,
"s": 3143,
"text": "Process P1 will finish its execution. "
},
{
"code": null,
"e": 3229,
"s": 3182,
"text": "The burst time of P3, P5, and P2 is compared. "
},
{
"code": null,
"e": 3300,
"s": 3229,
"text": "Process P2 is executed because its burst time is the lowest among all."
},
{
"code": null,
"e": 3312,
"s": 3300,
"text": "At time=9, "
},
{
"code": null,
"e": 3376,
"s": 3312,
"text": "Process P2 is executing and P3 and P5 are in the waiting Table."
},
{
"code": null,
"e": 3391,
"s": 3376,
"text": "At time = 11, "
},
{
"code": null,
"e": 3434,
"s": 3391,
"text": "The execution of Process P2 will be done. "
},
{
"code": null,
"e": 3476,
"s": 3434,
"text": "The burst time of P3 and P5 is compared. "
},
{
"code": null,
"e": 3540,
"s": 3476,
"text": "Process P5 is executed because its burst time is lower than P3."
},
{
"code": null,
"e": 3554,
"s": 3540,
"text": "At time = 15,"
},
{
"code": null,
"e": 3592,
"s": 3554,
"text": "Process P5 will finish its execution."
},
{
"code": null,
"e": 3607,
"s": 3592,
"text": "At time = 23, "
},
{
"code": null,
"e": 3645,
"s": 3607,
"text": "Process P3 will finish its execution."
},
{
"code": null,
"e": 3708,
"s": 3645,
"text": "The overall execution of the processes will be as shown below:"
},
{
"code": null,
"e": 3741,
"s": 3708,
"text": "Gantt chart for above execution:"
},
{
"code": null,
"e": 3753,
"s": 3741,
"text": "Gantt chart"
},
{
"code": null,
"e": 3818,
"s": 3753,
"text": "Now, let’s calculate the average waiting time for above example:"
},
{
"code": null,
"e": 3833,
"s": 3818,
"text": "P4 = 0 – 0 = 0"
},
{
"code": null,
"e": 3848,
"s": 3833,
"text": "P1 = 3 – 2 = 1"
},
{
"code": null,
"e": 3863,
"s": 3848,
"text": "P2 = 9 – 5 = 4"
},
{
"code": null,
"e": 3879,
"s": 3863,
"text": "P5 = 11 – 4 = 7"
},
{
"code": null,
"e": 3896,
"s": 3879,
"text": "P3 = 15 – 1 = 14"
},
{
"code": null,
"e": 3953,
"s": 3896,
"text": "Average Waiting Time = 0 + 1 + 4 + 7 + 14/5 = 26/5 = 5.2"
},
{
"code": null,
"e": 3972,
"s": 3953,
"text": "Advantages of SJF:"
},
{
"code": null,
"e": 4074,
"s": 3972,
"text": "SJF is better than the First come first serve(FCFS) algorithm as it reduces the average waiting time."
},
{
"code": null,
"e": 4121,
"s": 4074,
"text": "SJF is generally used for long term scheduling"
},
{
"code": null,
"e": 4204,
"s": 4121,
"text": "It is suitable for the jobs running in batches, where run times are already known."
},
{
"code": null,
"e": 4265,
"s": 4204,
"text": "SJF is probably optimal in terms of average turnaround time."
},
{
"code": null,
"e": 4288,
"s": 4265,
"text": "Disadvantages of SJF: "
},
{
"code": null,
"e": 4345,
"s": 4288,
"text": "SJF may cause very long turn-around times or starvation."
},
{
"code": null,
"e": 4432,
"s": 4345,
"text": "In SJF job completion time must be known earlier, but sometimes it is hard to predict."
},
{
"code": null,
"e": 4512,
"s": 4432,
"text": "Sometimes, it is complicated to predict the length of the upcoming CPU request."
},
{
"code": null,
"e": 4586,
"s": 4512,
"text": "It leads to the starvation that does not reduce average turnaround time. "
},
{
"code": null,
"e": 4588,
"s": 4586,
"text": "C"
},
{
"code": "#include <stdio.h>int main(){ int A[100][4]; // Matrix for storing Process Id, Burst // Time, Average Waiting Time & Average // Turn Around Time. int i, j, n, total = 0, index, temp; float avg_wt, avg_tat; printf(\"Enter number of process: \"); scanf(\"%d\", &n); printf(\"Enter Burst Time:\\n\"); // User Input Burst Time and alloting Process Id. for (i = 0; i < n; i++) { printf(\"P%d: \", i + 1); scanf(\"%d\", &A[i][1]); A[i][0] = i + 1; } // Sorting process according to their Burst Time. for (i = 0; i < n; i++) { index = i; for (j = i + 1; j < n; j++) if (A[j][1] < A[index][1]) index = j; temp = A[i][1]; A[i][1] = A[index][1]; A[index][1] = temp; temp = A[i][0]; A[i][0] = A[index][0]; A[index][0] = temp; } A[0][2] = 0; // Calculation of Waiting Times for (i = 1; i < n; i++) { A[i][2] = 0; for (j = 0; j < i; j++) A[i][2] += A[j][1]; total += A[i][2]; } avg_wt = (float)total / n; total = 0; printf(\"P BT WT TAT\\n\"); // Calculation of Turn Around Time and printing the // data. for (i = 0; i < n; i++) { A[i][3] = A[i][1] + A[i][2]; total += A[i][3]; printf(\"P%d %d %d %d\\n\", A[i][0], A[i][1], A[i][2], A[i][3]); } avg_tat = (float)total / n; printf(\"Average Waiting Time= %f\", avg_wt); printf(\"\\nAverage Turnaround Time= %f\", avg_tat);}",
"e": 6136,
"s": 4588,
"text": null
},
{
"code": null,
"e": 6238,
"s": 6136,
"text": "Note: In this post, we have assumed arrival times as 0, so turn around and completion times are same."
},
{
"code": null,
"e": 6328,
"s": 6238,
"text": "In Set-2 we will discuss the preemptive version of SJF i.e. Shortest Remaining Time First"
},
{
"code": null,
"e": 6761,
"s": 6328,
"text": "This article is contributed by Mahesh Kumar(NCE, Chandi). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 6771,
"s": 6761,
"text": "anish3007"
},
{
"code": null,
"e": 6780,
"s": 6771,
"text": "msujawal"
},
{
"code": null,
"e": 6792,
"s": 6780,
"text": "sanjeev2552"
},
{
"code": null,
"e": 6808,
"s": 6792,
"text": "dharanendralv23"
},
{
"code": null,
"e": 6831,
"s": 6808,
"text": "etcherlarevanthrao9402"
},
{
"code": null,
"e": 6844,
"s": 6831,
"text": "tanvibugdani"
},
{
"code": null,
"e": 6858,
"s": 6844,
"text": "kashishkumar2"
},
{
"code": null,
"e": 6871,
"s": 6858,
"text": "amancselover"
},
{
"code": null,
"e": 6886,
"s": 6871,
"text": "cpu-scheduling"
},
{
"code": null,
"e": 6893,
"s": 6886,
"text": "Greedy"
},
{
"code": null,
"e": 6911,
"s": 6893,
"text": "Operating Systems"
},
{
"code": null,
"e": 6929,
"s": 6911,
"text": "Operating Systems"
},
{
"code": null,
"e": 6936,
"s": 6929,
"text": "Greedy"
},
{
"code": null,
"e": 7034,
"s": 6936,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7085,
"s": 7034,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 7112,
"s": 7085,
"text": "Program for array rotation"
},
{
"code": null,
"e": 7163,
"s": 7112,
"text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5"
},
{
"code": null,
"e": 7223,
"s": 7163,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 7281,
"s": 7223,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
},
{
"code": null,
"e": 7319,
"s": 7281,
"text": "Cache Memory in Computer Organization"
},
{
"code": null,
"e": 7344,
"s": 7319,
"text": "LRU Cache Implementation"
},
{
"code": null,
"e": 7377,
"s": 7344,
"text": "'crontab' in Linux with Examples"
},
{
"code": null,
"e": 7392,
"s": 7377,
"text": "Cd cmd command"
}
] |
BigInteger divide() Method in Java with Examples | 07 Jun, 2019
The java.math.BigInteger.divide(BigInteger val) is used to calculate the division of two BigIntegers. BigInteger class internally uses array of integers for processing, the operation on object of BigIntegers are not as fast as on primitives. This method performs an operation upon the current BigInteger by which this method is called and BigInteger passed as the parameter.
Syntax:
public BigInteger divide(BigInteger val)
Parameters: This method accepts a parameter val which is the value that divides this BigInteger.
Return value: This method returns a BigInteger which holds division (this / val) in Integer (non – floating point value) i.e. it rounds off the result to its floor value.
Exception: The parameter val must not be 0 otherwise Arithmetic Exception is thrown.
Below programs is used to illustrate the divide() method of BigInteger.
Example 1:
// Java program to demonstrate// divide() method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // BigInteger object to store result BigInteger div; // Two objects of String created // Holds the values to calculate the division String input1 = "400000000000000000" + "000000000000000000"; String input2 = "8000000"; // Convert the string input to BigInteger BigInteger a = new BigInteger(input1); BigInteger b = new BigInteger(input2); // Using divide() method div = a.divide(b); // Display the result in BigInteger System.out.println("The division of\n" + a + " \nby\n" + b + " " + "\nis\n" + div); }}
The division of
400000000000000000000000000000000000
by
8000000
is
50000000000000000000000000000
Example 2: To demonstrate how it rounds off the result
// Java program to demonstrate// divide() method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // BigInteger object to store result BigInteger div; // Two objects of String created // Holds the values to calculate the division String input1 = "456216545"; String input2 = "21255132"; // Convert the string input to BigInteger BigInteger a = new BigInteger(input1); BigInteger b = new BigInteger(input2); // Using divide() method div = a.divide(b); // Display the result in BigInteger System.out.println("The division of\n" + a + " \nby\n" + b + " " + "\nis " + div); double d = Double.parseDouble(input1) / Double.parseDouble(input2); // Display result in double type // To match both the results System.out.print("Using double result is " + d); }}
The division of
456216545
by
21255132
is 21
Using double result is 21.46383024109189
Example 3: To demonstrate Exception thrown when divided by 0
// Java program to demonstrate// divide() method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // BigInteger object to store result BigInteger div; // Two objects of String created // Holds the values to calculate the division String input1 = "456216545" + "452133155"; String input2 = "0"; // Convert the string input to BigInteger BigInteger a = new BigInteger(input1); BigInteger b = new BigInteger(input2); // Using divide() method try { div = a.divide(b); // Display the result in BigInteger System.out.println("The division of\n" + a + " \nby\n" + b + " " + "\nis\n" + div + "\n"); } catch (ArithmeticException e) { System.out.println(e); } }}
java.lang.ArithmeticException: BigInteger divide by zero
Reference: https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/math/BigInteger.html#divide(java.math.BigInteger)
Akanksha_Rai
Java-BigInteger
Java-Functions
Java-math-package
Java
Java-BigInteger
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
Stream In Java
Multidimensional Arrays in Java
Singleton Class in Java
Set in Java | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Jun, 2019"
},
{
"code": null,
"e": 403,
"s": 28,
"text": "The java.math.BigInteger.divide(BigInteger val) is used to calculate the division of two BigIntegers. BigInteger class internally uses array of integers for processing, the operation on object of BigIntegers are not as fast as on primitives. This method performs an operation upon the current BigInteger by which this method is called and BigInteger passed as the parameter."
},
{
"code": null,
"e": 411,
"s": 403,
"text": "Syntax:"
},
{
"code": null,
"e": 453,
"s": 411,
"text": "public BigInteger divide(BigInteger val)\n"
},
{
"code": null,
"e": 550,
"s": 453,
"text": "Parameters: This method accepts a parameter val which is the value that divides this BigInteger."
},
{
"code": null,
"e": 721,
"s": 550,
"text": "Return value: This method returns a BigInteger which holds division (this / val) in Integer (non – floating point value) i.e. it rounds off the result to its floor value."
},
{
"code": null,
"e": 806,
"s": 721,
"text": "Exception: The parameter val must not be 0 otherwise Arithmetic Exception is thrown."
},
{
"code": null,
"e": 878,
"s": 806,
"text": "Below programs is used to illustrate the divide() method of BigInteger."
},
{
"code": null,
"e": 889,
"s": 878,
"text": "Example 1:"
},
{
"code": "// Java program to demonstrate// divide() method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // BigInteger object to store result BigInteger div; // Two objects of String created // Holds the values to calculate the division String input1 = \"400000000000000000\" + \"000000000000000000\"; String input2 = \"8000000\"; // Convert the string input to BigInteger BigInteger a = new BigInteger(input1); BigInteger b = new BigInteger(input2); // Using divide() method div = a.divide(b); // Display the result in BigInteger System.out.println(\"The division of\\n\" + a + \" \\nby\\n\" + b + \" \" + \"\\nis\\n\" + div); }}",
"e": 1757,
"s": 889,
"text": null
},
{
"code": null,
"e": 1857,
"s": 1757,
"text": "The division of\n400000000000000000000000000000000000 \nby\n8000000 \nis\n50000000000000000000000000000\n"
},
{
"code": null,
"e": 1912,
"s": 1857,
"text": "Example 2: To demonstrate how it rounds off the result"
},
{
"code": "// Java program to demonstrate// divide() method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // BigInteger object to store result BigInteger div; // Two objects of String created // Holds the values to calculate the division String input1 = \"456216545\"; String input2 = \"21255132\"; // Convert the string input to BigInteger BigInteger a = new BigInteger(input1); BigInteger b = new BigInteger(input2); // Using divide() method div = a.divide(b); // Display the result in BigInteger System.out.println(\"The division of\\n\" + a + \" \\nby\\n\" + b + \" \" + \"\\nis \" + div); double d = Double.parseDouble(input1) / Double.parseDouble(input2); // Display result in double type // To match both the results System.out.print(\"Using double result is \" + d); }}",
"e": 2954,
"s": 1912,
"text": null
},
{
"code": null,
"e": 3042,
"s": 2954,
"text": "The division of\n456216545 \nby\n21255132 \nis 21\nUsing double result is 21.46383024109189\n"
},
{
"code": null,
"e": 3103,
"s": 3042,
"text": "Example 3: To demonstrate Exception thrown when divided by 0"
},
{
"code": "// Java program to demonstrate// divide() method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // BigInteger object to store result BigInteger div; // Two objects of String created // Holds the values to calculate the division String input1 = \"456216545\" + \"452133155\"; String input2 = \"0\"; // Convert the string input to BigInteger BigInteger a = new BigInteger(input1); BigInteger b = new BigInteger(input2); // Using divide() method try { div = a.divide(b); // Display the result in BigInteger System.out.println(\"The division of\\n\" + a + \" \\nby\\n\" + b + \" \" + \"\\nis\\n\" + div + \"\\n\"); } catch (ArithmeticException e) { System.out.println(e); } }}",
"e": 4078,
"s": 3103,
"text": null
},
{
"code": null,
"e": 4136,
"s": 4078,
"text": "java.lang.ArithmeticException: BigInteger divide by zero\n"
},
{
"code": null,
"e": 4263,
"s": 4136,
"text": "Reference: https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/math/BigInteger.html#divide(java.math.BigInteger)"
},
{
"code": null,
"e": 4276,
"s": 4263,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 4292,
"s": 4276,
"text": "Java-BigInteger"
},
{
"code": null,
"e": 4307,
"s": 4292,
"text": "Java-Functions"
},
{
"code": null,
"e": 4325,
"s": 4307,
"text": "Java-math-package"
},
{
"code": null,
"e": 4330,
"s": 4325,
"text": "Java"
},
{
"code": null,
"e": 4346,
"s": 4330,
"text": "Java-BigInteger"
},
{
"code": null,
"e": 4351,
"s": 4346,
"text": "Java"
},
{
"code": null,
"e": 4449,
"s": 4351,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4500,
"s": 4449,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 4531,
"s": 4500,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 4550,
"s": 4531,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 4580,
"s": 4550,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 4598,
"s": 4580,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 4618,
"s": 4598,
"text": "Collections in Java"
},
{
"code": null,
"e": 4633,
"s": 4618,
"text": "Stream In Java"
},
{
"code": null,
"e": 4665,
"s": 4633,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 4689,
"s": 4665,
"text": "Singleton Class in Java"
}
] |
How to submit form on pressing Enter with Angular 9? | 05 Nov, 2020
To submit a form in angular we have the following options:
Create a button to submit the form.Assign a key to submit the formOr we can do both.
Create a button to submit the form.
Assign a key to submit the form
Or we can do both.
In this tutorial, we will see how to use a specific key(Enter in this case) to submit a form.
Approach:
We can use angular keydown event to use Enter key as our submit key.
Add keydown directive inside the form tag.
Create a function to submit the form as soon as Enter is pressed.
Assign the keydown event to the function.
Example:
Let’s create a form having both, button and Enter key as mode of form submission.
We will use bootstrap classes, so add bootstrap scripts in your index.html.
html
<html lang="en"> <head> <meta charset="utf-8" /> <title>Tutorial</title> <!--add bootstrap script here--> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous" /> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> </head> <body> <app-root></app-root> </body></html>
code for the component:
javascript
import { Component } from '@angular/core';@Component({ selector: 'app-root',//here we used inline template format. template: ` <div style="text-align: center;"> <h1> {{title}} </h1></div> <!--using keydown to assign the event to call EnterSubmit method--> <form #geeksForm="ngForm" (keydown)="EnterSubmit($event, geeksForm.form)" (ngSubmit)="submitit(geeksForm.form);"> <button class="btn btn-primary" [disabled]="!geeksForm.valid"> Submit </button> <input type="text" class="form-control" name="geek-name" ngModel #geekname="ngModel" required minlength="5" /> <div *ngIf="geekname.errors.required"> The geek name is required </div> <div *ngIf="geekname.errors.minlength">The geek name should be at least {{ geekname.errors.minlength.requiredLength }} characters long </div> <select class="form-control" name="geek-type" ngModel #geeksField="ngModel" required> <option *ngFor="let geek of geeks" [value]="geek.id"> {{ geek.name }} </option> <div *ngIf="geeksField.touched && !geeksField.valid"> The category is required </div> `, styleUrls: [] }) export class AppComponent { title = 'Form submission tutorial'; public name = "geek"; geeks = [ {id: 1, name: "c++geek"}, {id: 2, name: "pythongeek"}, {id: 3, name: "javageek"}, {id: 4, name: "javascriptgeek"}, {id: 5, name: "angulargeek"} ]; /*assigning EnterSubmit function to keydown event and using Enter key to submit the form. */ //Function will take two parameters: //1.The key pressed. //2.form. EnterSubmit(event, form) { //keycode for Enter is 13 if (event.keyCode === 13) { alert('Enter key is pressed, form will be submitted');//calling submit method if key pressed is Enter. this.submitit(form); } } //function to submit the form submitit(form){ console.log(form.value);alert("The form was submitted"); form.reset(); } } </select></form>
Output:
bunnyram19
AngularJS-Misc
Picked
AngularJS
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": "\n05 Nov, 2020"
},
{
"code": null,
"e": 87,
"s": 28,
"text": "To submit a form in angular we have the following options:"
},
{
"code": null,
"e": 172,
"s": 87,
"text": "Create a button to submit the form.Assign a key to submit the formOr we can do both."
},
{
"code": null,
"e": 208,
"s": 172,
"text": "Create a button to submit the form."
},
{
"code": null,
"e": 240,
"s": 208,
"text": "Assign a key to submit the form"
},
{
"code": null,
"e": 259,
"s": 240,
"text": "Or we can do both."
},
{
"code": null,
"e": 353,
"s": 259,
"text": "In this tutorial, we will see how to use a specific key(Enter in this case) to submit a form."
},
{
"code": null,
"e": 363,
"s": 353,
"text": "Approach:"
},
{
"code": null,
"e": 433,
"s": 363,
"text": "We can use angular keydown event to use Enter key as our submit key. "
},
{
"code": null,
"e": 476,
"s": 433,
"text": "Add keydown directive inside the form tag."
},
{
"code": null,
"e": 542,
"s": 476,
"text": "Create a function to submit the form as soon as Enter is pressed."
},
{
"code": null,
"e": 584,
"s": 542,
"text": "Assign the keydown event to the function."
},
{
"code": null,
"e": 593,
"s": 584,
"text": "Example:"
},
{
"code": null,
"e": 675,
"s": 593,
"text": "Let’s create a form having both, button and Enter key as mode of form submission."
},
{
"code": null,
"e": 751,
"s": 675,
"text": "We will use bootstrap classes, so add bootstrap scripts in your index.html."
},
{
"code": null,
"e": 756,
"s": 751,
"text": "html"
},
{
"code": "<html lang=\"en\"> <head> <meta charset=\"utf-8\" /> <title>Tutorial</title> <!--add bootstrap script here--> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css\" integrity=\"sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm\" crossorigin=\"anonymous\" /> <script src=\"https://code.jquery.com/jquery-3.2.1.slim.min.js\" integrity=\"sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN\" crossorigin=\"anonymous\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js\" integrity=\"sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q\" crossorigin=\"anonymous\"></script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js\" integrity=\"sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl\" crossorigin=\"anonymous\"></script> </head> <body> <app-root></app-root> </body></html>",
"e": 1917,
"s": 756,
"text": null
},
{
"code": null,
"e": 1941,
"s": 1917,
"text": "code for the component:"
},
{
"code": null,
"e": 1952,
"s": 1941,
"text": "javascript"
},
{
"code": "import { Component } from '@angular/core';@Component({ selector: 'app-root',//here we used inline template format. template: ` <div style=\"text-align: center;\"> <h1> {{title}} </h1></div> <!--using keydown to assign the event to call EnterSubmit method--> <form #geeksForm=\"ngForm\" (keydown)=\"EnterSubmit($event, geeksForm.form)\" (ngSubmit)=\"submitit(geeksForm.form);\"> <button class=\"btn btn-primary\" [disabled]=\"!geeksForm.valid\"> Submit </button> <input type=\"text\" class=\"form-control\" name=\"geek-name\" ngModel #geekname=\"ngModel\" required minlength=\"5\" /> <div *ngIf=\"geekname.errors.required\"> The geek name is required </div> <div *ngIf=\"geekname.errors.minlength\">The geek name should be at least {{ geekname.errors.minlength.requiredLength }} characters long </div> <select class=\"form-control\" name=\"geek-type\" ngModel #geeksField=\"ngModel\" required> <option *ngFor=\"let geek of geeks\" [value]=\"geek.id\"> {{ geek.name }} </option> <div *ngIf=\"geeksField.touched && !geeksField.valid\"> The category is required </div> `, styleUrls: [] }) export class AppComponent { title = 'Form submission tutorial'; public name = \"geek\"; geeks = [ {id: 1, name: \"c++geek\"}, {id: 2, name: \"pythongeek\"}, {id: 3, name: \"javageek\"}, {id: 4, name: \"javascriptgeek\"}, {id: 5, name: \"angulargeek\"} ]; /*assigning EnterSubmit function to keydown event and using Enter key to submit the form. */ //Function will take two parameters: //1.The key pressed. //2.form. EnterSubmit(event, form) { //keycode for Enter is 13 if (event.keyCode === 13) { alert('Enter key is pressed, form will be submitted');//calling submit method if key pressed is Enter. this.submitit(form); } } //function to submit the form submitit(form){ console.log(form.value);alert(\"The form was submitted\"); form.reset(); } } </select></form>",
"e": 4045,
"s": 1952,
"text": null
},
{
"code": null,
"e": 4053,
"s": 4045,
"text": "Output:"
},
{
"code": null,
"e": 4064,
"s": 4053,
"text": "bunnyram19"
},
{
"code": null,
"e": 4079,
"s": 4064,
"text": "AngularJS-Misc"
},
{
"code": null,
"e": 4086,
"s": 4079,
"text": "Picked"
},
{
"code": null,
"e": 4096,
"s": 4086,
"text": "AngularJS"
},
{
"code": null,
"e": 4113,
"s": 4096,
"text": "Web Technologies"
}
] |
PHP | array_sum() Function | 09 Mar, 2018
The array_sum() function returns the sum of all the values in an array(one dimensional and associative). It takes an array parameter and returns the sum of all the values in it.
number array_sum ( $array )
ArgumentThe only argument to the function is the array whose sum needs to be calculated.
Return valueThis function returns the sum obtained after adding all the elements together. The returned sum may be integer or float. It also returns 0 if the array is empty.
Examples:
Input : $a = array(12, 24, 36, 48);
print_r(array_sum($a));
Output :120
Input : $a = array();
print_r(array_sum($a));
Output :0
In the first example the array calculates the sum of the elements of the array and returns it. In the second example the answer returned is 0 since the array is empty.
Program – 1
<?php//array whose sum is to be calculated$a = array(12, 24, 36, 48); //calculating sumprint_r(array_sum($a));?>
Output:
120
Program – 2
<?php//array whose sum is to be calculated$a = array(); //calculating sumprint_r(array_sum($a));?>
Output:
0
Program – 3
<?php// array whose sum is to be calculated$b = array("anti" => 1.42, "biotic" => 12.3, "charisma" => 73.4); // calculating sumprint_r(array_sum($b));?>
Output:
87.12
Thanks to HGaur for providing above examples.
PHP-array
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n09 Mar, 2018"
},
{
"code": null,
"e": 231,
"s": 53,
"text": "The array_sum() function returns the sum of all the values in an array(one dimensional and associative). It takes an array parameter and returns the sum of all the values in it."
},
{
"code": null,
"e": 260,
"s": 231,
"text": "number array_sum ( $array )\n"
},
{
"code": null,
"e": 349,
"s": 260,
"text": "ArgumentThe only argument to the function is the array whose sum needs to be calculated."
},
{
"code": null,
"e": 523,
"s": 349,
"text": "Return valueThis function returns the sum obtained after adding all the elements together. The returned sum may be integer or float. It also returns 0 if the array is empty."
},
{
"code": null,
"e": 533,
"s": 523,
"text": "Examples:"
},
{
"code": null,
"e": 679,
"s": 533,
"text": "Input : $a = array(12, 24, 36, 48);\n print_r(array_sum($a));\nOutput :120\n\nInput : $a = array();\n print_r(array_sum($a));\nOutput :0\n"
},
{
"code": null,
"e": 847,
"s": 679,
"text": "In the first example the array calculates the sum of the elements of the array and returns it. In the second example the answer returned is 0 since the array is empty."
},
{
"code": null,
"e": 859,
"s": 847,
"text": "Program – 1"
},
{
"code": "<?php//array whose sum is to be calculated$a = array(12, 24, 36, 48); //calculating sumprint_r(array_sum($a));?>",
"e": 973,
"s": 859,
"text": null
},
{
"code": null,
"e": 981,
"s": 973,
"text": "Output:"
},
{
"code": null,
"e": 986,
"s": 981,
"text": "120\n"
},
{
"code": null,
"e": 998,
"s": 986,
"text": "Program – 2"
},
{
"code": "<?php//array whose sum is to be calculated$a = array(); //calculating sumprint_r(array_sum($a));?>",
"e": 1098,
"s": 998,
"text": null
},
{
"code": null,
"e": 1106,
"s": 1098,
"text": "Output:"
},
{
"code": null,
"e": 1109,
"s": 1106,
"text": "0\n"
},
{
"code": null,
"e": 1121,
"s": 1109,
"text": "Program – 3"
},
{
"code": "<?php// array whose sum is to be calculated$b = array(\"anti\" => 1.42, \"biotic\" => 12.3, \"charisma\" => 73.4); // calculating sumprint_r(array_sum($b));?>",
"e": 1275,
"s": 1121,
"text": null
},
{
"code": null,
"e": 1283,
"s": 1275,
"text": "Output:"
},
{
"code": null,
"e": 1290,
"s": 1283,
"text": "87.12\n"
},
{
"code": null,
"e": 1336,
"s": 1290,
"text": "Thanks to HGaur for providing above examples."
},
{
"code": null,
"e": 1346,
"s": 1336,
"text": "PHP-array"
},
{
"code": null,
"e": 1359,
"s": 1346,
"text": "PHP-function"
},
{
"code": null,
"e": 1363,
"s": 1359,
"text": "PHP"
},
{
"code": null,
"e": 1380,
"s": 1363,
"text": "Web Technologies"
},
{
"code": null,
"e": 1384,
"s": 1380,
"text": "PHP"
}
] |
How to Install Apache JMeter on Linux? | 06 Oct, 2021
In this article, we will see how to install Apache JMeter in Linux. Here we will use Ubuntu which is a Linux distribution based on Debian and composed mostly of free and open-source software. JMeter is developed by Java so it is necessary to have java 8 or higher version on your computer.
Checking Java Version:
Use java –version or javac –version to check if java is already installed on your computer or not.
$ java --version
If you get the same message then skip step 2 i.e. installation of java and move to step 3.
If you get “java not found” in output, so first install Java.
Step 1: Use the following command to install openjdk – 11-jre.
$ sudo apt install openjdk-11-jre-headless
Then enter the sudo password and enter “Y” to confirm the download.
It will take some time according to your internet speed.
Step 2: Use the following command to install openjdk-11-jdk.
$ sudo apt install openjdk-11-jdk-headless
Step 3: If download completes then check again using java –version command.
First, we will download the latest JMeter version from the official JMeter website. Go to the given link and click on the “apache-jmeter-5.4.1.zip” link to download the binary zip file of JMeter.
After clicking on the zip file a dialog box will appear and check the save file box and click ok. It will start the download.
The file will be placed in the Downloads folder. Open the folder, right-click on the zip file and click on Extract here.
Now we have successfully downloaded the JMeter and extracted it.
Open the terminal and use the following command to go to the directory from where we can run JMeter
$ cd Downloads/apache-jmeter-5.4.1/bin
Cd stands for change directory, a Linux command to move between directories.
Run the following command to start the JMeter.
$ ./jmeter
This will look like this.
how-to-install
Picked
How To
Installation Guide
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Set Git Username and Password in GitBash?
How to Install Jupyter Notebook on MacOS?
How to Install and Use NVM on Windows?
How to Install Python Packages for AWS Lambda Layers?
How to Install Git in VS Code?
Installation of Node.js on Linux
Installation of Node.js on Windows
How to Install Jupyter Notebook on MacOS?
How to Install and Use NVM on Windows?
How to Install Pygame on Windows ? | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n06 Oct, 2021"
},
{
"code": null,
"e": 344,
"s": 53,
"text": "In this article, we will see how to install Apache JMeter in Linux. Here we will use Ubuntu which is a Linux distribution based on Debian and composed mostly of free and open-source software. JMeter is developed by Java so it is necessary to have java 8 or higher version on your computer."
},
{
"code": null,
"e": 367,
"s": 344,
"text": "Checking Java Version:"
},
{
"code": null,
"e": 466,
"s": 367,
"text": "Use java –version or javac –version to check if java is already installed on your computer or not."
},
{
"code": null,
"e": 483,
"s": 466,
"text": "$ java --version"
},
{
"code": null,
"e": 574,
"s": 483,
"text": "If you get the same message then skip step 2 i.e. installation of java and move to step 3."
},
{
"code": null,
"e": 636,
"s": 574,
"text": "If you get “java not found” in output, so first install Java."
},
{
"code": null,
"e": 699,
"s": 636,
"text": "Step 1: Use the following command to install openjdk – 11-jre."
},
{
"code": null,
"e": 742,
"s": 699,
"text": "$ sudo apt install openjdk-11-jre-headless"
},
{
"code": null,
"e": 811,
"s": 742,
"text": "Then enter the sudo password and enter “Y” to confirm the download. "
},
{
"code": null,
"e": 868,
"s": 811,
"text": "It will take some time according to your internet speed."
},
{
"code": null,
"e": 929,
"s": 868,
"text": "Step 2: Use the following command to install openjdk-11-jdk."
},
{
"code": null,
"e": 972,
"s": 929,
"text": "$ sudo apt install openjdk-11-jdk-headless"
},
{
"code": null,
"e": 1048,
"s": 972,
"text": "Step 3: If download completes then check again using java –version command."
},
{
"code": null,
"e": 1244,
"s": 1048,
"text": "First, we will download the latest JMeter version from the official JMeter website. Go to the given link and click on the “apache-jmeter-5.4.1.zip” link to download the binary zip file of JMeter."
},
{
"code": null,
"e": 1370,
"s": 1244,
"text": "After clicking on the zip file a dialog box will appear and check the save file box and click ok. It will start the download."
},
{
"code": null,
"e": 1491,
"s": 1370,
"text": "The file will be placed in the Downloads folder. Open the folder, right-click on the zip file and click on Extract here."
},
{
"code": null,
"e": 1556,
"s": 1491,
"text": "Now we have successfully downloaded the JMeter and extracted it."
},
{
"code": null,
"e": 1656,
"s": 1556,
"text": "Open the terminal and use the following command to go to the directory from where we can run JMeter"
},
{
"code": null,
"e": 1695,
"s": 1656,
"text": "$ cd Downloads/apache-jmeter-5.4.1/bin"
},
{
"code": null,
"e": 1772,
"s": 1695,
"text": "Cd stands for change directory, a Linux command to move between directories."
},
{
"code": null,
"e": 1819,
"s": 1772,
"text": "Run the following command to start the JMeter."
},
{
"code": null,
"e": 1830,
"s": 1819,
"text": "$ ./jmeter"
},
{
"code": null,
"e": 1856,
"s": 1830,
"text": "This will look like this."
},
{
"code": null,
"e": 1871,
"s": 1856,
"text": "how-to-install"
},
{
"code": null,
"e": 1878,
"s": 1871,
"text": "Picked"
},
{
"code": null,
"e": 1885,
"s": 1878,
"text": "How To"
},
{
"code": null,
"e": 1904,
"s": 1885,
"text": "Installation Guide"
},
{
"code": null,
"e": 1915,
"s": 1904,
"text": "Linux-Unix"
},
{
"code": null,
"e": 2013,
"s": 1915,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2062,
"s": 2013,
"text": "How to Set Git Username and Password in GitBash?"
},
{
"code": null,
"e": 2104,
"s": 2062,
"text": "How to Install Jupyter Notebook on MacOS?"
},
{
"code": null,
"e": 2143,
"s": 2104,
"text": "How to Install and Use NVM on Windows?"
},
{
"code": null,
"e": 2197,
"s": 2143,
"text": "How to Install Python Packages for AWS Lambda Layers?"
},
{
"code": null,
"e": 2228,
"s": 2197,
"text": "How to Install Git in VS Code?"
},
{
"code": null,
"e": 2261,
"s": 2228,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2296,
"s": 2261,
"text": "Installation of Node.js on Windows"
},
{
"code": null,
"e": 2338,
"s": 2296,
"text": "How to Install Jupyter Notebook on MacOS?"
},
{
"code": null,
"e": 2377,
"s": 2338,
"text": "How to Install and Use NVM on Windows?"
}
] |
Perl | Comparing Scalars | 06 Jan, 2022
Perl has two types of comparison operator sets. Just like other mathematical operators, instead of performing operations, these operators compare scalars. There are two types of sets of Perl comparison operators.
One is for numeric scalar values and one is for string scalar values. Both the types are illustrated in below table:
Explanations for above Numeric and String Scalars Comparison Operators:
== and eq: This operator is used to check the equality. In the following code, outputs of codes after using == and eq are compared and show how it works for numeric and string scalars differently.Example 1:
Perl
# Perl program to illustrate# == operator # taking two numeric scalars$x = 5;$y = 5; # using "==" operatorif($x == $y){ print "== works with numeric value!";}
Output:
== works with numeric value!
Example 2:
Perl
# Perl program to illustrate# == and eq operator # string scalar$str = "geekforgeeks"; if($str == "GEEKSFORGEEKS"){ print "== doesn't work with string values!"; } # comparing with capital stringif($str eq "GEEKSFORGEEKS"){ print "eq works with string values!";}
Output:
== doesn't work with string values!
Explanation: In the output of example 2, the Last print statement will not be executed because $str and GEEKSFORGEEKS aren’t equal. Also, ASCII codes of ‘g’ and ‘G’ are different. Hence, == works fine for numeric values but fails in the case of string values and eq works fine for String scalars only.
!= and neIn the following code there is a comparison of outputs after using != and ne and showed which one works properly for string and which one works properly for numeric scalar values.Example 1:
Perl
# Perl program to demonstrate the # != operator # numeric scalars$x = 5;$y = 10; # using != operatorif($x != $y){ print "!= works with numeric value!";}
Output:
!= works with numeric value!
Example 2:
Perl
# Perl program to demonstrate the # != and ne operator # string scalar$str = "geekforgeeks"; # using != operatorif($str != "GEEKSFORGEEKS"){ print "\n!= doesn't work with string values!"; } # comparing with capital stringif($str ne "GEEKSFORGEEKS"){ print"ne works with string values!";}
Output:
ne works with string values!
Explanation: In the second example, the first print statement will not be executed because != converts both strings to 0. Hence, != works fine for numeric values but fails in the case of string values and ne works fine for string scalars.
(> or gt) And (< or lt)In the below codes, we will compare outputs after using (> or gt) and (< or lt) and will see which one works properly for string and which one works properly for numeric scalar values.Example 1:
Perl
# Perl program to demonstrate the # (> or gt) And (< or lt)# operator # numeric scalars$x = 4;$y = 5; # using (> or gt) And (< or lt)if(($x < $y) and ($x lt $y) ){ print "< and lt works with numeric value!";} if(($y > $x) and ($y gt $x) ){ print "\n> and gt works with numeric value!";}
Output:
< and lt works with numeric value!
> and gt works with numeric value!
Example 2:
Perl
# Perl program to demonstrate the # (> or gt) And (< or lt)# operator # string scalar$str = "geekforgeeks"; if($str < "GEEKSFORGEEKS"){ print "< doesn't work with string values!";} # comparing with capital stringif($str lt "GEEKSFORGEEKSZZZ"){ print"lt works with string values!";} # comparing with capital stringif($str gt "GEEKSFORGEEKSZZZ"){ print"gt works with string values!";} # comparing with capital stringif($str lt "kEEKSFORGEEKS"){ print"\nlt works with string values!";}
Output:
gt works with string values!
lt works with string values!
Explanation: The above code tells us some interesting things about how Perl works with strings. The first example’s output is very obvious since both string and numeric operators treat Numeric scalars the same way. But in the second Output, the “lt” didn’t behave as we expected. Let’s say the Perl “lt” operator is not case sensitive, but we even put “ZZZ” after that and even in that case $str is not less than the string in quotes and the next output showed that it was greater. This point can be clear from the second line of the second example’s output Perl’s string operator only first check the first character of String and compares ASCII codes. Since block letters come first in the ASCII table. The Perl compiler matched the first letter and then matched the rest.
(>= or ge) And (<= or le) These operators also work on the ASCII values which are checked in the case of string operators. The value is checked in the case of numeric operators.Example:
Perl
# Perl program to demonstrate the # (>= or ge) And (<= or le)# operator # numeric scalars$x = 5;$y = 10; if(($x <= $y) and ($y >= $x)){ print "<= and>= works";} # string scalar$str= "geeksforgeeks"; if (($str le "keeksforgeeks") and ($str ge "feeksforgeeks")){ print "\nle and ge works!";}
Output:
<= and>= works
le and ge works!
Important Points to Remember:
The numeric operator will always convert String values to 0. When we compare two string scalars with Numeric operators like ==, >= or <= then it will always convert the scalars to 0 or 0.0. Since they are not string. And hence it will be true in case of ==, >= or <= as shown in the below example:
Perl
# Perl program to illustrate # above point # numeric scalars$x = "BBB";$y = "aaa"; if (($x == $y and ($x <= $y) and ($x >= $y))){ print "True";}
Output:
True
Explanation: In the above code “aaa” is less than BBB in every aspect (Lower case and also ASCII of a is greater than B) but still both strings will be equal since the numeric comparison operator converted the string to 0.
The string operator doesn’t compare numeric values, instead, it compares their ASCII values. String operators compare ASCII values for numeric values. In the following example “9 gt 17” is true but “17 gt 9” will give the result as false.
Perl
# Perl program to illustrate # above point # numeric scalar$x = 9;$y = 17; if ($x gt $y){ print "True";}
Output:
True
shubham_singh
chhabradhanvi
perl-basics
Perl-Scalars
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Jan, 2022"
},
{
"code": null,
"e": 242,
"s": 28,
"text": "Perl has two types of comparison operator sets. Just like other mathematical operators, instead of performing operations, these operators compare scalars. There are two types of sets of Perl comparison operators. "
},
{
"code": null,
"e": 360,
"s": 242,
"text": "One is for numeric scalar values and one is for string scalar values. Both the types are illustrated in below table: "
},
{
"code": null,
"e": 433,
"s": 360,
"text": "Explanations for above Numeric and String Scalars Comparison Operators: "
},
{
"code": null,
"e": 641,
"s": 433,
"text": "== and eq: This operator is used to check the equality. In the following code, outputs of codes after using == and eq are compared and show how it works for numeric and string scalars differently.Example 1: "
},
{
"code": null,
"e": 646,
"s": 641,
"text": "Perl"
},
{
"code": "# Perl program to illustrate# == operator # taking two numeric scalars$x = 5;$y = 5; # using \"==\" operatorif($x == $y){ print \"== works with numeric value!\";}",
"e": 812,
"s": 646,
"text": null
},
{
"code": null,
"e": 821,
"s": 812,
"text": "Output: "
},
{
"code": null,
"e": 850,
"s": 821,
"text": "== works with numeric value!"
},
{
"code": null,
"e": 861,
"s": 850,
"text": "Example 2:"
},
{
"code": null,
"e": 866,
"s": 861,
"text": "Perl"
},
{
"code": "# Perl program to illustrate# == and eq operator # string scalar$str = \"geekforgeeks\"; if($str == \"GEEKSFORGEEKS\"){ print \"== doesn't work with string values!\"; } # comparing with capital stringif($str eq \"GEEKSFORGEEKS\"){ print \"eq works with string values!\";}",
"e": 1142,
"s": 866,
"text": null
},
{
"code": null,
"e": 1151,
"s": 1142,
"text": "Output: "
},
{
"code": null,
"e": 1187,
"s": 1151,
"text": "== doesn't work with string values!"
},
{
"code": null,
"e": 1489,
"s": 1187,
"text": "Explanation: In the output of example 2, the Last print statement will not be executed because $str and GEEKSFORGEEKS aren’t equal. Also, ASCII codes of ‘g’ and ‘G’ are different. Hence, == works fine for numeric values but fails in the case of string values and eq works fine for String scalars only."
},
{
"code": null,
"e": 1688,
"s": 1489,
"text": "!= and neIn the following code there is a comparison of outputs after using != and ne and showed which one works properly for string and which one works properly for numeric scalar values.Example 1:"
},
{
"code": null,
"e": 1693,
"s": 1688,
"text": "Perl"
},
{
"code": "# Perl program to demonstrate the # != operator # numeric scalars$x = 5;$y = 10; # using != operatorif($x != $y){ print \"!= works with numeric value!\";}",
"e": 1853,
"s": 1693,
"text": null
},
{
"code": null,
"e": 1862,
"s": 1853,
"text": "Output: "
},
{
"code": null,
"e": 1891,
"s": 1862,
"text": "!= works with numeric value!"
},
{
"code": null,
"e": 1902,
"s": 1891,
"text": "Example 2:"
},
{
"code": null,
"e": 1907,
"s": 1902,
"text": "Perl"
},
{
"code": "# Perl program to demonstrate the # != and ne operator # string scalar$str = \"geekforgeeks\"; # using != operatorif($str != \"GEEKSFORGEEKS\"){ print \"\\n!= doesn't work with string values!\"; } # comparing with capital stringif($str ne \"GEEKSFORGEEKS\"){ print\"ne works with string values!\";}",
"e": 2209,
"s": 1907,
"text": null
},
{
"code": null,
"e": 2218,
"s": 2209,
"text": "Output: "
},
{
"code": null,
"e": 2247,
"s": 2218,
"text": "ne works with string values!"
},
{
"code": null,
"e": 2486,
"s": 2247,
"text": "Explanation: In the second example, the first print statement will not be executed because != converts both strings to 0. Hence, != works fine for numeric values but fails in the case of string values and ne works fine for string scalars."
},
{
"code": null,
"e": 2704,
"s": 2486,
"text": "(> or gt) And (< or lt)In the below codes, we will compare outputs after using (> or gt) and (< or lt) and will see which one works properly for string and which one works properly for numeric scalar values.Example 1:"
},
{
"code": null,
"e": 2709,
"s": 2704,
"text": "Perl"
},
{
"code": "# Perl program to demonstrate the # (> or gt) And (< or lt)# operator # numeric scalars$x = 4;$y = 5; # using (> or gt) And (< or lt)if(($x < $y) and ($x lt $y) ){ print \"< and lt works with numeric value!\";} if(($y > $x) and ($y gt $x) ){ print \"\\n> and gt works with numeric value!\";}",
"e": 3008,
"s": 2709,
"text": null
},
{
"code": null,
"e": 3017,
"s": 3008,
"text": "Output: "
},
{
"code": null,
"e": 3087,
"s": 3017,
"text": "< and lt works with numeric value!\n> and gt works with numeric value!"
},
{
"code": null,
"e": 3098,
"s": 3087,
"text": "Example 2:"
},
{
"code": null,
"e": 3103,
"s": 3098,
"text": "Perl"
},
{
"code": "# Perl program to demonstrate the # (> or gt) And (< or lt)# operator # string scalar$str = \"geekforgeeks\"; if($str < \"GEEKSFORGEEKS\"){ print \"< doesn't work with string values!\";} # comparing with capital stringif($str lt \"GEEKSFORGEEKSZZZ\"){ print\"lt works with string values!\";} # comparing with capital stringif($str gt \"GEEKSFORGEEKSZZZ\"){ print\"gt works with string values!\";} # comparing with capital stringif($str lt \"kEEKSFORGEEKS\"){ print\"\\nlt works with string values!\";}",
"e": 3608,
"s": 3103,
"text": null
},
{
"code": null,
"e": 3617,
"s": 3608,
"text": "Output: "
},
{
"code": null,
"e": 3675,
"s": 3617,
"text": "gt works with string values!\nlt works with string values!"
},
{
"code": null,
"e": 4450,
"s": 3675,
"text": "Explanation: The above code tells us some interesting things about how Perl works with strings. The first example’s output is very obvious since both string and numeric operators treat Numeric scalars the same way. But in the second Output, the “lt” didn’t behave as we expected. Let’s say the Perl “lt” operator is not case sensitive, but we even put “ZZZ” after that and even in that case $str is not less than the string in quotes and the next output showed that it was greater. This point can be clear from the second line of the second example’s output Perl’s string operator only first check the first character of String and compares ASCII codes. Since block letters come first in the ASCII table. The Perl compiler matched the first letter and then matched the rest."
},
{
"code": null,
"e": 4636,
"s": 4450,
"text": "(>= or ge) And (<= or le) These operators also work on the ASCII values which are checked in the case of string operators. The value is checked in the case of numeric operators.Example:"
},
{
"code": null,
"e": 4641,
"s": 4636,
"text": "Perl"
},
{
"code": "# Perl program to demonstrate the # (>= or ge) And (<= or le)# operator # numeric scalars$x = 5;$y = 10; if(($x <= $y) and ($y >= $x)){ print \"<= and>= works\";} # string scalar$str= \"geeksforgeeks\"; if (($str le \"keeksforgeeks\") and ($str ge \"feeksforgeeks\")){ print \"\\nle and ge works!\";}",
"e": 4945,
"s": 4641,
"text": null
},
{
"code": null,
"e": 4954,
"s": 4945,
"text": "Output: "
},
{
"code": null,
"e": 4986,
"s": 4954,
"text": "<= and>= works\nle and ge works!"
},
{
"code": null,
"e": 5016,
"s": 4986,
"text": "Important Points to Remember:"
},
{
"code": null,
"e": 5315,
"s": 5016,
"text": "The numeric operator will always convert String values to 0. When we compare two string scalars with Numeric operators like ==, >= or <= then it will always convert the scalars to 0 or 0.0. Since they are not string. And hence it will be true in case of ==, >= or <= as shown in the below example: "
},
{
"code": null,
"e": 5320,
"s": 5315,
"text": "Perl"
},
{
"code": "# Perl program to illustrate # above point # numeric scalars$x = \"BBB\";$y = \"aaa\"; if (($x == $y and ($x <= $y) and ($x >= $y))){ print \"True\";}",
"e": 5472,
"s": 5320,
"text": null
},
{
"code": null,
"e": 5481,
"s": 5472,
"text": "Output: "
},
{
"code": null,
"e": 5486,
"s": 5481,
"text": "True"
},
{
"code": null,
"e": 5710,
"s": 5486,
"text": "Explanation: In the above code “aaa” is less than BBB in every aspect (Lower case and also ASCII of a is greater than B) but still both strings will be equal since the numeric comparison operator converted the string to 0. "
},
{
"code": null,
"e": 5950,
"s": 5710,
"text": "The string operator doesn’t compare numeric values, instead, it compares their ASCII values. String operators compare ASCII values for numeric values. In the following example “9 gt 17” is true but “17 gt 9” will give the result as false. "
},
{
"code": null,
"e": 5955,
"s": 5950,
"text": "Perl"
},
{
"code": "# Perl program to illustrate # above point # numeric scalar$x = 9;$y = 17; if ($x gt $y){ print \"True\";}",
"e": 6067,
"s": 5955,
"text": null
},
{
"code": null,
"e": 6076,
"s": 6067,
"text": "Output: "
},
{
"code": null,
"e": 6081,
"s": 6076,
"text": "True"
},
{
"code": null,
"e": 6095,
"s": 6081,
"text": "shubham_singh"
},
{
"code": null,
"e": 6109,
"s": 6095,
"text": "chhabradhanvi"
},
{
"code": null,
"e": 6121,
"s": 6109,
"text": "perl-basics"
},
{
"code": null,
"e": 6134,
"s": 6121,
"text": "Perl-Scalars"
},
{
"code": null,
"e": 6139,
"s": 6134,
"text": "Perl"
},
{
"code": null,
"e": 6144,
"s": 6139,
"text": "Perl"
}
] |
Dora module in Python | 11 Oct, 2020
Dora is a library designed to simplify the exploratory data analysis which is such a painful part. It automates the repetitive tasks that consume most of the time.
The library has functions that are very convenient for data cleaning, visualization, feature extraction and selection, visualization. Apart from this, it is also used for model validation by partitioning data, and transformations of data.
This library uses scikit-learn, pandas, and matplotlib. The intention of this library is to add additional features to general library mentioned before for exploratory data analysis.
Installation:
pip install Dora
Usage:
In-order to implement it in datasets use the below syntax:
Python3
from Dora import Dora
It can be used for :
Reading Data & Configuration
Cleaning
Feature Selection & Extraction
Visualization
Model Validation
Data Versioning
Below is the most basic implementation of Dora module on a dataset in Python:
Python
# Import required modulefrom Dora import Dora # Create objectdora = Dora() # Add dataset path as argument dora.configure(output = 'A', data = 'data.csv') # Display datasetdora.data
Output:
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Convert integer to string in Python
Python | os.path.join() method
Create a Pandas DataFrame from Lists
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python OOPs Concepts
How To Convert Python Dictionary To JSON? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Oct, 2020"
},
{
"code": null,
"e": 193,
"s": 28,
"text": "Dora is a library designed to simplify the exploratory data analysis which is such a painful part. It automates the repetitive tasks that consume most of the time. "
},
{
"code": null,
"e": 432,
"s": 193,
"text": "The library has functions that are very convenient for data cleaning, visualization, feature extraction and selection, visualization. Apart from this, it is also used for model validation by partitioning data, and transformations of data."
},
{
"code": null,
"e": 616,
"s": 432,
"text": "This library uses scikit-learn, pandas, and matplotlib. The intention of this library is to add additional features to general library mentioned before for exploratory data analysis. "
},
{
"code": null,
"e": 630,
"s": 616,
"text": "Installation:"
},
{
"code": null,
"e": 648,
"s": 630,
"text": "pip install Dora\n"
},
{
"code": null,
"e": 655,
"s": 648,
"text": "Usage:"
},
{
"code": null,
"e": 714,
"s": 655,
"text": "In-order to implement it in datasets use the below syntax:"
},
{
"code": null,
"e": 722,
"s": 714,
"text": "Python3"
},
{
"code": "from Dora import Dora",
"e": 744,
"s": 722,
"text": null
},
{
"code": null,
"e": 765,
"s": 744,
"text": "It can be used for :"
},
{
"code": null,
"e": 794,
"s": 765,
"text": "Reading Data & Configuration"
},
{
"code": null,
"e": 803,
"s": 794,
"text": "Cleaning"
},
{
"code": null,
"e": 834,
"s": 803,
"text": "Feature Selection & Extraction"
},
{
"code": null,
"e": 848,
"s": 834,
"text": "Visualization"
},
{
"code": null,
"e": 865,
"s": 848,
"text": "Model Validation"
},
{
"code": null,
"e": 881,
"s": 865,
"text": "Data Versioning"
},
{
"code": null,
"e": 960,
"s": 881,
"text": "Below is the most basic implementation of Dora module on a dataset in Python: "
},
{
"code": null,
"e": 967,
"s": 960,
"text": "Python"
},
{
"code": "# Import required modulefrom Dora import Dora # Create objectdora = Dora() # Add dataset path as argument dora.configure(output = 'A', data = 'data.csv') # Display datasetdora.data",
"e": 1152,
"s": 967,
"text": null
},
{
"code": null,
"e": 1160,
"s": 1152,
"text": "Output:"
},
{
"code": null,
"e": 1175,
"s": 1160,
"text": "python-modules"
},
{
"code": null,
"e": 1182,
"s": 1175,
"text": "Python"
},
{
"code": null,
"e": 1280,
"s": 1182,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1312,
"s": 1280,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1341,
"s": 1312,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 1368,
"s": 1341,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1404,
"s": 1368,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 1435,
"s": 1404,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1472,
"s": 1435,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 1495,
"s": 1472,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1551,
"s": 1495,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1572,
"s": 1551,
"text": "Python OOPs Concepts"
}
] |
C++ Program to Find Largest Element of an Array | An array contains multiple elements and the largest element in an array is the one that is greater than other elements.
For example.
In the above array, 7 is the largest element and it is at index 2.
A program to find the largest element of an array is given as follows.
Live Demo
#include <iostream>
using namespace std;
int main() {
int a[] = {4, 9, 1, 3, 8};
int largest, i, pos;
largest = a[0];
for(i=1; i<5; i++) {
if(a[i]>largest) {
largest = a[i];
pos = i;
}
}
cout<<"The largest element in the array is "<<largest<<" and it is at index "<<pos;
return 0;
}
The largest element in the array is 9 and it is at index 1
In the above program, a[] is the array that contains 5 elements. The variable largest will store the largest element of the array.
Initially largest stores the first element of the array. Then a for loop is started which runs from the index 1 to n. For each iteration of the loop, the value of largest is compared with a[i]. If a[i] is greater than largest, then that value is stored in largest. And the corresponding value of i is stored in pos.
This is demonstrated by the following code snippet.
for(i=1; i<5; i++) {
if(a[i]>largest) {
largest = a[i];
pos = i;
}
}
After this, the value of the largest element in the array and its position is printed.
This is shown as follows −
cout<<"The largest element in the array is "<<largest<<" and it is at index "<<pos; | [
{
"code": null,
"e": 1182,
"s": 1062,
"text": "An array contains multiple elements and the largest element in an array is the one that is greater than other elements."
},
{
"code": null,
"e": 1195,
"s": 1182,
"text": "For example."
},
{
"code": null,
"e": 1262,
"s": 1195,
"text": "In the above array, 7 is the largest element and it is at index 2."
},
{
"code": null,
"e": 1333,
"s": 1262,
"text": "A program to find the largest element of an array is given as follows."
},
{
"code": null,
"e": 1344,
"s": 1333,
"text": " Live Demo"
},
{
"code": null,
"e": 1678,
"s": 1344,
"text": "#include <iostream>\nusing namespace std;\nint main() {\n int a[] = {4, 9, 1, 3, 8};\n int largest, i, pos;\n largest = a[0];\n for(i=1; i<5; i++) {\n if(a[i]>largest) {\n largest = a[i];\n pos = i;\n }\n }\n cout<<\"The largest element in the array is \"<<largest<<\" and it is at index \"<<pos;\n return 0;\n}"
},
{
"code": null,
"e": 1737,
"s": 1678,
"text": "The largest element in the array is 9 and it is at index 1"
},
{
"code": null,
"e": 1868,
"s": 1737,
"text": "In the above program, a[] is the array that contains 5 elements. The variable largest will store the largest element of the array."
},
{
"code": null,
"e": 2184,
"s": 1868,
"text": "Initially largest stores the first element of the array. Then a for loop is started which runs from the index 1 to n. For each iteration of the loop, the value of largest is compared with a[i]. If a[i] is greater than largest, then that value is stored in largest. And the corresponding value of i is stored in pos."
},
{
"code": null,
"e": 2236,
"s": 2184,
"text": "This is demonstrated by the following code snippet."
},
{
"code": null,
"e": 2323,
"s": 2236,
"text": "for(i=1; i<5; i++) {\n if(a[i]>largest) {\n largest = a[i];\n pos = i;\n }\n}"
},
{
"code": null,
"e": 2410,
"s": 2323,
"text": "After this, the value of the largest element in the array and its position is printed."
},
{
"code": null,
"e": 2437,
"s": 2410,
"text": "This is shown as follows −"
},
{
"code": null,
"e": 2521,
"s": 2437,
"text": "cout<<\"The largest element in the array is \"<<largest<<\" and it is at index \"<<pos;"
}
] |
Area of intersection of two circles | Practice | GeeksforGeeks | Given the coordinates of the centres of two circles (X1, Y1) and (X2, Y2) as well as the radii of the respective circles R1 and R2.Find the floor of the area of their intersection.
Note: Use the value of Pi as 3.14
Example 1:
Input:
X1=0,Y1=0,R1=4
X2=6,Y2=0,R2=4
Output:
7
Explanation:
The intersecting area equals 7.25298806.
So,Answer is 7.
Example 2:
Input:
X1=0,Y1=0,R1=5
X2=11,Y2=0,R2=5
Output:
0
Explanation:
The circles don't intersect.
Your Task:
You don't need to read input or print anything. Your task is to complete the function intersectionArea() which takes the coordinates of the centers as well as the radii(X1, Y1, R1, X2, Y2, R2) as input parameters and returns the area of intersection of the two circles.
Expected Time Complexity:O(LogN)
Expected Auxillary Space:O(1)
Constraints:
-109<=X1,Y1,X2,Y2<=109
1<=R1,R2<=109
-4
Naveen Kotha8 months ago
Naveen Kotha
long double Pi = 3.14; long double d, alpha, beta, a1, a2; long long int ans; d = sqrt((X2 - X1) * (X2 - X1) + (Y2 - Y1) * (Y2 - Y1));
if (d > R1 + R2) ans = 0; else if (d <= abs(R2 - R1) && R1 >= R2) ans = floor(Pi * R2 * R2);
else if (d <= abs(R2 - R1) && R2 >= R1) ans = floor(Pi * R1 * R1);
else { alpha = acos((R1 * R1 + d * d - R2 * R2) / (2 * R1 * d)) * 2; beta = acos((R2 * R2 + d * d - R1 * R1) / (2 * R2 * d)) * 2; a1 = 0.5 * beta * R2 * R2 - 0.5 * R2 * R2 * sin(beta); a2 = 0.5 * alpha * R1 * R1 - 0.5 * R1 * R1 * sin(alpha); ans = floor(a1 + a2); } return ans;
-1
Hazem5 years ago
Hazem
There are three more cases not mentioned in the solution here http://code.geeksforgeeks.o... (and by the way, most solutions I found online). They are:
- d is less than one radius but larger than the other- d is less than both radii
In either case, one circle is almost inside the other. The intersection area is then the area of the smaller circle minus the difference of the circular segments (i.e. minus area(r1,r2,d)-area(r2,r1,d))
0
Quandray5 years ago
Quandray
Input:-11786939 388749051 844435993 -11696460 388789113 844535886
Its Correct output is:2240182216213578196
And Your Output is:2240182216213578283
For this test case, the smaller circle is inside the larger, so the overlap is the area of the smaller circle. 844435993*844435993*pi.I make that 2240182216213578283.58.
In my code I have the lineconst long double pi=3.1415926535897932384L;With that line, I get the answer 2240182216213578283If I remove the L from the end of that line, pi is shortened and I get the expected, but wrong, answer 2240182216213578196.Please can someone correct this.
-2
张昆玮6 years ago
张昆玮
I think my solution is correct. http://code.geeksforgeeks.o... . How can you show the expected output is more accurate than my solution?
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab. | [
{
"code": null,
"e": 441,
"s": 226,
"text": "Given the coordinates of the centres of two circles (X1, Y1) and (X2, Y2) as well as the radii of the respective circles R1 and R2.Find the floor of the area of their intersection.\nNote: Use the value of Pi as 3.14"
},
{
"code": null,
"e": 452,
"s": 441,
"text": "Example 1:"
},
{
"code": null,
"e": 569,
"s": 452,
"text": "Input:\nX1=0,Y1=0,R1=4\nX2=6,Y2=0,R2=4\nOutput:\n7\nExplanation:\nThe intersecting area equals 7.25298806.\nSo,Answer is 7."
},
{
"code": null,
"e": 580,
"s": 569,
"text": "Example 2:"
},
{
"code": null,
"e": 670,
"s": 580,
"text": "Input:\nX1=0,Y1=0,R1=5\nX2=11,Y2=0,R2=5\nOutput:\n0\nExplanation:\nThe circles don't intersect."
},
{
"code": null,
"e": 952,
"s": 670,
"text": "\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function intersectionArea() which takes the coordinates of the centers as well as the radii(X1, Y1, R1, X2, Y2, R2) as input parameters and returns the area of intersection of the two circles."
},
{
"code": null,
"e": 1016,
"s": 952,
"text": "\nExpected Time Complexity:O(LogN)\nExpected Auxillary Space:O(1)"
},
{
"code": null,
"e": 1067,
"s": 1016,
"text": "\nConstraints:\n-109<=X1,Y1,X2,Y2<=109\n1<=R1,R2<=109"
},
{
"code": null,
"e": 1070,
"s": 1067,
"text": "-4"
},
{
"code": null,
"e": 1095,
"s": 1070,
"text": "Naveen Kotha8 months ago"
},
{
"code": null,
"e": 1108,
"s": 1095,
"text": "Naveen Kotha"
},
{
"code": null,
"e": 1264,
"s": 1108,
"text": "long double Pi = 3.14; long double d, alpha, beta, a1, a2; long long int ans; d = sqrt((X2 - X1) * (X2 - X1) + (Y2 - Y1) * (Y2 - Y1));"
},
{
"code": null,
"e": 1384,
"s": 1264,
"text": " if (d > R1 + R2) ans = 0; else if (d <= abs(R2 - R1) && R1 >= R2) ans = floor(Pi * R2 * R2);"
},
{
"code": null,
"e": 1470,
"s": 1384,
"text": " else if (d <= abs(R2 - R1) && R2 >= R1) ans = floor(Pi * R1 * R1);"
},
{
"code": null,
"e": 1824,
"s": 1470,
"text": " else { alpha = acos((R1 * R1 + d * d - R2 * R2) / (2 * R1 * d)) * 2; beta = acos((R2 * R2 + d * d - R1 * R1) / (2 * R2 * d)) * 2; a1 = 0.5 * beta * R2 * R2 - 0.5 * R2 * R2 * sin(beta); a2 = 0.5 * alpha * R1 * R1 - 0.5 * R1 * R1 * sin(alpha); ans = floor(a1 + a2); } return ans;"
},
{
"code": null,
"e": 1827,
"s": 1824,
"text": "-1"
},
{
"code": null,
"e": 1844,
"s": 1827,
"text": "Hazem5 years ago"
},
{
"code": null,
"e": 1850,
"s": 1844,
"text": "Hazem"
},
{
"code": null,
"e": 2002,
"s": 1850,
"text": "There are three more cases not mentioned in the solution here http://code.geeksforgeeks.o... (and by the way, most solutions I found online). They are:"
},
{
"code": null,
"e": 2083,
"s": 2002,
"text": "- d is less than one radius but larger than the other- d is less than both radii"
},
{
"code": null,
"e": 2286,
"s": 2083,
"text": "In either case, one circle is almost inside the other. The intersection area is then the area of the smaller circle minus the difference of the circular segments (i.e. minus area(r1,r2,d)-area(r2,r1,d))"
},
{
"code": null,
"e": 2288,
"s": 2286,
"text": "0"
},
{
"code": null,
"e": 2308,
"s": 2288,
"text": "Quandray5 years ago"
},
{
"code": null,
"e": 2317,
"s": 2308,
"text": "Quandray"
},
{
"code": null,
"e": 2383,
"s": 2317,
"text": "Input:-11786939 388749051 844435993 -11696460 388789113 844535886"
},
{
"code": null,
"e": 2425,
"s": 2383,
"text": "Its Correct output is:2240182216213578196"
},
{
"code": null,
"e": 2464,
"s": 2425,
"text": "And Your Output is:2240182216213578283"
},
{
"code": null,
"e": 2636,
"s": 2464,
"text": "For this test case, the smaller circle is inside the larger, so the overlap is the area of the smaller circle. 844435993*844435993*pi.I make that 2240182216213578283.58."
},
{
"code": null,
"e": 2914,
"s": 2636,
"text": "In my code I have the lineconst long double pi=3.1415926535897932384L;With that line, I get the answer 2240182216213578283If I remove the L from the end of that line, pi is shortened and I get the expected, but wrong, answer 2240182216213578196.Please can someone correct this."
},
{
"code": null,
"e": 2917,
"s": 2914,
"text": "-2"
},
{
"code": null,
"e": 2932,
"s": 2917,
"text": "张昆玮6 years ago"
},
{
"code": null,
"e": 2936,
"s": 2932,
"text": "张昆玮"
},
{
"code": null,
"e": 3073,
"s": 2936,
"text": "I think my solution is correct. http://code.geeksforgeeks.o... . How can you show the expected output is more accurate than my solution?"
},
{
"code": null,
"e": 3219,
"s": 3073,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 3255,
"s": 3219,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 3265,
"s": 3255,
"text": "\nProblem\n"
},
{
"code": null,
"e": 3275,
"s": 3265,
"text": "\nContest\n"
},
{
"code": null,
"e": 3338,
"s": 3275,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 3486,
"s": 3338,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 3694,
"s": 3486,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 3800,
"s": 3694,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Ansible - Quick Guide | Ansible is simple open source IT engine which automates application deployment, intra service orchestration, cloud provisioning and many other IT tools.
Ansible is easy to deploy because it does not use any agents or custom security infrastructure.
Ansible uses playbook to describe automation jobs, and playbook uses very simple language i.e. YAML (It’s a human-readable data serialization language & is commonly used for configuration files, but could be used in many applications where data is being stored)which is very easy for humans to understand, read and write. Hence the advantage is that even the IT infrastructure support guys can read and understand the playbook and debug if needed (YAML – It is in human readable form).
Ansible is designed for multi-tier deployment. Ansible does not manage one system at time, it models IT infrastructure by describing all of your systems are interrelated. Ansible is completely agentless which means Ansible works by connecting your nodes through ssh(by default). But if you want other method for connection like Kerberos, Ansible gives that option to you.
After connecting to your nodes, Ansible pushes small programs called as “Ansible Modules”. Ansible runs that modules on your nodes and removes them when finished. Ansible manages your inventory in simple text files (These are the hosts file). Ansible uses the hosts file where one can group the hosts and can control the actions on a specific group in the playbooks.
This is the content of hosts file −
#File name: hosts
#Description: Inventory file for your application. Defines machine type abc
node to deploy specific artifacts
# Defines machine type def node to upload
metadata.
[abc-node]
#server1 ansible_host = <target machine for DU deployment> ansible_user = <Ansible
user> ansible_connection = ssh
server1 ansible_host = <your host name> ansible_user = <your unix user>
ansible_connection = ssh
[def-node]
#server2 ansible_host = <target machine for artifact upload>
ansible_user = <Ansible user> ansible_connection = ssh
server2 ansible_host = <host> ansible_user = <user> ansible_connection = ssh
Configuration management in terms of Ansible means that it maintains configuration of the product performance by keeping a record and updating detailed information which describes an enterprise’s hardware and software.
Such information typically includes the exact versions and updates that have been applied to installed software packages and the locations and network addresses of hardware devices. For e.g. If you want to install the new version of WebLogic/WebSphere server on all of the machines present in your enterprise, it is not feasible for you to manually go and update each and every machine.
You can install WebLogic/WebSphere in one go on all of your machines with Ansible playbooks and inventory written in the most simple way. All you have to do is list out the IP addresses of your nodes in the inventory and write a playbook to install WebLogic/WebSphere. Run the playbook from your control machine & it will be installed on all your nodes.
The picture given below shows the working of Ansible.
Ansible works by connecting to your nodes and pushing out small programs, called "Ansible modules" to them. Ansible then executes these modules (over SSH by default), and removes them when finished. Your library of modules can reside on any machine, and there are no servers, daemons, or databases required.
The management node in the above picture is the controlling node (managing node) which controls the entire execution of the playbook. It’s the node from which you are running the installation. The inventory file provides the list of hosts where the Ansible modules needs to be run and the management node does a SSH connection and executes the small modules on the hosts machine and installs the product/software.
Beauty of Ansible is that it removes the modules once those are installed so effectively it connects to host machine , executes the instructions and if it’s successfully installed removes the code which was copied on the host machine which was executed.
In this chapter, we will learn about the environment setup of Ansible.
Mainly, there are two types of machines when we talk about deployment −
Control machine − Machine from where we can manage other machines.
Control machine − Machine from where we can manage other machines.
Remote machine − Machines which are handled/controlled by control machine.
Remote machine − Machines which are handled/controlled by control machine.
There can be multiple remote machines which are handled by one control machine. So, for managing remote machines we have to install Ansible on control machine.
Ansible can be run from any machine with Python 2 (versions 2.6 or 2.7) or Python 3 (versions 3.5 and higher) installed.
Note − Windows does not support control machine.
By default, Ansible uses ssh to manage remote machine.
Ansible does not add any database. It does not require any daemons to start or keep it running. While managing remote machines, Ansible does not leave any software installed or running on them. Hence, there is no question of how to upgrade it when moving to a new version.
Ansible can be installed on control machine which have above mentioned requirements in different ways. You can install the latest release through Apt, yum, pkg, pip, OpenCSW, pacman, etc.
For installing Ansible you have to configure PPA on your machine. For this, you have to run the following line of code −
$ sudo apt-get update
$ sudo apt-get install software-properties-common
$ sudo apt-add-repository ppa:ansible/ansible $ sudo apt-get update
$ sudo apt-get install ansible
After running the above line of code, you are ready to manage remote machines through Ansible. Just run Ansible–version to check the version and just to check whether Ansible was installed properly or not.
Ansible uses YAML syntax for expressing Ansible playbooks. This chapter provides an overview of YAML. Ansible uses YAML because it is very easy for humans to understand, read and write when compared to other data formats like XML and JSON.
Every YAML file optionally starts with “---” and ends with “...”.
In this section, we will learn the different ways in which the YAML data is represented.
YAML uses simple key-value pair to represent the data. The dictionary is represented in key: value pair.
Note − There should be space between : and value.
--- #Optional YAML start syntax
james:
name: james john
rollNo: 34
div: B
sex: male
... #Optional YAML end syntax
You can also use abbreviation to represent dictionaries.
James: {name: james john, rollNo: 34, div: B, sex: male}
We can also represent List in YAML. Every element(member) of list should be written in a new line with same indentation starting with “- “ (- and space).
---
countries:
- America
- China
- Canada
- Iceland
...
You can also use abbreviation to represent lists.
Countries: [‘America’, ‘China’, ‘Canada’, ‘Iceland’]
We can use list inside dictionaries, i.e., value of key is list.
---
james:
name: james john
rollNo: 34
div: B
sex: male
likes:
- maths
- physics
- english
...
We can also make list of dictionaries.
---
- james:
name: james john
rollNo: 34
div: B
sex: male
likes:
- maths
- physics
- english
- robert:
name: robert richardson
rollNo: 53
div: B
sex: male
likes:
- biology
- chemistry
...
YAML uses “|” to include newlines while showing multiple lines and “>” to suppress newlines while showing multiple lines. Due to this we can read and edit large lines. In both the cases intendentation will be ignored.
We can also represent Boolean (True/false) values in YAML. where boolean values can be case insensitive.
---
- james:
name: james john
rollNo: 34
div: B
sex: male
likes:
- maths
- physics
- english
result:
maths: 87
chemistry: 45
biology: 56
physics: 70
english: 80
passed: TRUE
messageIncludeNewLines: |
Congratulation!!
You passed with 79%
messageExcludeNewLines: >
Congratulation!!
You passed with 79%
Service/Server − A process on the machine that provides the service.
Machine − A physical server, vm(virtual machine) or a container.
Target machine − A machine we are about to configure with Ansible.
Task − An action(run this, delete that) etc managed by Ansible.
Playbook − The yml file where Ansible commands are written and yml is executed on a machine.
Ad hoc commands are commands which can be run individually to perform quick functions. These commands need not be performed later.
For example, you have to reboot all your company servers. For this, you will run the Adhoc commands from ‘/usr/bin/ansible’.
These ad-hoc commands are not used for configuration management and deployment, because these commands are of one time usage.
ansible-playbook is used for configuration management and deployment.
Reboot your company server in 12 parallel forks at time. For this, we need to set up SSHagent for connection.
$ ssh-agent bash
$ ssh-add ~/.ssh/id_rsa
To run reboot for all your company servers in a group, 'abc', in 12 parallel forks −
$ Ansible abc -a "/sbin/reboot" -f 12
By default, Ansible will run the above Ad-hoc commands form current user account. If you want to change this behavior, you will have to pass the username in Ad-hoc commands as follows −
$ Ansible abc -a "/sbin/reboot" -f 12 -u username
You can use the Ad-hoc commands for doing SCP (Secure Copy Protocol) lots of files in parallel on multiple machines.
$ Ansible abc -m copy -a "src = /etc/yum.conf dest = /tmp/yum.conf"
$ Ansible abc -m file -a "dest = /path/user1/new mode = 777 owner = user1 group = user1 state = directory"
$ Ansible abc -m file -a "dest = /path/user1/new state = absent"
The Ad-hoc commands are available for yum and apt. Following are some Ad-hoc commands using yum.
The following command checks if yum package is installed or not, but does not update it.
$ Ansible abc -m yum -a "name = demo-tomcat-1 state = present"
The following command check the package is not installed.
$ Ansible abc -m yum -a "name = demo-tomcat-1 state = absent"
The following command checks the latest version of package is installed.
$ Ansible abc -m yum -a "name = demo-tomcat-1 state = latest"
Facts can be used for implementing conditional statements in playbook. You can find adhoc information of all your facts through the following Ad-hoc command −
$ Ansible all -m setup
In this chapter, we will learn about Playbooks in Ansible.
Playbooks are the files where Ansible code is written. Playbooks are written in YAML format. YAML stands for Yet Another Markup Language. Playbooks are one of the core features of Ansible and tell Ansible what to execute. They are like a to-do list for Ansible that contains a list of tasks.
Playbooks contain the steps which the user wants to execute on a particular machine. Playbooks are run sequentially. Playbooks are the building blocks for all the use cases of Ansible.
Each playbook is an aggregation of one or more plays in it. Playbooks are structured using Plays. There can be more than one play inside a playbook.
The function of a play is to map a set of instructions defined against a particular host.
YAML is a strict typed language; so, extra care needs to be taken while writing the YAML files. There are different YAML editors but we will prefer to use a simple editor like notepad++. Just open notepad++ and copy and paste the below yaml and change the language to YAML (Language → YAML).
A YAML starts with --- (3 hyphens)
Let us start by writing a sample YAML file. We will walk through each section written in a yaml file.
---
name: install and configure DB
hosts: testServer
become: yes
vars:
oracle_db_port_value : 1521
tasks:
-name: Install the Oracle DB
yum: <code to install the DB>
-name: Ensure the installed service is enabled and running
service:
name: <your service name>
The above is a sample Playbook where we are trying to cover the basic syntax of a playbook. Save the above content in a file as test.yml. A YAML syntax needs to follow the correct indentation and one needs to be a little careful while writing the syntax.
Let us now go through the different YAML tags. The different tags are described below −
This tag specifies the name of the Ansible playbook. As in what this playbook will be doing. Any logical name can be given to the playbook.
This tag specifies the lists of hosts or host group against which we want to run the task. The hosts field/tag is mandatory. It tells Ansible on which hosts to run the listed tasks. The tasks can be run on the same machine or on a remote machine. One can run the tasks on multiple machines and hence hosts tag can have a group of hosts’ entry as well.
Vars tag lets you define the variables which you can use in your playbook. Usage is similar to variables in any programming language.
All playbooks should contain tasks or a list of tasks to be executed. Tasks are a list of actions one needs to perform. A tasks field contains the name of the task. This works as the help text for the user. It is not mandatory but proves useful in debugging the playbook. Each task internally links to a piece of code called a module. A module that should be executed, and arguments that are required for the module you want to execute.
Roles provide a framework for fully independent, or interdependent collections of variables, tasks, files, templates, and modules.
In Ansible, the role is the primary mechanism for breaking a playbook into multiple files. This simplifies writing complex playbooks, and it makes them easier to reuse. The breaking of playbook allows you to logically break the playbook into reusable components.
Each role is basically limited to a particular functionality or desired output, with all the necessary steps to provide that result either within that role itself or in other roles listed as dependencies.
Roles are not playbooks. Roles are small functionality which can be independently used but have to be used within playbooks. There is no way to directly execute a role. Roles have no explicit setting for which host the role will apply to.
Top-level playbooks are the bridge holding the hosts from your inventory file to roles that should be applied to those hosts.
The directory structure for roles is essential to create a new role.
Roles have a structured layout on the file system. The default structure can be changed but for now let us stick to defaults.
Each role is a directory tree in itself. The role name is the directory name within the /roles directory.
$ ansible-galaxy -h
ansible-galaxy [delete|import|info|init|install|list|login|remove|search|setup] [--help] [options] ...
-h, --help − Show this help message and exit.
-h, --help − Show this help message and exit.
-v, --verbose − Verbose mode (-vvv for more, -vvvv to enable connection debugging)
-v, --verbose − Verbose mode (-vvv for more, -vvvv to enable connection debugging)
--version − Show program's version number and exit.
--version − Show program's version number and exit.
The above command has created the role directories.
$ ansible-galaxy init vivekrole
ERROR! The API server (https://galaxy.ansible.com/api/) is not responding, please try again later.
$ ansible-galaxy init --force --offline vivekrole
- vivekrole was created successfully
$ tree vivekrole/
vivekrole/
├── defaults
│ └── main.yml
├── files ├── handlers
│ └── main.yml
├── meta
│ └── main.yml
├── README.md ├── tasks
│ └── main.yml
├── templates ├── tests │ ├── inventory
│ └── test.yml
└── vars
└── main.yml
8 directories, 8 files
Not all the directories will be used in the example and we will show the use of some of them in the example.
This is the code of the playbook we have written for demo purpose. This code is of the playbook vivek_orchestrate.yml. We have defined the hosts: tomcat-node and called the two roles – install-tomcat and start-tomcat.
The problem statement is that we have a war which we need to deploy on a machine via Ansible.
---
- hosts: tomcat-node
roles:
- {role: install-tomcat}
- {role: start-tomcat}
Contents of our directory structure from where we are running the playbook.
$ ls
ansible.cfg hosts roles vivek_orchestrate.retry vivek_orchestrate.yml
There is a tasks directory under each directory and it contains a main.yml. The main.yml contents of install-tomcat are −
---
#Install vivek artifacts
-
block:
- name: Install Tomcat artifacts
action: >
yum name = "demo-tomcat-1" state = present
register: Output
always:
- debug:
msg:
- "Install Tomcat artifacts task ended with message: {{Output}}"
- "Installed Tomcat artifacts - {{Output.changed}}"
The contents of main.yml of the start tomcat are −
#Start Tomcat
-
block:
- name: Start Tomcat
command: <path of tomcat>/bin/startup.sh"
register: output
become: true
always:
- debug:
msg:
- "Start Tomcat task ended with message: {{output}}"
- "Tomcat started - {{output.changed}}"
The advantage of breaking the playbook into roles is that anyone who wants to use the Install tomcat feature can call the Install Tomcat role.
If not for the roles, the content of the main.yml of the respective role can be copied in the playbook yml file. But to have modularity, roles were created.
Any logical entity which can be reused as a reusable function, that entity can be moved to role. The example for this is shown above
Ran the command to run the playbook.
-vvv option for verbose output – verbose output
$ cd vivek-playbook/
This is the command to run the playbook
$ sudo ansible-playbook -i hosts vivek_orchestrate.yml –vvv
-----------------------------------------------------------------
-----------------------------------------------------------------------
The generated output is as seen on the screen −
Using /users/demo/vivek-playbook/ansible.cfg as config file.
PLAYBOOK: vivek_orchestrate.yml *********************************************************
***********************************************************
1 plays in vivek_orchestrate.yml
PLAY [tomcat-node] **********************************************************************
******** *************************************************
TASK [Gathering Facts] *************************************************
****************************** *********************************************
Tuesday 21 November 2017 13:02:05 +0530 (0:00:00.056) 0:00:00.056 ******
Using module file /usr/lib/python2.7/sitepackages/ansible/modules/system/setup.py
<localhost> ESTABLISH LOCAL CONNECTION FOR USER: root
<localhost> EXEC /bin/sh -c 'echo ~ && sleep 0'
<localhost> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo
/root/.ansible/tmp/ansible-tmp-1511249525.88-259535494116870 `" &&
echo ansible-tmp-1511249525.88-259535494116870="`
echo /root/.ansible/tmp/ansibletmp-1511249525.88-259535494116870 `" ) && sleep 0'
<localhost> PUT /tmp/tmpPEPrkd TO
/root/.ansible/tmp/ansible-tmp-1511249525.88259535494116870/setup.py
<localhost> EXEC /bin/sh -c 'chmod u+x
/root/.ansible/tmp/ansible-tmp1511249525.88-259535494116870/
/root/.ansible/tmp/ansible-tmp-1511249525.88259535494116870/setup.py && sleep 0'
<localhost> EXEC /bin/sh -c '/usr/bin/python
/root/.ansible/tmp/ansible-tmp1511249525.88-259535494116870/setup.py; rm -rf
"/root/.ansible/tmp/ansible-tmp1511249525.88-259535494116870/" > /dev/null 2>&1 && sleep 0'
ok: [server1]
META: ran handlers
TASK [install-tomcat : Install Tomcat artifacts] ***********************************
***************************************************************
task path: /users/demo/vivek-playbook/roles/install-tomcat/tasks/main.yml:5
Tuesday 21 November 2017 13:02:07 +0530 (0:00:01.515) 0:00:01.572 ******
Using module file /usr/lib/python2.7/sitepackages/ansible/modules/packaging/os/yum.py
<localhost> ESTABLISH LOCAL CONNECTION FOR USER: root
<localhost> EXEC /bin/sh -c 'echo ~ && sleep 0'
<localhost> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo
/root/.ansible/tmp/ansible-tmp-1511249527.34-40247177825302 `" && echo
ansibletmp-1511249527.34-40247177825302="` echo
/root/.ansible/tmp/ansible-tmp1511249527.34-40247177825302 `" ) && sleep 0'
<localhost> PUT /tmp/tmpu83chg TO
/root/.ansible/tmp/ansible-tmp-1511249527.3440247177825302/yum.py
<localhost> EXEC /bin/sh -c 'chmod u+x
/root/.ansible/tmp/ansible-tmp1511249527.34-40247177825302/
/root/.ansible/tmp/ansible-tmp-1511249527.3440247177825302/yum.py && sleep 0'
<localhost> EXEC /bin/sh -c '/usr/bin/python
/root/.ansible/tmp/ansible-tmp1511249527.34-40247177825302/yum.py; rm -rf
"/root/.ansible/tmp/ansible-tmp1511249527.34-40247177825302/" > /dev/null 2>
&1 && sleep 0'
changed: [server1] => {
"changed": true,
"invocation": {
"module_args": {
"conf_file": null,
"disable_gpg_check": false,
"disablerepo": null,
"enablerepo": null,
"exclude": null,
"install_repoquery": true,
"installroot": "/",
"list": null,
"name": ["demo-tomcat-1"],
"skip_broken": false,
"state": "present",
"update_cache": false,
"validate_certs": true
}
},
"msg": "",
"rc": 0,
"results": [
"Loaded plugins: product-id,
search-disabled-repos,
subscriptionmanager\nThis system is not registered to Red Hat Subscription Management.
You can use subscription-manager to register.\nResolving Dependencies\n-->
Running transaction check\n--->
Package demo-tomcat-1.noarch 0:SNAPSHOT-1 will be installed\n--> Finished Dependency
Resolution\n\nDependencies Resolved\n
\n================================================================================\n
Package Arch Version Repository
Size\n==================================================================\nInstalling:\n
demo-tomcat-1 noarch SNAPSHOT-1 demo-repo1 7.1 M\n\nTransaction
Summary\n==================================================================\nInstall 1
Package\n\nTotal download size: 7.1 M\nInstalled size: 7.9 M\nDownloading
packages:\nRunning transaction
check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n Installing :
demotomcat-1-SNAPSHOT-1.noarch 1/1 \n Verifying :
demo-tomcat-1-SNAPSHOT-1.noarch 1/1 \n\nInstalled:\n
demo-tomcat-1.noarch 0:SNAPSHOT-1 \n\nComplete!\n"
]
}
TASK [install-tomcat : debug] **********************************************************
***************************************************************************
task path: /users/demo/vivek-playbook/roles/install-tomcat/tasks/main.yml:11
Tuesday 21 November 2017 13:02:13 +0530 (0:00:06.757) 0:00:08.329 ******
ok: [server1] => {
"changed": false,
"msg": [
"Install Tomcat artifacts task ended with message: {
u'msg': u'', u'changed': True, u'results':
[u'Loaded plugins: product-id,
search-disabledrepos,
subscription-manager\\nThis system is not registered to Red Hat Subscription Management.
You can use subscription-manager to register.\\nResolving Dependencies\\n-->
Running transaction check\\n--->
Package demo-tomcat-1.noarch 0:SNAPSHOT-1 will be installed\\n-->
Finished Dependency Resolution\\n
\\nDependencies
Resolved\\n\\n==================================================================\\n
Package Arch Version Repository
Size\\n========================================================================
=====\\nInstalling:\\n demo-tomcat-1 noarch SNAPSHOT-1 demo-repo1 7.1 M\\n\\nTransaction
Summary\\n=========================================================\\nInstall 1
Package\\n\\nTotal download size: 7.1 M\\nInstalled size: 7.9 M\\nDownloading
packages:\\nRunning
transaction check\\nRunning transaction test\\nTransaction test succeeded\\nRunning
transaction\\n
Installing : demo-tomcat-1-SNAPSHOT-1.noarch 1/1 \\n Verifying :
demo-tomcat-1-SNAPSHOT-1.noarch
1/1 \\n\\nInstalled:\\n demo-tomcat-1.noarch 0:SNAPSHOT-1 \\n\\nComplete!\\n'], u'rc': 0
}",
"Installed Tomcat artifacts - True"
]
}
TASK [install-tomcat : Clean DEMO environment] ****************************************
************************************************************
task path: /users/demo/vivek-playbook/roles/install-tomcat/tasks/main.yml:19
Tuesday 21 November 2017 13:02:13 +0530 (0:00:00.057) 0:00:08.387 ******
[WARNING]: when statements should not include jinja2 templating delimiters such as {{ }} or
{% %}. Found: {{installationOutput.changed}}
Using module file /usr/lib/python2.7/sitepackages/ansible/modules/files/file.py
<localhost> ESTABLISH LOCAL CONNECTION FOR USER: root
<localhost> EXEC /bin/sh -c 'echo ~ && sleep 0'
<localhost> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo
/root/.ansible/tmp/ansible-tmp-1511249534.13-128345805983963 `" && echo
ansible-tmp-1511249534.13-128345805983963="` echo
/root/.ansible/tmp/ansibletmp-1511249534.13-128345805983963 `" ) && sleep 0'
<localhost> PUT /tmp/tmp0aXel7 TO
/root/.ansible/tmp/ansible-tmp-1511249534.13128345805983963/file.py
<localhost> EXEC /bin/sh -c 'chmod u+x
/root/.ansible/tmp/ansible-tmp1511249534.13-128345805983963/
/root/.ansible/tmp/ansible-tmp-1511249534.13128345805983963/file.py && sleep 0'
<localhost> EXEC /bin/sh -c '/usr/bin/python
/root/.ansible/tmp/ansible-tmp1511249534.13-128345805983963/file.py; rm -rf
"/root/.ansible/tmp/ansible-tmp1511249534.13-128345805983963/" > /dev/null 2>&1
&& sleep 0'
changed: [server1] => {
"changed": true,
"diff": {
"after": {
"path": "/users/demo/DEMO",
"state": "absent"
},
"before": {
"path": "/users/demo/DEMO",
"state": "directory"
}
},
"invocation": {
"module_args": {
"attributes": null,
"backup": null,
"content": null,
"delimiter": null,
"diff_peek": null,
"directory_mode": null,
"follow": false,
"force": false,
"group": null,
"mode": null,
"original_basename": null,
"owner": null,
"path": "/users/demo/DEMO",
"recurse": false,
"regexp": null,
"remote_src": null,
"selevel": null,
"serole": null,
"setype": null,
"seuser": null,
"src": null,
"state": "absent",
"unsafe_writes": null,
"validate": null
}
},
"path": "/users/demo/DEMO",
"state": "absent"
}
TASK [install-tomcat : debug] ********************************************************
*************************************************************
task path: /users/demo/vivek-playbook/roles/install-tomcat/tasks/main.yml:29
Tuesday 21 November 2017 13:02:14 +0530 (0:00:00.257) 0:00:08.645 ******
ok: [server1] => {
"changed": false,
"msg": [
"Clean DEMO environment task ended with message:{u'diff': {u'after': {u'path':
u'/users/demo/DEMO', u'state': u'absent'},
u'before': {u'path': u'/users/demo/DEMO', u'state': u'directory'}}, u'state': u'absent',
u'changed': True, u'path': u'/users/demo/DEMO'}",
"check value :True"
]
}
TASK [install-tomcat : Copy Tomcat to user home] *************************************
********************************************************
task path: /users/demo/vivek-playbook/roles/install-tomcat/tasks/main.yml:37
Tuesday 21 November 2017 13:02:14 +0530 (0:00:00.055) 0:00:08.701 ******
[WARNING]: when statements should not include jinja2 templating delimiters such as {{ }} or
{% %}. Found: {{installationOutput.changed}}
Using module file /usr/lib/python2.7/sitepackages/ansible/modules/commands/command.py
<localhost> ESTABLISH LOCAL CONNECTION FOR USER: root
<localhost> EXEC /bin/sh -c 'echo ~ && sleep 0'
<localhost> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo
/root/.ansible/tmp/ansible-tmp-1511249534.43-41077200718443 `" && echo
ansibletmp-1511249534.43-41077200718443="` echo
/root/.ansible/tmp/ansible-tmp1511249534.43-41077200718443 `" ) && sleep 0'
<localhost> PUT /tmp/tmp25deWs TO
/root/.ansible/tmp/ansible-tmp-1511249534.4341077200718443/command.py
<localhost> EXEC /bin/sh -c 'chmod u+x
/root/.ansible/tmp/ansible-tmp1511249534.43-41077200718443/
/root/.ansible/tmp/ansible-tmp-1511249534.4341077200718443/command.py && sleep 0'
<localhost> EXEC /bin/sh -c '/usr/bin/python
/root/.ansible/tmp/ansible-tmp1511249534.43-41077200718443/command.py; rm -rf
"/root/.ansible/tmp/ansibletmp-1511249534.43-41077200718443/" > /dev/null 2>&1
&& sleep 0'
changed: [server1] => {
"changed": true,
"cmd": [
"cp",
"-r",
"/opt/ansible/tomcat/demo",
"/users/demo/DEMO/"
],
"delta": "0:00:00.017923",
"end": "2017-11-21 13:02:14.547633",
"invocation": {
"module_args": {
"_raw_params": "cp -r /opt/ansible/tomcat/demo /users/demo/DEMO/",
"_uses_shell": false,
"chdir": null,
"creates": null,
"executable": null,
"removes": null,
"warn": true
}
},
"rc": 0,
"start": "2017-11-21 13:02:14.529710",
"stderr": "",
"stderr_lines": [],
"stdout": "",
"stdout_lines": []
}
TASK [install-tomcat : debug] ********************************************************
**********************************************************
task path: /users/demo/vivek-playbook/roles/install-tomcat/tasks/main.yml:47
Tuesday 21 November 2017 13:02:14 +0530 (0:00:00.260) 0:00:08.961 ******
ok: [server1] => {
"changed": false,
"msg": "Copy Tomcat to user home task ended with message {
'stderr_lines': [], u'changed': True, u'end': u'2017-11-21 13:02:14.547633', u'stdout':
u'', u'cmd': [u'cp', u'-r', u'/opt/ansible/tomcat/demo', u'/users/demo/DEMO/'], u'rc': 0,
u'start': u'2017-11-21 13:02:14.529710', u'stderr': u'', u'delta': u'0:00:00.017923',
'stdout_lines': []}"
}
TASK [start-tomcat : Start Tomcat] **************************************************
**********************************************************
task path: /users/demo/vivek-playbook/roles/start-tomcat/tasks/main.yml:5
Tuesday 21 November 2017 13:02:14 +0530 (0:00:00.044) 0:00:09.006 ******
Using module file /usr/lib/python2.7/sitepackages/ansible/modules/commands/command.py
<localhost> ESTABLISH LOCAL CONNECTION FOR USER: root
<localhost> EXEC /bin/sh -c 'echo ~ && sleep 0'
<localhost> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo
/root/.ansible/tmp/ansible-tmp-1511249534.63-46501211251197 `" && echo
ansibletmp-1511249534.63-46501211251197="` echo
/root/.ansible/tmp/ansible-tmp1511249534.63-46501211251197 `" ) && sleep 0'
<localhost> PUT /tmp/tmp9f06MQ TO
/root/.ansible/tmp/ansible-tmp-1511249534.6346501211251197/command.py
<localhost> EXEC /bin/sh -c 'chmod u+x
/root/.ansible/tmp/ansible-tmp1511249534.63-46501211251197/
/root/.ansible/tmp/ansible-tmp-1511249534.6346501211251197/command.py && sleep 0'
<localhost> EXEC /bin/sh -c '/usr/bin/python
/root/.ansible/tmp/ansible-tmp1511249534.63-46501211251197/command.py; rm -rf
"/root/.ansible/tmp/ansibletmp-1511249534.63-46501211251197/" > /dev/null 2>&1
&& sleep 0'
changed: [server1] => {
"changed": true,
"cmd": [ "/users/demo/DEMO/bin/startup.sh" ],
"delta": "0:00:00.020024",
"end": "2017-11-21 13:02:14.741649",
"invocation": {
"module_args": {
"_raw_params": "/users/demo/DEMO/bin/startup.sh",
"_uses_shell": false,
"chdir": null,
"creates": null,
"executable": null,
"removes": null,
"warn": true
}
},
"rc": 0,
"start": "2017-11-21 13:02:14.721625",
"stderr": "",
"stderr_lines": [],
"stdout": "Tomcat started.",
"stdout_lines": [ "Tomcat started." ]
}
TASK [start-tomcat : debug] *************************************************
**********************************************************************
task path: /users/demo/vivek-playbook/roles/start-tomcat/tasks/main.yml:10
Tuesday 21 November 2017 13:02:14 +0530 (0:00:00.150) 0:00:09.156 ******
ok: [server1] => {
"changed": false,
"msg": [
"Start Tomcat task ended with message: {'
stderr_lines': [], u'changed': True, u'end': u'2017-11-21 13:02:14.741649', u'stdout':
u'Tomcat started.', u'cmd': [u'/users/demo/DEMO/bin/startup.sh'], u'rc': 0, u'start':
u'2017-11-21 13:02:14.721625', u'stderr': u'', u'delta': u'0:00:00.020024',
'stdout_lines': [u'Tomcat started.']}",
"Tomcat started - True"
]
}
META: ran handlers
META: ran handlers
PLAY RECAP *******************************************************************************
*********************************************************
server1 : ok = 9 changed = 4 unreachable = 0 failed = 0
Tuesday 21 November 2017 13:02:14 +0530 (0:00:00.042) 0:00:09.198 ******
===============================================================================
install-tomcat : Install Tomcat artifacts ------------------------------- 6.76s
/users/demo/vivek-playbook/roles/install-tomcat/tasks/main.yml:5 --------------
Gathering Facts --------------------------------------------------------- 1.52s
------------------------------------------------------------------------------
install-tomcat : Copy Tomcat to user home ------------------------------- 0.26s
/users/demo/vivek-playbook/roles/install-tomcat/tasks/main.yml:37 -------------
install-tomcat : Clean DEMO environment --------------------------------- 0.26s
/users/demo/vivek-playbook/roles/install-tomcat/tasks/main.yml:19 -------------
start-tomcat : Start Tomcat --------------------------------------------- 0.15s
/users/demo/vivek-playbook/roles/start-tomcat/tasks/main.yml:5 ----------------
install-tomcat : debug -------------------------------------------------- 0.06s
/users/demo/vivek-playbook/roles/install-tomcat/tasks/main.yml:11 -------------
install-tomcat : debug -------------------------------------------------- 0.06s
/users/demo/vivek-playbook/roles/install-tomcat/tasks/main.yml:29 -------------
install-tomcat : debug -------------------------------------------------- 0.04s
/users/demo/vivek-playbook/roles/install-tomcat/tasks/main.yml:47 -------------
start-tomcat : debug ---------------------------------------------------- 0.04s
/users/demo/vivek-playbook/roles/start-tomcat/tasks/main.yml:10 ---------------
Hit the following URL and you will be directed to a page as shown below − http://10.76.0.134:11677/HelloWorld/HelloWorld
The deployed war just has a servlet which displays “Hello World”. The detailed output shows the time taken by each and every task because of the entry added in ansible.cfg file −
[defaults]
callback_whitelist = profile_tasks
Variable in playbooks are very similar to using variables in any programming language. It helps you to use and assign a value to a variable and use that anywhere in the playbook. One can put conditions around the value of the variables and accordingly use them in the playbook.
- hosts : <your hosts>
vars:
tomcat_port : 8080
In the above example, we have defined a variable name tomcat_port and assigned the value 8080 to that variable and can use that in your playbook wherever needed.
Now taking a reference from the example shared. The following code is from one of the roles (install-tomcat) −
block:
- name: Install Tomcat artifacts
action: >
yum name = "demo-tomcat-1" state = present
register: Output
always:
- debug:
msg:
- "Install Tomcat artifacts task ended with message: {{Output}}"
- "Installed Tomcat artifacts - {{Output.changed}}"
Here, the output is the variable used.
Let us walk through all the keywords used in the above code −
block − Ansible syntax to execute a given block.
block − Ansible syntax to execute a given block.
name − Relevant name of the block - this is used in logging and helps in debugging that which all blocks were successfully executed.
name − Relevant name of the block - this is used in logging and helps in debugging that which all blocks were successfully executed.
action − The code next to action tag is the task to be executed. The action again is a Ansible keyword used in yaml.
action − The code next to action tag is the task to be executed. The action again is a Ansible keyword used in yaml.
register − The output of the action is registered using the register keyword and Output is the variable name which holds the action output.
register − The output of the action is registered using the register keyword and Output is the variable name which holds the action output.
always − Again a Ansible keyword , it states that below will always be executed.
always − Again a Ansible keyword , it states that below will always be executed.
msg − Displays the message.
msg − Displays the message.
This will read the value of variable Output. Also as it is used in the msg tab, it will print the value of the output variable.
Additionally, you can use the sub properties of the variable as well. Like in the case checking {{Output.changed}} whether the output got changed and accordingly use it.
Exception handling in Ansible is similar to exception handling in any programming language. An example of the exception handling in playbook is shown below.
tasks:
- name: Name of the task to be executed
block:
- debug: msg = 'Just a debug message , relevant for logging'
- command: <the command to execute>
rescue:
- debug: msg = 'There was an exception.. '
- command: <Rescue mechanism for the above exception occurred)
always:
- debug: msg = "this will execute in all scenarios. Always will get logged"
Following is the syntax for exception handling.
rescue and always are the keywords specific to exception handling.
rescue and always are the keywords specific to exception handling.
Block is where the code is written (anything to be executed on the Unix machine).
Block is where the code is written (anything to be executed on the Unix machine).
If the command written inside the block feature fails, then the execution reaches rescue block and it gets executed. In case there is no error in the command under block feature, then rescue will not be executed.
If the command written inside the block feature fails, then the execution reaches rescue block and it gets executed. In case there is no error in the command under block feature, then rescue will not be executed.
Always gets executed in all cases.
Always gets executed in all cases.
So if we compare the same with java, then it is similar to try, catch and finally block.
So if we compare the same with java, then it is similar to try, catch and finally block.
Here, Block is similar to try block where you write the code to be executed and rescue is similar to catch block and always is similar to finally.
Here, Block is similar to try block where you write the code to be executed and rescue is similar to catch block and always is similar to finally.
Below is the example to demonstrate the usage of Loops in Ansible.
The tasks is to copy the set of all the war files from one directory to tomcat webapps folder.
Most of the commands used in the example below are already covered before. Here, we will concentrate on the usage of loops.
Initially in the 'shell' command we have done ls *.war. So, it will list all the war files in the directory.
Output of that command is taken in a variable named output.
To loop, the 'with_items' syntax is being used.
with_items: "{{output.stdout_lines}}" --> output.stdout_lines gives us the line by line output and then we loop on the output with the with_items command of Ansible.
Attaching the example output just to make one understand how we used the stdout_lines in the with_items command.
---
#Tsting
- hosts: tomcat-node
tasks:
- name: Install Apache
shell: "ls *.war"
register: output
args:
chdir: /opt/ansible/tomcat/demo/webapps
- file:
src: '/opt/ansible/tomcat/demo/webapps/{{ item }}'
dest: '/users/demo/vivek/{{ item }}'
state: link
with_items: "{{output.stdout_lines}}"
The playbook in totality is broken into blocks. The smallest piece of steps to execute is written in block. Writing the specific instruction in blocks helps to segregate functionality and handle it with exception handling if needed.
Example of blocks is covered in variable usage,exception handling and loops above.
Conditionals are used where one needs to run a specific step based on a condition.
---
#Tsting
- hosts: all
vars:
test1: "Hello Vivek"
tasks:
- name: Testing Ansible variable
debug:
msg: "Equals"
when: test1 == "Hello Vivek"
In this case, Equals will be printed as the test1 variable is equal as mentioned in the when condition. when can be used with a logical OR and logical AND condition as in all the programming languages.
Just change the value of test1 variable from Hello Vivek to say Hello World and see the output.
In this chapter, we will learn what is advanced execution with Ansible.
This is a very important execution strategy where one needs to execute only one execution and not the entire playbook. For example, suppose you only want to stop a server (in case a production issue comes) and then post applying a patch you would like to only start the server.
Here in original playbook stop and start were a part of different roles in the same playbook but this can be handled with the usage of tags. We can provide different tags to different roles (which in turn will have tasks) and hence based on the tags provided by the executor only that specified role/task gets executed. So for the above example provided, we can add tags like the following −
- {role: start-tomcat, tags: ['install']}}
The following command helps in using tags −
ansible-playbook -i hosts <your yaml> --tags "install" -vvv
With the above command, only the start-tomcat role will be called. The tag provided is case-sensitive. Ensure exact match is being passed to the command.
There are two ways to achieve the execution of specific steps on specific hosts. For a specific role, one defines the hosts - as to which specific hosts that specific role should be run.
- hosts: <A>
environment: "{{your env}}"
pre_tasks:
- debug: msg = "Started deployment.
Current time is {{ansible_date_time.date}} {{ansible_date_time.time}} "
roles:
- {role: <your role>, tags: ['<respective tag>']}
post_tasks:
- debug: msg = "Completed deployment.
Current time is {{ansible_date_time.date}} {{ansible_date_time.time}}"
- hosts: <B>
pre_tasks:
- debug: msg = "started....
Current time is {{ansible_date_time.date}} {{ansible_date_time.time}} "
roles:
- {role: <your role>, tags: ['<respective tag>']}
post_tasks:
- debug: msg = "Completed the task..
Current time is {{ansible_date_time.date}} {{ansible_date_time.time}}"
As per the above example, depending on the hosts provided, the respective roles will only be called. Now my hosts A and B are defined in the hosts (inventory file).
A different solution might be defining the playbook's hosts using a variable, then passing in a specific host address via --extra-vars −
# file: user.yml (playbook)
---
- hosts: '{{ target }}'
user: ...
playbook contd....
ansible-playbook user.yml --extra-vars "target = "<your host variable>"
If {{ target }} isn't defined, the playbook does nothing. A group from the hosts file can also be passed through if need be. This does not harm if the extra vars is not provided.
$ ansible-playbook user.yml --extra-vars "target = <your hosts variable>" --listhosts
The most common strategies for debugging Ansible playbooks are using the modules given below −
These two are the modules available in Ansible. For debugging purpose, we need to use the two modules judiciously. Examples are demonstrated below.
With the Ansible command, one can provide the verbosity level. You can run the commands with verbosity level one (-v) or two (-vv).
In this section, we will go through a few examples to understand a few concepts.
If you are not quoting an argument that starts with a variable. For example,
vars:
age_path: {{vivek.name}}/demo/
{{vivek.name}}
This will throw an error.
vars:
age_path: "{{vivek.name}}/demo/" – marked in yellow is the fix.
How to use register -> Copy this code into a yml file say test.yml and run it
---
#Tsting
- hosts: tomcat-node
tasks:
- shell: /usr/bin/uptime
register: myvar
- name: Just debugging usage
debug: var = myvar
When I run this code via the command Ansible-playbook -i hosts test.yml, I get the output as shown below.
If you see the yaml , we have registered the output of a command into a variable – myvar and just printed the output.
The text marked yellow, tells us about property of the variable –myvar that can be used for further flow control. This way we can find out about the properties that are exposed of a particular variable. The following debug command helps in this.
$ ansible-playbook -i hosts test.yml
PLAY [tomcat-node] ***************************************************************
**************** ****************************************************************
*************** ******************************
TASK [Gathering Facts] *****************************************************************
************** *****************************************************************
************** **************************
Monday 05 February 2018 17:33:14 +0530 (0:00:00.051) 0:00:00.051 *******
ok: [server1]
TASK [command] ******************************************************************
************* ******************************************************************
************* **********************************
Monday 05 February 2018 17:33:16 +0530 (0:00:01.697) 0:00:01.748 *******
changed: [server1]
TASK [Just debugging usage] ******************************************************************
************* ******************************************************************
************* *********************
Monday 05 February 2018 17:33:16 +0530 (0:00:00.226) 0:00:01.974 *******
ok: [server1] => {
"myvar": {
"changed": true,
"cmd": "/usr/bin/uptime",
"delta": "0:00:00.011306",
"end": "2018-02-05 17:33:16.424647",
"rc": 0,
"start": "2018-02-05 17:33:16.413341",
"stderr": "",
"stderr_lines": [],
"stdout": " 17:33:16 up 7 days, 35 min, 1 user, load average: 0.18, 0.15, 0.14",
"stdout_lines": [
" 17:33:16 up 7 days, 35 min, 1 user, load average: 0.18, 0.15, 0.14"
]
}
}
PLAY RECAP ****************************************************************************
**********************************************************************************
**************************************
server1 : ok = 3 changed = 1 unreachable = 0 failed = 0
In this section, we will learn about the a few common playbook issues. The issues are −
Quoting
Indentation
Playbook is written in yaml format and the above two are the most common issues in yaml/playbook.
Yaml does not support tab based indentation and supports space based indentation, so one needs to be careful about the same.
Note − once you are done with writing the yaml , open this site(https://editor.swagger.io/) and copy paste your yaml on the left hand side to ensure that the yaml compiles properly. This is just a tip.
Swagger qualifies errors in warning as well as error.
41 Lectures
5 hours
AR Shankar
11 Lectures
58 mins
Musab Zayadneh
59 Lectures
15.5 hours
Narendra P
11 Lectures
1 hours
Sagar Mehta
39 Lectures
4 hours
Vikas Yadav
4 Lectures
3.5 hours
GreyCampus Inc.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 1944,
"s": 1791,
"text": "Ansible is simple open source IT engine which automates application deployment, intra service orchestration, cloud provisioning and many other IT tools."
},
{
"code": null,
"e": 2040,
"s": 1944,
"text": "Ansible is easy to deploy because it does not use any agents or custom security infrastructure."
},
{
"code": null,
"e": 2526,
"s": 2040,
"text": "Ansible uses playbook to describe automation jobs, and playbook uses very simple language i.e. YAML (It’s a human-readable data serialization language & is commonly used for configuration files, but could be used in many applications where data is being stored)which is very easy for humans to understand, read and write. Hence the advantage is that even the IT infrastructure support guys can read and understand the playbook and debug if needed (YAML – It is in human readable form)."
},
{
"code": null,
"e": 2898,
"s": 2526,
"text": "Ansible is designed for multi-tier deployment. Ansible does not manage one system at time, it models IT infrastructure by describing all of your systems are interrelated. Ansible is completely agentless which means Ansible works by connecting your nodes through ssh(by default). But if you want other method for connection like Kerberos, Ansible gives that option to you."
},
{
"code": null,
"e": 3265,
"s": 2898,
"text": "After connecting to your nodes, Ansible pushes small programs called as “Ansible Modules”. Ansible runs that modules on your nodes and removes them when finished. Ansible manages your inventory in simple text files (These are the hosts file). Ansible uses the hosts file where one can group the hosts and can control the actions on a specific group in the playbooks."
},
{
"code": null,
"e": 3301,
"s": 3265,
"text": "This is the content of hosts file −"
},
{
"code": null,
"e": 3910,
"s": 3301,
"text": "#File name: hosts\n#Description: Inventory file for your application. Defines machine type abc\nnode to deploy specific artifacts\n# Defines machine type def node to upload\nmetadata.\n\n[abc-node]\n#server1 ansible_host = <target machine for DU deployment> ansible_user = <Ansible\nuser> ansible_connection = ssh\nserver1 ansible_host = <your host name> ansible_user = <your unix user>\nansible_connection = ssh\n\n[def-node]\n#server2 ansible_host = <target machine for artifact upload>\nansible_user = <Ansible user> ansible_connection = ssh\nserver2 ansible_host = <host> ansible_user = <user> ansible_connection = ssh\n"
},
{
"code": null,
"e": 4129,
"s": 3910,
"text": "Configuration management in terms of Ansible means that it maintains configuration of the product performance by keeping a record and updating detailed information which describes an enterprise’s hardware and software."
},
{
"code": null,
"e": 4516,
"s": 4129,
"text": "Such information typically includes the exact versions and updates that have been applied to installed software packages and the locations and network addresses of hardware devices. For e.g. If you want to install the new version of WebLogic/WebSphere server on all of the machines present in your enterprise, it is not feasible for you to manually go and update each and every machine."
},
{
"code": null,
"e": 4870,
"s": 4516,
"text": "You can install WebLogic/WebSphere in one go on all of your machines with Ansible playbooks and inventory written in the most simple way. All you have to do is list out the IP addresses of your nodes in the inventory and write a playbook to install WebLogic/WebSphere. Run the playbook from your control machine & it will be installed on all your nodes."
},
{
"code": null,
"e": 4924,
"s": 4870,
"text": "The picture given below shows the working of Ansible."
},
{
"code": null,
"e": 5232,
"s": 4924,
"text": "Ansible works by connecting to your nodes and pushing out small programs, called \"Ansible modules\" to them. Ansible then executes these modules (over SSH by default), and removes them when finished. Your library of modules can reside on any machine, and there are no servers, daemons, or databases required."
},
{
"code": null,
"e": 5647,
"s": 5232,
"text": "The management node in the above picture is the controlling node (managing node) which controls the entire execution of the playbook. It’s the node from which you are running the installation. The inventory file provides the list of hosts where the Ansible modules needs to be run and the management node does a SSH connection and executes the small modules on the hosts machine and installs the product/software."
},
{
"code": null,
"e": 5901,
"s": 5647,
"text": "Beauty of Ansible is that it removes the modules once those are installed so effectively it connects to host machine , executes the instructions and if it’s successfully installed removes the code which was copied on the host machine which was executed."
},
{
"code": null,
"e": 5972,
"s": 5901,
"text": "In this chapter, we will learn about the environment setup of Ansible."
},
{
"code": null,
"e": 6044,
"s": 5972,
"text": "Mainly, there are two types of machines when we talk about deployment −"
},
{
"code": null,
"e": 6111,
"s": 6044,
"text": "Control machine − Machine from where we can manage other machines."
},
{
"code": null,
"e": 6178,
"s": 6111,
"text": "Control machine − Machine from where we can manage other machines."
},
{
"code": null,
"e": 6253,
"s": 6178,
"text": "Remote machine − Machines which are handled/controlled by control machine."
},
{
"code": null,
"e": 6328,
"s": 6253,
"text": "Remote machine − Machines which are handled/controlled by control machine."
},
{
"code": null,
"e": 6488,
"s": 6328,
"text": "There can be multiple remote machines which are handled by one control machine. So, for managing remote machines we have to install Ansible on control machine."
},
{
"code": null,
"e": 6609,
"s": 6488,
"text": "Ansible can be run from any machine with Python 2 (versions 2.6 or 2.7) or Python 3 (versions 3.5 and higher) installed."
},
{
"code": null,
"e": 6658,
"s": 6609,
"text": "Note − Windows does not support control machine."
},
{
"code": null,
"e": 6713,
"s": 6658,
"text": "By default, Ansible uses ssh to manage remote machine."
},
{
"code": null,
"e": 6986,
"s": 6713,
"text": "Ansible does not add any database. It does not require any daemons to start or keep it running. While managing remote machines, Ansible does not leave any software installed or running on them. Hence, there is no question of how to upgrade it when moving to a new version."
},
{
"code": null,
"e": 7174,
"s": 6986,
"text": "Ansible can be installed on control machine which have above mentioned requirements in different ways. You can install the latest release through Apt, yum, pkg, pip, OpenCSW, pacman, etc."
},
{
"code": null,
"e": 7295,
"s": 7174,
"text": "For installing Ansible you have to configure PPA on your machine. For this, you have to run the following line of code −"
},
{
"code": null,
"e": 7470,
"s": 7295,
"text": "$ sudo apt-get update \n$ sudo apt-get install software-properties-common \n$ sudo apt-add-repository ppa:ansible/ansible $ sudo apt-get update \n$ sudo apt-get install ansible\n"
},
{
"code": null,
"e": 7676,
"s": 7470,
"text": "After running the above line of code, you are ready to manage remote machines through Ansible. Just run Ansible–version to check the version and just to check whether Ansible was installed properly or not."
},
{
"code": null,
"e": 7916,
"s": 7676,
"text": "Ansible uses YAML syntax for expressing Ansible playbooks. This chapter provides an overview of YAML. Ansible uses YAML because it is very easy for humans to understand, read and write when compared to other data formats like XML and JSON."
},
{
"code": null,
"e": 7982,
"s": 7916,
"text": "Every YAML file optionally starts with “---” and ends with “...”."
},
{
"code": null,
"e": 8071,
"s": 7982,
"text": "In this section, we will learn the different ways in which the YAML data is represented."
},
{
"code": null,
"e": 8176,
"s": 8071,
"text": "YAML uses simple key-value pair to represent the data. The dictionary is represented in key: value pair."
},
{
"code": null,
"e": 8226,
"s": 8176,
"text": "Note − There should be space between : and value."
},
{
"code": null,
"e": 8360,
"s": 8226,
"text": "--- #Optional YAML start syntax \njames: \n name: james john \n rollNo: 34 \n div: B \n sex: male \n... #Optional YAML end syntax \n"
},
{
"code": null,
"e": 8417,
"s": 8360,
"text": "You can also use abbreviation to represent dictionaries."
},
{
"code": null,
"e": 8475,
"s": 8417,
"text": "James: {name: james john, rollNo: 34, div: B, sex: male}\n"
},
{
"code": null,
"e": 8629,
"s": 8475,
"text": "We can also represent List in YAML. Every element(member) of list should be written in a new line with same indentation starting with “- “ (- and space)."
},
{
"code": null,
"e": 8704,
"s": 8629,
"text": "---\ncountries: \n - America \n - China \n - Canada \n - Iceland \n...\n"
},
{
"code": null,
"e": 8754,
"s": 8704,
"text": "You can also use abbreviation to represent lists."
},
{
"code": null,
"e": 8809,
"s": 8754,
"text": "Countries: [‘America’, ‘China’, ‘Canada’, ‘Iceland’] \n"
},
{
"code": null,
"e": 8874,
"s": 8809,
"text": "We can use list inside dictionaries, i.e., value of key is list."
},
{
"code": null,
"e": 9015,
"s": 8874,
"text": "--- \njames: \n name: james john \n rollNo: 34 \n div: B \n sex: male \n likes: \n - maths \n - physics \n - english \n... \n"
},
{
"code": null,
"e": 9054,
"s": 9015,
"text": "We can also make list of dictionaries."
},
{
"code": null,
"e": 9340,
"s": 9054,
"text": "--- \n- james: \n name: james john \n rollNo: 34 \n div: B \n sex: male \n likes: \n - maths \n - physics \n - english \n\n- robert: \n name: robert richardson \n rollNo: 53 \n div: B \n sex: male \n likes: \n - biology \n - chemistry \n... \n"
},
{
"code": null,
"e": 9558,
"s": 9340,
"text": "YAML uses “|” to include newlines while showing multiple lines and “>” to suppress newlines while showing multiple lines. Due to this we can read and edit large lines. In both the cases intendentation will be ignored."
},
{
"code": null,
"e": 9663,
"s": 9558,
"text": "We can also represent Boolean (True/false) values in YAML. where boolean values can be case insensitive."
},
{
"code": null,
"e": 10103,
"s": 9663,
"text": "--- \n- james: \n name: james john \n rollNo: 34 \n div: B \n sex: male \n likes: \n - maths \n - physics \n - english \n \n result: \n maths: 87 \n chemistry: 45 \n biology: 56 \n physics: 70 \n english: 80 \n \n passed: TRUE \n \n messageIncludeNewLines: | \n Congratulation!! \n You passed with 79% \n \n messageExcludeNewLines: > \n Congratulation!! \n You passed with 79% \n"
},
{
"code": null,
"e": 10172,
"s": 10103,
"text": "Service/Server − A process on the machine that provides the service."
},
{
"code": null,
"e": 10237,
"s": 10172,
"text": "Machine − A physical server, vm(virtual machine) or a container."
},
{
"code": null,
"e": 10304,
"s": 10237,
"text": "Target machine − A machine we are about to configure with Ansible."
},
{
"code": null,
"e": 10368,
"s": 10304,
"text": "Task − An action(run this, delete that) etc managed by Ansible."
},
{
"code": null,
"e": 10461,
"s": 10368,
"text": "Playbook − The yml file where Ansible commands are written and yml is executed on a machine."
},
{
"code": null,
"e": 10592,
"s": 10461,
"text": "Ad hoc commands are commands which can be run individually to perform quick functions. These commands need not be performed later."
},
{
"code": null,
"e": 10717,
"s": 10592,
"text": "For example, you have to reboot all your company servers. For this, you will run the Adhoc commands from ‘/usr/bin/ansible’."
},
{
"code": null,
"e": 10843,
"s": 10717,
"text": "These ad-hoc commands are not used for configuration management and deployment, because these commands are of one time usage."
},
{
"code": null,
"e": 10913,
"s": 10843,
"text": "ansible-playbook is used for configuration management and deployment."
},
{
"code": null,
"e": 11023,
"s": 10913,
"text": "Reboot your company server in 12 parallel forks at time. For this, we need to set up SSHagent for connection."
},
{
"code": null,
"e": 11067,
"s": 11023,
"text": "$ ssh-agent bash \n$ ssh-add ~/.ssh/id_rsa \n"
},
{
"code": null,
"e": 11152,
"s": 11067,
"text": "To run reboot for all your company servers in a group, 'abc', in 12 parallel forks −"
},
{
"code": null,
"e": 11191,
"s": 11152,
"text": "$ Ansible abc -a \"/sbin/reboot\" -f 12\n"
},
{
"code": null,
"e": 11377,
"s": 11191,
"text": "By default, Ansible will run the above Ad-hoc commands form current user account. If you want to change this behavior, you will have to pass the username in Ad-hoc commands as follows −"
},
{
"code": null,
"e": 11428,
"s": 11377,
"text": "$ Ansible abc -a \"/sbin/reboot\" -f 12 -u username\n"
},
{
"code": null,
"e": 11545,
"s": 11428,
"text": "You can use the Ad-hoc commands for doing SCP (Secure Copy Protocol) lots of files in parallel on multiple machines."
},
{
"code": null,
"e": 11614,
"s": 11545,
"text": "$ Ansible abc -m copy -a \"src = /etc/yum.conf dest = /tmp/yum.conf\"\n"
},
{
"code": null,
"e": 11723,
"s": 11614,
"text": "$ Ansible abc -m file -a \"dest = /path/user1/new mode = 777 owner = user1 group = user1 state = directory\" \n"
},
{
"code": null,
"e": 11789,
"s": 11723,
"text": "$ Ansible abc -m file -a \"dest = /path/user1/new state = absent\"\n"
},
{
"code": null,
"e": 11886,
"s": 11789,
"text": "The Ad-hoc commands are available for yum and apt. Following are some Ad-hoc commands using yum."
},
{
"code": null,
"e": 11975,
"s": 11886,
"text": "The following command checks if yum package is installed or not, but does not update it."
},
{
"code": null,
"e": 12039,
"s": 11975,
"text": "$ Ansible abc -m yum -a \"name = demo-tomcat-1 state = present\"\n"
},
{
"code": null,
"e": 12097,
"s": 12039,
"text": "The following command check the package is not installed."
},
{
"code": null,
"e": 12161,
"s": 12097,
"text": "$ Ansible abc -m yum -a \"name = demo-tomcat-1 state = absent\" \n"
},
{
"code": null,
"e": 12234,
"s": 12161,
"text": "The following command checks the latest version of package is installed."
},
{
"code": null,
"e": 12298,
"s": 12234,
"text": "$ Ansible abc -m yum -a \"name = demo-tomcat-1 state = latest\" \n"
},
{
"code": null,
"e": 12457,
"s": 12298,
"text": "Facts can be used for implementing conditional statements in playbook. You can find adhoc information of all your facts through the following Ad-hoc command −"
},
{
"code": null,
"e": 12482,
"s": 12457,
"text": "$ Ansible all -m setup \n"
},
{
"code": null,
"e": 12541,
"s": 12482,
"text": "In this chapter, we will learn about Playbooks in Ansible."
},
{
"code": null,
"e": 12833,
"s": 12541,
"text": "Playbooks are the files where Ansible code is written. Playbooks are written in YAML format. YAML stands for Yet Another Markup Language. Playbooks are one of the core features of Ansible and tell Ansible what to execute. They are like a to-do list for Ansible that contains a list of tasks."
},
{
"code": null,
"e": 13018,
"s": 12833,
"text": "Playbooks contain the steps which the user wants to execute on a particular machine. Playbooks are run sequentially. Playbooks are the building blocks for all the use cases of Ansible."
},
{
"code": null,
"e": 13167,
"s": 13018,
"text": "Each playbook is an aggregation of one or more plays in it. Playbooks are structured using Plays. There can be more than one play inside a playbook."
},
{
"code": null,
"e": 13257,
"s": 13167,
"text": "The function of a play is to map a set of instructions defined against a particular host."
},
{
"code": null,
"e": 13549,
"s": 13257,
"text": "YAML is a strict typed language; so, extra care needs to be taken while writing the YAML files. There are different YAML editors but we will prefer to use a simple editor like notepad++. Just open notepad++ and copy and paste the below yaml and change the language to YAML (Language → YAML)."
},
{
"code": null,
"e": 13584,
"s": 13549,
"text": "A YAML starts with --- (3 hyphens)"
},
{
"code": null,
"e": 13686,
"s": 13584,
"text": "Let us start by writing a sample YAML file. We will walk through each section written in a yaml file."
},
{
"code": null,
"e": 13999,
"s": 13686,
"text": "--- \n name: install and configure DB\n hosts: testServer\n become: yes\n\n vars: \n oracle_db_port_value : 1521\n \n tasks:\n -name: Install the Oracle DB\n yum: <code to install the DB>\n \n -name: Ensure the installed service is enabled and running\n service:\n name: <your service name>"
},
{
"code": null,
"e": 14254,
"s": 13999,
"text": "The above is a sample Playbook where we are trying to cover the basic syntax of a playbook. Save the above content in a file as test.yml. A YAML syntax needs to follow the correct indentation and one needs to be a little careful while writing the syntax."
},
{
"code": null,
"e": 14342,
"s": 14254,
"text": "Let us now go through the different YAML tags. The different tags are described below −"
},
{
"code": null,
"e": 14482,
"s": 14342,
"text": "This tag specifies the name of the Ansible playbook. As in what this playbook will be doing. Any logical name can be given to the playbook."
},
{
"code": null,
"e": 14834,
"s": 14482,
"text": "This tag specifies the lists of hosts or host group against which we want to run the task. The hosts field/tag is mandatory. It tells Ansible on which hosts to run the listed tasks. The tasks can be run on the same machine or on a remote machine. One can run the tasks on multiple machines and hence hosts tag can have a group of hosts’ entry as well."
},
{
"code": null,
"e": 14968,
"s": 14834,
"text": "Vars tag lets you define the variables which you can use in your playbook. Usage is similar to variables in any programming language."
},
{
"code": null,
"e": 15405,
"s": 14968,
"text": "All playbooks should contain tasks or a list of tasks to be executed. Tasks are a list of actions one needs to perform. A tasks field contains the name of the task. This works as the help text for the user. It is not mandatory but proves useful in debugging the playbook. Each task internally links to a piece of code called a module. A module that should be executed, and arguments that are required for the module you want to execute."
},
{
"code": null,
"e": 15536,
"s": 15405,
"text": "Roles provide a framework for fully independent, or interdependent collections of variables, tasks, files, templates, and modules."
},
{
"code": null,
"e": 15799,
"s": 15536,
"text": "In Ansible, the role is the primary mechanism for breaking a playbook into multiple files. This simplifies writing complex playbooks, and it makes them easier to reuse. The breaking of playbook allows you to logically break the playbook into reusable components."
},
{
"code": null,
"e": 16004,
"s": 15799,
"text": "Each role is basically limited to a particular functionality or desired output, with all the necessary steps to provide that result either within that role itself or in other roles listed as dependencies."
},
{
"code": null,
"e": 16243,
"s": 16004,
"text": "Roles are not playbooks. Roles are small functionality which can be independently used but have to be used within playbooks. There is no way to directly execute a role. Roles have no explicit setting for which host the role will apply to."
},
{
"code": null,
"e": 16369,
"s": 16243,
"text": "Top-level playbooks are the bridge holding the hosts from your inventory file to roles that should be applied to those hosts."
},
{
"code": null,
"e": 16438,
"s": 16369,
"text": "The directory structure for roles is essential to create a new role."
},
{
"code": null,
"e": 16564,
"s": 16438,
"text": "Roles have a structured layout on the file system. The default structure can be changed but for now let us stick to defaults."
},
{
"code": null,
"e": 16670,
"s": 16564,
"text": "Each role is a directory tree in itself. The role name is the directory name within the /roles directory."
},
{
"code": null,
"e": 16692,
"s": 16670,
"text": "$ ansible-galaxy -h \n"
},
{
"code": null,
"e": 16797,
"s": 16692,
"text": "ansible-galaxy [delete|import|info|init|install|list|login|remove|search|setup] [--help] [options] ... \n"
},
{
"code": null,
"e": 16843,
"s": 16797,
"text": "-h, --help − Show this help message and exit."
},
{
"code": null,
"e": 16889,
"s": 16843,
"text": "-h, --help − Show this help message and exit."
},
{
"code": null,
"e": 16972,
"s": 16889,
"text": "-v, --verbose − Verbose mode (-vvv for more, -vvvv to enable connection debugging)"
},
{
"code": null,
"e": 17055,
"s": 16972,
"text": "-v, --verbose − Verbose mode (-vvv for more, -vvvv to enable connection debugging)"
},
{
"code": null,
"e": 17107,
"s": 17055,
"text": "--version − Show program's version number and exit."
},
{
"code": null,
"e": 17159,
"s": 17107,
"text": "--version − Show program's version number and exit."
},
{
"code": null,
"e": 17211,
"s": 17159,
"text": "The above command has created the role directories."
},
{
"code": null,
"e": 17725,
"s": 17211,
"text": "$ ansible-galaxy init vivekrole \nERROR! The API server (https://galaxy.ansible.com/api/) is not responding, please try again later. \n\n$ ansible-galaxy init --force --offline vivekrole \n- vivekrole was created successfully \n\n$ tree vivekrole/ \nvivekrole/ \n├── defaults \n│ └── main.yml \n├── files ├── handlers \n│ └── main.yml \n├── meta \n│ └── main.yml \n├── README.md ├── tasks \n│ └── main.yml \n├── templates ├── tests │ ├── inventory \n│ └── test.yml \n└── vars \n └── main.yml \n \n8 directories, 8 files"
},
{
"code": null,
"e": 17834,
"s": 17725,
"text": "Not all the directories will be used in the example and we will show the use of some of them in the example."
},
{
"code": null,
"e": 18052,
"s": 17834,
"text": "This is the code of the playbook we have written for demo purpose. This code is of the playbook vivek_orchestrate.yml. We have defined the hosts: tomcat-node and called the two roles – install-tomcat and start-tomcat."
},
{
"code": null,
"e": 18146,
"s": 18052,
"text": "The problem statement is that we have a war which we need to deploy on a machine via Ansible."
},
{
"code": null,
"e": 18237,
"s": 18146,
"text": "--- \n- hosts: tomcat-node \nroles: \n - {role: install-tomcat} \n - {role: start-tomcat} "
},
{
"code": null,
"e": 18313,
"s": 18237,
"text": "Contents of our directory structure from where we are running the playbook."
},
{
"code": null,
"e": 18394,
"s": 18313,
"text": "$ ls \nansible.cfg hosts roles vivek_orchestrate.retry vivek_orchestrate.yml \n"
},
{
"code": null,
"e": 18516,
"s": 18394,
"text": "There is a tasks directory under each directory and it contains a main.yml. The main.yml contents of install-tomcat are −"
},
{
"code": null,
"e": 18902,
"s": 18516,
"text": "--- \n#Install vivek artifacts \n- \n block: \n - name: Install Tomcat artifacts\n action: > \n yum name = \"demo-tomcat-1\" state = present \n register: Output \n \n always: \n - debug: \n msg: \n - \"Install Tomcat artifacts task ended with message: {{Output}}\" \n - \"Installed Tomcat artifacts - {{Output.changed}}\" \n"
},
{
"code": null,
"e": 18953,
"s": 18902,
"text": "The contents of main.yml of the start tomcat are −"
},
{
"code": null,
"e": 19280,
"s": 18953,
"text": "#Start Tomcat \n- \n block: \n - name: Start Tomcat \n command: <path of tomcat>/bin/startup.sh\" \n register: output \n become: true \n \n always: \n - debug: \n msg: \n - \"Start Tomcat task ended with message: {{output}}\" \n - \"Tomcat started - {{output.changed}}\" \n"
},
{
"code": null,
"e": 19423,
"s": 19280,
"text": "The advantage of breaking the playbook into roles is that anyone who wants to use the Install tomcat feature can call the Install Tomcat role."
},
{
"code": null,
"e": 19580,
"s": 19423,
"text": "If not for the roles, the content of the main.yml of the respective role can be copied in the playbook yml file. But to have modularity, roles were created."
},
{
"code": null,
"e": 19713,
"s": 19580,
"text": "Any logical entity which can be reused as a reusable function, that entity can be moved to role. The example for this is shown above"
},
{
"code": null,
"e": 19750,
"s": 19713,
"text": "Ran the command to run the playbook."
},
{
"code": null,
"e": 19821,
"s": 19750,
"text": "-vvv option for verbose output – verbose output \n$ cd vivek-playbook/\n"
},
{
"code": null,
"e": 19861,
"s": 19821,
"text": "This is the command to run the playbook"
},
{
"code": null,
"e": 20062,
"s": 19861,
"text": "$ sudo ansible-playbook -i hosts vivek_orchestrate.yml –vvv \n-----------------------------------------------------------------\n----------------------------------------------------------------------- \n"
},
{
"code": null,
"e": 20110,
"s": 20062,
"text": "The generated output is as seen on the screen −"
},
{
"code": null,
"e": 20171,
"s": 20110,
"text": "Using /users/demo/vivek-playbook/ansible.cfg as config file."
},
{
"code": null,
"e": 37316,
"s": 20171,
"text": "PLAYBOOK: vivek_orchestrate.yml *********************************************************\n*********************************************************** \n1 plays in vivek_orchestrate.yml \n\nPLAY [tomcat-node] **********************************************************************\n******** ************************************************* \n \nTASK [Gathering Facts] *************************************************\n****************************** ********************************************* \nTuesday 21 November 2017 13:02:05 +0530 (0:00:00.056) 0:00:00.056 ****** \nUsing module file /usr/lib/python2.7/sitepackages/ansible/modules/system/setup.py \n<localhost> ESTABLISH LOCAL CONNECTION FOR USER: root \n<localhost> EXEC /bin/sh -c 'echo ~ && sleep 0' \n<localhost> EXEC /bin/sh -c '( umask 77 && mkdir -p \"` echo \n /root/.ansible/tmp/ansible-tmp-1511249525.88-259535494116870 `\" && \n echo ansible-tmp-1511249525.88-259535494116870=\"` \n echo /root/.ansible/tmp/ansibletmp-1511249525.88-259535494116870 `\" ) && sleep 0' \n<localhost> PUT /tmp/tmpPEPrkd TO \n /root/.ansible/tmp/ansible-tmp-1511249525.88259535494116870/setup.py \n<localhost> EXEC /bin/sh -c 'chmod u+x \n /root/.ansible/tmp/ansible-tmp1511249525.88-259535494116870/ \n /root/.ansible/tmp/ansible-tmp-1511249525.88259535494116870/setup.py && sleep 0' \n<localhost> EXEC /bin/sh -c '/usr/bin/python \n /root/.ansible/tmp/ansible-tmp1511249525.88-259535494116870/setup.py; rm -rf \n \"/root/.ansible/tmp/ansible-tmp1511249525.88-259535494116870/\" > /dev/null 2>&1 && sleep 0' \nok: [server1] \nMETA: ran handlers \n \nTASK [install-tomcat : Install Tomcat artifacts] ***********************************\n*************************************************************** \ntask path: /users/demo/vivek-playbook/roles/install-tomcat/tasks/main.yml:5 \nTuesday 21 November 2017 13:02:07 +0530 (0:00:01.515) 0:00:01.572 ****** \nUsing module file /usr/lib/python2.7/sitepackages/ansible/modules/packaging/os/yum.py \n<localhost> ESTABLISH LOCAL CONNECTION FOR USER: root \n<localhost> EXEC /bin/sh -c 'echo ~ && sleep 0' \n<localhost> EXEC /bin/sh -c '( umask 77 && mkdir -p \"` echo \n /root/.ansible/tmp/ansible-tmp-1511249527.34-40247177825302 `\" && echo \n ansibletmp-1511249527.34-40247177825302=\"` echo \n /root/.ansible/tmp/ansible-tmp1511249527.34-40247177825302 `\" ) && sleep 0' \n<localhost> PUT /tmp/tmpu83chg TO \n /root/.ansible/tmp/ansible-tmp-1511249527.3440247177825302/yum.py \n<localhost> EXEC /bin/sh -c 'chmod u+x \n /root/.ansible/tmp/ansible-tmp1511249527.34-40247177825302/ \n /root/.ansible/tmp/ansible-tmp-1511249527.3440247177825302/yum.py && sleep 0' \n<localhost> EXEC /bin/sh -c '/usr/bin/python \n /root/.ansible/tmp/ansible-tmp1511249527.34-40247177825302/yum.py; rm -rf \n \"/root/.ansible/tmp/ansible-tmp1511249527.34-40247177825302/\" > /dev/null 2>\n &1 && sleep 0' \nchanged: [server1] => { \n \"changed\": true, \n \"invocation\": { \n \"module_args\": { \n \"conf_file\": null, \n \"disable_gpg_check\": false, \n \"disablerepo\": null, \n \"enablerepo\": null, \n \"exclude\": null, \n \"install_repoquery\": true, \n \"installroot\": \"/\", \n \"list\": null, \n \"name\": [\"demo-tomcat-1\"], \n \"skip_broken\": false, \n \"state\": \"present\", \n \"update_cache\": false, \n \"validate_certs\": true \n } \n }, \n \"msg\": \"\", \n \"rc\": 0, \n \"results\": [ \n \"Loaded plugins: product-id, \n search-disabled-repos, \n subscriptionmanager\\nThis system is not registered to Red Hat Subscription Management. \n You can use subscription-manager to register.\\nResolving Dependencies\\n--> \n Running transaction check\\n---> \n Package demo-tomcat-1.noarch 0:SNAPSHOT-1 will be installed\\n--> Finished Dependency \n Resolution\\n\\nDependencies Resolved\\n\n \\n================================================================================\\n \n Package Arch Version Repository \n Size\\n==================================================================\\nInstalling:\\n \n demo-tomcat-1 noarch SNAPSHOT-1 demo-repo1 7.1 M\\n\\nTransaction \n Summary\\n==================================================================\\nInstall 1 \n Package\\n\\nTotal download size: 7.1 M\\nInstalled size: 7.9 M\\nDownloading \n packages:\\nRunning transaction \n check\\nRunning transaction test\\nTransaction test succeeded\\nRunning transaction\\n Installing : \n demotomcat-1-SNAPSHOT-1.noarch 1/1 \\n Verifying : \n demo-tomcat-1-SNAPSHOT-1.noarch 1/1 \\n\\nInstalled:\\n \n demo-tomcat-1.noarch 0:SNAPSHOT-1 \\n\\nComplete!\\n\" \n ] \n} \n \nTASK [install-tomcat : debug] **********************************************************\n*************************************************************************** \ntask path: /users/demo/vivek-playbook/roles/install-tomcat/tasks/main.yml:11 \nTuesday 21 November 2017 13:02:13 +0530 (0:00:06.757) 0:00:08.329 ****** \nok: [server1] => { \n \"changed\": false, \n \"msg\": [ \n \"Install Tomcat artifacts task ended with message: {\n u'msg': u'', u'changed': True, u'results': \n [u'Loaded plugins: product-id, \n search-disabledrepos, \n subscription-manager\\\\nThis system is not registered to Red Hat Subscription Management. \n You can use subscription-manager to register.\\\\nResolving Dependencies\\\\n--> \n Running transaction check\\\\n---> \n Package demo-tomcat-1.noarch 0:SNAPSHOT-1 will be installed\\\\n--> \n Finished Dependency Resolution\\\\n\n \\\\nDependencies \n Resolved\\\\n\\\\n==================================================================\\\\n \n Package Arch Version Repository \n Size\\\\n======================================================================== \n =====\\\\nInstalling:\\\\n demo-tomcat-1 noarch SNAPSHOT-1 demo-repo1 7.1 M\\\\n\\\\nTransaction \n Summary\\\\n=========================================================\\\\nInstall 1 \n Package\\\\n\\\\nTotal download size: 7.1 M\\\\nInstalled size: 7.9 M\\\\nDownloading \n packages:\\\\nRunning \n transaction check\\\\nRunning transaction test\\\\nTransaction test succeeded\\\\nRunning \n transaction\\\\n \n Installing : demo-tomcat-1-SNAPSHOT-1.noarch 1/1 \\\\n Verifying : \n demo-tomcat-1-SNAPSHOT-1.noarch\n 1/1 \\\\n\\\\nInstalled:\\\\n demo-tomcat-1.noarch 0:SNAPSHOT-1 \\\\n\\\\nComplete!\\\\n'], u'rc': 0\n }\", \n \"Installed Tomcat artifacts - True\" \n ] \n} \n \nTASK [install-tomcat : Clean DEMO environment] ****************************************\n************************************************************ \ntask path: /users/demo/vivek-playbook/roles/install-tomcat/tasks/main.yml:19 \nTuesday 21 November 2017 13:02:13 +0530 (0:00:00.057) 0:00:08.387 ****** \n[WARNING]: when statements should not include jinja2 templating delimiters such as {{ }} or \n {% %}. Found: {{installationOutput.changed}} \n \nUsing module file /usr/lib/python2.7/sitepackages/ansible/modules/files/file.py \n<localhost> ESTABLISH LOCAL CONNECTION FOR USER: root \n<localhost> EXEC /bin/sh -c 'echo ~ && sleep 0' \n<localhost> EXEC /bin/sh -c '( umask 77 && mkdir -p \"` echo \n /root/.ansible/tmp/ansible-tmp-1511249534.13-128345805983963 `\" && echo \n ansible-tmp-1511249534.13-128345805983963=\"` echo \n /root/.ansible/tmp/ansibletmp-1511249534.13-128345805983963 `\" ) && sleep 0' \n<localhost> PUT /tmp/tmp0aXel7 TO \n /root/.ansible/tmp/ansible-tmp-1511249534.13128345805983963/file.py \n<localhost> EXEC /bin/sh -c 'chmod u+x \n /root/.ansible/tmp/ansible-tmp1511249534.13-128345805983963/ \n /root/.ansible/tmp/ansible-tmp-1511249534.13128345805983963/file.py && sleep 0' \n<localhost> EXEC /bin/sh -c '/usr/bin/python \n /root/.ansible/tmp/ansible-tmp1511249534.13-128345805983963/file.py; rm -rf \n \"/root/.ansible/tmp/ansible-tmp1511249534.13-128345805983963/\" > /dev/null 2>&1 \n && sleep 0' \nchanged: [server1] => { \n \"changed\": true, \n \"diff\": { \n \"after\": { \n \"path\": \"/users/demo/DEMO\", \n \"state\": \"absent\" \n }, \n \"before\": { \n \"path\": \"/users/demo/DEMO\", \n \"state\": \"directory\" \n } \n },\n\n \"invocation\": { \n \"module_args\": { \n \"attributes\": null, \n \"backup\": null, \n \"content\": null, \n \"delimiter\": null, \n \"diff_peek\": null, \n \"directory_mode\": null, \n \"follow\": false, \n \"force\": false, \n \"group\": null, \n \"mode\": null, \n \"original_basename\": null, \n \"owner\": null, \n \"path\": \"/users/demo/DEMO\", \n \"recurse\": false, \n \"regexp\": null, \n \"remote_src\": null, \n \"selevel\": null, \n \"serole\": null, \n \"setype\": null, \n \"seuser\": null, \n \"src\": null, \n \"state\": \"absent\", \n \"unsafe_writes\": null, \n \"validate\": null \n } \n }, \n \"path\": \"/users/demo/DEMO\", \n \"state\": \"absent\" \n} \n \nTASK [install-tomcat : debug] ********************************************************\n************************************************************* \ntask path: /users/demo/vivek-playbook/roles/install-tomcat/tasks/main.yml:29 \nTuesday 21 November 2017 13:02:14 +0530 (0:00:00.257) 0:00:08.645 ****** \nok: [server1] => {\n \"changed\": false, \n \"msg\": [ \n \"Clean DEMO environment task ended with message:{u'diff': {u'after': {u'path': \n u'/users/demo/DEMO', u'state': u'absent'}, \n u'before': {u'path': u'/users/demo/DEMO', u'state': u'directory'}}, u'state': u'absent', \n u'changed': True, u'path': u'/users/demo/DEMO'}\", \n \"check value :True\" \n ] \n} \n \nTASK [install-tomcat : Copy Tomcat to user home] *************************************\n******************************************************** \ntask path: /users/demo/vivek-playbook/roles/install-tomcat/tasks/main.yml:37 \nTuesday 21 November 2017 13:02:14 +0530 (0:00:00.055) 0:00:08.701 ****** \n[WARNING]: when statements should not include jinja2 templating delimiters such as {{ }} or \n {% %}. Found: {{installationOutput.changed}} \n \nUsing module file /usr/lib/python2.7/sitepackages/ansible/modules/commands/command.py \n<localhost> ESTABLISH LOCAL CONNECTION FOR USER: root \n<localhost> EXEC /bin/sh -c 'echo ~ && sleep 0' \n<localhost> EXEC /bin/sh -c '( umask 77 && mkdir -p \"` echo \n /root/.ansible/tmp/ansible-tmp-1511249534.43-41077200718443 `\" && echo \n ansibletmp-1511249534.43-41077200718443=\"` echo \n /root/.ansible/tmp/ansible-tmp1511249534.43-41077200718443 `\" ) && sleep 0' \n<localhost> PUT /tmp/tmp25deWs TO \n /root/.ansible/tmp/ansible-tmp-1511249534.4341077200718443/command.py \n<localhost> EXEC /bin/sh -c 'chmod u+x \n /root/.ansible/tmp/ansible-tmp1511249534.43-41077200718443/ \n /root/.ansible/tmp/ansible-tmp-1511249534.4341077200718443/command.py && sleep 0' \n<localhost> EXEC /bin/sh -c '/usr/bin/python \n /root/.ansible/tmp/ansible-tmp1511249534.43-41077200718443/command.py; rm -rf \n \"/root/.ansible/tmp/ansibletmp-1511249534.43-41077200718443/\" > /dev/null 2>&1 \n && sleep 0' \nchanged: [server1] => { \n \"changed\": true, \n \"cmd\": [ \n \"cp\", \n \"-r\", \n \"/opt/ansible/tomcat/demo\", \n \"/users/demo/DEMO/\" \n ],\n \"delta\": \"0:00:00.017923\", \n \"end\": \"2017-11-21 13:02:14.547633\", \n \"invocation\": { \n \"module_args\": { \n \"_raw_params\": \"cp -r /opt/ansible/tomcat/demo /users/demo/DEMO/\", \n \"_uses_shell\": false, \n \"chdir\": null, \n \"creates\": null, \n \"executable\": null, \n \"removes\": null, \n \"warn\": true \n } \n }, \n \"rc\": 0, \n \"start\": \"2017-11-21 13:02:14.529710\", \n \"stderr\": \"\", \n \"stderr_lines\": [], \n \"stdout\": \"\", \n \"stdout_lines\": [] \n} \n \nTASK [install-tomcat : debug] ********************************************************\n********************************************************** \ntask path: /users/demo/vivek-playbook/roles/install-tomcat/tasks/main.yml:47 \nTuesday 21 November 2017 13:02:14 +0530 (0:00:00.260) 0:00:08.961 ****** \nok: [server1] => { \n \"changed\": false, \n \"msg\": \"Copy Tomcat to user home task ended with message {\n 'stderr_lines': [], u'changed': True, u'end': u'2017-11-21 13:02:14.547633', u'stdout': \n u'', u'cmd': [u'cp', u'-r', u'/opt/ansible/tomcat/demo', u'/users/demo/DEMO/'], u'rc': 0, \n u'start': u'2017-11-21 13:02:14.529710', u'stderr': u'', u'delta': u'0:00:00.017923', \n 'stdout_lines': []}\" \n} \n \nTASK [start-tomcat : Start Tomcat] **************************************************\n********************************************************** \ntask path: /users/demo/vivek-playbook/roles/start-tomcat/tasks/main.yml:5 \nTuesday 21 November 2017 13:02:14 +0530 (0:00:00.044) 0:00:09.006 ****** \nUsing module file /usr/lib/python2.7/sitepackages/ansible/modules/commands/command.py \n<localhost> ESTABLISH LOCAL CONNECTION FOR USER: root \n<localhost> EXEC /bin/sh -c 'echo ~ && sleep 0' \n<localhost> EXEC /bin/sh -c '( umask 77 && mkdir -p \"` echo \n /root/.ansible/tmp/ansible-tmp-1511249534.63-46501211251197 `\" && echo \n ansibletmp-1511249534.63-46501211251197=\"` echo \n /root/.ansible/tmp/ansible-tmp1511249534.63-46501211251197 `\" ) && sleep 0' \n<localhost> PUT /tmp/tmp9f06MQ TO \n /root/.ansible/tmp/ansible-tmp-1511249534.6346501211251197/command.py \n<localhost> EXEC /bin/sh -c 'chmod u+x \n /root/.ansible/tmp/ansible-tmp1511249534.63-46501211251197/ \n /root/.ansible/tmp/ansible-tmp-1511249534.6346501211251197/command.py && sleep 0' \n<localhost> EXEC /bin/sh -c '/usr/bin/python \n /root/.ansible/tmp/ansible-tmp1511249534.63-46501211251197/command.py; rm -rf \n \"/root/.ansible/tmp/ansibletmp-1511249534.63-46501211251197/\" > /dev/null 2>&1 \n && sleep 0' \nchanged: [server1] => { \n \"changed\": true, \n \"cmd\": [ \"/users/demo/DEMO/bin/startup.sh\" ], \n \"delta\": \"0:00:00.020024\", \n \"end\": \"2017-11-21 13:02:14.741649\", \n \"invocation\": { \n \"module_args\": { \n \"_raw_params\": \"/users/demo/DEMO/bin/startup.sh\", \n \"_uses_shell\": false, \n \"chdir\": null, \n \"creates\": null, \n \"executable\": null, \n \"removes\": null, \n \"warn\": true \n } \n }, \n \"rc\": 0, \n \"start\": \"2017-11-21 13:02:14.721625\", \n \"stderr\": \"\", \n \"stderr_lines\": [], \n \"stdout\": \"Tomcat started.\", \n \"stdout_lines\": [ \"Tomcat started.\" ] \n} \n \nTASK [start-tomcat : debug] *************************************************\n********************************************************************** \ntask path: /users/demo/vivek-playbook/roles/start-tomcat/tasks/main.yml:10 \nTuesday 21 November 2017 13:02:14 +0530 (0:00:00.150) 0:00:09.156 ****** \nok: [server1] => { \n \"changed\": false, \n \"msg\": [ \n \"Start Tomcat task ended with message: {'\n stderr_lines': [], u'changed': True, u'end': u'2017-11-21 13:02:14.741649', u'stdout': \n u'Tomcat started.', u'cmd': [u'/users/demo/DEMO/bin/startup.sh'], u'rc': 0, u'start': \n u'2017-11-21 13:02:14.721625', u'stderr': u'', u'delta': u'0:00:00.020024', \n 'stdout_lines': [u'Tomcat started.']}\", \n \"Tomcat started - True\" \n ] \n} \nMETA: ran handlers \nMETA: ran handlers \n \nPLAY RECAP ******************************************************************************* \n********************************************************* \nserver1 : ok = 9 changed = 4 unreachable = 0 failed = 0 \n \nTuesday 21 November 2017 13:02:14 +0530 (0:00:00.042) 0:00:09.198 ****** \n=============================================================================== \ninstall-tomcat : Install Tomcat artifacts ------------------------------- 6.76s \n/users/demo/vivek-playbook/roles/install-tomcat/tasks/main.yml:5 -------------- \nGathering Facts --------------------------------------------------------- 1.52s \n ------------------------------------------------------------------------------ \ninstall-tomcat : Copy Tomcat to user home ------------------------------- 0.26s \n/users/demo/vivek-playbook/roles/install-tomcat/tasks/main.yml:37 ------------- \n\ninstall-tomcat : Clean DEMO environment --------------------------------- 0.26s \n/users/demo/vivek-playbook/roles/install-tomcat/tasks/main.yml:19 ------------- \n\nstart-tomcat : Start Tomcat --------------------------------------------- 0.15s \n/users/demo/vivek-playbook/roles/start-tomcat/tasks/main.yml:5 ----------------\n\ninstall-tomcat : debug -------------------------------------------------- 0.06s \n/users/demo/vivek-playbook/roles/install-tomcat/tasks/main.yml:11 ------------- \n\ninstall-tomcat : debug -------------------------------------------------- 0.06s \n/users/demo/vivek-playbook/roles/install-tomcat/tasks/main.yml:29 ------------- \n\ninstall-tomcat : debug -------------------------------------------------- 0.04s \n/users/demo/vivek-playbook/roles/install-tomcat/tasks/main.yml:47 ------------- \n\nstart-tomcat : debug ---------------------------------------------------- 0.04s \n/users/demo/vivek-playbook/roles/start-tomcat/tasks/main.yml:10 --------------- \n"
},
{
"code": null,
"e": 37438,
"s": 37316,
"text": "Hit the following URL and you will be directed to a page as shown below − http://10.76.0.134:11677/HelloWorld/HelloWorld"
},
{
"code": null,
"e": 37617,
"s": 37438,
"text": "The deployed war just has a servlet which displays “Hello World”. The detailed output shows the time taken by each and every task because of the entry added in ansible.cfg file −"
},
{
"code": null,
"e": 37666,
"s": 37617,
"text": "[defaults] \ncallback_whitelist = profile_tasks \n"
},
{
"code": null,
"e": 37944,
"s": 37666,
"text": "Variable in playbooks are very similar to using variables in any programming language. It helps you to use and assign a value to a variable and use that anywhere in the playbook. One can put conditions around the value of the variables and accordingly use them in the playbook."
},
{
"code": null,
"e": 37995,
"s": 37944,
"text": "- hosts : <your hosts> \nvars:\ntomcat_port : 8080 \n"
},
{
"code": null,
"e": 38157,
"s": 37995,
"text": "In the above example, we have defined a variable name tomcat_port and assigned the value 8080 to that variable and can use that in your playbook wherever needed."
},
{
"code": null,
"e": 38268,
"s": 38157,
"text": "Now taking a reference from the example shared. The following code is from one of the roles (install-tomcat) −"
},
{
"code": null,
"e": 38602,
"s": 38268,
"text": "block: \n - name: Install Tomcat artifacts \n action: > \n yum name = \"demo-tomcat-1\" state = present \n register: Output \n \n always: \n - debug: \n msg: \n - \"Install Tomcat artifacts task ended with message: {{Output}}\" \n - \"Installed Tomcat artifacts - {{Output.changed}}\" \n"
},
{
"code": null,
"e": 38641,
"s": 38602,
"text": "Here, the output is the variable used."
},
{
"code": null,
"e": 38703,
"s": 38641,
"text": "Let us walk through all the keywords used in the above code −"
},
{
"code": null,
"e": 38752,
"s": 38703,
"text": "block − Ansible syntax to execute a given block."
},
{
"code": null,
"e": 38801,
"s": 38752,
"text": "block − Ansible syntax to execute a given block."
},
{
"code": null,
"e": 38934,
"s": 38801,
"text": "name − Relevant name of the block - this is used in logging and helps in debugging that which all blocks were successfully executed."
},
{
"code": null,
"e": 39067,
"s": 38934,
"text": "name − Relevant name of the block - this is used in logging and helps in debugging that which all blocks were successfully executed."
},
{
"code": null,
"e": 39184,
"s": 39067,
"text": "action − The code next to action tag is the task to be executed. The action again is a Ansible keyword used in yaml."
},
{
"code": null,
"e": 39301,
"s": 39184,
"text": "action − The code next to action tag is the task to be executed. The action again is a Ansible keyword used in yaml."
},
{
"code": null,
"e": 39441,
"s": 39301,
"text": "register − The output of the action is registered using the register keyword and Output is the variable name which holds the action output."
},
{
"code": null,
"e": 39581,
"s": 39441,
"text": "register − The output of the action is registered using the register keyword and Output is the variable name which holds the action output."
},
{
"code": null,
"e": 39662,
"s": 39581,
"text": "always − Again a Ansible keyword , it states that below will always be executed."
},
{
"code": null,
"e": 39743,
"s": 39662,
"text": "always − Again a Ansible keyword , it states that below will always be executed."
},
{
"code": null,
"e": 39771,
"s": 39743,
"text": "msg − Displays the message."
},
{
"code": null,
"e": 39799,
"s": 39771,
"text": "msg − Displays the message."
},
{
"code": null,
"e": 39927,
"s": 39799,
"text": "This will read the value of variable Output. Also as it is used in the msg tab, it will print the value of the output variable."
},
{
"code": null,
"e": 40097,
"s": 39927,
"text": "Additionally, you can use the sub properties of the variable as well. Like in the case checking {{Output.changed}} whether the output got changed and accordingly use it."
},
{
"code": null,
"e": 40254,
"s": 40097,
"text": "Exception handling in Ansible is similar to exception handling in any programming language. An example of the exception handling in playbook is shown below."
},
{
"code": null,
"e": 40694,
"s": 40254,
"text": "tasks: \n - name: Name of the task to be executed \n block: \n - debug: msg = 'Just a debug message , relevant for logging' \n - command: <the command to execute> \n \n rescue: \n - debug: msg = 'There was an exception.. ' \n - command: <Rescue mechanism for the above exception occurred) \n \n always: \n - debug: msg = \"this will execute in all scenarios. Always will get logged\" \n"
},
{
"code": null,
"e": 40742,
"s": 40694,
"text": "Following is the syntax for exception handling."
},
{
"code": null,
"e": 40809,
"s": 40742,
"text": "rescue and always are the keywords specific to exception handling."
},
{
"code": null,
"e": 40876,
"s": 40809,
"text": "rescue and always are the keywords specific to exception handling."
},
{
"code": null,
"e": 40958,
"s": 40876,
"text": "Block is where the code is written (anything to be executed on the Unix machine)."
},
{
"code": null,
"e": 41040,
"s": 40958,
"text": "Block is where the code is written (anything to be executed on the Unix machine)."
},
{
"code": null,
"e": 41253,
"s": 41040,
"text": "If the command written inside the block feature fails, then the execution reaches rescue block and it gets executed. In case there is no error in the command under block feature, then rescue will not be executed."
},
{
"code": null,
"e": 41466,
"s": 41253,
"text": "If the command written inside the block feature fails, then the execution reaches rescue block and it gets executed. In case there is no error in the command under block feature, then rescue will not be executed."
},
{
"code": null,
"e": 41501,
"s": 41466,
"text": "Always gets executed in all cases."
},
{
"code": null,
"e": 41536,
"s": 41501,
"text": "Always gets executed in all cases."
},
{
"code": null,
"e": 41625,
"s": 41536,
"text": "So if we compare the same with java, then it is similar to try, catch and finally block."
},
{
"code": null,
"e": 41714,
"s": 41625,
"text": "So if we compare the same with java, then it is similar to try, catch and finally block."
},
{
"code": null,
"e": 41861,
"s": 41714,
"text": "Here, Block is similar to try block where you write the code to be executed and rescue is similar to catch block and always is similar to finally."
},
{
"code": null,
"e": 42008,
"s": 41861,
"text": "Here, Block is similar to try block where you write the code to be executed and rescue is similar to catch block and always is similar to finally."
},
{
"code": null,
"e": 42075,
"s": 42008,
"text": "Below is the example to demonstrate the usage of Loops in Ansible."
},
{
"code": null,
"e": 42170,
"s": 42075,
"text": "The tasks is to copy the set of all the war files from one directory to tomcat webapps folder."
},
{
"code": null,
"e": 42294,
"s": 42170,
"text": "Most of the commands used in the example below are already covered before. Here, we will concentrate on the usage of loops."
},
{
"code": null,
"e": 42403,
"s": 42294,
"text": "Initially in the 'shell' command we have done ls *.war. So, it will list all the war files in the directory."
},
{
"code": null,
"e": 42463,
"s": 42403,
"text": "Output of that command is taken in a variable named output."
},
{
"code": null,
"e": 42511,
"s": 42463,
"text": "To loop, the 'with_items' syntax is being used."
},
{
"code": null,
"e": 42677,
"s": 42511,
"text": "with_items: \"{{output.stdout_lines}}\" --> output.stdout_lines gives us the line by line output and then we loop on the output with the with_items command of Ansible."
},
{
"code": null,
"e": 42790,
"s": 42677,
"text": "Attaching the example output just to make one understand how we used the stdout_lines in the with_items command."
},
{
"code": null,
"e": 43177,
"s": 42790,
"text": "--- \n#Tsting \n- hosts: tomcat-node \n tasks: \n - name: Install Apache \n shell: \"ls *.war\" \n register: output \n args: \n chdir: /opt/ansible/tomcat/demo/webapps \n \n - file: \n src: '/opt/ansible/tomcat/demo/webapps/{{ item }}' \n dest: '/users/demo/vivek/{{ item }}' \n state: link \n with_items: \"{{output.stdout_lines}}\"\n\n"
},
{
"code": null,
"e": 43411,
"s": 43177,
"text": "The playbook in totality is broken into blocks. The smallest piece of steps to execute is written in block. Writing the specific instruction in blocks helps to segregate functionality and handle it with exception handling if needed."
},
{
"code": null,
"e": 43494,
"s": 43411,
"text": "Example of blocks is covered in variable usage,exception handling and loops above."
},
{
"code": null,
"e": 43577,
"s": 43494,
"text": "Conditionals are used where one needs to run a specific step based on a condition."
},
{
"code": null,
"e": 43772,
"s": 43577,
"text": "--- \n#Tsting \n- hosts: all \n vars: \n test1: \"Hello Vivek\" \n tasks: \n - name: Testing Ansible variable \n debug: \n msg: \"Equals\" \n when: test1 == \"Hello Vivek\" \n"
},
{
"code": null,
"e": 43974,
"s": 43772,
"text": "In this case, Equals will be printed as the test1 variable is equal as mentioned in the when condition. when can be used with a logical OR and logical AND condition as in all the programming languages."
},
{
"code": null,
"e": 44070,
"s": 43974,
"text": "Just change the value of test1 variable from Hello Vivek to say Hello World and see the output."
},
{
"code": null,
"e": 44142,
"s": 44070,
"text": "In this chapter, we will learn what is advanced execution with Ansible."
},
{
"code": null,
"e": 44420,
"s": 44142,
"text": "This is a very important execution strategy where one needs to execute only one execution and not the entire playbook. For example, suppose you only want to stop a server (in case a production issue comes) and then post applying a patch you would like to only start the server."
},
{
"code": null,
"e": 44812,
"s": 44420,
"text": "Here in original playbook stop and start were a part of different roles in the same playbook but this can be handled with the usage of tags. We can provide different tags to different roles (which in turn will have tasks) and hence based on the tags provided by the executor only that specified role/task gets executed. So for the above example provided, we can add tags like the following −"
},
{
"code": null,
"e": 44857,
"s": 44812,
"text": "- {role: start-tomcat, tags: ['install']}} \n"
},
{
"code": null,
"e": 44901,
"s": 44857,
"text": "The following command helps in using tags −"
},
{
"code": null,
"e": 44962,
"s": 44901,
"text": "ansible-playbook -i hosts <your yaml> --tags \"install\" -vvv\n"
},
{
"code": null,
"e": 45116,
"s": 44962,
"text": "With the above command, only the start-tomcat role will be called. The tag provided is case-sensitive. Ensure exact match is being passed to the command."
},
{
"code": null,
"e": 45303,
"s": 45116,
"text": "There are two ways to achieve the execution of specific steps on specific hosts. For a specific role, one defines the hosts - as to which specific hosts that specific role should be run."
},
{
"code": null,
"e": 46059,
"s": 45303,
"text": "- hosts: <A> \n environment: \"{{your env}}\" \n pre_tasks: \n - debug: msg = \"Started deployment. \n Current time is {{ansible_date_time.date}} {{ansible_date_time.time}} \" \n \n roles: \n - {role: <your role>, tags: ['<respective tag>']} \n post_tasks: \n - debug: msg = \"Completed deployment. \n Current time is {{ansible_date_time.date}} {{ansible_date_time.time}}\" \n \n- hosts: <B> \n pre_tasks: \n - debug: msg = \"started.... \n Current time is {{ansible_date_time.date}} {{ansible_date_time.time}} \" \n \n roles: \n - {role: <your role>, tags: ['<respective tag>']} \n post_tasks: \n - debug: msg = \"Completed the task.. \n Current time is {{ansible_date_time.date}} {{ansible_date_time.time}}\" "
},
{
"code": null,
"e": 46224,
"s": 46059,
"text": "As per the above example, depending on the hosts provided, the respective roles will only be called. Now my hosts A and B are defined in the hosts (inventory file)."
},
{
"code": null,
"e": 46361,
"s": 46224,
"text": "A different solution might be defining the playbook's hosts using a variable, then passing in a specific host address via --extra-vars −"
},
{
"code": null,
"e": 46455,
"s": 46361,
"text": "# file: user.yml (playbook) \n--- \n- hosts: '{{ target }}' \n user: ... \nplaybook contd.... "
},
{
"code": null,
"e": 46528,
"s": 46455,
"text": "ansible-playbook user.yml --extra-vars \"target = \"<your host variable>\"\n"
},
{
"code": null,
"e": 46707,
"s": 46528,
"text": "If {{ target }} isn't defined, the playbook does nothing. A group from the hosts file can also be passed through if need be. This does not harm if the extra vars is not provided."
},
{
"code": null,
"e": 46795,
"s": 46707,
"text": "$ ansible-playbook user.yml --extra-vars \"target = <your hosts variable>\" --listhosts \n"
},
{
"code": null,
"e": 46890,
"s": 46795,
"text": "The most common strategies for debugging Ansible playbooks are using the modules given below −"
},
{
"code": null,
"e": 47038,
"s": 46890,
"text": "These two are the modules available in Ansible. For debugging purpose, we need to use the two modules judiciously. Examples are demonstrated below."
},
{
"code": null,
"e": 47170,
"s": 47038,
"text": "With the Ansible command, one can provide the verbosity level. You can run the commands with verbosity level one (-v) or two (-vv)."
},
{
"code": null,
"e": 47251,
"s": 47170,
"text": "In this section, we will go through a few examples to understand a few concepts."
},
{
"code": null,
"e": 47328,
"s": 47251,
"text": "If you are not quoting an argument that starts with a variable. For example,"
},
{
"code": null,
"e": 47391,
"s": 47328,
"text": "vars: \n age_path: {{vivek.name}}/demo/ \n \n{{vivek.name}} \n"
},
{
"code": null,
"e": 47417,
"s": 47391,
"text": "This will throw an error."
},
{
"code": null,
"e": 47740,
"s": 47417,
"text": "vars: \n age_path: \"{{vivek.name}}/demo/\" – marked in yellow is the fix. \n \nHow to use register -> Copy this code into a yml file say test.yml and run it \n--- \n#Tsting \n- hosts: tomcat-node \n tasks: \n \n - shell: /usr/bin/uptime \n register: myvar \n - name: Just debugging usage \n debug: var = myvar "
},
{
"code": null,
"e": 47846,
"s": 47740,
"text": "When I run this code via the command Ansible-playbook -i hosts test.yml, I get the output as shown below."
},
{
"code": null,
"e": 47964,
"s": 47846,
"text": "If you see the yaml , we have registered the output of a command into a variable – myvar and just printed the output."
},
{
"code": null,
"e": 48210,
"s": 47964,
"text": "The text marked yellow, tells us about property of the variable –myvar that can be used for further flow control. This way we can find out about the properties that are exposed of a particular variable. The following debug command helps in this."
},
{
"code": null,
"e": 50143,
"s": 48210,
"text": "$ ansible-playbook -i hosts test.yml \n\nPLAY [tomcat-node] ***************************************************************\n**************** ****************************************************************\n*************** ****************************** \n \nTASK [Gathering Facts] *****************************************************************\n************** *****************************************************************\n************** ************************** \nMonday 05 February 2018 17:33:14 +0530 (0:00:00.051) 0:00:00.051 ******* \nok: [server1] \n \nTASK [command] ******************************************************************\n************* ******************************************************************\n************* ********************************** \nMonday 05 February 2018 17:33:16 +0530 (0:00:01.697) 0:00:01.748 ******* \nchanged: [server1] \n \nTASK [Just debugging usage] ******************************************************************\n************* ******************************************************************\n************* ********************* \nMonday 05 February 2018 17:33:16 +0530 (0:00:00.226) 0:00:01.974 ******* \nok: [server1] => { \n \"myvar\": { \n \"changed\": true, \n \"cmd\": \"/usr/bin/uptime\", \n \"delta\": \"0:00:00.011306\", \n \"end\": \"2018-02-05 17:33:16.424647\", \n \"rc\": 0, \n \"start\": \"2018-02-05 17:33:16.413341\", \n \"stderr\": \"\", \n \"stderr_lines\": [], \n \"stdout\": \" 17:33:16 up 7 days, 35 min, 1 user, load average: 0.18, 0.15, 0.14\", \n \"stdout_lines\": [ \n \" 17:33:16 up 7 days, 35 min, 1 user, load average: 0.18, 0.15, 0.14\" \n ] \n } \n} \n \nPLAY RECAP ****************************************************************************\n**********************************************************************************\n ************************************** \nserver1 : ok = 3 changed = 1 unreachable = 0 failed = 0 \n"
},
{
"code": null,
"e": 50231,
"s": 50143,
"text": "In this section, we will learn about the a few common playbook issues. The issues are −"
},
{
"code": null,
"e": 50239,
"s": 50231,
"text": "Quoting"
},
{
"code": null,
"e": 50251,
"s": 50239,
"text": "Indentation"
},
{
"code": null,
"e": 50349,
"s": 50251,
"text": "Playbook is written in yaml format and the above two are the most common issues in yaml/playbook."
},
{
"code": null,
"e": 50474,
"s": 50349,
"text": "Yaml does not support tab based indentation and supports space based indentation, so one needs to be careful about the same."
},
{
"code": null,
"e": 50676,
"s": 50474,
"text": "Note − once you are done with writing the yaml , open this site(https://editor.swagger.io/) and copy paste your yaml on the left hand side to ensure that the yaml compiles properly. This is just a tip."
},
{
"code": null,
"e": 50730,
"s": 50676,
"text": "Swagger qualifies errors in warning as well as error."
},
{
"code": null,
"e": 50763,
"s": 50730,
"text": "\n 41 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 50775,
"s": 50763,
"text": " AR Shankar"
},
{
"code": null,
"e": 50807,
"s": 50775,
"text": "\n 11 Lectures \n 58 mins\n"
},
{
"code": null,
"e": 50823,
"s": 50807,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 50859,
"s": 50823,
"text": "\n 59 Lectures \n 15.5 hours \n"
},
{
"code": null,
"e": 50871,
"s": 50859,
"text": " Narendra P"
},
{
"code": null,
"e": 50904,
"s": 50871,
"text": "\n 11 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 50917,
"s": 50904,
"text": " Sagar Mehta"
},
{
"code": null,
"e": 50950,
"s": 50917,
"text": "\n 39 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 50963,
"s": 50950,
"text": " Vikas Yadav"
},
{
"code": null,
"e": 50997,
"s": 50963,
"text": "\n 4 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 51014,
"s": 50997,
"text": " GreyCampus Inc."
},
{
"code": null,
"e": 51021,
"s": 51014,
"text": " Print"
},
{
"code": null,
"e": 51032,
"s": 51021,
"text": " Add Notes"
}
] |
Tcl - File I/O | Tcl supports file handling with the help of the built in commands open, read, puts, gets, and close.
A file represents a sequence of bytes, does not matter if it is a text file or binary file.
Tcl uses the open command to open files in Tcl. The syntax for opening a file is as follows −
open fileName accessMode
Here, filename is string literal, which you will use to name your file and accessMode can have one of the following values −
r
Opens an existing text file for reading purpose and the file must exist. This is the default mode used when no accessMode is specified.
w
Opens a text file for writing, if it does not exist, then a new file is created else existing file is truncated.
a
Opens a text file for writing in appending mode and file must exist. Here, your program will start appending content in the existing file content.
r+
Opens a text file for reading and writing both. File must exist already.
w+
Opens a text file for reading and writing both. It first truncate the file to zero length if it exists otherwise create the file if it does not exist.
a+
Opens a text file for reading and writing both. It creates the file if it does not exist. The reading will start from the beginning, but writing can only be appended.
To close a file, use the close command. The syntax for close is as follows −
close fileName
Any file that has been opened by a program must be closed when the program finishes using that file. In most cases, the files need not be closed explicitly; they are closed automatically when File objects are terminated automatically.
Puts command is used to write to an open file.
puts $filename "text to write"
A simple example for writing to a file is shown below.
#!/usr/bin/tclsh
set fp [open "input.txt" w+]
puts $fp "test"
close $fp
When the above code is compiled and executed, it creates a new file input.txt in the directory that it has been started under (in the program's working directory).
Following is the simple command to read from a file −
set file_data [read $fp]
A complete example of read and write is shown below −
#!/usr/bin/tclsh
set fp [open "input.txt" w+]
puts $fp "test"
close $fp
set fp [open "input.txt" r]
set file_data [read $fp]
puts $file_data
close $fp
When the above code is compiled and executed, it reads the file created in previous section and produces the following result −
test
Here is another example for reading file till end of file line by line −
#!/usr/bin/tclsh
set fp [open "input.txt" w+]
puts $fp "test\ntest"
close $fp
set fp [open "input.txt" r]
while { [gets $fp data] >= 0 } {
puts $data
}
close $fp
When the above code is compiled and executed, it reads the file created in previous section and produces the following result −
test
test
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2302,
"s": 2201,
"text": "Tcl supports file handling with the help of the built in commands open, read, puts, gets, and close."
},
{
"code": null,
"e": 2394,
"s": 2302,
"text": "A file represents a sequence of bytes, does not matter if it is a text file or binary file."
},
{
"code": null,
"e": 2488,
"s": 2394,
"text": "Tcl uses the open command to open files in Tcl. The syntax for opening a file is as follows −"
},
{
"code": null,
"e": 2514,
"s": 2488,
"text": "open fileName accessMode\n"
},
{
"code": null,
"e": 2639,
"s": 2514,
"text": "Here, filename is string literal, which you will use to name your file and accessMode can have one of the following values −"
},
{
"code": null,
"e": 2641,
"s": 2639,
"text": "r"
},
{
"code": null,
"e": 2777,
"s": 2641,
"text": "Opens an existing text file for reading purpose and the file must exist. This is the default mode used when no accessMode is specified."
},
{
"code": null,
"e": 2779,
"s": 2777,
"text": "w"
},
{
"code": null,
"e": 2892,
"s": 2779,
"text": "Opens a text file for writing, if it does not exist, then a new file is created else existing file is truncated."
},
{
"code": null,
"e": 2894,
"s": 2892,
"text": "a"
},
{
"code": null,
"e": 3041,
"s": 2894,
"text": "Opens a text file for writing in appending mode and file must exist. Here, your program will start appending content in the existing file content."
},
{
"code": null,
"e": 3044,
"s": 3041,
"text": "r+"
},
{
"code": null,
"e": 3117,
"s": 3044,
"text": "Opens a text file for reading and writing both. File must exist already."
},
{
"code": null,
"e": 3120,
"s": 3117,
"text": "w+"
},
{
"code": null,
"e": 3271,
"s": 3120,
"text": "Opens a text file for reading and writing both. It first truncate the file to zero length if it exists otherwise create the file if it does not exist."
},
{
"code": null,
"e": 3274,
"s": 3271,
"text": "a+"
},
{
"code": null,
"e": 3441,
"s": 3274,
"text": "Opens a text file for reading and writing both. It creates the file if it does not exist. The reading will start from the beginning, but writing can only be appended."
},
{
"code": null,
"e": 3518,
"s": 3441,
"text": "To close a file, use the close command. The syntax for close is as follows −"
},
{
"code": null,
"e": 3535,
"s": 3518,
"text": "close fileName \n"
},
{
"code": null,
"e": 3770,
"s": 3535,
"text": "Any file that has been opened by a program must be closed when the program finishes using that file. In most cases, the files need not be closed explicitly; they are closed automatically when File objects are terminated automatically."
},
{
"code": null,
"e": 3817,
"s": 3770,
"text": "Puts command is used to write to an open file."
},
{
"code": null,
"e": 3849,
"s": 3817,
"text": "puts $filename \"text to write\"\n"
},
{
"code": null,
"e": 3904,
"s": 3849,
"text": "A simple example for writing to a file is shown below."
},
{
"code": null,
"e": 3977,
"s": 3904,
"text": "#!/usr/bin/tclsh\n\nset fp [open \"input.txt\" w+]\nputs $fp \"test\"\nclose $fp"
},
{
"code": null,
"e": 4141,
"s": 3977,
"text": "When the above code is compiled and executed, it creates a new file input.txt in the directory that it has been started under (in the program's working directory)."
},
{
"code": null,
"e": 4195,
"s": 4141,
"text": "Following is the simple command to read from a file −"
},
{
"code": null,
"e": 4221,
"s": 4195,
"text": "set file_data [read $fp]\n"
},
{
"code": null,
"e": 4275,
"s": 4221,
"text": "A complete example of read and write is shown below −"
},
{
"code": null,
"e": 4427,
"s": 4275,
"text": "#!/usr/bin/tclsh\n\nset fp [open \"input.txt\" w+]\nputs $fp \"test\"\nclose $fp\nset fp [open \"input.txt\" r]\nset file_data [read $fp]\nputs $file_data\nclose $fp"
},
{
"code": null,
"e": 4555,
"s": 4427,
"text": "When the above code is compiled and executed, it reads the file created in previous section and produces the following result −"
},
{
"code": null,
"e": 4561,
"s": 4555,
"text": "test\n"
},
{
"code": null,
"e": 4634,
"s": 4561,
"text": "Here is another example for reading file till end of file line by line −"
},
{
"code": null,
"e": 4801,
"s": 4634,
"text": "#!/usr/bin/tclsh\n\nset fp [open \"input.txt\" w+]\nputs $fp \"test\\ntest\"\nclose $fp\nset fp [open \"input.txt\" r]\n\nwhile { [gets $fp data] >= 0 } {\n puts $data\n}\nclose $fp"
},
{
"code": null,
"e": 4929,
"s": 4801,
"text": "When the above code is compiled and executed, it reads the file created in previous section and produces the following result −"
},
{
"code": null,
"e": 4940,
"s": 4929,
"text": "test\ntest\n"
},
{
"code": null,
"e": 4947,
"s": 4940,
"text": " Print"
},
{
"code": null,
"e": 4958,
"s": 4947,
"text": " Add Notes"
}
] |
Interval List Intersections in C++ | Suppose we have two lists of closed intervals, here each list of intervals is pairwise disjoint and in sorted order. We have ti find the intersection of these two interval lists.
We know that the closed interval [a, b] is denoted as a <= b. the set of real numbers x with a <= x <= b. The intersection of two closed intervals is a set of real numbers that is either empty, or can be represented as a closed interval.
So if the input is like A = [[0,2],[5,10],[13,23],[24,25]] and B = [[1,5],[8,12],[15,24],[25,27]], then the output will be [[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]].
To solve this, we will follow these steps −
Make a list res, set I := 0 and j := 0
Make a list res, set I := 0 and j := 0
Define a method called intersect(), this will take a and b −
Define a method called intersect(), this will take a and b −
if a[0] <= b[0] and a[1] >= b[0], then return true,
if a[0] <= b[0] and a[1] >= b[0], then return true,
otherwise when b[0] <= a[0] and b[1] >= a[0], then return true, otherwise return False
otherwise when b[0] <= a[0] and b[1] >= a[0], then return true, otherwise return False
while I < size of A and j > size of Bif intersect(A[i], B[i])temp := max of A[i, 0], B[j, 0], minimum of A[i,1] and B[j, 1]A[i,0] := temp[1] + 1, B[j,0] := temp[1] + 1if A[i,0] > A[i,1] or A[i,1] <= temp[0], then increase i by 1if B[j,0]>B[j,1] or B[j,1] <= temp[0]: then increase j by 1result.append(temp)Skip for the next iterationif A[i,0] > B[j, 1], then increase j by 1, otherwise increase i by 1
while I < size of A and j > size of B
if intersect(A[i], B[i])temp := max of A[i, 0], B[j, 0], minimum of A[i,1] and B[j, 1]A[i,0] := temp[1] + 1, B[j,0] := temp[1] + 1if A[i,0] > A[i,1] or A[i,1] <= temp[0], then increase i by 1if B[j,0]>B[j,1] or B[j,1] <= temp[0]: then increase j by 1result.append(temp)Skip for the next iteration
if intersect(A[i], B[i])
temp := max of A[i, 0], B[j, 0], minimum of A[i,1] and B[j, 1]
temp := max of A[i, 0], B[j, 0], minimum of A[i,1] and B[j, 1]
A[i,0] := temp[1] + 1, B[j,0] := temp[1] + 1
A[i,0] := temp[1] + 1, B[j,0] := temp[1] + 1
if A[i,0] > A[i,1] or A[i,1] <= temp[0], then increase i by 1
if A[i,0] > A[i,1] or A[i,1] <= temp[0], then increase i by 1
if B[j,0]>B[j,1] or B[j,1] <= temp[0]: then increase j by 1
if B[j,0]>B[j,1] or B[j,1] <= temp[0]: then increase j by 1
result.append(temp)
result.append(temp)
Skip for the next iteration
Skip for the next iteration
if A[i,0] > B[j, 1], then increase j by 1, otherwise increase i by 1
if A[i,0] > B[j, 1], then increase j by 1, otherwise increase i by 1
Let us see the following implementation to get better understanding −
Live Demo
class Solution(object):
def intervalIntersection(self, A, B):
result = []
i,j = 0,0
while i < len(A) and j < len(B):
if self.intersect(A[i],B[j]):
temp = [max(A[i][0],B[j][0]),min(A[i][1],B[j][1])]
A[i][0]=temp[1]+1
B[j][0] = temp[1]+1
if A[i][0] > A[i][1] or A[i][1] <= temp[0]:
i+=1
if B[j][0]>B[j][1] or B[j][1] <= temp[0]:
j+=1
result.append(temp)
continue
if A[i][0]>B[j][1]:
j+=1
else:
i+=1
return result
def intersect(self,a,b):
if a[0]<=b[0] and a[1]>=b[0]:
return True
if b[0]<=a[0] and b[1] >=a[0]:
return True
return False
ob = Solution()
print(ob.intervalIntersection([[0,2],[5,10],[13,23],[24,25]],[[1,5],[8,12],[15,24],[25,27]]))
[[0,2],[5,10],[13,23],[24,25]]
[[1,5],[8,12],[15,24],[25,27]]
[[1, 2], [5, 5], [8, 10], [15, 23], [24, 24], [25, 25]] | [
{
"code": null,
"e": 1241,
"s": 1062,
"text": "Suppose we have two lists of closed intervals, here each list of intervals is pairwise disjoint and in sorted order. We have ti find the intersection of these two interval lists."
},
{
"code": null,
"e": 1479,
"s": 1241,
"text": "We know that the closed interval [a, b] is denoted as a <= b. the set of real numbers x with a <= x <= b. The intersection of two closed intervals is a set of real numbers that is either empty, or can be represented as a closed interval."
},
{
"code": null,
"e": 1648,
"s": 1479,
"text": "So if the input is like A = [[0,2],[5,10],[13,23],[24,25]] and B = [[1,5],[8,12],[15,24],[25,27]], then the output will be [[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]]."
},
{
"code": null,
"e": 1692,
"s": 1648,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1731,
"s": 1692,
"text": "Make a list res, set I := 0 and j := 0"
},
{
"code": null,
"e": 1770,
"s": 1731,
"text": "Make a list res, set I := 0 and j := 0"
},
{
"code": null,
"e": 1831,
"s": 1770,
"text": "Define a method called intersect(), this will take a and b −"
},
{
"code": null,
"e": 1892,
"s": 1831,
"text": "Define a method called intersect(), this will take a and b −"
},
{
"code": null,
"e": 1944,
"s": 1892,
"text": "if a[0] <= b[0] and a[1] >= b[0], then return true,"
},
{
"code": null,
"e": 1996,
"s": 1944,
"text": "if a[0] <= b[0] and a[1] >= b[0], then return true,"
},
{
"code": null,
"e": 2083,
"s": 1996,
"text": "otherwise when b[0] <= a[0] and b[1] >= a[0], then return true, otherwise return False"
},
{
"code": null,
"e": 2170,
"s": 2083,
"text": "otherwise when b[0] <= a[0] and b[1] >= a[0], then return true, otherwise return False"
},
{
"code": null,
"e": 2572,
"s": 2170,
"text": "while I < size of A and j > size of Bif intersect(A[i], B[i])temp := max of A[i, 0], B[j, 0], minimum of A[i,1] and B[j, 1]A[i,0] := temp[1] + 1, B[j,0] := temp[1] + 1if A[i,0] > A[i,1] or A[i,1] <= temp[0], then increase i by 1if B[j,0]>B[j,1] or B[j,1] <= temp[0]: then increase j by 1result.append(temp)Skip for the next iterationif A[i,0] > B[j, 1], then increase j by 1, otherwise increase i by 1"
},
{
"code": null,
"e": 2610,
"s": 2572,
"text": "while I < size of A and j > size of B"
},
{
"code": null,
"e": 2907,
"s": 2610,
"text": "if intersect(A[i], B[i])temp := max of A[i, 0], B[j, 0], minimum of A[i,1] and B[j, 1]A[i,0] := temp[1] + 1, B[j,0] := temp[1] + 1if A[i,0] > A[i,1] or A[i,1] <= temp[0], then increase i by 1if B[j,0]>B[j,1] or B[j,1] <= temp[0]: then increase j by 1result.append(temp)Skip for the next iteration"
},
{
"code": null,
"e": 2932,
"s": 2907,
"text": "if intersect(A[i], B[i])"
},
{
"code": null,
"e": 2995,
"s": 2932,
"text": "temp := max of A[i, 0], B[j, 0], minimum of A[i,1] and B[j, 1]"
},
{
"code": null,
"e": 3058,
"s": 2995,
"text": "temp := max of A[i, 0], B[j, 0], minimum of A[i,1] and B[j, 1]"
},
{
"code": null,
"e": 3103,
"s": 3058,
"text": "A[i,0] := temp[1] + 1, B[j,0] := temp[1] + 1"
},
{
"code": null,
"e": 3148,
"s": 3103,
"text": "A[i,0] := temp[1] + 1, B[j,0] := temp[1] + 1"
},
{
"code": null,
"e": 3210,
"s": 3148,
"text": "if A[i,0] > A[i,1] or A[i,1] <= temp[0], then increase i by 1"
},
{
"code": null,
"e": 3272,
"s": 3210,
"text": "if A[i,0] > A[i,1] or A[i,1] <= temp[0], then increase i by 1"
},
{
"code": null,
"e": 3332,
"s": 3272,
"text": "if B[j,0]>B[j,1] or B[j,1] <= temp[0]: then increase j by 1"
},
{
"code": null,
"e": 3392,
"s": 3332,
"text": "if B[j,0]>B[j,1] or B[j,1] <= temp[0]: then increase j by 1"
},
{
"code": null,
"e": 3412,
"s": 3392,
"text": "result.append(temp)"
},
{
"code": null,
"e": 3432,
"s": 3412,
"text": "result.append(temp)"
},
{
"code": null,
"e": 3460,
"s": 3432,
"text": "Skip for the next iteration"
},
{
"code": null,
"e": 3488,
"s": 3460,
"text": "Skip for the next iteration"
},
{
"code": null,
"e": 3557,
"s": 3488,
"text": "if A[i,0] > B[j, 1], then increase j by 1, otherwise increase i by 1"
},
{
"code": null,
"e": 3626,
"s": 3557,
"text": "if A[i,0] > B[j, 1], then increase j by 1, otherwise increase i by 1"
},
{
"code": null,
"e": 3696,
"s": 3626,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 3707,
"s": 3696,
"text": " Live Demo"
},
{
"code": null,
"e": 4528,
"s": 3707,
"text": "class Solution(object):\n def intervalIntersection(self, A, B):\n result = []\n i,j = 0,0\n while i < len(A) and j < len(B):\n if self.intersect(A[i],B[j]):\n temp = [max(A[i][0],B[j][0]),min(A[i][1],B[j][1])]\n A[i][0]=temp[1]+1\n B[j][0] = temp[1]+1\n if A[i][0] > A[i][1] or A[i][1] <= temp[0]:\n i+=1\n if B[j][0]>B[j][1] or B[j][1] <= temp[0]:\n j+=1\n result.append(temp)\n continue\n if A[i][0]>B[j][1]:\n j+=1\n else:\n i+=1\n return result\n def intersect(self,a,b):\n if a[0]<=b[0] and a[1]>=b[0]:\n return True\n if b[0]<=a[0] and b[1] >=a[0]:\n return True\n return False\nob = Solution()\nprint(ob.intervalIntersection([[0,2],[5,10],[13,23],[24,25]],[[1,5],[8,12],[15,24],[25,27]]))"
},
{
"code": null,
"e": 4590,
"s": 4528,
"text": "[[0,2],[5,10],[13,23],[24,25]]\n[[1,5],[8,12],[15,24],[25,27]]"
},
{
"code": null,
"e": 4646,
"s": 4590,
"text": "[[1, 2], [5, 5], [8, 10], [15, 23], [24, 24], [25, 25]]"
}
] |
How to inject service in angular 6 component ? - GeeksforGeeks | 01 Jul, 2021
Service is a special class in Angular which is primarily used for inter-component communication. Sometimes there are components that need a common pool to interact with each other mostly for data or information procurement. Service makes it possible. The two (or more) components may or may not be related to each other. That means there may exist a parent-child relationship or nothing at all.
Services and other dependencies are injected directly into the constructor of the component like this:
constructor(private _myService: MyService) {
}
By doing this, we are actually creating an instance of the service. That means we have to access all the public variables and methods of the service.
To create a new service, we can use the code scaffolding tool:
// Generate service
ng g s my-custom-service
Injecting a service into a component is pretty straightforward. Let’s say we have a service called MyCustomService. This is how we can inject it into a component:
MyCustomComponent.ts
import {...} from "@angular/core";
import { MyCustomService } from "../...PATH";
@Component({
selector: "...",
templateUrl: "...",
styleUrls: ["..."],
})
export class MyCustomComponent {
// INJECTING SERVICE INTO THE CONSTRUCTOR
constructor(private _myCustomService: MyCustomService) {}
// USING THE SERVICE MEMBERS
this._myCustomService.sampleMethod();
}
This may not make any sense until and unless we get our hands dirty. So let’s quickly create a service and see how it is injected and can be accessed easily. For this demo, we will create two simple custom components. Let’s say, Ladies and Gentlemen. There is no parent-child relationship between these two components. Both are absolutely independent. Gentlemen will greet Ladies with “Good morning” with the click of a button. For this, we will use a service that will interact between the two components. We will call it InteractionService.
First thing first, we will create our 2 components and 1 service.
Now we have everything that we need. Since this demo is particularly for service injection. We will not discuss the components in detail. Let’s start with service first. Here is the code:
interaction.service.ts
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class InteractionService {
private _messageSource = new Subject<string>();
greeting$=this._messageSource.asObservable();
sendMessage(message: string) {
this._messageSource.next(message);
}
}
This been done. We will now inject this service into both our components.
gentlemen.component.html
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h2>Welcome To GFG</h2>
<button (click)="greetLadies()">Greet</button>
</body>
</html>
We will now create the first component using:
// Generate component
ng g c gentlemen
gentlemen.component.ts
import {...} from "@angular/core";
...
import { InteractionService } from "../services/interaction.service";
@Component({
selector: "app-gentlemen",
templateUrl: "./gentlemen.component.html",
styleUrls: ["./gentlemen.component.scss"],
})
export class GentlemenComponent {
// SERVICE INJECTION
constructor(private _interactionService: InteractionService) {}
greetLadies() {
this._interactionService.sendMessage("Good morning");
}
}
Quickly create our last component:
// Generate component
ng g c ladies
ladies.component.ts
import {...} from "@angular/core";
...
import { InteractionService } from "../services/interaction.service";
@Component({
selector: "app-ladies",
templateUrl: "./ladies.component.html",
styleUrls: ["./ladies.component.scss"],
})
export class LadiesComponent implements OnInit {
// SERVICE INJECTION
constructor(private _interactionService: InteractionService) {}
ngOnInit() {
this._interactionService.greeting$.subscribe(message => {
console.log(message);
})
}
}
This is how we can inject and use the service to interact between components. We just saw a use case of service injection.
We will have this as our final product:
UI/UX Screenshot
On click on buttons we can expect the following output:
Expected output
AngularJS-Questions
Picked
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 10 Angular Libraries For Web Developers
How to use <mat-chip-list> and <mat-chip> in Angular Material ?
How to make a Bootstrap Modal Popup in Angular 9/8 ?
Angular PrimeNG Dropdown Component
Angular 10 (blur) Event
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 25101,
"s": 25070,
"text": " \n01 Jul, 2021\n"
},
{
"code": null,
"e": 25496,
"s": 25101,
"text": "Service is a special class in Angular which is primarily used for inter-component communication. Sometimes there are components that need a common pool to interact with each other mostly for data or information procurement. Service makes it possible. The two (or more) components may or may not be related to each other. That means there may exist a parent-child relationship or nothing at all."
},
{
"code": null,
"e": 25599,
"s": 25496,
"text": "Services and other dependencies are injected directly into the constructor of the component like this:"
},
{
"code": null,
"e": 25646,
"s": 25599,
"text": "constructor(private _myService: MyService) {\n}"
},
{
"code": null,
"e": 25796,
"s": 25646,
"text": "By doing this, we are actually creating an instance of the service. That means we have to access all the public variables and methods of the service."
},
{
"code": null,
"e": 25859,
"s": 25796,
"text": "To create a new service, we can use the code scaffolding tool:"
},
{
"code": null,
"e": 25904,
"s": 25859,
"text": "// Generate service\nng g s my-custom-service"
},
{
"code": null,
"e": 26067,
"s": 25904,
"text": "Injecting a service into a component is pretty straightforward. Let’s say we have a service called MyCustomService. This is how we can inject it into a component:"
},
{
"code": null,
"e": 26088,
"s": 26067,
"text": "MyCustomComponent.ts"
},
{
"code": "\n\n\n\n\n\n\nimport {...} from \"@angular/core\"; \nimport { MyCustomService } from \"../...PATH\"; \n \n@Component({ \n selector: \"...\", \n templateUrl: \"...\", \n styleUrls: [\"...\"], \n}) \nexport class MyCustomComponent { \n \n // INJECTING SERVICE INTO THE CONSTRUCTOR \n constructor(private _myCustomService: MyCustomService) {} \n \n // USING THE SERVICE MEMBERS \n this._myCustomService.sampleMethod(); \n}\n\n\n\n\n\n",
"e": 26514,
"s": 26098,
"text": null
},
{
"code": null,
"e": 27057,
"s": 26514,
"text": "This may not make any sense until and unless we get our hands dirty. So let’s quickly create a service and see how it is injected and can be accessed easily. For this demo, we will create two simple custom components. Let’s say, Ladies and Gentlemen. There is no parent-child relationship between these two components. Both are absolutely independent. Gentlemen will greet Ladies with “Good morning” with the click of a button. For this, we will use a service that will interact between the two components. We will call it InteractionService."
},
{
"code": null,
"e": 27123,
"s": 27057,
"text": "First thing first, we will create our 2 components and 1 service."
},
{
"code": null,
"e": 27311,
"s": 27123,
"text": "Now we have everything that we need. Since this demo is particularly for service injection. We will not discuss the components in detail. Let’s start with service first. Here is the code:"
},
{
"code": null,
"e": 27334,
"s": 27311,
"text": "interaction.service.ts"
},
{
"code": "\n\n\n\n\n\n\nimport { Injectable } from '@angular/core'; \nimport { Subject } from 'rxjs'; \n \n@Injectable({ \n providedIn: 'root'\n}) \nexport class InteractionService { \n private _messageSource = new Subject<string>(); \n \n greeting$=this._messageSource.asObservable(); \n \n sendMessage(message: string) { \n this._messageSource.next(message); \n } \n}\n\n\n\n\n\n",
"e": 27704,
"s": 27344,
"text": null
},
{
"code": null,
"e": 27778,
"s": 27704,
"text": "This been done. We will now inject this service into both our components."
},
{
"code": null,
"e": 27803,
"s": 27778,
"text": "gentlemen.component.html"
},
{
"code": "\n\n\n\n\n\n\n<!DOCTYPE html> \n<html> \n <head> \n <title>Page Title</title> \n </head> \n <body> \n <h2>Welcome To GFG</h2> \n <button (click)=\"greetLadies()\">Greet</button> \n </body> \n</html>\n\n\n\n\n\n",
"e": 28019,
"s": 27813,
"text": null
},
{
"code": null,
"e": 28065,
"s": 28019,
"text": "We will now create the first component using:"
},
{
"code": "\n\n\n\n\n\n\n// Generate component \nng g c gentlemen\n\n\n\n\n\n",
"e": 28128,
"s": 28075,
"text": null
},
{
"code": null,
"e": 28151,
"s": 28128,
"text": "gentlemen.component.ts"
},
{
"code": "\n\n\n\n\n\n\nimport {...} from \"@angular/core\"; \n... \nimport { InteractionService } from \"../services/interaction.service\"; \n \n@Component({ \n selector: \"app-gentlemen\", \n templateUrl: \"./gentlemen.component.html\", \n styleUrls: [\"./gentlemen.component.scss\"], \n}) \nexport class GentlemenComponent { \n \n // SERVICE INJECTION \n constructor(private _interactionService: InteractionService) {} \n \n greetLadies() { \n this._interactionService.sendMessage(\"Good morning\"); \n } \n}\n\n\n\n\n\n",
"e": 28646,
"s": 28161,
"text": null
},
{
"code": null,
"e": 28681,
"s": 28646,
"text": "Quickly create our last component:"
},
{
"code": "\n\n\n\n\n\n\n// Generate component \nng g c ladies\n\n\n\n\n\n",
"e": 28741,
"s": 28691,
"text": null
},
{
"code": null,
"e": 28761,
"s": 28741,
"text": "ladies.component.ts"
},
{
"code": "\n\n\n\n\n\n\nimport {...} from \"@angular/core\"; \n... \nimport { InteractionService } from \"../services/interaction.service\"; \n \n@Component({ \n selector: \"app-ladies\", \n templateUrl: \"./ladies.component.html\", \n styleUrls: [\"./ladies.component.scss\"], \n}) \nexport class LadiesComponent implements OnInit { \n \n // SERVICE INJECTION \n constructor(private _interactionService: InteractionService) {} \n \n ngOnInit() { \n this._interactionService.greeting$.subscribe(message => { \n console.log(message); \n }) \n } \n}\n\n\n\n\n\n",
"e": 29302,
"s": 28771,
"text": null
},
{
"code": null,
"e": 29426,
"s": 29302,
"text": "This is how we can inject and use the service to interact between components. We just saw a use case of service injection. "
},
{
"code": null,
"e": 29466,
"s": 29426,
"text": "We will have this as our final product:"
},
{
"code": null,
"e": 29483,
"s": 29466,
"text": "UI/UX Screenshot"
},
{
"code": null,
"e": 29539,
"s": 29483,
"text": "On click on buttons we can expect the following output:"
},
{
"code": null,
"e": 29555,
"s": 29539,
"text": "Expected output"
},
{
"code": null,
"e": 29577,
"s": 29555,
"text": "\nAngularJS-Questions\n"
},
{
"code": null,
"e": 29586,
"s": 29577,
"text": "\nPicked\n"
},
{
"code": null,
"e": 29598,
"s": 29586,
"text": "\nAngularJS\n"
},
{
"code": null,
"e": 29617,
"s": 29598,
"text": "\nWeb Technologies\n"
},
{
"code": null,
"e": 29822,
"s": 29617,
"text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n "
},
{
"code": null,
"e": 29866,
"s": 29822,
"text": "Top 10 Angular Libraries For Web Developers"
},
{
"code": null,
"e": 29930,
"s": 29866,
"text": "How to use <mat-chip-list> and <mat-chip> in Angular Material ?"
},
{
"code": null,
"e": 29983,
"s": 29930,
"text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?"
},
{
"code": null,
"e": 30018,
"s": 29983,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 30042,
"s": 30018,
"text": "Angular 10 (blur) Event"
},
{
"code": null,
"e": 30084,
"s": 30042,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 30117,
"s": 30084,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 30179,
"s": 30117,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 30222,
"s": 30179,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
C library function - asin() | The C library function double asin(double x) returns the arc sine of x in radians.
Following is the declaration for asin() function.
double asin(double x)
x − This is the floating point value in the interval [-1,+1].
x − This is the floating point value in the interval [-1,+1].
This function returns the arc sine of x, in the interval [-pi/2,+pi/2] radians.
The following example shows the usage of asin() function.
#include <stdio.h>
#include <math.h>
#define PI 3.14159265
int main () {
double x, ret, val;
x = 0.9;
val = 180.0 / PI;
ret = asin(x) * val;
printf("The arc sine of %lf is %lf degrees", x, ret);
return(0);
}
Let us compile and run the above program that will produce the following result −
The arc sine of 0.900000 is 64.158067 degrees
12 Lectures
2 hours
Nishant Malik
12 Lectures
2.5 hours
Nishant Malik
48 Lectures
6.5 hours
Asif Hussain
12 Lectures
2 hours
Richa Maheshwari
20 Lectures
3.5 hours
Vandana Annavaram
44 Lectures
1 hours
Amit Diwan
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2090,
"s": 2007,
"text": "The C library function double asin(double x) returns the arc sine of x in radians."
},
{
"code": null,
"e": 2140,
"s": 2090,
"text": "Following is the declaration for asin() function."
},
{
"code": null,
"e": 2162,
"s": 2140,
"text": "double asin(double x)"
},
{
"code": null,
"e": 2224,
"s": 2162,
"text": "x − This is the floating point value in the interval [-1,+1]."
},
{
"code": null,
"e": 2286,
"s": 2224,
"text": "x − This is the floating point value in the interval [-1,+1]."
},
{
"code": null,
"e": 2366,
"s": 2286,
"text": "This function returns the arc sine of x, in the interval [-pi/2,+pi/2] radians."
},
{
"code": null,
"e": 2424,
"s": 2366,
"text": "The following example shows the usage of asin() function."
},
{
"code": null,
"e": 2657,
"s": 2424,
"text": "#include <stdio.h>\n#include <math.h>\n\n#define PI 3.14159265\n\nint main () {\n double x, ret, val;\n x = 0.9;\n val = 180.0 / PI;\n\n ret = asin(x) * val;\n printf(\"The arc sine of %lf is %lf degrees\", x, ret);\n \n return(0);\n}"
},
{
"code": null,
"e": 2739,
"s": 2657,
"text": "Let us compile and run the above program that will produce the following result −"
},
{
"code": null,
"e": 2786,
"s": 2739,
"text": "The arc sine of 0.900000 is 64.158067 degrees\n"
},
{
"code": null,
"e": 2819,
"s": 2786,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 2834,
"s": 2819,
"text": " Nishant Malik"
},
{
"code": null,
"e": 2869,
"s": 2834,
"text": "\n 12 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 2884,
"s": 2869,
"text": " Nishant Malik"
},
{
"code": null,
"e": 2919,
"s": 2884,
"text": "\n 48 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 2933,
"s": 2919,
"text": " Asif Hussain"
},
{
"code": null,
"e": 2966,
"s": 2933,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 2984,
"s": 2966,
"text": " Richa Maheshwari"
},
{
"code": null,
"e": 3019,
"s": 2984,
"text": "\n 20 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 3038,
"s": 3019,
"text": " Vandana Annavaram"
},
{
"code": null,
"e": 3071,
"s": 3038,
"text": "\n 44 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3083,
"s": 3071,
"text": " Amit Diwan"
},
{
"code": null,
"e": 3090,
"s": 3083,
"text": " Print"
},
{
"code": null,
"e": 3101,
"s": 3090,
"text": " Add Notes"
}
] |
Accessing Values of Dictionary in Python | To access dictionary elements, you can use the familiar square brackets along with the key to obtain its value.
Following is a simple example −
Live Demo
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print "dict['Name']: ", dict['Name']
print "dict['Age']: ", dict['Age']
When the above code is executed, it produces the following result −
dict['Name']: Zara
dict['Age']: 7
If we attempt to access a data item with a key, which is not part of the dictionary, we get an error as follows −
Live Demo
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print "dict['Alice']: ", dict['Alice']
When the above code is executed, it produces the following result −
dict['Alice']:
Traceback (most recent call last):
File "test.py", line 4, in <module>
print "dict['Alice']: ", dict['Alice'];
KeyError: 'Alice' | [
{
"code": null,
"e": 1174,
"s": 1062,
"text": "To access dictionary elements, you can use the familiar square brackets along with the key to obtain its value."
},
{
"code": null,
"e": 1206,
"s": 1174,
"text": "Following is a simple example −"
},
{
"code": null,
"e": 1217,
"s": 1206,
"text": " Live Demo"
},
{
"code": null,
"e": 1359,
"s": 1217,
"text": "#!/usr/bin/python\ndict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}\nprint \"dict['Name']: \", dict['Name']\nprint \"dict['Age']: \", dict['Age']"
},
{
"code": null,
"e": 1427,
"s": 1359,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 1461,
"s": 1427,
"text": "dict['Name']: Zara\ndict['Age']: 7"
},
{
"code": null,
"e": 1575,
"s": 1461,
"text": "If we attempt to access a data item with a key, which is not part of the dictionary, we get an error as follows −"
},
{
"code": null,
"e": 1586,
"s": 1575,
"text": " Live Demo"
},
{
"code": null,
"e": 1695,
"s": 1586,
"text": "#!/usr/bin/python\ndict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}\nprint \"dict['Alice']: \", dict['Alice']"
},
{
"code": null,
"e": 1763,
"s": 1695,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 1907,
"s": 1763,
"text": "dict['Alice']:\nTraceback (most recent call last):\nFile \"test.py\", line 4, in <module>\nprint \"dict['Alice']: \", dict['Alice'];\nKeyError: 'Alice'"
}
] |
Scheduled Web Scraping with Django and Heroku | by GreekDataGuy | Towards Data Science | We often need a lot of training data for machine learning, and web scraping can be a way to acquire it.
But in the past, there was a company I really wanted to work for. They didn’t currently have a data science posting but as soon as they did, I wanted to apply.
The solution? Scrape their job board daily so I was notified anytime a new job was posted.
Let’s build a simple django app, deploy to Heroku, and scrape a job board daily.
Create the directory for the app and cd into it.
mkdir jobs && cd jobs
Open this in whatever code editor your prefer. I’m using Sublime.
Create and start our virtual environment. Then install the packages we’ll need.
python -m venv envsource env/bin/activatepip3 install django psycopg2 django-heroku bs4 gunicorn
Create the project (django’s version of a web application).
django-admin startproject jobs
cd into the project and create an app for scraping.
cd jobsdjango-admin startapp scraping
We’ll only need to define 1 model in this app, a Job model. This represents jobs that we’ll collect.
Overwrite /scraping/models.py with the following.
from django.db import modelsfrom django.utils import timezoneclass Job(models.Model): url = models.CharField(max_length=250, unique=True) title = models.CharField(max_length=250) location = models.CharField(max_length=250) created_date = models.DateTimeField(default=timezone.now) def __str__(self): return self.title class Meta: ordering = ['title'] class Admin: pass
Register your model in /scraping/admin.py. This allows us to view records in Django’s default admin panel (we’ll get to this shortly).
from scraping.models import Jobadmin.site.register(Job)
Add scraping to installed apps in /jobs/settings.py .
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'scraping']
Setup the database. I love postgres so we’ll use that.
At this point, ensure you’ve previously installed postgres on your mac with brew and started it (this is beyond the scope of this article).
Create a database for this project on the command line. You can open the postgres console with the below command.
psql -d template1
Create a user and a database, then exit.
create user django_user;create database django_jobs owner django_user;\q
In /jobs/settings.py, update DATABASES. In other frameworks you’d want to scope these specifically for the development environment, but here we won’t worry about it. It will work on Heroku anyway (we’ll get there shortly).
Note these are the user and database names we created above.
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'django_jobs', 'USER': 'django_user', 'HOST': '', 'PORT': '' }}
Create migrations, and migrate the database from the command line.
python manage.py makemigrationspython manage.py migrate
This will create a table called scraping_job. This is a django namespace convention because it belongs to the scraping app.
Now create a superuser and give it a password in your command line.
python manage.py createsuperuser --email [email protected] --username admin
We’ve done some work so far but we have no idea if anything works. Let’s test it out before going further.
On the command line.
python manage.py runserver
Then navigate to http://127.0.0.1:8000/admin in your browser. Login with the superuser you just created.
After logging in, click “jobs” under “scraping”, then “add job” in the top right. Now fill in some made up information and click “save”. If you can see the job you created, everything works up until this point!
We’re going to setup a custom django-admin command that scrapes a job board. This is what we’ll automatically schedule at the infrastructure level in order to automate scraping.
Inside the /scraping module, create a directory called /management, and a directory inside /management called /commands. Then create 2 python files, _private.py and scrape.py in /commands.
Drop this code into scrape.py.
from django.core.management.base import BaseCommandfrom urllib.request import urlopenfrom bs4 import BeautifulSoupimport jsonfrom scraping.models import Jobclass Command(BaseCommand): help = "collect jobs" # define logic of command def handle(self, *args, **options): # collect html html = urlopen('https://jobs.lever.co/opencare') # convert to soup soup = BeautifulSoup(html, 'html.parser') # grab all postings postings = soup.find_all("div", class_="posting") for p in postings: url = p.find('a', class_='posting-btn-submit')['href'] title = p.find('h5').text location = p.find('span', class_='sort-by-location').text # check if url in db try: # save in db Job.objects.create( url=url, title=title, location=location ) print('%s added' % (title,)) except: print('%s already exists' % (title,)) self.stdout.write( 'job complete' )
Putting the code in a directory structure like this, then defining a Command class with a handle function tells django this is a custom django-admin command.
Here we’re using beautiful soup to scrape a Lever job board, then save it in our database. I have no affiliation but the job board I’ve chosen is for a fantastic company called Opencare - you should apply if they post something!
You can now run this from your command line like below.
python manage.py scrape
And you’ll see this output.
Run it again and you’ll see this.
That’s because we’ve prevented adding duplicate job records in the scrape.py code above.
If you have a database administration program setup (like dbeaver), you can also inspect rows in your database. We won’t get into that here but it should look like below.
Now let’s get this onto Heroku.
Freeze your requirements so Heroku knows what to install on deploy.
pip3 freeze > requirements.txt
On the command line, run nano .gitignore and add below.
.DS_Storejobs/__pycache__scraping/__pycache__
Then ctrl+x, y, enter to save and close (on mac). This prevents deploying unnecessary files.
Create a file named Procfile in your root, and paste below inside. This tells heroku to boot up a web dyno, and the 2nd command migrates the db.
web: gunicorn jobs.wsgirelease: python manage.py migrate
The file tree will look like.
Make sure you have a Heroku account then login with heroku login on the command line.
Create an app with any name you want. But it will needs to be unique across all the apps on Heroku. I ran heroku create django-scraper-879 , where the app name is django-scraper-879 . But you’ll need to pick your own.
Now add these lines to the very bottom of settings.py. heroku_django takes care of some settings configuration like (Static files / WhiteNoise) for you.
import django_herokudjango_heroku.settings(locals())
Update DEBUG in settings. Don’t want to deploy to prod in debug mode.
DEBUG = False
Adds files to git with below.
git initgit add . -Agit commit -m 'first commit'
Now push our app to Heroku with this.
git push heroku master
You can manually run the job from your local command line with heroku run python manage.py scrape but it would be annoying to have to manually run it every day.
Let’s automate this.
Log into your Heroku console and click on “Resources,” then “find more add-ons”.
Now find and click on this add-on. Try a “ctrl+f” for “schedule” to help locate it. Heroku has a ton of potential add-ons. It looks like below.
Now add it to your app, so you now have.
Click on it and create a job, everyday at... 12am UTC . It’s not nice to ping websites more than necessary!
Input your command and save it.
Save and we’re done!
Now just wait until 12am UTC (or whatever time you picked) and you’re database will populate.
We touched on a lot of things here. Django, Heroku, Scheduling, Web Scraping, Postgres.
While I used the example of wanting to know when a company posted a new job, there are lots of reasons you might want to scrape a website.
E-commerce companies want to monitor competitor prices.
Executive recruiters may want to see when a company posts a job opening.
You or I may want to see when a new competition is added on Kaggle.
This tutorial was just to illustrate what’s possible. Let me know if you’ve built anything cool with web scraping in the comments. | [
{
"code": null,
"e": 276,
"s": 172,
"text": "We often need a lot of training data for machine learning, and web scraping can be a way to acquire it."
},
{
"code": null,
"e": 436,
"s": 276,
"text": "But in the past, there was a company I really wanted to work for. They didn’t currently have a data science posting but as soon as they did, I wanted to apply."
},
{
"code": null,
"e": 527,
"s": 436,
"text": "The solution? Scrape their job board daily so I was notified anytime a new job was posted."
},
{
"code": null,
"e": 608,
"s": 527,
"text": "Let’s build a simple django app, deploy to Heroku, and scrape a job board daily."
},
{
"code": null,
"e": 657,
"s": 608,
"text": "Create the directory for the app and cd into it."
},
{
"code": null,
"e": 679,
"s": 657,
"text": "mkdir jobs && cd jobs"
},
{
"code": null,
"e": 745,
"s": 679,
"text": "Open this in whatever code editor your prefer. I’m using Sublime."
},
{
"code": null,
"e": 825,
"s": 745,
"text": "Create and start our virtual environment. Then install the packages we’ll need."
},
{
"code": null,
"e": 922,
"s": 825,
"text": "python -m venv envsource env/bin/activatepip3 install django psycopg2 django-heroku bs4 gunicorn"
},
{
"code": null,
"e": 982,
"s": 922,
"text": "Create the project (django’s version of a web application)."
},
{
"code": null,
"e": 1013,
"s": 982,
"text": "django-admin startproject jobs"
},
{
"code": null,
"e": 1065,
"s": 1013,
"text": "cd into the project and create an app for scraping."
},
{
"code": null,
"e": 1103,
"s": 1065,
"text": "cd jobsdjango-admin startapp scraping"
},
{
"code": null,
"e": 1204,
"s": 1103,
"text": "We’ll only need to define 1 model in this app, a Job model. This represents jobs that we’ll collect."
},
{
"code": null,
"e": 1254,
"s": 1204,
"text": "Overwrite /scraping/models.py with the following."
},
{
"code": null,
"e": 1665,
"s": 1254,
"text": "from django.db import modelsfrom django.utils import timezoneclass Job(models.Model): url = models.CharField(max_length=250, unique=True) title = models.CharField(max_length=250) location = models.CharField(max_length=250) created_date = models.DateTimeField(default=timezone.now) def __str__(self): return self.title class Meta: ordering = ['title'] class Admin: pass"
},
{
"code": null,
"e": 1800,
"s": 1665,
"text": "Register your model in /scraping/admin.py. This allows us to view records in Django’s default admin panel (we’ll get to this shortly)."
},
{
"code": null,
"e": 1856,
"s": 1800,
"text": "from scraping.models import Jobadmin.site.register(Job)"
},
{
"code": null,
"e": 1910,
"s": 1856,
"text": "Add scraping to installed apps in /jobs/settings.py ."
},
{
"code": null,
"e": 2124,
"s": 1910,
"text": "INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'scraping']"
},
{
"code": null,
"e": 2179,
"s": 2124,
"text": "Setup the database. I love postgres so we’ll use that."
},
{
"code": null,
"e": 2319,
"s": 2179,
"text": "At this point, ensure you’ve previously installed postgres on your mac with brew and started it (this is beyond the scope of this article)."
},
{
"code": null,
"e": 2433,
"s": 2319,
"text": "Create a database for this project on the command line. You can open the postgres console with the below command."
},
{
"code": null,
"e": 2451,
"s": 2433,
"text": "psql -d template1"
},
{
"code": null,
"e": 2492,
"s": 2451,
"text": "Create a user and a database, then exit."
},
{
"code": null,
"e": 2565,
"s": 2492,
"text": "create user django_user;create database django_jobs owner django_user;\\q"
},
{
"code": null,
"e": 2788,
"s": 2565,
"text": "In /jobs/settings.py, update DATABASES. In other frameworks you’d want to scope these specifically for the development environment, but here we won’t worry about it. It will work on Heroku anyway (we’ll get there shortly)."
},
{
"code": null,
"e": 2849,
"s": 2788,
"text": "Note these are the user and database names we created above."
},
{
"code": null,
"e": 3041,
"s": 2849,
"text": "DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'django_jobs', 'USER': 'django_user', 'HOST': '', 'PORT': '' }}"
},
{
"code": null,
"e": 3108,
"s": 3041,
"text": "Create migrations, and migrate the database from the command line."
},
{
"code": null,
"e": 3164,
"s": 3108,
"text": "python manage.py makemigrationspython manage.py migrate"
},
{
"code": null,
"e": 3288,
"s": 3164,
"text": "This will create a table called scraping_job. This is a django namespace convention because it belongs to the scraping app."
},
{
"code": null,
"e": 3356,
"s": 3288,
"text": "Now create a superuser and give it a password in your command line."
},
{
"code": null,
"e": 3432,
"s": 3356,
"text": "python manage.py createsuperuser --email [email protected] --username admin"
},
{
"code": null,
"e": 3539,
"s": 3432,
"text": "We’ve done some work so far but we have no idea if anything works. Let’s test it out before going further."
},
{
"code": null,
"e": 3560,
"s": 3539,
"text": "On the command line."
},
{
"code": null,
"e": 3587,
"s": 3560,
"text": "python manage.py runserver"
},
{
"code": null,
"e": 3692,
"s": 3587,
"text": "Then navigate to http://127.0.0.1:8000/admin in your browser. Login with the superuser you just created."
},
{
"code": null,
"e": 3903,
"s": 3692,
"text": "After logging in, click “jobs” under “scraping”, then “add job” in the top right. Now fill in some made up information and click “save”. If you can see the job you created, everything works up until this point!"
},
{
"code": null,
"e": 4081,
"s": 3903,
"text": "We’re going to setup a custom django-admin command that scrapes a job board. This is what we’ll automatically schedule at the infrastructure level in order to automate scraping."
},
{
"code": null,
"e": 4270,
"s": 4081,
"text": "Inside the /scraping module, create a directory called /management, and a directory inside /management called /commands. Then create 2 python files, _private.py and scrape.py in /commands."
},
{
"code": null,
"e": 4301,
"s": 4270,
"text": "Drop this code into scrape.py."
},
{
"code": null,
"e": 5396,
"s": 4301,
"text": "from django.core.management.base import BaseCommandfrom urllib.request import urlopenfrom bs4 import BeautifulSoupimport jsonfrom scraping.models import Jobclass Command(BaseCommand): help = \"collect jobs\" # define logic of command def handle(self, *args, **options): # collect html html = urlopen('https://jobs.lever.co/opencare') # convert to soup soup = BeautifulSoup(html, 'html.parser') # grab all postings postings = soup.find_all(\"div\", class_=\"posting\") for p in postings: url = p.find('a', class_='posting-btn-submit')['href'] title = p.find('h5').text location = p.find('span', class_='sort-by-location').text # check if url in db try: # save in db Job.objects.create( url=url, title=title, location=location ) print('%s added' % (title,)) except: print('%s already exists' % (title,)) self.stdout.write( 'job complete' )"
},
{
"code": null,
"e": 5554,
"s": 5396,
"text": "Putting the code in a directory structure like this, then defining a Command class with a handle function tells django this is a custom django-admin command."
},
{
"code": null,
"e": 5783,
"s": 5554,
"text": "Here we’re using beautiful soup to scrape a Lever job board, then save it in our database. I have no affiliation but the job board I’ve chosen is for a fantastic company called Opencare - you should apply if they post something!"
},
{
"code": null,
"e": 5839,
"s": 5783,
"text": "You can now run this from your command line like below."
},
{
"code": null,
"e": 5863,
"s": 5839,
"text": "python manage.py scrape"
},
{
"code": null,
"e": 5891,
"s": 5863,
"text": "And you’ll see this output."
},
{
"code": null,
"e": 5925,
"s": 5891,
"text": "Run it again and you’ll see this."
},
{
"code": null,
"e": 6014,
"s": 5925,
"text": "That’s because we’ve prevented adding duplicate job records in the scrape.py code above."
},
{
"code": null,
"e": 6185,
"s": 6014,
"text": "If you have a database administration program setup (like dbeaver), you can also inspect rows in your database. We won’t get into that here but it should look like below."
},
{
"code": null,
"e": 6217,
"s": 6185,
"text": "Now let’s get this onto Heroku."
},
{
"code": null,
"e": 6285,
"s": 6217,
"text": "Freeze your requirements so Heroku knows what to install on deploy."
},
{
"code": null,
"e": 6316,
"s": 6285,
"text": "pip3 freeze > requirements.txt"
},
{
"code": null,
"e": 6372,
"s": 6316,
"text": "On the command line, run nano .gitignore and add below."
},
{
"code": null,
"e": 6418,
"s": 6372,
"text": ".DS_Storejobs/__pycache__scraping/__pycache__"
},
{
"code": null,
"e": 6511,
"s": 6418,
"text": "Then ctrl+x, y, enter to save and close (on mac). This prevents deploying unnecessary files."
},
{
"code": null,
"e": 6656,
"s": 6511,
"text": "Create a file named Procfile in your root, and paste below inside. This tells heroku to boot up a web dyno, and the 2nd command migrates the db."
},
{
"code": null,
"e": 6713,
"s": 6656,
"text": "web: gunicorn jobs.wsgirelease: python manage.py migrate"
},
{
"code": null,
"e": 6743,
"s": 6713,
"text": "The file tree will look like."
},
{
"code": null,
"e": 6829,
"s": 6743,
"text": "Make sure you have a Heroku account then login with heroku login on the command line."
},
{
"code": null,
"e": 7047,
"s": 6829,
"text": "Create an app with any name you want. But it will needs to be unique across all the apps on Heroku. I ran heroku create django-scraper-879 , where the app name is django-scraper-879 . But you’ll need to pick your own."
},
{
"code": null,
"e": 7200,
"s": 7047,
"text": "Now add these lines to the very bottom of settings.py. heroku_django takes care of some settings configuration like (Static files / WhiteNoise) for you."
},
{
"code": null,
"e": 7253,
"s": 7200,
"text": "import django_herokudjango_heroku.settings(locals())"
},
{
"code": null,
"e": 7323,
"s": 7253,
"text": "Update DEBUG in settings. Don’t want to deploy to prod in debug mode."
},
{
"code": null,
"e": 7337,
"s": 7323,
"text": "DEBUG = False"
},
{
"code": null,
"e": 7367,
"s": 7337,
"text": "Adds files to git with below."
},
{
"code": null,
"e": 7416,
"s": 7367,
"text": "git initgit add . -Agit commit -m 'first commit'"
},
{
"code": null,
"e": 7454,
"s": 7416,
"text": "Now push our app to Heroku with this."
},
{
"code": null,
"e": 7477,
"s": 7454,
"text": "git push heroku master"
},
{
"code": null,
"e": 7638,
"s": 7477,
"text": "You can manually run the job from your local command line with heroku run python manage.py scrape but it would be annoying to have to manually run it every day."
},
{
"code": null,
"e": 7659,
"s": 7638,
"text": "Let’s automate this."
},
{
"code": null,
"e": 7740,
"s": 7659,
"text": "Log into your Heroku console and click on “Resources,” then “find more add-ons”."
},
{
"code": null,
"e": 7884,
"s": 7740,
"text": "Now find and click on this add-on. Try a “ctrl+f” for “schedule” to help locate it. Heroku has a ton of potential add-ons. It looks like below."
},
{
"code": null,
"e": 7925,
"s": 7884,
"text": "Now add it to your app, so you now have."
},
{
"code": null,
"e": 8033,
"s": 7925,
"text": "Click on it and create a job, everyday at... 12am UTC . It’s not nice to ping websites more than necessary!"
},
{
"code": null,
"e": 8065,
"s": 8033,
"text": "Input your command and save it."
},
{
"code": null,
"e": 8086,
"s": 8065,
"text": "Save and we’re done!"
},
{
"code": null,
"e": 8180,
"s": 8086,
"text": "Now just wait until 12am UTC (or whatever time you picked) and you’re database will populate."
},
{
"code": null,
"e": 8268,
"s": 8180,
"text": "We touched on a lot of things here. Django, Heroku, Scheduling, Web Scraping, Postgres."
},
{
"code": null,
"e": 8407,
"s": 8268,
"text": "While I used the example of wanting to know when a company posted a new job, there are lots of reasons you might want to scrape a website."
},
{
"code": null,
"e": 8463,
"s": 8407,
"text": "E-commerce companies want to monitor competitor prices."
},
{
"code": null,
"e": 8536,
"s": 8463,
"text": "Executive recruiters may want to see when a company posts a job opening."
},
{
"code": null,
"e": 8604,
"s": 8536,
"text": "You or I may want to see when a new competition is added on Kaggle."
}
] |
.NET Core - Project Files | In this chapter, we will discuss .NET Core project files and how you can add existing files in your project.
Let us understand a simple example in which we have some files which are already created; we have to add these files in our FirstApp project.
Here is the implementation of the Student.cs file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace FirstApp {
public class Student {
public int ID { get; set; }
public string LastName { get; set; }
public string FirstMidName { get; set; }
public DateTime EnrollmentDate { get; set; }
}
}
Here is the implementation of the Course.cs file.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace FirstApp {
public class Course {
public int CourseID { get; set; }
public string Title { get; set; }
public int Credits { get; set; }
}
}
Let us now save these three files in your disk and the source folder of your project.
Now if you are familiar with .NET and this one was a traditional .NET framework console application, it is important to understand how to add these files in your project in Visual Studio.
Now if you are familiar with .NET and this one was a traditional .NET framework console application, it is important to understand how to add these files in your project in Visual Studio.
You first need to drag the files to the solution explorer to copy them in your project folder, because your project needs reference to these files.
You first need to drag the files to the solution explorer to copy them in your project folder, because your project needs reference to these files.
One of the benefits of .NET Core is the approach taken with the project file (project.json); we can just drop files into the root of our project and then these will be automatically included in our project.
One of the benefits of .NET Core is the approach taken with the project file (project.json); we can just drop files into the root of our project and then these will be automatically included in our project.
We don’t have to manually reference files like we did in the past for traditional .NET Framework application in Visual Studio.
We don’t have to manually reference files like we did in the past for traditional .NET Framework application in Visual Studio.
Let us now open the root of your project.
Let us now copy all of the three files into the root of your project.
You can now see all the files copied to the root folder.
Let us now go to Visual Studio; you will receive the following dialog box.
Click Yes to All to reload your project.
You will now that files are automatically included in your project.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2495,
"s": 2386,
"text": "In this chapter, we will discuss .NET Core project files and how you can add existing files in your project."
},
{
"code": null,
"e": 2637,
"s": 2495,
"text": "Let us understand a simple example in which we have some files which are already created; we have to add these files in our FirstApp project."
},
{
"code": null,
"e": 2687,
"s": 2637,
"text": "Here is the implementation of the Student.cs file"
},
{
"code": null,
"e": 3027,
"s": 2687,
"text": "using System; \nusing System.Collections.Generic; \nusing System.Linq; \nusing System.Threading.Tasks; \n \nnamespace FirstApp { \n public class Student { \n public int ID { get; set; } \n public string LastName { get; set; } \n public string FirstMidName { get; set; } \n public DateTime EnrollmentDate { get; set; } \n } \n}"
},
{
"code": null,
"e": 3077,
"s": 3027,
"text": "Here is the implementation of the Course.cs file."
},
{
"code": null,
"e": 3359,
"s": 3077,
"text": "using System; \nusing System.Collections.Generic; \nusing System.Linq; \nusing System.Threading.Tasks; \n \nnamespace FirstApp { \n public class Course { \n public int CourseID { get; set; } \n public string Title { get; set; } \n public int Credits { get; set; } \n } \n}"
},
{
"code": null,
"e": 3445,
"s": 3359,
"text": "Let us now save these three files in your disk and the source folder of your project."
},
{
"code": null,
"e": 3633,
"s": 3445,
"text": "Now if you are familiar with .NET and this one was a traditional .NET framework console application, it is important to understand how to add these files in your project in Visual Studio."
},
{
"code": null,
"e": 3821,
"s": 3633,
"text": "Now if you are familiar with .NET and this one was a traditional .NET framework console application, it is important to understand how to add these files in your project in Visual Studio."
},
{
"code": null,
"e": 3969,
"s": 3821,
"text": "You first need to drag the files to the solution explorer to copy them in your project folder, because your project needs reference to these files."
},
{
"code": null,
"e": 4117,
"s": 3969,
"text": "You first need to drag the files to the solution explorer to copy them in your project folder, because your project needs reference to these files."
},
{
"code": null,
"e": 4324,
"s": 4117,
"text": "One of the benefits of .NET Core is the approach taken with the project file (project.json); we can just drop files into the root of our project and then these will be automatically included in our project."
},
{
"code": null,
"e": 4531,
"s": 4324,
"text": "One of the benefits of .NET Core is the approach taken with the project file (project.json); we can just drop files into the root of our project and then these will be automatically included in our project."
},
{
"code": null,
"e": 4658,
"s": 4531,
"text": "We don’t have to manually reference files like we did in the past for traditional .NET Framework application in Visual Studio."
},
{
"code": null,
"e": 4785,
"s": 4658,
"text": "We don’t have to manually reference files like we did in the past for traditional .NET Framework application in Visual Studio."
},
{
"code": null,
"e": 4827,
"s": 4785,
"text": "Let us now open the root of your project."
},
{
"code": null,
"e": 4897,
"s": 4827,
"text": "Let us now copy all of the three files into the root of your project."
},
{
"code": null,
"e": 4954,
"s": 4897,
"text": "You can now see all the files copied to the root folder."
},
{
"code": null,
"e": 5029,
"s": 4954,
"text": "Let us now go to Visual Studio; you will receive the following dialog box."
},
{
"code": null,
"e": 5070,
"s": 5029,
"text": "Click Yes to All to reload your project."
},
{
"code": null,
"e": 5138,
"s": 5070,
"text": "You will now that files are automatically included in your project."
},
{
"code": null,
"e": 5145,
"s": 5138,
"text": " Print"
},
{
"code": null,
"e": 5156,
"s": 5145,
"text": " Add Notes"
}
] |
Generate all distinct subsequences of array using backtracking - GeeksforGeeks | 06 Oct, 2021
Given an array arr[] consisting of N positive integers, the task is to generate all distinct subsequences of the array.
Examples:
Input: arr[] = {1, 2, 2}Output: {} {1} {1, 2} {1, 2, 2} {2} {2, 2}Explanation:The total subsequences of the given array are {}, {1}, {2}, {2}, {1, 2}, {1, 2}, {2, 2}, {1, 2, 2}.Since {2} and {1, 2} are repeated twice, print all the remaining subsequences of the array.
Input: arr[] = {1, 2, 3, 3}Output: {} {1} {1, 2} {1, 2, 3} {1, 2, 3, 3} {1, 3} {1, 3, 3} {2} {2, 3} {2, 3, 3} {3} {3, 3}
Approach: Follow the steps below to solve the problem:
Sort the given array.Initialize a vector of vectors to store all distinct subsequences.Traverse the array and considering two choices for each array element, to include it in a subsequence or not to include it.If duplicates are found, ignore them and check for the remaining elements. Otherwise, add the current array element to the current subsequence and traverse the remaining elements to generate subsequences.After generating the subsequences, remove the current array element.
Sort the given array.
Initialize a vector of vectors to store all distinct subsequences.
Traverse the array and considering two choices for each array element, to include it in a subsequence or not to include it.
If duplicates are found, ignore them and check for the remaining elements. Otherwise, add the current array element to the current subsequence and traverse the remaining elements to generate subsequences.
After generating the subsequences, remove the current array element.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to generate all distinct// subsequences of the array using backtrackingvoid backtrack(vector<int>& nums, int start, vector<vector<int> >& resultset, vector<int> curr_set){ resultset.push_back(curr_set); for (int i = start; i < nums.size(); i++) { // If the current element is repeating if (i > start && nums[i] == nums[i - 1]) { continue; } // Include current element // into the subsequence curr_set.push_back(nums[i]); // Proceed to the remaining array // to generate subsequences // including current array element backtrack(nums, i + 1, resultset, curr_set); // Remove current element // from the subsequence curr_set.pop_back(); }} // Function to sort the array and generate// subsequences using Backtrackingvector<vector<int> > AllSubsets( vector<int> nums){ // Stores the subsequences vector<vector<int> > resultset; // Stores the current // subsequence vector<int> curr_set; // Sort the vector sort(nums.begin(), nums.end()); // Backtrack function to // generate subsequences backtrack(nums, 0, resultset, curr_set); // Return the result return resultset;} // Function to print all subsequencesvoid print(vector<vector<int> > result){ for (int i = 0; i < result.size(); i++) { cout << "{"; for (int j = 0; j < result[i].size(); j++) { cout << result[i][j]; if (j < result[i].size() - 1) { cout << ", "; } } cout << "} "; }} // Driver Codeint main(){ vector<int> v{ 1, 2, 2 }; // Function call vector<vector<int> > result = AllSubsets(v); // Print function print(result); return 0;}
// Java program to implement// the above approachimport java.io.*;import java.util.*; class GFG{ // Function to generate all distinct// subsequences of the array using backtrackingpublic static void backtrack(ArrayList<Integer> nums, int start, ArrayList<Integer> curr_set){ System.out.print(curr_set + " "); for(int i = start; i < nums.size(); i++) { // If the current element is repeating if (i > start && nums.get(i) == nums.get(i - 1)) { continue; } // Include current element // into the subsequence curr_set.add(nums.get(i)); // Proceed to the remaining array // to generate subsequences // including current array element backtrack(nums, i + 1, curr_set); // Remove current element // from the subsequence curr_set.remove(curr_set.size() - 1); }} // Function to sort the array and generate// subsequences using Backtrackingpublic static void AllSubsets(ArrayList<Integer> nums){ // Stores the current // subsequence ArrayList<Integer> curr_set = new ArrayList<>(); // Sort the vector Collections.sort(nums); // Backtrack function to // generate subsequences backtrack(nums, 0, curr_set);} // Driver Codepublic static void main(String[] args){ ArrayList<Integer> v = new ArrayList<>(); v.add(1); v.add(2); v.add(2); // Function call AllSubsets(v);}} // This code is contributed by hemanthswarna1506
# Python3 program to implement# the above approachresult = [] # Function to generate all distinct# subsequences of the array# using backtrackingdef backtrack(nums, start, curr_set): # Global result result.append(list(curr_set)) for i in range(start, len(nums)): # If the current element is repeating if (i > start and nums[i] == nums[i - 1]): continue # Include current element # into the subsequence curr_set.append(nums[i]) # Proceed to the remaining array # to generate subsequences # including current array element backtrack(nums, i + 1, curr_set) # Remove current element # from the subsequence curr_set.pop() # Function to sort the array and generate# subsequences using Backtrackingdef AllSubsets(nums): # Stores the current # subsequence curr_set = [] # Sort the vector nums.sort() # Backtrack function to # generate subsequences backtrack(nums, 0, curr_set) # Function to prints all subsequencesdef prints(): global result for i in range(len(result)): print('{', end = '') for j in range(len(result[i])): print(result[i][j], end = '') if (j < len(result[i]) - 1): print(',', end = ' ') print('} ', end = '') # Driver Codeif __name__=='__main__': v = [ 1, 2, 2 ] # Function call AllSubsets(v) # Print function prints() # This code is contributed by rutvik_56
// C# program to implement// the above approachusing System;using System.Collections.Generic;class GFG{ // Function to generate all distinct// subsequences of the array using// backtrackingpublic static void backtrack(List<int> nums, int start, List<int> curr_set){ Console.Write(" {"); foreach(int i in curr_set) { Console.Write(i); Console.Write(", "); } Console.Write("}"); for(int i = start; i < nums.Count; i++) { // If the current element // is repeating if (i > start && nums[i] == nums[i - 1]) { continue; } // Include current element // into the subsequence curr_set.Add(nums[i]); // Proceed to the remaining array // to generate subsequences // including current array element backtrack(nums, i + 1, curr_set); // Remove current element // from the subsequence curr_set.Remove(curr_set.Count - 1); }} // Function to sort the array and generate// subsequences using Backtrackingpublic static void AllSubsets(List<int> nums){ // Stores the current // subsequence List<int> curr_set = new List<int>(); // Sort the vector nums.Sort(); // Backtrack function to // generate subsequences backtrack(nums, 0, curr_set);} // Driver Codepublic static void Main(String[] args){ List<int> v = new List<int>(); v.Add(1); v.Add(2); v.Add(2); // Function call AllSubsets(v);}} // This code is contributed by 29AjayKumar
<script> // Javascript program to implement the above approach // Function to generate all distinct // subsequences of the array using // backtracking function backtrack(nums, start, curr_set) { document.write(" {"); for(let i = 0; i < curr_set.length - 1; i++) { document.write(curr_set[i]); document.write(", "); } if(curr_set.length >= 1) { document.write(curr_set[curr_set.length - 1]); document.write("}"); } else { document.write("}"); } for(let i = start; i < nums.length; i++) { // If the current element // is repeating if (i > start && nums[i] == nums[i - 1]) { continue; } // Include current element // into the subsequence curr_set.push(nums[i]); // Proceed to the remaining array // to generate subsequences // including current array element backtrack(nums, i + 1, curr_set); // Remove current element // from the subsequence curr_set.pop(); } } // Function to sort the array and generate // subsequences using Backtracking function AllSubsets(nums) { // Stores the current // subsequence let curr_set = []; // Sort the vector nums.sort(); // Backtrack function to // generate subsequences backtrack(nums, 0, curr_set); } let v = []; v.push(1); v.push(2); v.push(2); // Function call AllSubsets(v); // This code is contributed by mukesh07.</script>
{} {1} {1, 2} {1, 2, 2} {2} {2, 2}
Time Complexity: O(2N)Auxiliary Space: O(N)
hemanthswarna1506
29AjayKumar
rutvik_56
mukesh07
subsequence
Arrays
Backtracking
Combinatorial
Recursion
Sorting
Arrays
Recursion
Sorting
Combinatorial
Backtracking
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Stack Data Structure (Introduction and Program)
Introduction to Arrays
Multidimensional Arrays in Java
N Queen Problem | Backtracking-3
Write a program to print all permutations of a given string
Backtracking | Introduction
Rat in a Maze | Backtracking-2
The Knight's tour problem | Backtracking-1 | [
{
"code": null,
"e": 26581,
"s": 26553,
"text": "\n06 Oct, 2021"
},
{
"code": null,
"e": 26701,
"s": 26581,
"text": "Given an array arr[] consisting of N positive integers, the task is to generate all distinct subsequences of the array."
},
{
"code": null,
"e": 26711,
"s": 26701,
"text": "Examples:"
},
{
"code": null,
"e": 26980,
"s": 26711,
"text": "Input: arr[] = {1, 2, 2}Output: {} {1} {1, 2} {1, 2, 2} {2} {2, 2}Explanation:The total subsequences of the given array are {}, {1}, {2}, {2}, {1, 2}, {1, 2}, {2, 2}, {1, 2, 2}.Since {2} and {1, 2} are repeated twice, print all the remaining subsequences of the array."
},
{
"code": null,
"e": 27101,
"s": 26980,
"text": "Input: arr[] = {1, 2, 3, 3}Output: {} {1} {1, 2} {1, 2, 3} {1, 2, 3, 3} {1, 3} {1, 3, 3} {2} {2, 3} {2, 3, 3} {3} {3, 3}"
},
{
"code": null,
"e": 27156,
"s": 27101,
"text": "Approach: Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 27639,
"s": 27156,
"text": "Sort the given array.Initialize a vector of vectors to store all distinct subsequences.Traverse the array and considering two choices for each array element, to include it in a subsequence or not to include it.If duplicates are found, ignore them and check for the remaining elements. Otherwise, add the current array element to the current subsequence and traverse the remaining elements to generate subsequences.After generating the subsequences, remove the current array element."
},
{
"code": null,
"e": 27661,
"s": 27639,
"text": "Sort the given array."
},
{
"code": null,
"e": 27728,
"s": 27661,
"text": "Initialize a vector of vectors to store all distinct subsequences."
},
{
"code": null,
"e": 27852,
"s": 27728,
"text": "Traverse the array and considering two choices for each array element, to include it in a subsequence or not to include it."
},
{
"code": null,
"e": 28057,
"s": 27852,
"text": "If duplicates are found, ignore them and check for the remaining elements. Otherwise, add the current array element to the current subsequence and traverse the remaining elements to generate subsequences."
},
{
"code": null,
"e": 28126,
"s": 28057,
"text": "After generating the subsequences, remove the current array element."
},
{
"code": null,
"e": 28177,
"s": 28126,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 28181,
"s": 28177,
"text": "C++"
},
{
"code": null,
"e": 28186,
"s": 28181,
"text": "Java"
},
{
"code": null,
"e": 28194,
"s": 28186,
"text": "Python3"
},
{
"code": null,
"e": 28197,
"s": 28194,
"text": "C#"
},
{
"code": null,
"e": 28208,
"s": 28197,
"text": "Javascript"
},
{
"code": "// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to generate all distinct// subsequences of the array using backtrackingvoid backtrack(vector<int>& nums, int start, vector<vector<int> >& resultset, vector<int> curr_set){ resultset.push_back(curr_set); for (int i = start; i < nums.size(); i++) { // If the current element is repeating if (i > start && nums[i] == nums[i - 1]) { continue; } // Include current element // into the subsequence curr_set.push_back(nums[i]); // Proceed to the remaining array // to generate subsequences // including current array element backtrack(nums, i + 1, resultset, curr_set); // Remove current element // from the subsequence curr_set.pop_back(); }} // Function to sort the array and generate// subsequences using Backtrackingvector<vector<int> > AllSubsets( vector<int> nums){ // Stores the subsequences vector<vector<int> > resultset; // Stores the current // subsequence vector<int> curr_set; // Sort the vector sort(nums.begin(), nums.end()); // Backtrack function to // generate subsequences backtrack(nums, 0, resultset, curr_set); // Return the result return resultset;} // Function to print all subsequencesvoid print(vector<vector<int> > result){ for (int i = 0; i < result.size(); i++) { cout << \"{\"; for (int j = 0; j < result[i].size(); j++) { cout << result[i][j]; if (j < result[i].size() - 1) { cout << \", \"; } } cout << \"} \"; }} // Driver Codeint main(){ vector<int> v{ 1, 2, 2 }; // Function call vector<vector<int> > result = AllSubsets(v); // Print function print(result); return 0;}",
"e": 30165,
"s": 28208,
"text": null
},
{
"code": "// Java program to implement// the above approachimport java.io.*;import java.util.*; class GFG{ // Function to generate all distinct// subsequences of the array using backtrackingpublic static void backtrack(ArrayList<Integer> nums, int start, ArrayList<Integer> curr_set){ System.out.print(curr_set + \" \"); for(int i = start; i < nums.size(); i++) { // If the current element is repeating if (i > start && nums.get(i) == nums.get(i - 1)) { continue; } // Include current element // into the subsequence curr_set.add(nums.get(i)); // Proceed to the remaining array // to generate subsequences // including current array element backtrack(nums, i + 1, curr_set); // Remove current element // from the subsequence curr_set.remove(curr_set.size() - 1); }} // Function to sort the array and generate// subsequences using Backtrackingpublic static void AllSubsets(ArrayList<Integer> nums){ // Stores the current // subsequence ArrayList<Integer> curr_set = new ArrayList<>(); // Sort the vector Collections.sort(nums); // Backtrack function to // generate subsequences backtrack(nums, 0, curr_set);} // Driver Codepublic static void main(String[] args){ ArrayList<Integer> v = new ArrayList<>(); v.add(1); v.add(2); v.add(2); // Function call AllSubsets(v);}} // This code is contributed by hemanthswarna1506",
"e": 31725,
"s": 30165,
"text": null
},
{
"code": "# Python3 program to implement# the above approachresult = [] # Function to generate all distinct# subsequences of the array# using backtrackingdef backtrack(nums, start, curr_set): # Global result result.append(list(curr_set)) for i in range(start, len(nums)): # If the current element is repeating if (i > start and nums[i] == nums[i - 1]): continue # Include current element # into the subsequence curr_set.append(nums[i]) # Proceed to the remaining array # to generate subsequences # including current array element backtrack(nums, i + 1, curr_set) # Remove current element # from the subsequence curr_set.pop() # Function to sort the array and generate# subsequences using Backtrackingdef AllSubsets(nums): # Stores the current # subsequence curr_set = [] # Sort the vector nums.sort() # Backtrack function to # generate subsequences backtrack(nums, 0, curr_set) # Function to prints all subsequencesdef prints(): global result for i in range(len(result)): print('{', end = '') for j in range(len(result[i])): print(result[i][j], end = '') if (j < len(result[i]) - 1): print(',', end = ' ') print('} ', end = '') # Driver Codeif __name__=='__main__': v = [ 1, 2, 2 ] # Function call AllSubsets(v) # Print function prints() # This code is contributed by rutvik_56",
"e": 33306,
"s": 31725,
"text": null
},
{
"code": "// C# program to implement// the above approachusing System;using System.Collections.Generic;class GFG{ // Function to generate all distinct// subsequences of the array using// backtrackingpublic static void backtrack(List<int> nums, int start, List<int> curr_set){ Console.Write(\" {\"); foreach(int i in curr_set) { Console.Write(i); Console.Write(\", \"); } Console.Write(\"}\"); for(int i = start; i < nums.Count; i++) { // If the current element // is repeating if (i > start && nums[i] == nums[i - 1]) { continue; } // Include current element // into the subsequence curr_set.Add(nums[i]); // Proceed to the remaining array // to generate subsequences // including current array element backtrack(nums, i + 1, curr_set); // Remove current element // from the subsequence curr_set.Remove(curr_set.Count - 1); }} // Function to sort the array and generate// subsequences using Backtrackingpublic static void AllSubsets(List<int> nums){ // Stores the current // subsequence List<int> curr_set = new List<int>(); // Sort the vector nums.Sort(); // Backtrack function to // generate subsequences backtrack(nums, 0, curr_set);} // Driver Codepublic static void Main(String[] args){ List<int> v = new List<int>(); v.Add(1); v.Add(2); v.Add(2); // Function call AllSubsets(v);}} // This code is contributed by 29AjayKumar",
"e": 34787,
"s": 33306,
"text": null
},
{
"code": "<script> // Javascript program to implement the above approach // Function to generate all distinct // subsequences of the array using // backtracking function backtrack(nums, start, curr_set) { document.write(\" {\"); for(let i = 0; i < curr_set.length - 1; i++) { document.write(curr_set[i]); document.write(\", \"); } if(curr_set.length >= 1) { document.write(curr_set[curr_set.length - 1]); document.write(\"}\"); } else { document.write(\"}\"); } for(let i = start; i < nums.length; i++) { // If the current element // is repeating if (i > start && nums[i] == nums[i - 1]) { continue; } // Include current element // into the subsequence curr_set.push(nums[i]); // Proceed to the remaining array // to generate subsequences // including current array element backtrack(nums, i + 1, curr_set); // Remove current element // from the subsequence curr_set.pop(); } } // Function to sort the array and generate // subsequences using Backtracking function AllSubsets(nums) { // Stores the current // subsequence let curr_set = []; // Sort the vector nums.sort(); // Backtrack function to // generate subsequences backtrack(nums, 0, curr_set); } let v = []; v.push(1); v.push(2); v.push(2); // Function call AllSubsets(v); // This code is contributed by mukesh07.</script>",
"e": 36397,
"s": 34787,
"text": null
},
{
"code": null,
"e": 36432,
"s": 36397,
"text": "{} {1} {1, 2} {1, 2, 2} {2} {2, 2}"
},
{
"code": null,
"e": 36476,
"s": 36432,
"text": "Time Complexity: O(2N)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 36494,
"s": 36476,
"text": "hemanthswarna1506"
},
{
"code": null,
"e": 36506,
"s": 36494,
"text": "29AjayKumar"
},
{
"code": null,
"e": 36516,
"s": 36506,
"text": "rutvik_56"
},
{
"code": null,
"e": 36525,
"s": 36516,
"text": "mukesh07"
},
{
"code": null,
"e": 36537,
"s": 36525,
"text": "subsequence"
},
{
"code": null,
"e": 36544,
"s": 36537,
"text": "Arrays"
},
{
"code": null,
"e": 36557,
"s": 36544,
"text": "Backtracking"
},
{
"code": null,
"e": 36571,
"s": 36557,
"text": "Combinatorial"
},
{
"code": null,
"e": 36581,
"s": 36571,
"text": "Recursion"
},
{
"code": null,
"e": 36589,
"s": 36581,
"text": "Sorting"
},
{
"code": null,
"e": 36596,
"s": 36589,
"text": "Arrays"
},
{
"code": null,
"e": 36606,
"s": 36596,
"text": "Recursion"
},
{
"code": null,
"e": 36614,
"s": 36606,
"text": "Sorting"
},
{
"code": null,
"e": 36628,
"s": 36614,
"text": "Combinatorial"
},
{
"code": null,
"e": 36641,
"s": 36628,
"text": "Backtracking"
},
{
"code": null,
"e": 36739,
"s": 36641,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36807,
"s": 36739,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 36851,
"s": 36807,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 36899,
"s": 36851,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 36922,
"s": 36899,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 36954,
"s": 36922,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 36987,
"s": 36954,
"text": "N Queen Problem | Backtracking-3"
},
{
"code": null,
"e": 37047,
"s": 36987,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 37075,
"s": 37047,
"text": "Backtracking | Introduction"
},
{
"code": null,
"e": 37106,
"s": 37075,
"text": "Rat in a Maze | Backtracking-2"
}
] |
CSS - Fade In Effect | The image come or cause to come gradually into or out of view, or to merge into another shot.
@keyframes fadeIn {
0% {opacity: 0;}
100% {opacity: 1;}
}
Transform − Transform applies to 2d and 3d transformation to an element.
Transform − Transform applies to 2d and 3d transformation to an element.
Opacity − Opacity applies to an element to make translucence.
Opacity − Opacity applies to an element to make translucence.
<html>
<head>
<style>
.animated {
background-image: url(/css/images/logo.png);
background-repeat: no-repeat;
background-position: left top;
padding-top:95px;
margin-bottom:60px;
-webkit-animation-duration: 10s;
animation-duration: 10s;
-webkit-animation-fill-mode: both;
animation-fill-mode: both;
}
@-webkit-keyframes fadeIn {
0% {opacity: 0;}
100% {opacity: 1;}
}
@keyframes fadeIn {
0% {opacity: 0;}
100% {opacity: 1;}
}
.fadeIn {
-webkit-animation-name: fadeIn;
animation-name: fadeIn;
}
</style>
</head>
<body>
<div id = "animated-example" class = "animated fadeIn"></div>
<button onclick = "myFunction()">Reload page</button>
<script>
function myFunction() {
location.reload();
}
</script>
</body>
</html>
It will produce the following result −
Academic Tutorials
Big Data & Analytics
Computer Programming
Computer Science
Databases
DevOps
Digital Marketing
Engineering Tutorials
Exams Syllabus
Famous Monuments
GATE Exams Tutorials
Latest Technologies
Machine Learning
Mainframe Development
Management Tutorials
Mathematics Tutorials
Microsoft Technologies
Misc tutorials
Mobile Development
Java Technologies
Python Technologies
SAP Tutorials
Programming Scripts
Selected Reading
Software Quality
Soft Skills
Telecom Tutorials
UPSC IAS Exams
Web Development
Sports Tutorials
XML Technologies
Multi-Language
Interview Questions
Academic Tutorials
Big Data & Analytics
Computer Programming
Computer Science
Databases
DevOps
Digital Marketing
Engineering Tutorials
Exams Syllabus
Famous Monuments
GATE Exams Tutorials
Latest Technologies
Machine Learning
Mainframe Development
Management Tutorials
Mathematics Tutorials
Microsoft Technologies
Misc tutorials
Mobile Development
Java Technologies
Python Technologies
SAP Tutorials
Programming Scripts
Selected Reading
Software Quality
Soft Skills
Telecom Tutorials
UPSC IAS Exams
Web Development
Sports Tutorials
XML Technologies
Multi-Language
Interview Questions
Selected Reading
UPSC IAS Exams Notes
Developer's Best Practices
Questions and Answers
Effective Resume Writing
HR Interview Questions
Computer Glossary
Who is Who
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2720,
"s": 2626,
"text": "The image come or cause to come gradually into or out of view, or to merge into another shot."
},
{
"code": null,
"e": 2785,
"s": 2720,
"text": "@keyframes fadeIn {\n 0% {opacity: 0;}\n 100% {opacity: 1;}\n} "
},
{
"code": null,
"e": 2858,
"s": 2785,
"text": "Transform − Transform applies to 2d and 3d transformation to an element."
},
{
"code": null,
"e": 2931,
"s": 2858,
"text": "Transform − Transform applies to 2d and 3d transformation to an element."
},
{
"code": null,
"e": 2993,
"s": 2931,
"text": "Opacity − Opacity applies to an element to make translucence."
},
{
"code": null,
"e": 3055,
"s": 2993,
"text": "Opacity − Opacity applies to an element to make translucence."
},
{
"code": null,
"e": 4146,
"s": 3055,
"text": "<html>\n <head>\n <style>\n .animated {\n background-image: url(/css/images/logo.png);\n background-repeat: no-repeat;\n background-position: left top;\n padding-top:95px;\n margin-bottom:60px;\n -webkit-animation-duration: 10s;\n animation-duration: 10s;\n -webkit-animation-fill-mode: both;\n animation-fill-mode: both;\n }\n \n @-webkit-keyframes fadeIn {\n 0% {opacity: 0;}\n 100% {opacity: 1;}\n }\n \n @keyframes fadeIn {\n 0% {opacity: 0;}\n 100% {opacity: 1;}\n }\n \n .fadeIn {\n -webkit-animation-name: fadeIn;\n animation-name: fadeIn;\n }\n </style>\n </head>\n\n <body>\n \n <div id = \"animated-example\" class = \"animated fadeIn\"></div>\n <button onclick = \"myFunction()\">Reload page</button>\n \n <script>\n function myFunction() {\n location.reload();\n }\n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 4185,
"s": 4146,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 4832,
"s": 4185,
"text": "\n\n Academic Tutorials\n Big Data & Analytics \n Computer Programming \n Computer Science \n Databases \n DevOps \n Digital Marketing \n Engineering Tutorials \n Exams Syllabus \n Famous Monuments \n GATE Exams Tutorials\n Latest Technologies \n Machine Learning \n Mainframe Development \n Management Tutorials \n Mathematics Tutorials\n Microsoft Technologies \n Misc tutorials \n Mobile Development \n Java Technologies \n Python Technologies \n SAP Tutorials \nProgramming Scripts \n Selected Reading \n Software Quality \n Soft Skills \n Telecom Tutorials \n UPSC IAS Exams \n Web Development \n Sports Tutorials \n XML Technologies \n Multi-Language\n Interview Questions\n\n"
},
{
"code": null,
"e": 4852,
"s": 4832,
"text": " Academic Tutorials"
},
{
"code": null,
"e": 4875,
"s": 4852,
"text": " Big Data & Analytics "
},
{
"code": null,
"e": 4898,
"s": 4875,
"text": " Computer Programming "
},
{
"code": null,
"e": 4917,
"s": 4898,
"text": " Computer Science "
},
{
"code": null,
"e": 4929,
"s": 4917,
"text": " Databases "
},
{
"code": null,
"e": 4938,
"s": 4929,
"text": " DevOps "
},
{
"code": null,
"e": 4958,
"s": 4938,
"text": " Digital Marketing "
},
{
"code": null,
"e": 4982,
"s": 4958,
"text": " Engineering Tutorials "
},
{
"code": null,
"e": 4999,
"s": 4982,
"text": " Exams Syllabus "
},
{
"code": null,
"e": 5018,
"s": 4999,
"text": " Famous Monuments "
},
{
"code": null,
"e": 5040,
"s": 5018,
"text": " GATE Exams Tutorials"
},
{
"code": null,
"e": 5062,
"s": 5040,
"text": " Latest Technologies "
},
{
"code": null,
"e": 5081,
"s": 5062,
"text": " Machine Learning "
},
{
"code": null,
"e": 5105,
"s": 5081,
"text": " Mainframe Development "
},
{
"code": null,
"e": 5128,
"s": 5105,
"text": " Management Tutorials "
},
{
"code": null,
"e": 5151,
"s": 5128,
"text": " Mathematics Tutorials"
},
{
"code": null,
"e": 5176,
"s": 5151,
"text": " Microsoft Technologies "
},
{
"code": null,
"e": 5193,
"s": 5176,
"text": " Misc tutorials "
},
{
"code": null,
"e": 5214,
"s": 5193,
"text": " Mobile Development "
},
{
"code": null,
"e": 5234,
"s": 5214,
"text": " Java Technologies "
},
{
"code": null,
"e": 5256,
"s": 5234,
"text": " Python Technologies "
},
{
"code": null,
"e": 5272,
"s": 5256,
"text": " SAP Tutorials "
},
{
"code": null,
"e": 5293,
"s": 5272,
"text": "Programming Scripts "
},
{
"code": null,
"e": 5312,
"s": 5293,
"text": " Selected Reading "
},
{
"code": null,
"e": 5331,
"s": 5312,
"text": " Software Quality "
},
{
"code": null,
"e": 5345,
"s": 5331,
"text": " Soft Skills "
},
{
"code": null,
"e": 5365,
"s": 5345,
"text": " Telecom Tutorials "
},
{
"code": null,
"e": 5382,
"s": 5365,
"text": " UPSC IAS Exams "
},
{
"code": null,
"e": 5400,
"s": 5382,
"text": " Web Development "
},
{
"code": null,
"e": 5419,
"s": 5400,
"text": " Sports Tutorials "
},
{
"code": null,
"e": 5438,
"s": 5419,
"text": " XML Technologies "
},
{
"code": null,
"e": 5454,
"s": 5438,
"text": " Multi-Language"
},
{
"code": null,
"e": 5475,
"s": 5454,
"text": " Interview Questions"
},
{
"code": null,
"e": 5492,
"s": 5475,
"text": "Selected Reading"
},
{
"code": null,
"e": 5513,
"s": 5492,
"text": "UPSC IAS Exams Notes"
},
{
"code": null,
"e": 5540,
"s": 5513,
"text": "Developer's Best Practices"
},
{
"code": null,
"e": 5562,
"s": 5540,
"text": "Questions and Answers"
},
{
"code": null,
"e": 5587,
"s": 5562,
"text": "Effective Resume Writing"
},
{
"code": null,
"e": 5610,
"s": 5587,
"text": "HR Interview Questions"
},
{
"code": null,
"e": 5628,
"s": 5610,
"text": "Computer Glossary"
},
{
"code": null,
"e": 5639,
"s": 5628,
"text": "Who is Who"
},
{
"code": null,
"e": 5646,
"s": 5639,
"text": " Print"
},
{
"code": null,
"e": 5657,
"s": 5646,
"text": " Add Notes"
}
] |
C++ Program to remove spaces from a string - GeeksforGeeks | 17 May, 2018
Given a string, remove all spaces from it. For example “g e e k” should be converted to “geek” and ” g e ” should be converted to “ge”.
The idea is to traverse the string from left to right and ignore spaces while traversing. We need to keep track of two indexes, one for current character being red and other for current index in output.
// C++ program to evaluate a given expression#include <iostream>using namespace std; char *removeSpaces(char *str){ int i = 0, j = 0; while (str[i]) { if (str[i] != ' ') str[j++] = str[i]; i++; } str[j] = '\0'; return str;} // Driver program to test above functionint main(){ char str1[] = "gee k "; cout << removeSpaces(str1) << endl; char str2[] = " g e e k "; cout << removeSpaces(str2); return 0;}
Output:
geek
geek
Time complexity of above implementation is O(n) where n is number of characters in input string.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Array of Strings in C++ (5 Different Ways to Create)
Convert string to char array in C++
Caesar Cipher in Cryptography
Top 50 String Coding Problems for Interviews
Check whether two strings are anagram of each other
Length of the longest substring without repeating characters
Reverse words in a given string
How to split a string in C/C++, Python and Java?
Remove duplicates from a given string
Reverse string in Python (5 different ways) | [
{
"code": null,
"e": 26581,
"s": 26553,
"text": "\n17 May, 2018"
},
{
"code": null,
"e": 26717,
"s": 26581,
"text": "Given a string, remove all spaces from it. For example “g e e k” should be converted to “geek” and ” g e ” should be converted to “ge”."
},
{
"code": null,
"e": 26920,
"s": 26717,
"text": "The idea is to traverse the string from left to right and ignore spaces while traversing. We need to keep track of two indexes, one for current character being red and other for current index in output."
},
{
"code": "// C++ program to evaluate a given expression#include <iostream>using namespace std; char *removeSpaces(char *str){ int i = 0, j = 0; while (str[i]) { if (str[i] != ' ') str[j++] = str[i]; i++; } str[j] = '\\0'; return str;} // Driver program to test above functionint main(){ char str1[] = \"gee k \"; cout << removeSpaces(str1) << endl; char str2[] = \" g e e k \"; cout << removeSpaces(str2); return 0;}",
"e": 27388,
"s": 26920,
"text": null
},
{
"code": null,
"e": 27396,
"s": 27388,
"text": "Output:"
},
{
"code": null,
"e": 27406,
"s": 27396,
"text": "geek\ngeek"
},
{
"code": null,
"e": 27503,
"s": 27406,
"text": "Time complexity of above implementation is O(n) where n is number of characters in input string."
},
{
"code": null,
"e": 27627,
"s": 27503,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 27635,
"s": 27627,
"text": "Strings"
},
{
"code": null,
"e": 27643,
"s": 27635,
"text": "Strings"
},
{
"code": null,
"e": 27741,
"s": 27643,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27794,
"s": 27741,
"text": "Array of Strings in C++ (5 Different Ways to Create)"
},
{
"code": null,
"e": 27830,
"s": 27794,
"text": "Convert string to char array in C++"
},
{
"code": null,
"e": 27860,
"s": 27830,
"text": "Caesar Cipher in Cryptography"
},
{
"code": null,
"e": 27905,
"s": 27860,
"text": "Top 50 String Coding Problems for Interviews"
},
{
"code": null,
"e": 27957,
"s": 27905,
"text": "Check whether two strings are anagram of each other"
},
{
"code": null,
"e": 28018,
"s": 27957,
"text": "Length of the longest substring without repeating characters"
},
{
"code": null,
"e": 28050,
"s": 28018,
"text": "Reverse words in a given string"
},
{
"code": null,
"e": 28099,
"s": 28050,
"text": "How to split a string in C/C++, Python and Java?"
},
{
"code": null,
"e": 28137,
"s": 28099,
"text": "Remove duplicates from a given string"
}
] |
Print all paths from a given source to a destination in C++ | In this problem we are given a directed graph and we have to print all paths from the source to the destination of the graph.
Directed graph is a graph in with edges that are directed from vertex a to b.
Let’s take an example to understand the problem
Source = K destination = P
Output:
K -> T -> Y -> A -> P
K -> T -> Y -> P
K -> A -> P
Here, we have found paths from K to P. We have traversed paths and printed all paths from K that direct us to P.
To solve this problem, we will traverse the graph using depth-first search traversal technique. Starting from source, we will traverse each vertex store in our path array and mark it as visited (to avoid multiple visiting of the same vertex). And print this path, when the destination vertex is reached.
Let’s see the program implementing the logic -
Live Demo
#include<iostream>
#include <list>
using namespace std;
class Graph {
int V;
list<int> *adj;
void findNewPath(int , int , bool [], int [], int &);
public:
Graph(int V);
void addEdge(int u, int v);
void printPaths(int s, int d);
};
Graph::Graph(int V) {
this->V = V;
adj = new list<int>[V];
}
void Graph::addEdge(int u, int v) {
adj[u].push_back(v);
}
void Graph::printPaths(int s, int d) {
bool *visited = new bool[V];
int *path = new int[V];
int path_index = 0;
for (int i = 0; i < V; i++)
visited[i] = false;
findNewPath(s, d, visited, path, path_index);
}
void Graph::findNewPath(int u, int d, bool visited[],
int path[], int &path_index) {
visited[u] = true;
path[path_index] = u;
path_index++;
if (u == d) {
for (int i = 0; i<path_index; i++)
cout<<path[i]<<" ";
cout << endl;
} else {
list<int>::iterator i;
for (i = adj[u].begin(); i != adj[u].end(); ++i)
if (!visited[*i])
findNewPath(*i, d, visited, path, path_index);
}
path_index--;
visited[u] = false;
}
int main() {
Graph g(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(0, 3);
g.addEdge(2, 0);
g.addEdge(2, 1);
g.addEdge(1, 3);
int s = 2, d = 3;
cout<<"Following are all different paths from source to destination : \n";
g.printPaths(s, d);
return 0;
}
Following are all different paths from source to destination :
2 0 1 3
2 0 3
2 1 3 | [
{
"code": null,
"e": 1188,
"s": 1062,
"text": "In this problem we are given a directed graph and we have to print all paths from the source to the destination of the graph."
},
{
"code": null,
"e": 1266,
"s": 1188,
"text": "Directed graph is a graph in with edges that are directed from vertex a to b."
},
{
"code": null,
"e": 1315,
"s": 1266,
"text": "Let’s take an example to understand the problem "
},
{
"code": null,
"e": 1342,
"s": 1315,
"text": "Source = K destination = P"
},
{
"code": null,
"e": 1350,
"s": 1342,
"text": "Output:"
},
{
"code": null,
"e": 1401,
"s": 1350,
"text": "K -> T -> Y -> A -> P\nK -> T -> Y -> P\nK -> A -> P"
},
{
"code": null,
"e": 1514,
"s": 1401,
"text": "Here, we have found paths from K to P. We have traversed paths and printed all paths from K that direct us to P."
},
{
"code": null,
"e": 1818,
"s": 1514,
"text": "To solve this problem, we will traverse the graph using depth-first search traversal technique. Starting from source, we will traverse each vertex store in our path array and mark it as visited (to avoid multiple visiting of the same vertex). And print this path, when the destination vertex is reached."
},
{
"code": null,
"e": 1865,
"s": 1818,
"text": "Let’s see the program implementing the logic -"
},
{
"code": null,
"e": 1876,
"s": 1865,
"text": " Live Demo"
},
{
"code": null,
"e": 3250,
"s": 1876,
"text": "#include<iostream>\n#include <list>\nusing namespace std;\nclass Graph {\n int V;\n list<int> *adj;\n void findNewPath(int , int , bool [], int [], int &);\n public:\n Graph(int V);\n void addEdge(int u, int v);\n void printPaths(int s, int d);\n};\nGraph::Graph(int V) {\n this->V = V;\n adj = new list<int>[V];\n}\nvoid Graph::addEdge(int u, int v) {\n adj[u].push_back(v);\n}\nvoid Graph::printPaths(int s, int d) {\n bool *visited = new bool[V];\n int *path = new int[V];\n int path_index = 0;\n for (int i = 0; i < V; i++)\n visited[i] = false;\n findNewPath(s, d, visited, path, path_index);\n}\nvoid Graph::findNewPath(int u, int d, bool visited[],\nint path[], int &path_index) {\n visited[u] = true;\n path[path_index] = u;\n path_index++;\n if (u == d) {\n for (int i = 0; i<path_index; i++)\n cout<<path[i]<<\" \";\n cout << endl;\n } else {\n list<int>::iterator i;\n for (i = adj[u].begin(); i != adj[u].end(); ++i)\n if (!visited[*i])\n findNewPath(*i, d, visited, path, path_index);\n }\n path_index--;\n visited[u] = false;\n}\nint main() {\n Graph g(4);\n g.addEdge(0, 1);\n g.addEdge(0, 2);\n g.addEdge(0, 3);\n g.addEdge(2, 0);\n g.addEdge(2, 1);\n g.addEdge(1, 3);\n int s = 2, d = 3;\n cout<<\"Following are all different paths from source to destination : \\n\";\n g.printPaths(s, d);\n return 0;\n}"
},
{
"code": null,
"e": 3333,
"s": 3250,
"text": "Following are all different paths from source to destination :\n2 0 1 3\n2 0 3\n2 1 3"
}
] |
Nesting Columns in Bootstrap | To nest your content with the default grid, add a new .row and set of .col-md-* columns within an existing .col-md-* column.
You can try to run the following code to learn how to implement nesting columns in Bootstrap −
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Example</title>
<link href="/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<script src = "/scripts/jquery.min.js"></script>
<script src = "/bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<div class = "box">
<h1>Heading</h1>
<div class = "row">
<div class = "col-md-3" style = "background-color: gray; color: white;
box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;">
<h4>Heading</h4>
<p>This is demo text.</p>
</div>
<div class = "col-md-9" style = "background-color: gray;color: white;
box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;">
<h4>Heading</h4>
<p>This is demo text.</p>
<div class = "row">
<div class = "col-md-6" style = "background-color: orange;
box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;">
<p>This is box 1.</p>
</div>
<div class = "col-md-6" style = "background-color: orange;
box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;">
<p>This is box 2.</p>
</div>
</div>
<div class = "row">
<div class = "col-md-6" style = "background-color: orange;
box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;">
<p>This is box 3.</p>
</div>
<div class = "col-md-6" style = "background-color: orange;
box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;">
<p>This is box 4.</p>
</div>
</div>
</div>
</div>
</div>
</body>
</html> | [
{
"code": null,
"e": 1188,
"s": 1062,
"text": "To nest your content with the default grid, add a new .row and set of .col-md-* columns within an existing .col-md-* column. "
},
{
"code": null,
"e": 1283,
"s": 1188,
"text": "You can try to run the following code to learn how to implement nesting columns in Bootstrap −"
},
{
"code": null,
"e": 1294,
"s": 1283,
"text": " Live Demo"
},
{
"code": null,
"e": 3245,
"s": 1294,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <link href=\"/bootstrap/css/bootstrap.min.css\" rel=\"stylesheet\">\n <script src = \"/scripts/jquery.min.js\"></script>\n <script src = \"/bootstrap/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <div class = \"box\">\n <h1>Heading</h1>\n <div class = \"row\">\n <div class = \"col-md-3\" style = \"background-color: gray; color: white;\n box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;\">\n <h4>Heading</h4>\n <p>This is demo text.</p>\n </div>\n <div class = \"col-md-9\" style = \"background-color: gray;color: white;\n box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;\">\n <h4>Heading</h4>\n <p>This is demo text.</p>\n <div class = \"row\">\n <div class = \"col-md-6\" style = \"background-color: orange;\n box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;\">\n <p>This is box 1.</p>\n </div>\n <div class = \"col-md-6\" style = \"background-color: orange;\n box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;\">\n <p>This is box 2.</p>\n </div>\n </div>\n <div class = \"row\">\n <div class = \"col-md-6\" style = \"background-color: orange;\n box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;\">\n <p>This is box 3.</p>\n </div>\n <div class = \"col-md-6\" style = \"background-color: orange;\n box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;\">\n <p>This is box 4.</p>\n </div>\n </div>\n </div>\n </div>\n </div>\n </body>\n</html>"
}
] |
Arguments in Discrete Mathematics - GeeksforGeeks | 19 Feb, 2021
Arguments are an important part of logical reasoning and philosophy. It also plays a vital role in mathematical proofs. In this article, we will throw some light on arguments in logical reasoning. Logical proofs can be proven by mathematical logic. The proof is a valid argument that determines the truth values of mathematical statements. The argument is a set of statements or propositions which contains premises and conclusion. The end or last statement is called a conclusion and the rest statements are called premises.
The premises of the argument are those statements or propositions which are used to provide the support or evidence while the conclusions of an argument is that statement or proposition that simply defines that premises are intended to provide support.
An argument is denoted by the following expression as follows.
P1, P2, ..., Pn $ Q
Where P1, P2...... Pn is the premises and Q is the conclusion.
Example of Arguments :
Example-1 :
Every student of Information Technology studies Data Structures.
Data structures necessarily contain the study of arguments.
Therefore, every student of Information Technology studies arguments.
Example-2 :
Every parent is a mature person.
Children should listen to mature people.
Therefore, every child should listen to their parents.
Example-3 :
Every mother is a woman.
All women are caring.
Therefore, every mother is caring.
Types of Arguments :
1. Deductive Argument –
We can say that an argument where the truth of the premises always results in the truth of the conclusion. The true value of premises never gives a false value of conclusion, where no such condition occurs, is called deductive arguments.
Example –
All men are busy
Ram is a man
______________
Ram is busy
2. Inductive Argument –
An argument where the premises point to a few instances of some pattern and the end expresses that this pattern will hold as a rule generally. An inductive argument won’t be deductively valid, in light of the fact that regardless of whether a pattern is discovered ordinarily, that doesn’t promise it will consistently be found. Consequently, an inductive argument gives weaker, less reliable support for the conclusion than a deductive argument does.
Example –
We have seen 800 ducks, and every one of them has been white
________________________________________________
All ducks are white
Validity and Soundness of argument :
An argument is said to be valid only if it’s not possible for the premises to have true value and the conclusion to have false value. If the above statement does not hold then it is called invalid. Arguments that are invalid are also called a fallacy. If the truth of the premises logically confirms the truth of the conclusion then the argument is valid.
Note –
A deductive argument is said to be sound if and only if it is both factually correct and valid. Otherwise, deductive arguments are unsound.
Uses and Application :
Arguments are used in computer programming.
Arguments are used in critical thinking.
Arguments are used to test logical ability.
Arguments offer proof for a claim or conclusion.
Argument mapping is useful in philosophy, management reporting, military, and intelligence analysis, and public debates.
Conclusion :
An argument is a set of statements, including premises and the conclusion. The conclusion is derived from premises. There are two types of argument; valid argument and invalid arguments and sound and unsound. Apart from these, arguments can be deductive and inductive. There are many uses of arguments in logical reasoning and mathematical proofs.
Engineering Mathematics
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Activation Functions
Difference between Propositional Logic and Predicate Logic
Logic Notations in LaTeX
Univariate, Bivariate and Multivariate data and its analysis
Z-test
Proof that vertex cover is NP complete
Brackets in Latex
Betweenness Centrality (Centrality Measure)
Introduction of Statistics and its Types
Mathematics | Introduction of Set theory | [
{
"code": null,
"e": 26162,
"s": 26134,
"text": "\n19 Feb, 2021"
},
{
"code": null,
"e": 26688,
"s": 26162,
"text": "Arguments are an important part of logical reasoning and philosophy. It also plays a vital role in mathematical proofs. In this article, we will throw some light on arguments in logical reasoning. Logical proofs can be proven by mathematical logic. The proof is a valid argument that determines the truth values of mathematical statements. The argument is a set of statements or propositions which contains premises and conclusion. The end or last statement is called a conclusion and the rest statements are called premises."
},
{
"code": null,
"e": 26941,
"s": 26688,
"text": "The premises of the argument are those statements or propositions which are used to provide the support or evidence while the conclusions of an argument is that statement or proposition that simply defines that premises are intended to provide support."
},
{
"code": null,
"e": 27004,
"s": 26941,
"text": "An argument is denoted by the following expression as follows."
},
{
"code": null,
"e": 27089,
"s": 27004,
"text": " P1, P2, ..., Pn $ Q\n Where P1, P2...... Pn is the premises and Q is the conclusion."
},
{
"code": null,
"e": 27112,
"s": 27089,
"text": "Example of Arguments :"
},
{
"code": null,
"e": 27124,
"s": 27112,
"text": "Example-1 :"
},
{
"code": null,
"e": 27189,
"s": 27124,
"text": "Every student of Information Technology studies Data Structures."
},
{
"code": null,
"e": 27249,
"s": 27189,
"text": "Data structures necessarily contain the study of arguments."
},
{
"code": null,
"e": 27319,
"s": 27249,
"text": "Therefore, every student of Information Technology studies arguments."
},
{
"code": null,
"e": 27331,
"s": 27319,
"text": "Example-2 :"
},
{
"code": null,
"e": 27364,
"s": 27331,
"text": "Every parent is a mature person."
},
{
"code": null,
"e": 27405,
"s": 27364,
"text": "Children should listen to mature people."
},
{
"code": null,
"e": 27460,
"s": 27405,
"text": "Therefore, every child should listen to their parents."
},
{
"code": null,
"e": 27472,
"s": 27460,
"text": "Example-3 :"
},
{
"code": null,
"e": 27497,
"s": 27472,
"text": "Every mother is a woman."
},
{
"code": null,
"e": 27519,
"s": 27497,
"text": "All women are caring."
},
{
"code": null,
"e": 27554,
"s": 27519,
"text": "Therefore, every mother is caring."
},
{
"code": null,
"e": 27575,
"s": 27554,
"text": "Types of Arguments :"
},
{
"code": null,
"e": 27599,
"s": 27575,
"text": "1. Deductive Argument –"
},
{
"code": null,
"e": 27837,
"s": 27599,
"text": "We can say that an argument where the truth of the premises always results in the truth of the conclusion. The true value of premises never gives a false value of conclusion, where no such condition occurs, is called deductive arguments."
},
{
"code": null,
"e": 27849,
"s": 27837,
"text": "Example – "
},
{
"code": null,
"e": 27906,
"s": 27849,
"text": "All men are busy\nRam is a man\n______________\nRam is busy"
},
{
"code": null,
"e": 27931,
"s": 27906,
"text": "2. Inductive Argument – "
},
{
"code": null,
"e": 28385,
"s": 27931,
"text": "An argument where the premises point to a few instances of some pattern and the end expresses that this pattern will hold as a rule generally. An inductive argument won’t be deductively valid, in light of the fact that regardless of whether a pattern is discovered ordinarily, that doesn’t promise it will consistently be found. Consequently, an inductive argument gives weaker, less reliable support for the conclusion than a deductive argument does. "
},
{
"code": null,
"e": 28397,
"s": 28385,
"text": "Example – "
},
{
"code": null,
"e": 28533,
"s": 28397,
"text": "We have seen 800 ducks, and every one of them has been white \n________________________________________________ \nAll ducks are white "
},
{
"code": null,
"e": 28570,
"s": 28533,
"text": "Validity and Soundness of argument :"
},
{
"code": null,
"e": 28926,
"s": 28570,
"text": "An argument is said to be valid only if it’s not possible for the premises to have true value and the conclusion to have false value. If the above statement does not hold then it is called invalid. Arguments that are invalid are also called a fallacy. If the truth of the premises logically confirms the truth of the conclusion then the argument is valid."
},
{
"code": null,
"e": 28933,
"s": 28926,
"text": "Note –"
},
{
"code": null,
"e": 29073,
"s": 28933,
"text": "A deductive argument is said to be sound if and only if it is both factually correct and valid. Otherwise, deductive arguments are unsound."
},
{
"code": null,
"e": 29096,
"s": 29073,
"text": "Uses and Application :"
},
{
"code": null,
"e": 29140,
"s": 29096,
"text": "Arguments are used in computer programming."
},
{
"code": null,
"e": 29181,
"s": 29140,
"text": "Arguments are used in critical thinking."
},
{
"code": null,
"e": 29225,
"s": 29181,
"text": "Arguments are used to test logical ability."
},
{
"code": null,
"e": 29274,
"s": 29225,
"text": "Arguments offer proof for a claim or conclusion."
},
{
"code": null,
"e": 29395,
"s": 29274,
"text": "Argument mapping is useful in philosophy, management reporting, military, and intelligence analysis, and public debates."
},
{
"code": null,
"e": 29409,
"s": 29395,
"text": "Conclusion : "
},
{
"code": null,
"e": 29757,
"s": 29409,
"text": "An argument is a set of statements, including premises and the conclusion. The conclusion is derived from premises. There are two types of argument; valid argument and invalid arguments and sound and unsound. Apart from these, arguments can be deductive and inductive. There are many uses of arguments in logical reasoning and mathematical proofs."
},
{
"code": null,
"e": 29781,
"s": 29757,
"text": "Engineering Mathematics"
},
{
"code": null,
"e": 29879,
"s": 29781,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29900,
"s": 29879,
"text": "Activation Functions"
},
{
"code": null,
"e": 29959,
"s": 29900,
"text": "Difference between Propositional Logic and Predicate Logic"
},
{
"code": null,
"e": 29984,
"s": 29959,
"text": "Logic Notations in LaTeX"
},
{
"code": null,
"e": 30045,
"s": 29984,
"text": "Univariate, Bivariate and Multivariate data and its analysis"
},
{
"code": null,
"e": 30052,
"s": 30045,
"text": "Z-test"
},
{
"code": null,
"e": 30091,
"s": 30052,
"text": "Proof that vertex cover is NP complete"
},
{
"code": null,
"e": 30109,
"s": 30091,
"text": "Brackets in Latex"
},
{
"code": null,
"e": 30153,
"s": 30109,
"text": "Betweenness Centrality (Centrality Measure)"
},
{
"code": null,
"e": 30194,
"s": 30153,
"text": "Introduction of Statistics and its Types"
}
] |
How to detect the version of a browser ? - GeeksforGeeks | 18 Nov, 2020
This article includes basic theory and technique of browser detection in JavaScript-enabled web browsers.
Description: Even though most of the scripts works on JavaScript-enabled web browser, there are certain things that is not going to work on some browsers i.e. they are browser dependent and in some cases old web browser doesn’t support some script.In some cases, it becomes very important to know the client’s web browser for delivering some content or information appropriately. Basically, it allows you to know the client web browser version and name and here we need to write different functions for different browsers for the purpose of detection.
Browser Detection: Mainly there are two objects that are used for browser detection which is as follows:
navigator.appName
navigator.appVersion
The purpose of the first object is to determine the web browser whereas the purpose of the second one is to determine the version of the web browser.
For Example, if the browser is Mozilla Firefox, navigator.appName returns the string “Mozilla Firefox”. If it is Internet Explorer, navigator.appName returns the string “Microsoft Internet Explorer”. Using both objects, we can create an alert box to display what web browser the client is using and this navigator object contain all the information about web browser version, name, and more.
Example:
Javascript
<!DOCTYPE html><html> <head> <script Language="JavaScript"> var objappVersion = navigator.appVersion; var browserAgent = navigator.userAgent; var browserName = navigator.appName; var browserVersion = '' + parseFloat(navigator.appVersion); var browserMajorVersion = parseInt(navigator.appVersion, 10); var Offset, OffsetVersion, ix; // For Chrome if ((OffsetVersion = browserAgent.indexOf("Chrome")) != -1) { browserName = "Chrome"; browserVersion = browserAgent.substring(OffsetVersion + 7); } // For Microsoft internet explorer else if ((OffsetVersion = browserAgent.indexOf("MSIE")) != -1) { browserName = "Microsoft Internet Explorer"; browserVersion = browserAgent.substring(OffsetVersion + 5); } // For Firefox else if ((OffsetVersion = browserAgent.indexOf("Firefox")) != -1) { browserName = "Firefox"; } // For Safari else if ((OffsetVersion = browserAgent.indexOf("Safari")) != -1) { browserName = "Safari"; browserVersion = browserAgent.substring(OffsetVersion + 7); if ((OffsetVersion = browserAgent.indexOf("Version")) != -1) browserVersion = browserAgent.substring(OffsetVersion + 8); } // For other browser "name/version" is at the end of userAgent else if ((Offset = browserAgent.lastIndexOf(' ') + 1) < (OffsetVersion = browserAgent.lastIndexOf('/'))) { browserName = browserAgent.substring(Offset, OffsetVersion); browserVersion = browserAgent.substring(OffsetVersion + 1); if (browserName.toLowerCase() == browserName.toUpperCase()) { browserName = navigator.appName; } } // Trimming the fullVersion string at // semicolon/space if present if ((ix = browserVersion.indexOf(";")) != -1) browserVersion = browserVersion.substring(0, ix); if ((ix = browserVersion.indexOf(" ")) != -1) browserVersion = browserVersion.substring(0, ix); browserMajorVersion = parseInt('' + browserVersion, 10); if (isNaN(browserMajorVersion)) { browserVersion = '' + parseFloat(navigator.appVersion); browserMajorVersion = parseInt(navigator.appVersion, 10); } document.write('' + 'Name of Browser = ' + browserName + '<br>' + 'Full version = ' + browserVersion + '<br>' + 'Major version = ' + browserMajorVersion + '<br>' + 'navigator.appName = ' + navigator.appName + '<br>' + 'navigator.userAgent = ' + navigator.userAgent + '<br>' ); </script></head> </html>
Output:
Below Output represents the output of browser detection for “Chrome”Name of Browser = ChromeFull version = 86.0.4240.183Major version = 86navigator.appName = Netscapenavigator.userAgent = Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.183 Safari/537.36
Name of Browser = ChromeFull version = 86.0.4240.183Major version = 86navigator.appName = Netscapenavigator.userAgent = Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.183 Safari/537.36
Below Output represents the output of browser detection for “Mozilla Firefox”Name of Browser = FirefoxFull version = 5Major version = 5navigator.appName = Netscapenavigator.userAgent = Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:80.0)Gecko/20100101 Firefox/80.0
Name of Browser = FirefoxFull version = 5Major version = 5navigator.appName = Netscapenavigator.userAgent = Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:80.0)Gecko/20100101 Firefox/80.0
Conclusion: This article starts with the theory of browser detection and later on it explains the browser detection scheme and script for detection. It is very beneficial in the current environment because all browsers support this application. So detect/find the browser and then write the corresponding code.
HTML-Misc
JavaScript-Misc
HTML
JavaScript
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
HTML Cheat Sheet - A Basic Guide to HTML
Design a web page using HTML and CSS
Form validation using jQuery
Angular File Upload
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript? | [
{
"code": null,
"e": 26139,
"s": 26111,
"text": "\n18 Nov, 2020"
},
{
"code": null,
"e": 26245,
"s": 26139,
"text": "This article includes basic theory and technique of browser detection in JavaScript-enabled web browsers."
},
{
"code": null,
"e": 26797,
"s": 26245,
"text": "Description: Even though most of the scripts works on JavaScript-enabled web browser, there are certain things that is not going to work on some browsers i.e. they are browser dependent and in some cases old web browser doesn’t support some script.In some cases, it becomes very important to know the client’s web browser for delivering some content or information appropriately. Basically, it allows you to know the client web browser version and name and here we need to write different functions for different browsers for the purpose of detection."
},
{
"code": null,
"e": 26902,
"s": 26797,
"text": "Browser Detection: Mainly there are two objects that are used for browser detection which is as follows:"
},
{
"code": null,
"e": 26920,
"s": 26902,
"text": "navigator.appName"
},
{
"code": null,
"e": 26941,
"s": 26920,
"text": "navigator.appVersion"
},
{
"code": null,
"e": 27091,
"s": 26941,
"text": "The purpose of the first object is to determine the web browser whereas the purpose of the second one is to determine the version of the web browser."
},
{
"code": null,
"e": 27484,
"s": 27091,
"text": "For Example, if the browser is Mozilla Firefox, navigator.appName returns the string “Mozilla Firefox”. If it is Internet Explorer, navigator.appName returns the string “Microsoft Internet Explorer”. Using both objects, we can create an alert box to display what web browser the client is using and this navigator object contain all the information about web browser version, name, and more. "
},
{
"code": null,
"e": 27493,
"s": 27484,
"text": "Example:"
},
{
"code": null,
"e": 27504,
"s": 27493,
"text": "Javascript"
},
{
"code": "<!DOCTYPE html><html> <head> <script Language=\"JavaScript\"> var objappVersion = navigator.appVersion; var browserAgent = navigator.userAgent; var browserName = navigator.appName; var browserVersion = '' + parseFloat(navigator.appVersion); var browserMajorVersion = parseInt(navigator.appVersion, 10); var Offset, OffsetVersion, ix; // For Chrome if ((OffsetVersion = browserAgent.indexOf(\"Chrome\")) != -1) { browserName = \"Chrome\"; browserVersion = browserAgent.substring(OffsetVersion + 7); } // For Microsoft internet explorer else if ((OffsetVersion = browserAgent.indexOf(\"MSIE\")) != -1) { browserName = \"Microsoft Internet Explorer\"; browserVersion = browserAgent.substring(OffsetVersion + 5); } // For Firefox else if ((OffsetVersion = browserAgent.indexOf(\"Firefox\")) != -1) { browserName = \"Firefox\"; } // For Safari else if ((OffsetVersion = browserAgent.indexOf(\"Safari\")) != -1) { browserName = \"Safari\"; browserVersion = browserAgent.substring(OffsetVersion + 7); if ((OffsetVersion = browserAgent.indexOf(\"Version\")) != -1) browserVersion = browserAgent.substring(OffsetVersion + 8); } // For other browser \"name/version\" is at the end of userAgent else if ((Offset = browserAgent.lastIndexOf(' ') + 1) < (OffsetVersion = browserAgent.lastIndexOf('/'))) { browserName = browserAgent.substring(Offset, OffsetVersion); browserVersion = browserAgent.substring(OffsetVersion + 1); if (browserName.toLowerCase() == browserName.toUpperCase()) { browserName = navigator.appName; } } // Trimming the fullVersion string at // semicolon/space if present if ((ix = browserVersion.indexOf(\";\")) != -1) browserVersion = browserVersion.substring(0, ix); if ((ix = browserVersion.indexOf(\" \")) != -1) browserVersion = browserVersion.substring(0, ix); browserMajorVersion = parseInt('' + browserVersion, 10); if (isNaN(browserMajorVersion)) { browserVersion = '' + parseFloat(navigator.appVersion); browserMajorVersion = parseInt(navigator.appVersion, 10); } document.write('' + 'Name of Browser = ' + browserName + '<br>' + 'Full version = ' + browserVersion + '<br>' + 'Major version = ' + browserMajorVersion + '<br>' + 'navigator.appName = ' + navigator.appName + '<br>' + 'navigator.userAgent = ' + navigator.userAgent + '<br>' ); </script></head> </html>",
"e": 30273,
"s": 27504,
"text": null
},
{
"code": null,
"e": 30281,
"s": 30273,
"text": "Output:"
},
{
"code": null,
"e": 30584,
"s": 30281,
"text": "Below Output represents the output of browser detection for “Chrome”Name of Browser = ChromeFull version = 86.0.4240.183Major version = 86navigator.appName = Netscapenavigator.userAgent = Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.183 Safari/537.36"
},
{
"code": null,
"e": 30819,
"s": 30584,
"text": "Name of Browser = ChromeFull version = 86.0.4240.183Major version = 86navigator.appName = Netscapenavigator.userAgent = Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.183 Safari/537.36"
},
{
"code": null,
"e": 31082,
"s": 30819,
"text": "Below Output represents the output of browser detection for “Mozilla Firefox”Name of Browser = FirefoxFull version = 5Major version = 5navigator.appName = Netscapenavigator.userAgent = Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:80.0)Gecko/20100101 Firefox/80.0"
},
{
"code": null,
"e": 31268,
"s": 31082,
"text": "Name of Browser = FirefoxFull version = 5Major version = 5navigator.appName = Netscapenavigator.userAgent = Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:80.0)Gecko/20100101 Firefox/80.0"
},
{
"code": null,
"e": 31579,
"s": 31268,
"text": "Conclusion: This article starts with the theory of browser detection and later on it explains the browser detection scheme and script for detection. It is very beneficial in the current environment because all browsers support this application. So detect/find the browser and then write the corresponding code."
},
{
"code": null,
"e": 31589,
"s": 31579,
"text": "HTML-Misc"
},
{
"code": null,
"e": 31605,
"s": 31589,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 31610,
"s": 31605,
"text": "HTML"
},
{
"code": null,
"e": 31621,
"s": 31610,
"text": "JavaScript"
},
{
"code": null,
"e": 31638,
"s": 31621,
"text": "Web Technologies"
},
{
"code": null,
"e": 31665,
"s": 31638,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 31670,
"s": 31665,
"text": "HTML"
},
{
"code": null,
"e": 31768,
"s": 31670,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31792,
"s": 31768,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 31833,
"s": 31792,
"text": "HTML Cheat Sheet - A Basic Guide to HTML"
},
{
"code": null,
"e": 31870,
"s": 31833,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 31899,
"s": 31870,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 31919,
"s": 31899,
"text": "Angular File Upload"
},
{
"code": null,
"e": 31959,
"s": 31919,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 32004,
"s": 31959,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 32065,
"s": 32004,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 32137,
"s": 32065,
"text": "Differences between Functional Components and Class Components in React"
}
] |
RecyclerView using ListView in Android With Example - GeeksforGeeks | 21 Dec, 2020
RecyclerView is more flexible and advanced version of ListView and GridView. RecyclerView is used for providing a limited window to a large data set, which means it is used to display a large amount of data that can be scrolled very efficiently by maintaining a limited number of Views. In RecyclerView we supply data and define how each item looks, and the RecyclerView library dynamically creates the content when it is needed. RecyclerView was introduced in Material Design in Android 5.0(API level 21.0).
RecyclerView is a ViewGroup that contains Views corresponding to your data. It itself a View so, it is added to the layout file as any other UI element is added.
ViewHolder Object is used to define each individual element in the list. View holder does not contain anything when it created, RecyclerView binds data to it. ViewHolder is defined by extending RecyclerView.ViewHolder.
Adapters are used to bind data to the Views. RecyclerView request views, and binds the views to their data, by calling methods in the adapter. The adapter can be defined by extending RecyclerView.Adapter.
LayoutManager arranges the individual elements in the list. It contains the reference of all views that are filled by the data of the entry.
LayoutManager class of RecyclerView provide three types of built-in LayoutManagers
LinearLayoutManager: It is used for displaying Horizontal and Vertical List
GridLayoutManager: It is used for displaying items in the forms of grids
StaggeredGridLayoutManager: It is used for displaying items in form of staggered grids
In this example, we are going to use RecyclerView as ListView. Here, we are going to display the list of courses with their images as a vertical list using RecyclerView.
Step 1: Create A New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Add Dependency
We are going to use RecyclerView as ListView. So, we need to add the dependency for it. For adding the dependency Go to Gradle Scripts > build.gradle(Module: app) and add the following dependency. After adding the dependency click on Sync Now.
dependencies {
implementation “androidx.recyclerview:recyclerview:1.1.0”
}
Before moving further let’s add some color attributes in order to enhance the app bar. Go to app > res > values > colors.xml and add the following color attributes.
XML
<resources> <color name="colorPrimary">#0F9D58</color> <color name="colorPrimaryDark">#16E37F</color> <color name="colorAccent">#03DAC5</color> </resources>
Step 3: Working with the activity_main.xml file
In this step, we will add a RecyclerView to our activity_main.xml file which is used to display data of listItems. Go to the app > res > layout > activity_main.xml and the following code snippet.
XML
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!--RecyclerView--> <androidx.recyclerview.widget.RecyclerView android:id="@+id/recyclerView" android:layout_width="match_parent" android:layout_height="match_parent"/> </LinearLayout>
Step 4: Create a new layout file list_item.xml
In this step, we will create a new layout file for the single list item view. Go to app > res > layout > right-click > New > Layout Resource File and name it as list_item. list_item.xml contains an ImageView and a TextView which is used for populating the RecyclerView.
XML
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <!--For image src we have used ic_launcher and for text "courseName" they are used only for reference how it will looks"--> <ImageView android:id="@+id/courseImg" android:layout_width="72dp" android:layout_height="72dp" android:padding="8dp" android:src="@mipmap/ic_launcher_round" /> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" android:layout_gravity="center"> <TextView android:id="@+id/courseName" android:text="courseName" android:textStyle="bold" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </LinearLayout> </LinearLayout>
Step 5: Create a new Adapter class
Now, we will create an Adapter class that acts as a bridge between the UI Component and the Data Source .i.e., courseImg, courseName, and RecyclerView. Go to the app > java > package > right-click and create a new java class and name it as Adapter. Below is the code snippet is given for it.
Java
import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView;import android.widget.TextView; import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView;import java.util.ArrayList; // Extends the Adapter class to RecyclerView.Adapter// and implement the unimplemented methodspublic class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> { ArrayList courseImg, courseName; Context context; // Constructor for initialization public Adapter(Context context, ArrayList courseImg, ArrayList courseName) { this.context = context; this.courseImg = courseImg; this.courseName = courseName; } @NonNull @Override public Adapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { // Inflating the Layout(Instantiates list_item.xml // layout file into View object) View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false); // Passing view to ViewHolder Adapter.ViewHolder viewHolder = new Adapter.ViewHolder(view); return viewHolder; } // Binding data to the into specified position @Override public void onBindViewHolder(@NonNull Adapter.ViewHolder holder, int position) { // TypeCast Object to int type int res = (int) courseImg.get(position); holder.images.setImageResource(res); holder.text.setText((String) courseName.get(position)); } @Override public int getItemCount() { // Returns number of items // currently available in Adapter return courseImg.size(); } // Initializing the Views public class ViewHolder extends RecyclerView.ViewHolder { ImageView images; TextView text; public ViewHolder(View view) { super(view); images = (ImageView) view.findViewById(R.id.courseImg); text = (TextView) view.findViewById(R.id.courseName); } }}
Step 6: Working with the MainActivity file
In MainActivity.java class we create two ArrayList for storing courseImg and courseName. These images are placed in the drawable folder(app > res > drawable). You can use any images in place of these. And then we get the reference RecyclerView and set the LayoutManager as LinearLayoutManager and Adapter, to show items in RecyclerView. Below is the code for the MainActivity.java file.
Java
import android.os.Bundle;import androidx.appcompat.app.AppCompatActivity;import androidx.recyclerview.widget.LinearLayoutManager;import androidx.recyclerview.widget.RecyclerView;import androidx.recyclerview.widget.StaggeredGridLayoutManager;import java.util.ArrayList;import java.util.Arrays; public class MainActivity extends AppCompatActivity { RecyclerView recyclerView; // Using ArrayList to store images data ArrayList courseImg = new ArrayList<>(Arrays.asList(R.drawable.data_structure, R.drawable.c_plus_plus, R.drawable.c_hash, R.drawable.java_script, R.drawable.java, R.drawable.c, R.drawable.html, R.drawable.css)); ArrayList courseName = new ArrayList<>(Arrays.asList("Data Structure", "C++", "C#", "JavaScript", "Java", "C-Language", "HTML 5", "CSS")); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Getting reference of recyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView); // Setting the layout as linear // layout for vertical orientation LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext()); recyclerView.setLayoutManager(linearLayoutManager); // Sending reference and data to Adapter Adapter adapter = new Adapter(MainActivity.this, courseImg, courseName); // Setting Adapter to RecyclerView recyclerView.setAdapter(adapter); }}
android
Picked
Technical Scripter 2020
Android
Java
Technical Scripter
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Create and Add Data to SQLite Database in Android?
Broadcast Receiver in Android With Example
Resource Raw Folder in Android Studio
Services in Android with Example
Android RecyclerView in Kotlin
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples | [
{
"code": null,
"e": 26157,
"s": 26129,
"text": "\n21 Dec, 2020"
},
{
"code": null,
"e": 26666,
"s": 26157,
"text": "RecyclerView is more flexible and advanced version of ListView and GridView. RecyclerView is used for providing a limited window to a large data set, which means it is used to display a large amount of data that can be scrolled very efficiently by maintaining a limited number of Views. In RecyclerView we supply data and define how each item looks, and the RecyclerView library dynamically creates the content when it is needed. RecyclerView was introduced in Material Design in Android 5.0(API level 21.0)."
},
{
"code": null,
"e": 26828,
"s": 26666,
"text": "RecyclerView is a ViewGroup that contains Views corresponding to your data. It itself a View so, it is added to the layout file as any other UI element is added."
},
{
"code": null,
"e": 27047,
"s": 26828,
"text": "ViewHolder Object is used to define each individual element in the list. View holder does not contain anything when it created, RecyclerView binds data to it. ViewHolder is defined by extending RecyclerView.ViewHolder."
},
{
"code": null,
"e": 27252,
"s": 27047,
"text": "Adapters are used to bind data to the Views. RecyclerView request views, and binds the views to their data, by calling methods in the adapter. The adapter can be defined by extending RecyclerView.Adapter."
},
{
"code": null,
"e": 27393,
"s": 27252,
"text": "LayoutManager arranges the individual elements in the list. It contains the reference of all views that are filled by the data of the entry."
},
{
"code": null,
"e": 27476,
"s": 27393,
"text": "LayoutManager class of RecyclerView provide three types of built-in LayoutManagers"
},
{
"code": null,
"e": 27552,
"s": 27476,
"text": "LinearLayoutManager: It is used for displaying Horizontal and Vertical List"
},
{
"code": null,
"e": 27625,
"s": 27552,
"text": "GridLayoutManager: It is used for displaying items in the forms of grids"
},
{
"code": null,
"e": 27712,
"s": 27625,
"text": "StaggeredGridLayoutManager: It is used for displaying items in form of staggered grids"
},
{
"code": null,
"e": 27882,
"s": 27712,
"text": "In this example, we are going to use RecyclerView as ListView. Here, we are going to display the list of courses with their images as a vertical list using RecyclerView."
},
{
"code": null,
"e": 27911,
"s": 27882,
"text": "Step 1: Create A New Project"
},
{
"code": null,
"e": 28073,
"s": 27911,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language."
},
{
"code": null,
"e": 28096,
"s": 28073,
"text": "Step 2: Add Dependency"
},
{
"code": null,
"e": 28341,
"s": 28096,
"text": "We are going to use RecyclerView as ListView. So, we need to add the dependency for it. For adding the dependency Go to Gradle Scripts > build.gradle(Module: app) and add the following dependency. After adding the dependency click on Sync Now. "
},
{
"code": null,
"e": 28356,
"s": 28341,
"text": "dependencies {"
},
{
"code": null,
"e": 28416,
"s": 28356,
"text": " implementation “androidx.recyclerview:recyclerview:1.1.0”"
},
{
"code": null,
"e": 28418,
"s": 28416,
"text": "}"
},
{
"code": null,
"e": 28585,
"s": 28418,
"text": "Before moving further let’s add some color attributes in order to enhance the app bar. Go to app > res > values > colors.xml and add the following color attributes. "
},
{
"code": null,
"e": 28589,
"s": 28585,
"text": "XML"
},
{
"code": "<resources> <color name=\"colorPrimary\">#0F9D58</color> <color name=\"colorPrimaryDark\">#16E37F</color> <color name=\"colorAccent\">#03DAC5</color> </resources> ",
"e": 28759,
"s": 28589,
"text": null
},
{
"code": null,
"e": 28807,
"s": 28759,
"text": "Step 3: Working with the activity_main.xml file"
},
{
"code": null,
"e": 29003,
"s": 28807,
"text": "In this step, we will add a RecyclerView to our activity_main.xml file which is used to display data of listItems. Go to the app > res > layout > activity_main.xml and the following code snippet."
},
{
"code": null,
"e": 29007,
"s": 29003,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!--RecyclerView--> <androidx.recyclerview.widget.RecyclerView android:id=\"@+id/recyclerView\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\"/> </LinearLayout>",
"e": 29554,
"s": 29007,
"text": null
},
{
"code": null,
"e": 29601,
"s": 29554,
"text": "Step 4: Create a new layout file list_item.xml"
},
{
"code": null,
"e": 29871,
"s": 29601,
"text": "In this step, we will create a new layout file for the single list item view. Go to app > res > layout > right-click > New > Layout Resource File and name it as list_item. list_item.xml contains an ImageView and a TextView which is used for populating the RecyclerView."
},
{
"code": null,
"e": 29875,
"s": 29871,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"horizontal\" > <!--For image src we have used ic_launcher and for text \"courseName\" they are used only for reference how it will looks\"--> <ImageView android:id=\"@+id/courseImg\" android:layout_width=\"72dp\" android:layout_height=\"72dp\" android:padding=\"8dp\" android:src=\"@mipmap/ic_launcher_round\" /> <LinearLayout android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:orientation=\"vertical\" android:layout_gravity=\"center\"> <TextView android:id=\"@+id/courseName\" android:text=\"courseName\" android:textStyle=\"bold\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\"/> </LinearLayout> </LinearLayout>",
"e": 30896,
"s": 29875,
"text": null
},
{
"code": null,
"e": 30931,
"s": 30896,
"text": "Step 5: Create a new Adapter class"
},
{
"code": null,
"e": 31223,
"s": 30931,
"text": "Now, we will create an Adapter class that acts as a bridge between the UI Component and the Data Source .i.e., courseImg, courseName, and RecyclerView. Go to the app > java > package > right-click and create a new java class and name it as Adapter. Below is the code snippet is given for it."
},
{
"code": null,
"e": 31228,
"s": 31223,
"text": "Java"
},
{
"code": "import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView;import android.widget.TextView; import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView;import java.util.ArrayList; // Extends the Adapter class to RecyclerView.Adapter// and implement the unimplemented methodspublic class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> { ArrayList courseImg, courseName; Context context; // Constructor for initialization public Adapter(Context context, ArrayList courseImg, ArrayList courseName) { this.context = context; this.courseImg = courseImg; this.courseName = courseName; } @NonNull @Override public Adapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { // Inflating the Layout(Instantiates list_item.xml // layout file into View object) View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false); // Passing view to ViewHolder Adapter.ViewHolder viewHolder = new Adapter.ViewHolder(view); return viewHolder; } // Binding data to the into specified position @Override public void onBindViewHolder(@NonNull Adapter.ViewHolder holder, int position) { // TypeCast Object to int type int res = (int) courseImg.get(position); holder.images.setImageResource(res); holder.text.setText((String) courseName.get(position)); } @Override public int getItemCount() { // Returns number of items // currently available in Adapter return courseImg.size(); } // Initializing the Views public class ViewHolder extends RecyclerView.ViewHolder { ImageView images; TextView text; public ViewHolder(View view) { super(view); images = (ImageView) view.findViewById(R.id.courseImg); text = (TextView) view.findViewById(R.id.courseName); } }}",
"e": 33295,
"s": 31228,
"text": null
},
{
"code": null,
"e": 33338,
"s": 33295,
"text": "Step 6: Working with the MainActivity file"
},
{
"code": null,
"e": 33725,
"s": 33338,
"text": "In MainActivity.java class we create two ArrayList for storing courseImg and courseName. These images are placed in the drawable folder(app > res > drawable). You can use any images in place of these. And then we get the reference RecyclerView and set the LayoutManager as LinearLayoutManager and Adapter, to show items in RecyclerView. Below is the code for the MainActivity.java file."
},
{
"code": null,
"e": 33730,
"s": 33725,
"text": "Java"
},
{
"code": "import android.os.Bundle;import androidx.appcompat.app.AppCompatActivity;import androidx.recyclerview.widget.LinearLayoutManager;import androidx.recyclerview.widget.RecyclerView;import androidx.recyclerview.widget.StaggeredGridLayoutManager;import java.util.ArrayList;import java.util.Arrays; public class MainActivity extends AppCompatActivity { RecyclerView recyclerView; // Using ArrayList to store images data ArrayList courseImg = new ArrayList<>(Arrays.asList(R.drawable.data_structure, R.drawable.c_plus_plus, R.drawable.c_hash, R.drawable.java_script, R.drawable.java, R.drawable.c, R.drawable.html, R.drawable.css)); ArrayList courseName = new ArrayList<>(Arrays.asList(\"Data Structure\", \"C++\", \"C#\", \"JavaScript\", \"Java\", \"C-Language\", \"HTML 5\", \"CSS\")); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Getting reference of recyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView); // Setting the layout as linear // layout for vertical orientation LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext()); recyclerView.setLayoutManager(linearLayoutManager); // Sending reference and data to Adapter Adapter adapter = new Adapter(MainActivity.this, courseImg, courseName); // Setting Adapter to RecyclerView recyclerView.setAdapter(adapter); }}",
"e": 35476,
"s": 33730,
"text": null
},
{
"code": null,
"e": 35484,
"s": 35476,
"text": "android"
},
{
"code": null,
"e": 35491,
"s": 35484,
"text": "Picked"
},
{
"code": null,
"e": 35515,
"s": 35491,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 35523,
"s": 35515,
"text": "Android"
},
{
"code": null,
"e": 35528,
"s": 35523,
"text": "Java"
},
{
"code": null,
"e": 35547,
"s": 35528,
"text": "Technical Scripter"
},
{
"code": null,
"e": 35552,
"s": 35547,
"text": "Java"
},
{
"code": null,
"e": 35560,
"s": 35552,
"text": "Android"
},
{
"code": null,
"e": 35658,
"s": 35560,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35716,
"s": 35658,
"text": "How to Create and Add Data to SQLite Database in Android?"
},
{
"code": null,
"e": 35759,
"s": 35716,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 35797,
"s": 35759,
"text": "Resource Raw Folder in Android Studio"
},
{
"code": null,
"e": 35830,
"s": 35797,
"text": "Services in Android with Example"
},
{
"code": null,
"e": 35861,
"s": 35830,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 35876,
"s": 35861,
"text": "Arrays in Java"
},
{
"code": null,
"e": 35920,
"s": 35876,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 35942,
"s": 35920,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 35993,
"s": 35942,
"text": "Object Oriented Programming (OOPs) Concept in Java"
}
] |
Passing Vector to a Function in C++ - GeeksforGeeks | 11 May, 2022
When we pass an array to a function, a pointer is actually passed.
However, to pass a vector there are two ways to do so:
Pass By valuePass By Reference
Pass By value
Pass By Reference
When a vector is passed to a function, a copy of the vector is created. This new copy of the vector is then used in the function and thus, any changes made to the vector in the function do not affect the original vector.
For example, we can see below the program, changes made inside the function are not reflected outside because the function has a copy.
Example(Pass By Value):
CPP
// C++ program to demonstrate that when vectors// are passed to functions without &, a copy is// created.#include <bits/stdc++.h>using namespace std; // The vect here is a copy of vect in main()void func(vector<int> vect) { vect.push_back(30); } int main(){ vector<int> vect; vect.push_back(10); vect.push_back(20); func(vect); // vect remains unchanged after function // call for (int i = 0; i < vect.size(); i++) cout << vect[i] << " "; return 0;}
10 20
Passing by value keeps the original vector unchanged and doesn’t modify the original values of the vector. However, the above style of passing might also take a lot of time in cases of large vectors. So, it is a good idea to pass by reference.
Example(Pass By Reference):
CPP
// C++ program to demonstrate how vectors// can be passed by reference.#include <bits/stdc++.h>using namespace std; // The vect is passed by reference and changes// made here reflect in main()void func(vector<int>& vect) { vect.push_back(30); } int main(){ vector<int> vect; vect.push_back(10); vect.push_back(20); func(vect); for (int i = 0; i < vect.size(); i++) cout << vect[i] << " "; return 0;}
10 20 30
Passing by reference saves a lot of time and makes the implementation of the code faster.
Note: If we do not want a function to modify a vector, we can pass it as a const reference also.
CPP
// C++ program to demonstrate how vectors // can be passed by reference with modifications // restricted. #include<bits/stdc++.h> using namespace std; // The vect is passed by constant reference // and cannot be changed by this function. void func(const vector<int> &vect) { // vect.push_back(30); // Uncommenting this line would // below error // "prog.cpp: In function 'void func(const std::vector<int>&)': // prog.cpp:9:18: error: passing 'const std::vector<int>' // as 'this' argument discards qualifiers [-fpermissive]" for (int i = 0; i < vect.size(); i++) cout << vect[i] << " "; } int main() { vector<int> vect; vect.push_back(10); vect.push_back(20); func(vect); return 0; }
10 20
This article is contributed by Kartik. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
anshikajain26
CPP-Functions
cpp-vector
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Friend class and function in C++
Sorting a vector in C++
std::string class in C++
Pair in C++ Standard Template Library (STL)
Inline Functions in C++
Array of Strings in C++ (5 Different Ways to Create)
Queue in C++ Standard Template Library (STL)
Convert string to char array in C++ | [
{
"code": null,
"e": 25367,
"s": 25339,
"text": "\n11 May, 2022"
},
{
"code": null,
"e": 25434,
"s": 25367,
"text": "When we pass an array to a function, a pointer is actually passed."
},
{
"code": null,
"e": 25489,
"s": 25434,
"text": "However, to pass a vector there are two ways to do so:"
},
{
"code": null,
"e": 25520,
"s": 25489,
"text": "Pass By valuePass By Reference"
},
{
"code": null,
"e": 25534,
"s": 25520,
"text": "Pass By value"
},
{
"code": null,
"e": 25552,
"s": 25534,
"text": "Pass By Reference"
},
{
"code": null,
"e": 25773,
"s": 25552,
"text": "When a vector is passed to a function, a copy of the vector is created. This new copy of the vector is then used in the function and thus, any changes made to the vector in the function do not affect the original vector."
},
{
"code": null,
"e": 25908,
"s": 25773,
"text": "For example, we can see below the program, changes made inside the function are not reflected outside because the function has a copy."
},
{
"code": null,
"e": 25932,
"s": 25908,
"text": "Example(Pass By Value):"
},
{
"code": null,
"e": 25936,
"s": 25932,
"text": "CPP"
},
{
"code": "// C++ program to demonstrate that when vectors// are passed to functions without &, a copy is// created.#include <bits/stdc++.h>using namespace std; // The vect here is a copy of vect in main()void func(vector<int> vect) { vect.push_back(30); } int main(){ vector<int> vect; vect.push_back(10); vect.push_back(20); func(vect); // vect remains unchanged after function // call for (int i = 0; i < vect.size(); i++) cout << vect[i] << \" \"; return 0;}",
"e": 26425,
"s": 25936,
"text": null
},
{
"code": null,
"e": 26432,
"s": 26425,
"text": "10 20 "
},
{
"code": null,
"e": 26676,
"s": 26432,
"text": "Passing by value keeps the original vector unchanged and doesn’t modify the original values of the vector. However, the above style of passing might also take a lot of time in cases of large vectors. So, it is a good idea to pass by reference."
},
{
"code": null,
"e": 26704,
"s": 26676,
"text": "Example(Pass By Reference):"
},
{
"code": null,
"e": 26708,
"s": 26704,
"text": "CPP"
},
{
"code": "// C++ program to demonstrate how vectors// can be passed by reference.#include <bits/stdc++.h>using namespace std; // The vect is passed by reference and changes// made here reflect in main()void func(vector<int>& vect) { vect.push_back(30); } int main(){ vector<int> vect; vect.push_back(10); vect.push_back(20); func(vect); for (int i = 0; i < vect.size(); i++) cout << vect[i] << \" \"; return 0;}",
"e": 27141,
"s": 26708,
"text": null
},
{
"code": null,
"e": 27151,
"s": 27141,
"text": "10 20 30 "
},
{
"code": null,
"e": 27241,
"s": 27151,
"text": "Passing by reference saves a lot of time and makes the implementation of the code faster."
},
{
"code": null,
"e": 27338,
"s": 27241,
"text": "Note: If we do not want a function to modify a vector, we can pass it as a const reference also."
},
{
"code": null,
"e": 27342,
"s": 27338,
"text": "CPP"
},
{
"code": "// C++ program to demonstrate how vectors // can be passed by reference with modifications // restricted. #include<bits/stdc++.h> using namespace std; // The vect is passed by constant reference // and cannot be changed by this function. void func(const vector<int> &vect) { // vect.push_back(30); // Uncommenting this line would // below error // \"prog.cpp: In function 'void func(const std::vector<int>&)': // prog.cpp:9:18: error: passing 'const std::vector<int>' // as 'this' argument discards qualifiers [-fpermissive]\" for (int i = 0; i < vect.size(); i++) cout << vect[i] << \" \"; } int main() { vector<int> vect; vect.push_back(10); vect.push_back(20); func(vect); return 0; }",
"e": 28118,
"s": 27342,
"text": null
},
{
"code": null,
"e": 28125,
"s": 28118,
"text": "10 20 "
},
{
"code": null,
"e": 28541,
"s": 28125,
"text": "This article is contributed by Kartik. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 28555,
"s": 28541,
"text": "anshikajain26"
},
{
"code": null,
"e": 28569,
"s": 28555,
"text": "CPP-Functions"
},
{
"code": null,
"e": 28580,
"s": 28569,
"text": "cpp-vector"
},
{
"code": null,
"e": 28584,
"s": 28580,
"text": "STL"
},
{
"code": null,
"e": 28588,
"s": 28584,
"text": "C++"
},
{
"code": null,
"e": 28592,
"s": 28588,
"text": "STL"
},
{
"code": null,
"e": 28596,
"s": 28592,
"text": "CPP"
},
{
"code": null,
"e": 28694,
"s": 28596,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28722,
"s": 28694,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 28742,
"s": 28722,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 28775,
"s": 28742,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 28799,
"s": 28775,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 28824,
"s": 28799,
"text": "std::string class in C++"
},
{
"code": null,
"e": 28868,
"s": 28824,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 28892,
"s": 28868,
"text": "Inline Functions in C++"
},
{
"code": null,
"e": 28945,
"s": 28892,
"text": "Array of Strings in C++ (5 Different Ways to Create)"
},
{
"code": null,
"e": 28990,
"s": 28945,
"text": "Queue in C++ Standard Template Library (STL)"
}
] |
PHP | str_shuffle() Function - GeeksforGeeks | 20 Aug, 2020
The str_shuffle() function is an inbuilt function in PHP and is used to randomly shuffle all the characters of a string passed to the function as a parameter. When a number is passed, it treats the number as the string and shuffles it. This function does not make any change in the original string or the number passed to it as a parameter. Instead, it returns a new string which is one of the possible permutations of the string passed to it in the parameter.
Syntax:
str_shuffle($string)
Parameter: This function accepts a single parameter $string. The parameter $string specifies the string whose characters are needed to be shuffled. In place of a string, a number can also be passed. If a number is passed instead of a string as a parameter then this function will treat that number as a string.
Return Value: The function returns a string of the same length but with shuffled characters within itself. Every time the program is executed, it displays a different output since shuffling of characters is different every time. The original string or the number can be the return value on some occasions.
Examples:
Input : $string = "raj"
Output : jar
Input : $string = "geeks"
Output : eeksg
Input : $string = 142
Output : 412
Note: The output will be different on every execution.
Below programs illustrate the str_shuffle() function:
Program 1: Program to demonstrate the str_shuffle() function when a string is passed.
<?php// PHP program to demonstrate the str_shuffle()// function when a string is passed$string = "geeks"; // prints the shuffled string echo str_shuffle($string);?>
Output:
keegs
Program 2: Program to demonstrate the str_shuffle() function when a number is passed.
<?php// PHP program to demonstrate the str_shuffle()// function when a number is passed$string = 142; // prints the shuffled string echo str_shuffle($string);?>
Output:
124
Reference:http://php.net/manual/en/function.str-shuffle.php
Akanksha_Rai
PHP-string
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to fetch data from localserver database and display on HTML table using PHP ?
How to create admin login page using PHP?
PHP str_replace() Function
How to pass form variables from one page to other page in PHP ?
Create a drop-down list that options fetched from a MySQL database in PHP
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 26217,
"s": 26189,
"text": "\n20 Aug, 2020"
},
{
"code": null,
"e": 26678,
"s": 26217,
"text": "The str_shuffle() function is an inbuilt function in PHP and is used to randomly shuffle all the characters of a string passed to the function as a parameter. When a number is passed, it treats the number as the string and shuffles it. This function does not make any change in the original string or the number passed to it as a parameter. Instead, it returns a new string which is one of the possible permutations of the string passed to it in the parameter."
},
{
"code": null,
"e": 26686,
"s": 26678,
"text": "Syntax:"
},
{
"code": null,
"e": 26708,
"s": 26686,
"text": "str_shuffle($string) "
},
{
"code": null,
"e": 27019,
"s": 26708,
"text": "Parameter: This function accepts a single parameter $string. The parameter $string specifies the string whose characters are needed to be shuffled. In place of a string, a number can also be passed. If a number is passed instead of a string as a parameter then this function will treat that number as a string."
},
{
"code": null,
"e": 27325,
"s": 27019,
"text": "Return Value: The function returns a string of the same length but with shuffled characters within itself. Every time the program is executed, it displays a different output since shuffling of characters is different every time. The original string or the number can be the return value on some occasions."
},
{
"code": null,
"e": 27335,
"s": 27325,
"text": "Examples:"
},
{
"code": null,
"e": 27514,
"s": 27335,
"text": "Input : $string = \"raj\" \nOutput : jar \n\nInput : $string = \"geeks\" \nOutput : eeksg \n\nInput : $string = 142 \nOutput : 412 \n\nNote: The output will be different on every execution. \n"
},
{
"code": null,
"e": 27568,
"s": 27514,
"text": "Below programs illustrate the str_shuffle() function:"
},
{
"code": null,
"e": 27654,
"s": 27568,
"text": "Program 1: Program to demonstrate the str_shuffle() function when a string is passed."
},
{
"code": "<?php// PHP program to demonstrate the str_shuffle()// function when a string is passed$string = \"geeks\"; // prints the shuffled string echo str_shuffle($string);?>",
"e": 27821,
"s": 27654,
"text": null
},
{
"code": null,
"e": 27829,
"s": 27821,
"text": "Output:"
},
{
"code": null,
"e": 27835,
"s": 27829,
"text": "keegs"
},
{
"code": null,
"e": 27921,
"s": 27835,
"text": "Program 2: Program to demonstrate the str_shuffle() function when a number is passed."
},
{
"code": "<?php// PHP program to demonstrate the str_shuffle()// function when a number is passed$string = 142; // prints the shuffled string echo str_shuffle($string);?>",
"e": 28084,
"s": 27921,
"text": null
},
{
"code": null,
"e": 28092,
"s": 28084,
"text": "Output:"
},
{
"code": null,
"e": 28096,
"s": 28092,
"text": "124"
},
{
"code": null,
"e": 28156,
"s": 28096,
"text": "Reference:http://php.net/manual/en/function.str-shuffle.php"
},
{
"code": null,
"e": 28169,
"s": 28156,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 28180,
"s": 28169,
"text": "PHP-string"
},
{
"code": null,
"e": 28184,
"s": 28180,
"text": "PHP"
},
{
"code": null,
"e": 28201,
"s": 28184,
"text": "Web Technologies"
},
{
"code": null,
"e": 28205,
"s": 28201,
"text": "PHP"
},
{
"code": null,
"e": 28303,
"s": 28205,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28385,
"s": 28303,
"text": "How to fetch data from localserver database and display on HTML table using PHP ?"
},
{
"code": null,
"e": 28427,
"s": 28385,
"text": "How to create admin login page using PHP?"
},
{
"code": null,
"e": 28454,
"s": 28427,
"text": "PHP str_replace() Function"
},
{
"code": null,
"e": 28518,
"s": 28454,
"text": "How to pass form variables from one page to other page in PHP ?"
},
{
"code": null,
"e": 28592,
"s": 28518,
"text": "Create a drop-down list that options fetched from a MySQL database in PHP"
},
{
"code": null,
"e": 28632,
"s": 28592,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28665,
"s": 28632,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28710,
"s": 28665,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28772,
"s": 28710,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
Python | Pandas dataframe.filter() - GeeksforGeeks | 19 Nov, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas dataframe.filter() function is used to Subset rows or columns of dataframe according to labels in the specified index. Note that this routine does not filter a dataframe on its contents. The filter is applied to the labels of the index.
Syntax: DataFrame.filter(items=None, like=None, regex=None, axis=None)
Parameters:items : List of info axis to restrict to (must not all be present)like : Keep info axis where “arg in col == True”regex : Keep info axis with re.search(regex, col) == Trueaxis : The axis to filter on. By default this is the info axis, ‘index’ for Series, ‘columns’ for DataFrame
Returns : same type as input object
The items, like, and regex parameters are enforced to be mutually exclusive. axis defaults to the info axis that is used when indexing with [].
For the link to CSV file click here
Example #1: Use filter() function to filter out any three columns of the dataframe.
# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.read_csv("nba.csv") # Print the dataframedf
Now filter the “Name”, “College” and “Salary” columns.
# applying filter function df.filter(["Name", "College", "Salary"])
Output :
Example #2: Use filter() function to subset all columns in a dataframe which has the letter ‘a’ or ‘A’ in its name.
Note : filter() function also takes a regular expression as one of its parameter.
# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.read_csv("nba.csv") # Using regular expression to extract all# columns which has letter 'a' or 'A' in its name.df.filter(regex ='[aA]')
Output :
The regular expression ‘[aA]’ looks for all column names which has an ‘a’ or an ‘A’ in its name.
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Convert integer to string in Python
sum() function in Python | [
{
"code": null,
"e": 26137,
"s": 26109,
"text": "\n19 Nov, 2018"
},
{
"code": null,
"e": 26351,
"s": 26137,
"text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier."
},
{
"code": null,
"e": 26595,
"s": 26351,
"text": "Pandas dataframe.filter() function is used to Subset rows or columns of dataframe according to labels in the specified index. Note that this routine does not filter a dataframe on its contents. The filter is applied to the labels of the index."
},
{
"code": null,
"e": 26666,
"s": 26595,
"text": "Syntax: DataFrame.filter(items=None, like=None, regex=None, axis=None)"
},
{
"code": null,
"e": 26956,
"s": 26666,
"text": "Parameters:items : List of info axis to restrict to (must not all be present)like : Keep info axis where “arg in col == True”regex : Keep info axis with re.search(regex, col) == Trueaxis : The axis to filter on. By default this is the info axis, ‘index’ for Series, ‘columns’ for DataFrame"
},
{
"code": null,
"e": 26992,
"s": 26956,
"text": "Returns : same type as input object"
},
{
"code": null,
"e": 27136,
"s": 26992,
"text": "The items, like, and regex parameters are enforced to be mutually exclusive. axis defaults to the info axis that is used when indexing with []."
},
{
"code": null,
"e": 27172,
"s": 27136,
"text": "For the link to CSV file click here"
},
{
"code": null,
"e": 27256,
"s": 27172,
"text": "Example #1: Use filter() function to filter out any three columns of the dataframe."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.read_csv(\"nba.csv\") # Print the dataframedf",
"e": 27379,
"s": 27256,
"text": null
},
{
"code": null,
"e": 27434,
"s": 27379,
"text": "Now filter the “Name”, “College” and “Salary” columns."
},
{
"code": "# applying filter function df.filter([\"Name\", \"College\", \"Salary\"])",
"e": 27502,
"s": 27434,
"text": null
},
{
"code": null,
"e": 27511,
"s": 27502,
"text": "Output :"
},
{
"code": null,
"e": 27628,
"s": 27511,
"text": " Example #2: Use filter() function to subset all columns in a dataframe which has the letter ‘a’ or ‘A’ in its name."
},
{
"code": null,
"e": 27710,
"s": 27628,
"text": "Note : filter() function also takes a regular expression as one of its parameter."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.read_csv(\"nba.csv\") # Using regular expression to extract all# columns which has letter 'a' or 'A' in its name.df.filter(regex ='[aA]')",
"e": 27925,
"s": 27710,
"text": null
},
{
"code": null,
"e": 27934,
"s": 27925,
"text": "Output :"
},
{
"code": null,
"e": 28031,
"s": 27934,
"text": "The regular expression ‘[aA]’ looks for all column names which has an ‘a’ or an ‘A’ in its name."
},
{
"code": null,
"e": 28055,
"s": 28031,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 28087,
"s": 28055,
"text": "Python pandas-dataFrame-methods"
},
{
"code": null,
"e": 28101,
"s": 28087,
"text": "Python-pandas"
},
{
"code": null,
"e": 28108,
"s": 28101,
"text": "Python"
},
{
"code": null,
"e": 28206,
"s": 28108,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28224,
"s": 28206,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28256,
"s": 28224,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28278,
"s": 28256,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28320,
"s": 28278,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28349,
"s": 28320,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 28386,
"s": 28349,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 28428,
"s": 28386,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28470,
"s": 28428,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28506,
"s": 28470,
"text": "Convert integer to string in Python"
}
] |
Replace all ‘0’ with ‘5’ in an input Integer - GeeksforGeeks | 23 Jan, 2022
Given an integer as input and replace all the ‘0’ with ‘5’ in the integer.
Examples:
Input: 102
Output: 152
Explanation: All the digits which are '0' is replaced by '5'
Input: 1020
Output: 1525
Explanation: All the digits which are '0' is replaced by '5'
Use of array to store all digits is not allowed.
Iterative Approach-1: By observing the test cases it is evident that all the 0 digits are replaced by 5. For Example, for input = 1020, output = 1525. The idea is simple, we assign a variable ‘temp’ to 0, we get the last digit using mod operator ‘%’. If the digit is 0, we replace it with 5, otherwise, keep it as it is. Then we multiply the ‘temp’ with 10 and add the digit got by mod operation. After that, we divide the original number by 10 to get the other digits. In this way, we will have a number in which all the ‘0’s are assigned with ‘5’s. If we reverse this number, we will get the desired answer.
Algorithm:
if the number is 0, directly return 5.else do the steps below.Create a variable temp= 0 to store the reversed number having all ‘0’s assigned to ‘5’s.Find the last digit using mod operator ‘%’. If the digit is ‘0’, then make the last digit as ‘5’.Multiply temp with 10 and add the last digit.Divide the number by 10 to get more digits by mod operation.Then reverse this number using the below approach.https://www.geeksforgeeks.org/write-a-program-to-reverse-digits-of-a-number/return the reversed number.
if the number is 0, directly return 5.
else do the steps below.
Create a variable temp= 0 to store the reversed number having all ‘0’s assigned to ‘5’s.
Find the last digit using mod operator ‘%’. If the digit is ‘0’, then make the last digit as ‘5’.
Multiply temp with 10 and add the last digit.
Divide the number by 10 to get more digits by mod operation.
Then reverse this number using the below approach.
https://www.geeksforgeeks.org/write-a-program-to-reverse-digits-of-a-number/
return the reversed number.
C++
Java
Python3
C#
Javascript
// C++ program to replace all ‘0’// with ‘5’ in an input Integer#include <iostream>using namespace std; // A iterative function to reverse a numberint reverseTheNumber(int temp){ int ans = 0; while (temp > 0) { int rem = temp % 10; ans = ans * 10 + rem; temp = temp / 10; } return ans;} int convert0To5(int num){ // if num is 0 return 5 if (num == 0) return 5; // Extract the last digit and // change it if needed else { int temp = 0; while (num > 0) { int digit = num % 10; //if digit is 0, make it 5 if (digit == 0) digit = 5; temp = temp * 10 + digit; num = num / 10; } // call the function reverseTheNumber by passing // temp return reverseTheNumber(temp); }} // Driver codeint main(){ int num = 10120; cout << convert0To5(num); return 0;} // This code is contributed by Vrashank Rao M.
// Java program for the above approachimport java.io.*; class GFG { // A iterative function to reverse a numberstatic int reverseTheNumber(int temp){ int ans = 0; while (temp > 0) { int rem = temp % 10; ans = ans * 10 + rem; temp = temp / 10; } return ans;} static int convert0To5(int num){ // if num is 0 return 5 if (num == 0) return 5; // Extract the last digit and // change it if needed else { int temp = 0; while (num > 0) { int digit = num % 10; //if digit is 0, make it 5 if (digit == 0) digit = 5; temp = temp * 10 + digit; num = num / 10; } // call the function reverseTheNumber by passing // temp return reverseTheNumber(temp); }} // Driver program public static void main(String args[]) { int num = 10120; System.out.println(convert0To5(num)); }} // This code is contributed by sanjoy_62.
# Python program for the above approach # A iterative function to reverse a numberdef reverseTheNumber(temp): ans = 0; while (temp > 0): rem = temp % 10; ans = ans * 10 + rem; temp = temp // 10; return ans; def convert0To5(num): # if num is 0 return 5 if (num == 0): return 5; # Extract the last digit and # change it if needed else: temp = 0; while (num > 0): digit = num % 10; # if digit is 0, make it 5 if (digit == 0): digit = 5; temp = temp * 10 + digit; num = num // 10; # call the function reverseTheNumber by passing # temp return reverseTheNumber(temp); # Driver programif __name__ == '__main__': num = 10120; print(convert0To5(num)); # This code is contributed by umadevi9616
// C# program for the above approachusing System;public class GFG { // A iterative function to reverse a numberstatic int reverseTheNumber(int temp){ int ans = 0; while (temp > 0) { int rem = temp % 10; ans = ans * 10 + rem; temp = temp / 10; } return ans;} static int convert0To5(int num){ // if num is 0 return 5 if (num == 0) return 5; // Extract the last digit and // change it if needed else { int temp = 0; while (num > 0) { int digit = num % 10; //if digit is 0, make it 5 if (digit == 0) digit = 5; temp = temp * 10 + digit; num = num / 10; } // call the function reverseTheNumber by passing // temp return reverseTheNumber(temp); }} // Driver Code public static void Main (string[] args) { int num = 10120; Console.Write(convert0To5(num)); }} // This code is contributed by splevel62.
<script>// javascript program for the above approach // A iterative function to reverse a number function reverseTheNumber(temp) { var ans = 0; while (temp > 0) { var rem = temp % 10; ans = ans * 10 + rem; temp = parseInt(temp / 10); } return ans; } function convert0To5(num) { // if num is 0 return 5 if (num == 0) return 5; // Extract the last digit and // change it if needed else { var temp = 0; while (num > 0) { var digit = num % 10; // if digit is 0, make it 5 if (digit == 0) digit = 5; temp = temp * 10 + digit; num = parseInt(num / 10); } // call the function reverseTheNumber by passing // temp return reverseTheNumber(temp); } } // Driver program var num = 10120; document.write(convert0To5(num)); // This code is contributed by umadevi9616</script>
15125
Complexity Analysis:
Time Complexity: O(2n), where n is number of digits in the number which takes O(n) to make 0s int 5s in the number, an extra O(n) to reverse the number
Space Complexity: O(1), no extra space is required.
Iterative Approach-2: By observing the test cases it is evident that all the 0 digits are replaced by 5. For Example, for input = 1020, output = 1525, which can be written as 1020 + 505, which can be further written as 1020 + 5*(10^2) + 5*(10^0). So the solution can be formed in an iterative way where if a ‘0’ digit is encountered find the place value of that digit and multiply it with 5 and find the sum for all 0’s in the number. Add that sum to the input number to find the output number.
Algorithm:
Create a variable sum = 0 to store the sum, place = 1 to store the place value of the current digit, and create a copy of the input variableIf the number is zero return 5Iterate the next step while the input variable is greater than 0Extract the last digit (n%10) and if the digit is zero, then update sum = sum + place*5, remove the last digit from the number n = n/10 and update place = place * 10Return the sum.
Create a variable sum = 0 to store the sum, place = 1 to store the place value of the current digit, and create a copy of the input variable
If the number is zero return 5
Iterate the next step while the input variable is greater than 0
Extract the last digit (n%10) and if the digit is zero, then update sum = sum + place*5, remove the last digit from the number n = n/10 and update place = place * 10
Return the sum.
C++
Java
Python3
C#
Javascript
#include<bits/stdc++.h>using namespace std; // Returns the number to be added to the// input to replace all zeroes with fiveint calculateAddedValue(int number){ // Amount to be added int result = 0; // Unit decimal place int decimalPlace = 1; if (number == 0) { result += (5 * decimalPlace); } while (number > 0) { if (number % 10 == 0) { // A number divisible by 10, then // this is a zero occurrence in // the input result += (5 * decimalPlace); } // Move one decimal place number /= 10; decimalPlace *= 10; } return result;} int replace0with5(int number){ return number += calculateAddedValue(number);} // Driver codeint main(){ cout << replace0with5(1020);} // This code is contributed by avanitrachhadiya2155
public class ReplaceDigits { static int replace0with5(int number) { return number += calculateAddedValue(number); } // returns the number to be added to the // input to replace all zeroes with five private static int calculateAddedValue(int number) { // amount to be added int result = 0; // unit decimal place int decimalPlace = 1; if (number == 0) { result += (5 * decimalPlace); } while (number > 0) { if (number % 10 == 0) // a number divisible by 10, then // this is a zero occurrence in the input result += (5 * decimalPlace); // move one decimal place number /= 10; decimalPlace *= 10; } return result; } public static void main(String[] args) { System.out.print(replace0with5(1020)); }}
def replace0with5(number): number += calculateAddedValue(number) return number # returns the number to be added to the# input to replace all zeroes with fivedef calculateAddedValue(number): # amount to be added result = 0 # unit decimal place decimalPlace = 1 if (number == 0): result += (5 * decimalPlace) while (number > 0): if (number % 10 == 0): # a number divisible by 10, then # this is a zero occurrence in the input result += (5 * decimalPlace) # move one decimal place number //= 10 decimalPlace *= 10 return result # Driver codeprint(replace0with5(1020)) # This code is contributed by shubhmasingh10
using System; class GFG{ static int replace0with5(int number){ return number += calculateAddedValue(number);} // Returns the number to be added to the// input to replace all zeroes with fivestatic int calculateAddedValue(int number){ // Amount to be added int result = 0; // Unit decimal place int decimalPlace = 1; if (number == 0) { result += (5 * decimalPlace); } while (number > 0) { if (number % 10 == 0) // A number divisible by 10, then // this is a zero occurrence in the input result += (5 * decimalPlace); // Move one decimal place number /= 10; decimalPlace *= 10; } return result;} // Driver Codestatic public void Main(){ Console.WriteLine(replace0with5(1020));}} // This code is contributed by rag2127
<script> // Returns the number to be added to the// input to replace all zeroes with fivefunction calculateAddedValue(number){ // Amount to be added let result = 0; // Unit decimal place let decimalPlace = 1; if (number == 0) { result += (5 * decimalPlace); } while (number > 0){ if (number % 10 == 0){ // A number divisible by 10, then // this is a zero occurrence in // the input result += (5 * decimalPlace); } // Move one decimal place number = Math.floor(number/10); decimalPlace *= 10; } return result;} function replace0with5(number){ return number += calculateAddedValue(number);} // Driver codedocument.write(replace0with5(1020)); </script>
Output:
1525
Complexity Analysis:
Time Complexity: O(k), the loops run only k times, where k is the number of digits of the number.
Space Complexity: O(1), no extra space is required.
Recursive Approach: The idea is simple, we get the last digit using mod operator ‘%’. If the digit is 0, we replace it with 5, otherwise, keep it as it is. Then we recur for the remaining digits. The approach remains the same, the basic difference is the loop is replaced by a recursive function.
Algorithm:
Check a base case when the number is 0 return 5, for all other cases form a recursive function.The function (solve(int n))can be defined as follows, if the number passed is 0 then return 0, else extract the last digit i.e. n = n/10 and remove the last digit. If the last digit is zero the assign 5 to it.Now return the value by calling the recursive function for n, i.e return solve(n)*10 + digit.Print the answer.
Check a base case when the number is 0 return 5, for all other cases form a recursive function.
The function (solve(int n))can be defined as follows, if the number passed is 0 then return 0, else extract the last digit i.e. n = n/10 and remove the last digit. If the last digit is zero the assign 5 to it.
Now return the value by calling the recursive function for n, i.e return solve(n)*10 + digit.
Print the answer.
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to replace all ‘0’// with ‘5’ in an input Integer#include <bits/stdc++.h>using namespace std; // A recursive function to replace all 0s// with 5s in an input number It doesn't// work if input number itself is 0.int convert0To5Rec(int num){ // Base case for recursion termination if (num == 0) return 0; // Extract the last digit and // change it if needed int digit = num % 10; if (digit == 0) digit = 5; // Convert remaining digits and // append the last digit return convert0To5Rec(num / 10) * 10 + digit;} // It handles 0 and calls convert0To5Rec()// for other numbersint convert0To5(int num){ if (num == 0) return 5; else return convert0To5Rec(num);} // Driver codeint main(){ int num = 10120; cout << convert0To5(num); return 0;} // This code is contributed by Code_Mech.
// C program to replace all ‘0’// with ‘5’ in an input Integer#include <stdio.h> // A recursive function to replace// all 0s with 5s in an input number// It doesn't work if input number itself is 0.int convert0To5Rec(int num){ // Base case for recursion termination if (num == 0) return 0; // Extract the last digit and change it if needed int digit = num % 10; if (digit == 0) digit = 5; // Convert remaining digits // and append the last digit return convert0To5Rec(num / 10) * 10 + digit;} // It handles 0 and calls// convert0To5Rec() for other numbersint convert0To5(int num){ if (num == 0) return 5; else return convert0To5Rec(num);} // Driver program to test above functionint main(){ int num = 10120; printf("%d", convert0To5(num)); return 0;}
// Java code for Replace all 0 with// 5 in an input Integerclass GFG { // A recursive function to replace all 0s with 5s in // an input number. It doesn't work if input number // itself is 0. static int convert0To5Rec(int num) { // Base case if (num == 0) return 0; // Extract the last digit and change it if needed int digit = num % 10; if (digit == 0) digit = 5; // Convert remaining digits and append the // last digit return convert0To5Rec(num / 10) * 10 + digit; } // It handles 0 and calls convert0To5Rec() for // other numbers static int convert0To5(int num) { if (num == 0) return 5; else return convert0To5Rec(num); } // Driver function public static void main(String[] args) { System.out.println(convert0To5(10120)); }} // This code is contributed by Kamal Rawal
# Python program to replace all# 0 with 5 in given integer # A recursive function to replace all 0s# with 5s in an integer# Does'nt work if the given number is 0 itselfdef convert0to5rec(num): # Base case for recursion termination if num == 0: return 0 # Extract the last digit and change it if needed digit = num % 10 if digit == 0: digit = 5 # Convert remaining digits and append the last digit return convert0to5rec(num // 10) * 10 + digit # It handles 0 to 5 calls convert0to5rec()# for other numbersdef convert0to5(num): if num == 0: return 5 else: return convert0to5rec(num) # Driver Programnum = 10120print (convert0to5(num)) # Contributed by Harshit Agrawal
// C# code for Replace all 0// with 5 in an input Integerusing System; class GFG { // A recursive function to replace // all 0s with 5s in an input number. // It doesn't work if input number // itself is 0. static int convert0To5Rec(int num) { // Base case if (num == 0) return 0; // Extract the last digit and // change it if needed int digit = num % 10; if (digit == 0) digit = 5; // Convert remaining digits // and append the last digit return convert0To5Rec(num / 10) * 10 + digit; } // It handles 0 and calls // convert0To5Rec() for other numbers static int convert0To5(int num) { if (num == 0) return 5; else return convert0To5Rec(num); } // Driver Code static public void Main() { Console.Write(convert0To5(10120)); }} // This code is contributed by Raj
<?php// PHP program to replace all 0 with 5// in given integer // A recursive function to replace all 0s// with 5s in an integer. Does'nt work if// the given number is 0 itselffunction convert0to5rec($num){ // Base case for recursion termination if ($num == 0) return 0; // Extract the last digit and // change it if needed $digit = ($num % 10); if ($digit == 0) $digit = 5; // Convert remaining digits and append // the last digit return convert0to5rec((int)($num / 10)) * 10 + $digit;} // It handles 0 to 5 calls convert0to5rec()// for other numbersfunction convert0to5($num){ if ($num == 0) return 5; else return convert0to5rec($num);} // Driver Code$num = 10120;print(convert0to5($num)); // This code is contributed by mits?>
<script>// javascript code for Replace all 0 with// 5 in an input Integer // A recursive function to replace all 0s with 5s in // an input number. It doesn't work if input number // itself is 0. function convert0To5Rec(num) { // Base case if (num == 0) return 0; // Extract the last digit and change it if needed var digit = num % 10; if (digit == 0) digit = 5; // Convert remaining digits and append the // last digit return convert0To5Rec(parseInt(num / 10)) * 10 + digit; } // It handles 0 and calls convert0To5Rec() for // other numbers function convert0To5(num) { if (num == 0) return 5; else return convert0To5Rec(num); } // Driver function document.write(convert0To5(10120)); // This code contributed by gauravrajput1</script>
15125
Output:
15125
Complexity Analysis:
Time Complexity: O(k), the recursive function is called only k times, where k is the number of digits of the number
Space Complexity: O(1), no extra space is required.
This article is contributed by Sai Kiran. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
R_Raj
Mithun Kumar
Code_Mech
carolinemarkoc
andrew1234
SHUBHAMSINGH10
avanitrachhadiya2155
rag2127
rohitsingh07052
GauravRajput1
simmytarika5
vrashankrao
splevel62
sanjoy_62
avtarkumar719
umadevi9616
amartyaghoshgfg
sumitgumber28
simranarora5sos
Amazon
number-digits
Arrays
Mathematical
Amazon
Arrays
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Linked List vs Array
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": 26285,
"s": 26257,
"text": "\n23 Jan, 2022"
},
{
"code": null,
"e": 26361,
"s": 26285,
"text": "Given an integer as input and replace all the ‘0’ with ‘5’ in the integer. "
},
{
"code": null,
"e": 26372,
"s": 26361,
"text": "Examples: "
},
{
"code": null,
"e": 26546,
"s": 26372,
"text": "Input: 102 \nOutput: 152\nExplanation: All the digits which are '0' is replaced by '5' \n\nInput: 1020 \nOutput: 1525\nExplanation: All the digits which are '0' is replaced by '5'"
},
{
"code": null,
"e": 26595,
"s": 26546,
"text": "Use of array to store all digits is not allowed."
},
{
"code": null,
"e": 27205,
"s": 26595,
"text": "Iterative Approach-1: By observing the test cases it is evident that all the 0 digits are replaced by 5. For Example, for input = 1020, output = 1525. The idea is simple, we assign a variable ‘temp’ to 0, we get the last digit using mod operator ‘%’. If the digit is 0, we replace it with 5, otherwise, keep it as it is. Then we multiply the ‘temp’ with 10 and add the digit got by mod operation. After that, we divide the original number by 10 to get the other digits. In this way, we will have a number in which all the ‘0’s are assigned with ‘5’s. If we reverse this number, we will get the desired answer."
},
{
"code": null,
"e": 27216,
"s": 27205,
"text": "Algorithm:"
},
{
"code": null,
"e": 27722,
"s": 27216,
"text": "if the number is 0, directly return 5.else do the steps below.Create a variable temp= 0 to store the reversed number having all ‘0’s assigned to ‘5’s.Find the last digit using mod operator ‘%’. If the digit is ‘0’, then make the last digit as ‘5’.Multiply temp with 10 and add the last digit.Divide the number by 10 to get more digits by mod operation.Then reverse this number using the below approach.https://www.geeksforgeeks.org/write-a-program-to-reverse-digits-of-a-number/return the reversed number."
},
{
"code": null,
"e": 27761,
"s": 27722,
"text": "if the number is 0, directly return 5."
},
{
"code": null,
"e": 27786,
"s": 27761,
"text": "else do the steps below."
},
{
"code": null,
"e": 27875,
"s": 27786,
"text": "Create a variable temp= 0 to store the reversed number having all ‘0’s assigned to ‘5’s."
},
{
"code": null,
"e": 27973,
"s": 27875,
"text": "Find the last digit using mod operator ‘%’. If the digit is ‘0’, then make the last digit as ‘5’."
},
{
"code": null,
"e": 28019,
"s": 27973,
"text": "Multiply temp with 10 and add the last digit."
},
{
"code": null,
"e": 28080,
"s": 28019,
"text": "Divide the number by 10 to get more digits by mod operation."
},
{
"code": null,
"e": 28131,
"s": 28080,
"text": "Then reverse this number using the below approach."
},
{
"code": null,
"e": 28208,
"s": 28131,
"text": "https://www.geeksforgeeks.org/write-a-program-to-reverse-digits-of-a-number/"
},
{
"code": null,
"e": 28236,
"s": 28208,
"text": "return the reversed number."
},
{
"code": null,
"e": 28240,
"s": 28236,
"text": "C++"
},
{
"code": null,
"e": 28245,
"s": 28240,
"text": "Java"
},
{
"code": null,
"e": 28253,
"s": 28245,
"text": "Python3"
},
{
"code": null,
"e": 28256,
"s": 28253,
"text": "C#"
},
{
"code": null,
"e": 28267,
"s": 28256,
"text": "Javascript"
},
{
"code": "// C++ program to replace all ‘0’// with ‘5’ in an input Integer#include <iostream>using namespace std; // A iterative function to reverse a numberint reverseTheNumber(int temp){ int ans = 0; while (temp > 0) { int rem = temp % 10; ans = ans * 10 + rem; temp = temp / 10; } return ans;} int convert0To5(int num){ // if num is 0 return 5 if (num == 0) return 5; // Extract the last digit and // change it if needed else { int temp = 0; while (num > 0) { int digit = num % 10; //if digit is 0, make it 5 if (digit == 0) digit = 5; temp = temp * 10 + digit; num = num / 10; } // call the function reverseTheNumber by passing // temp return reverseTheNumber(temp); }} // Driver codeint main(){ int num = 10120; cout << convert0To5(num); return 0;} // This code is contributed by Vrashank Rao M.",
"e": 29240,
"s": 28267,
"text": null
},
{
"code": "// Java program for the above approachimport java.io.*; class GFG { // A iterative function to reverse a numberstatic int reverseTheNumber(int temp){ int ans = 0; while (temp > 0) { int rem = temp % 10; ans = ans * 10 + rem; temp = temp / 10; } return ans;} static int convert0To5(int num){ // if num is 0 return 5 if (num == 0) return 5; // Extract the last digit and // change it if needed else { int temp = 0; while (num > 0) { int digit = num % 10; //if digit is 0, make it 5 if (digit == 0) digit = 5; temp = temp * 10 + digit; num = num / 10; } // call the function reverseTheNumber by passing // temp return reverseTheNumber(temp); }} // Driver program public static void main(String args[]) { int num = 10120; System.out.println(convert0To5(num)); }} // This code is contributed by sanjoy_62.",
"e": 30259,
"s": 29240,
"text": null
},
{
"code": "# Python program for the above approach # A iterative function to reverse a numberdef reverseTheNumber(temp): ans = 0; while (temp > 0): rem = temp % 10; ans = ans * 10 + rem; temp = temp // 10; return ans; def convert0To5(num): # if num is 0 return 5 if (num == 0): return 5; # Extract the last digit and # change it if needed else: temp = 0; while (num > 0): digit = num % 10; # if digit is 0, make it 5 if (digit == 0): digit = 5; temp = temp * 10 + digit; num = num // 10; # call the function reverseTheNumber by passing # temp return reverseTheNumber(temp); # Driver programif __name__ == '__main__': num = 10120; print(convert0To5(num)); # This code is contributed by umadevi9616",
"e": 31126,
"s": 30259,
"text": null
},
{
"code": "// C# program for the above approachusing System;public class GFG { // A iterative function to reverse a numberstatic int reverseTheNumber(int temp){ int ans = 0; while (temp > 0) { int rem = temp % 10; ans = ans * 10 + rem; temp = temp / 10; } return ans;} static int convert0To5(int num){ // if num is 0 return 5 if (num == 0) return 5; // Extract the last digit and // change it if needed else { int temp = 0; while (num > 0) { int digit = num % 10; //if digit is 0, make it 5 if (digit == 0) digit = 5; temp = temp * 10 + digit; num = num / 10; } // call the function reverseTheNumber by passing // temp return reverseTheNumber(temp); }} // Driver Code public static void Main (string[] args) { int num = 10120; Console.Write(convert0To5(num)); }} // This code is contributed by splevel62.",
"e": 32125,
"s": 31126,
"text": null
},
{
"code": "<script>// javascript program for the above approach // A iterative function to reverse a number function reverseTheNumber(temp) { var ans = 0; while (temp > 0) { var rem = temp % 10; ans = ans * 10 + rem; temp = parseInt(temp / 10); } return ans; } function convert0To5(num) { // if num is 0 return 5 if (num == 0) return 5; // Extract the last digit and // change it if needed else { var temp = 0; while (num > 0) { var digit = num % 10; // if digit is 0, make it 5 if (digit == 0) digit = 5; temp = temp * 10 + digit; num = parseInt(num / 10); } // call the function reverseTheNumber by passing // temp return reverseTheNumber(temp); } } // Driver program var num = 10120; document.write(convert0To5(num)); // This code is contributed by umadevi9616</script>",
"e": 33209,
"s": 32125,
"text": null
},
{
"code": null,
"e": 33218,
"s": 33212,
"text": "15125"
},
{
"code": null,
"e": 33241,
"s": 33220,
"text": "Complexity Analysis:"
},
{
"code": null,
"e": 33395,
"s": 33243,
"text": "Time Complexity: O(2n), where n is number of digits in the number which takes O(n) to make 0s int 5s in the number, an extra O(n) to reverse the number"
},
{
"code": null,
"e": 33447,
"s": 33395,
"text": "Space Complexity: O(1), no extra space is required."
},
{
"code": null,
"e": 33944,
"s": 33449,
"text": "Iterative Approach-2: By observing the test cases it is evident that all the 0 digits are replaced by 5. For Example, for input = 1020, output = 1525, which can be written as 1020 + 505, which can be further written as 1020 + 5*(10^2) + 5*(10^0). So the solution can be formed in an iterative way where if a ‘0’ digit is encountered find the place value of that digit and multiply it with 5 and find the sum for all 0’s in the number. Add that sum to the input number to find the output number."
},
{
"code": null,
"e": 33958,
"s": 33946,
"text": "Algorithm: "
},
{
"code": null,
"e": 34375,
"s": 33960,
"text": "Create a variable sum = 0 to store the sum, place = 1 to store the place value of the current digit, and create a copy of the input variableIf the number is zero return 5Iterate the next step while the input variable is greater than 0Extract the last digit (n%10) and if the digit is zero, then update sum = sum + place*5, remove the last digit from the number n = n/10 and update place = place * 10Return the sum."
},
{
"code": null,
"e": 34516,
"s": 34375,
"text": "Create a variable sum = 0 to store the sum, place = 1 to store the place value of the current digit, and create a copy of the input variable"
},
{
"code": null,
"e": 34547,
"s": 34516,
"text": "If the number is zero return 5"
},
{
"code": null,
"e": 34612,
"s": 34547,
"text": "Iterate the next step while the input variable is greater than 0"
},
{
"code": null,
"e": 34778,
"s": 34612,
"text": "Extract the last digit (n%10) and if the digit is zero, then update sum = sum + place*5, remove the last digit from the number n = n/10 and update place = place * 10"
},
{
"code": null,
"e": 34794,
"s": 34778,
"text": "Return the sum."
},
{
"code": null,
"e": 34800,
"s": 34796,
"text": "C++"
},
{
"code": null,
"e": 34805,
"s": 34800,
"text": "Java"
},
{
"code": null,
"e": 34813,
"s": 34805,
"text": "Python3"
},
{
"code": null,
"e": 34816,
"s": 34813,
"text": "C#"
},
{
"code": null,
"e": 34827,
"s": 34816,
"text": "Javascript"
},
{
"code": "#include<bits/stdc++.h>using namespace std; // Returns the number to be added to the// input to replace all zeroes with fiveint calculateAddedValue(int number){ // Amount to be added int result = 0; // Unit decimal place int decimalPlace = 1; if (number == 0) { result += (5 * decimalPlace); } while (number > 0) { if (number % 10 == 0) { // A number divisible by 10, then // this is a zero occurrence in // the input result += (5 * decimalPlace); } // Move one decimal place number /= 10; decimalPlace *= 10; } return result;} int replace0with5(int number){ return number += calculateAddedValue(number);} // Driver codeint main(){ cout << replace0with5(1020);} // This code is contributed by avanitrachhadiya2155",
"e": 35708,
"s": 34827,
"text": null
},
{
"code": "public class ReplaceDigits { static int replace0with5(int number) { return number += calculateAddedValue(number); } // returns the number to be added to the // input to replace all zeroes with five private static int calculateAddedValue(int number) { // amount to be added int result = 0; // unit decimal place int decimalPlace = 1; if (number == 0) { result += (5 * decimalPlace); } while (number > 0) { if (number % 10 == 0) // a number divisible by 10, then // this is a zero occurrence in the input result += (5 * decimalPlace); // move one decimal place number /= 10; decimalPlace *= 10; } return result; } public static void main(String[] args) { System.out.print(replace0with5(1020)); }}",
"e": 36620,
"s": 35708,
"text": null
},
{
"code": "def replace0with5(number): number += calculateAddedValue(number) return number # returns the number to be added to the# input to replace all zeroes with fivedef calculateAddedValue(number): # amount to be added result = 0 # unit decimal place decimalPlace = 1 if (number == 0): result += (5 * decimalPlace) while (number > 0): if (number % 10 == 0): # a number divisible by 10, then # this is a zero occurrence in the input result += (5 * decimalPlace) # move one decimal place number //= 10 decimalPlace *= 10 return result # Driver codeprint(replace0with5(1020)) # This code is contributed by shubhmasingh10",
"e": 37388,
"s": 36620,
"text": null
},
{
"code": "using System; class GFG{ static int replace0with5(int number){ return number += calculateAddedValue(number);} // Returns the number to be added to the// input to replace all zeroes with fivestatic int calculateAddedValue(int number){ // Amount to be added int result = 0; // Unit decimal place int decimalPlace = 1; if (number == 0) { result += (5 * decimalPlace); } while (number > 0) { if (number % 10 == 0) // A number divisible by 10, then // this is a zero occurrence in the input result += (5 * decimalPlace); // Move one decimal place number /= 10; decimalPlace *= 10; } return result;} // Driver Codestatic public void Main(){ Console.WriteLine(replace0with5(1020));}} // This code is contributed by rag2127",
"e": 38233,
"s": 37388,
"text": null
},
{
"code": "<script> // Returns the number to be added to the// input to replace all zeroes with fivefunction calculateAddedValue(number){ // Amount to be added let result = 0; // Unit decimal place let decimalPlace = 1; if (number == 0) { result += (5 * decimalPlace); } while (number > 0){ if (number % 10 == 0){ // A number divisible by 10, then // this is a zero occurrence in // the input result += (5 * decimalPlace); } // Move one decimal place number = Math.floor(number/10); decimalPlace *= 10; } return result;} function replace0with5(number){ return number += calculateAddedValue(number);} // Driver codedocument.write(replace0with5(1020)); </script>",
"e": 39005,
"s": 38233,
"text": null
},
{
"code": null,
"e": 39014,
"s": 39005,
"text": "Output: "
},
{
"code": null,
"e": 39019,
"s": 39014,
"text": "1525"
},
{
"code": null,
"e": 39040,
"s": 39019,
"text": "Complexity Analysis:"
},
{
"code": null,
"e": 39138,
"s": 39040,
"text": "Time Complexity: O(k), the loops run only k times, where k is the number of digits of the number."
},
{
"code": null,
"e": 39190,
"s": 39138,
"text": "Space Complexity: O(1), no extra space is required."
},
{
"code": null,
"e": 39487,
"s": 39190,
"text": "Recursive Approach: The idea is simple, we get the last digit using mod operator ‘%’. If the digit is 0, we replace it with 5, otherwise, keep it as it is. Then we recur for the remaining digits. The approach remains the same, the basic difference is the loop is replaced by a recursive function."
},
{
"code": null,
"e": 39499,
"s": 39487,
"text": "Algorithm: "
},
{
"code": null,
"e": 39914,
"s": 39499,
"text": "Check a base case when the number is 0 return 5, for all other cases form a recursive function.The function (solve(int n))can be defined as follows, if the number passed is 0 then return 0, else extract the last digit i.e. n = n/10 and remove the last digit. If the last digit is zero the assign 5 to it.Now return the value by calling the recursive function for n, i.e return solve(n)*10 + digit.Print the answer."
},
{
"code": null,
"e": 40010,
"s": 39914,
"text": "Check a base case when the number is 0 return 5, for all other cases form a recursive function."
},
{
"code": null,
"e": 40220,
"s": 40010,
"text": "The function (solve(int n))can be defined as follows, if the number passed is 0 then return 0, else extract the last digit i.e. n = n/10 and remove the last digit. If the last digit is zero the assign 5 to it."
},
{
"code": null,
"e": 40314,
"s": 40220,
"text": "Now return the value by calling the recursive function for n, i.e return solve(n)*10 + digit."
},
{
"code": null,
"e": 40332,
"s": 40314,
"text": "Print the answer."
},
{
"code": null,
"e": 40336,
"s": 40332,
"text": "C++"
},
{
"code": null,
"e": 40338,
"s": 40336,
"text": "C"
},
{
"code": null,
"e": 40343,
"s": 40338,
"text": "Java"
},
{
"code": null,
"e": 40351,
"s": 40343,
"text": "Python3"
},
{
"code": null,
"e": 40354,
"s": 40351,
"text": "C#"
},
{
"code": null,
"e": 40358,
"s": 40354,
"text": "PHP"
},
{
"code": null,
"e": 40369,
"s": 40358,
"text": "Javascript"
},
{
"code": "// C++ program to replace all ‘0’// with ‘5’ in an input Integer#include <bits/stdc++.h>using namespace std; // A recursive function to replace all 0s// with 5s in an input number It doesn't// work if input number itself is 0.int convert0To5Rec(int num){ // Base case for recursion termination if (num == 0) return 0; // Extract the last digit and // change it if needed int digit = num % 10; if (digit == 0) digit = 5; // Convert remaining digits and // append the last digit return convert0To5Rec(num / 10) * 10 + digit;} // It handles 0 and calls convert0To5Rec()// for other numbersint convert0To5(int num){ if (num == 0) return 5; else return convert0To5Rec(num);} // Driver codeint main(){ int num = 10120; cout << convert0To5(num); return 0;} // This code is contributed by Code_Mech.",
"e": 41233,
"s": 40369,
"text": null
},
{
"code": "// C program to replace all ‘0’// with ‘5’ in an input Integer#include <stdio.h> // A recursive function to replace// all 0s with 5s in an input number// It doesn't work if input number itself is 0.int convert0To5Rec(int num){ // Base case for recursion termination if (num == 0) return 0; // Extract the last digit and change it if needed int digit = num % 10; if (digit == 0) digit = 5; // Convert remaining digits // and append the last digit return convert0To5Rec(num / 10) * 10 + digit;} // It handles 0 and calls// convert0To5Rec() for other numbersint convert0To5(int num){ if (num == 0) return 5; else return convert0To5Rec(num);} // Driver program to test above functionint main(){ int num = 10120; printf(\"%d\", convert0To5(num)); return 0;}",
"e": 42053,
"s": 41233,
"text": null
},
{
"code": "// Java code for Replace all 0 with// 5 in an input Integerclass GFG { // A recursive function to replace all 0s with 5s in // an input number. It doesn't work if input number // itself is 0. static int convert0To5Rec(int num) { // Base case if (num == 0) return 0; // Extract the last digit and change it if needed int digit = num % 10; if (digit == 0) digit = 5; // Convert remaining digits and append the // last digit return convert0To5Rec(num / 10) * 10 + digit; } // It handles 0 and calls convert0To5Rec() for // other numbers static int convert0To5(int num) { if (num == 0) return 5; else return convert0To5Rec(num); } // Driver function public static void main(String[] args) { System.out.println(convert0To5(10120)); }} // This code is contributed by Kamal Rawal",
"e": 42997,
"s": 42053,
"text": null
},
{
"code": "# Python program to replace all# 0 with 5 in given integer # A recursive function to replace all 0s# with 5s in an integer# Does'nt work if the given number is 0 itselfdef convert0to5rec(num): # Base case for recursion termination if num == 0: return 0 # Extract the last digit and change it if needed digit = num % 10 if digit == 0: digit = 5 # Convert remaining digits and append the last digit return convert0to5rec(num // 10) * 10 + digit # It handles 0 to 5 calls convert0to5rec()# for other numbersdef convert0to5(num): if num == 0: return 5 else: return convert0to5rec(num) # Driver Programnum = 10120print (convert0to5(num)) # Contributed by Harshit Agrawal",
"e": 43723,
"s": 42997,
"text": null
},
{
"code": "// C# code for Replace all 0// with 5 in an input Integerusing System; class GFG { // A recursive function to replace // all 0s with 5s in an input number. // It doesn't work if input number // itself is 0. static int convert0To5Rec(int num) { // Base case if (num == 0) return 0; // Extract the last digit and // change it if needed int digit = num % 10; if (digit == 0) digit = 5; // Convert remaining digits // and append the last digit return convert0To5Rec(num / 10) * 10 + digit; } // It handles 0 and calls // convert0To5Rec() for other numbers static int convert0To5(int num) { if (num == 0) return 5; else return convert0To5Rec(num); } // Driver Code static public void Main() { Console.Write(convert0To5(10120)); }} // This code is contributed by Raj",
"e": 44665,
"s": 43723,
"text": null
},
{
"code": "<?php// PHP program to replace all 0 with 5// in given integer // A recursive function to replace all 0s// with 5s in an integer. Does'nt work if// the given number is 0 itselffunction convert0to5rec($num){ // Base case for recursion termination if ($num == 0) return 0; // Extract the last digit and // change it if needed $digit = ($num % 10); if ($digit == 0) $digit = 5; // Convert remaining digits and append // the last digit return convert0to5rec((int)($num / 10)) * 10 + $digit;} // It handles 0 to 5 calls convert0to5rec()// for other numbersfunction convert0to5($num){ if ($num == 0) return 5; else return convert0to5rec($num);} // Driver Code$num = 10120;print(convert0to5($num)); // This code is contributed by mits?>",
"e": 45491,
"s": 44665,
"text": null
},
{
"code": "<script>// javascript code for Replace all 0 with// 5 in an input Integer // A recursive function to replace all 0s with 5s in // an input number. It doesn't work if input number // itself is 0. function convert0To5Rec(num) { // Base case if (num == 0) return 0; // Extract the last digit and change it if needed var digit = num % 10; if (digit == 0) digit = 5; // Convert remaining digits and append the // last digit return convert0To5Rec(parseInt(num / 10)) * 10 + digit; } // It handles 0 and calls convert0To5Rec() for // other numbers function convert0To5(num) { if (num == 0) return 5; else return convert0To5Rec(num); } // Driver function document.write(convert0To5(10120)); // This code contributed by gauravrajput1</script>",
"e": 46384,
"s": 45491,
"text": null
},
{
"code": null,
"e": 46390,
"s": 46384,
"text": "15125"
},
{
"code": null,
"e": 46398,
"s": 46390,
"text": "Output:"
},
{
"code": null,
"e": 46404,
"s": 46398,
"text": "15125"
},
{
"code": null,
"e": 46426,
"s": 46404,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 46542,
"s": 46426,
"text": "Time Complexity: O(k), the recursive function is called only k times, where k is the number of digits of the number"
},
{
"code": null,
"e": 46594,
"s": 46542,
"text": "Space Complexity: O(1), no extra space is required."
},
{
"code": null,
"e": 46762,
"s": 46594,
"text": "This article is contributed by Sai Kiran. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 46768,
"s": 46762,
"text": "R_Raj"
},
{
"code": null,
"e": 46781,
"s": 46768,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 46791,
"s": 46781,
"text": "Code_Mech"
},
{
"code": null,
"e": 46806,
"s": 46791,
"text": "carolinemarkoc"
},
{
"code": null,
"e": 46817,
"s": 46806,
"text": "andrew1234"
},
{
"code": null,
"e": 46832,
"s": 46817,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 46853,
"s": 46832,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 46861,
"s": 46853,
"text": "rag2127"
},
{
"code": null,
"e": 46877,
"s": 46861,
"text": "rohitsingh07052"
},
{
"code": null,
"e": 46891,
"s": 46877,
"text": "GauravRajput1"
},
{
"code": null,
"e": 46904,
"s": 46891,
"text": "simmytarika5"
},
{
"code": null,
"e": 46916,
"s": 46904,
"text": "vrashankrao"
},
{
"code": null,
"e": 46926,
"s": 46916,
"text": "splevel62"
},
{
"code": null,
"e": 46936,
"s": 46926,
"text": "sanjoy_62"
},
{
"code": null,
"e": 46950,
"s": 46936,
"text": "avtarkumar719"
},
{
"code": null,
"e": 46962,
"s": 46950,
"text": "umadevi9616"
},
{
"code": null,
"e": 46978,
"s": 46962,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 46992,
"s": 46978,
"text": "sumitgumber28"
},
{
"code": null,
"e": 47008,
"s": 46992,
"text": "simranarora5sos"
},
{
"code": null,
"e": 47015,
"s": 47008,
"text": "Amazon"
},
{
"code": null,
"e": 47029,
"s": 47015,
"text": "number-digits"
},
{
"code": null,
"e": 47036,
"s": 47029,
"text": "Arrays"
},
{
"code": null,
"e": 47049,
"s": 47036,
"text": "Mathematical"
},
{
"code": null,
"e": 47056,
"s": 47049,
"text": "Amazon"
},
{
"code": null,
"e": 47063,
"s": 47056,
"text": "Arrays"
},
{
"code": null,
"e": 47076,
"s": 47063,
"text": "Mathematical"
},
{
"code": null,
"e": 47174,
"s": 47076,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 47242,
"s": 47174,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 47265,
"s": 47242,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 47297,
"s": 47265,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 47311,
"s": 47297,
"text": "Linear Search"
},
{
"code": null,
"e": 47332,
"s": 47311,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 47362,
"s": 47332,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 47422,
"s": 47362,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 47437,
"s": 47422,
"text": "C++ Data Types"
},
{
"code": null,
"e": 47480,
"s": 47437,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Pairs from an array that satisfy the given condition - GeeksforGeeks | 14 Apr, 2021
Given an array arr[], the task is to count all the valid pairs from the array. A pair (arr[i], arr[j]) is said to be valid if func( arr[i] ) + func( arr[j] ) = func( XOR(arr[i], arr[j]) ) where func(x) returns the number of set bits in x.
Examples:
Input: arr[] = {2, 3, 4, 5, 6} Output: 3 (2, 4), (2, 5) and (3, 4) are the only valid pairs.
Input: arr[] = {12, 13, 34, 25, 6} Output: 4
Approach: Iterating every possible pair and check whether the pair satisfies the given condition. If the condition is satisfied then update count = count + 1. Print the count in the end.
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the number// of set bits in nint setBits(int n){ int count = 0; while (n) { n = n & (n - 1); count++; } return count;} // Function to return the count of required pairsint countPairs(int a[], int n){ int count = 0; for (int i = 0; i < n - 1; i++) { // Set bits for first element of the pair int setbits_x = setBits(a[i]); for (int j = i + 1; j < n; j++) { // Set bits for second element of the pair int setbits_y = setBits(a[j]); // Set bits of the resultant number which is // the XOR of both the elements of the pair int setbits_xor_xy = setBits(a[i] ^ a[j]); // If the condition is satisfied if (setbits_x + setbits_y == setbits_xor_xy) // Increment the count count++; } } // Return the total count return count;} // Driver codeint main(){ int a[] = { 2, 3, 4, 5, 6 }; int n = sizeof(a) / sizeof(a[0]); cout << countPairs(a, n);}
// Java implementation of the approachimport java.io.*; class GFG{ // Function to return the number// of set bits in nstatic int setBits(int n){ int count = 0; while (n > 0) { n = n & (n - 1); count++; } return count;} // Function to return the count of// required pairsstatic int countPairs(int a[], int n){ int count = 0; for (int i = 0; i < n - 1; i++) { // Set bits for first element // of the pair int setbits_x = setBits(a[i]); for (int j = i + 1; j < n; j++) { // Set bits for second element // of the pair int setbits_y = setBits(a[j]); // Set bits of the resultant number which is // the XOR of both the elements of the pair int setbits_xor_xy = setBits(a[i] ^ a[j]); // If the condition is satisfied if (setbits_x + setbits_y == setbits_xor_xy) // Increment the count count++; } } // Return the total count return count;} // Driver code public static void main (String[] args) { int []a = { 2, 3, 4, 5, 6 }; int n = a.length; System.out.println(countPairs(a, n)); }} // This code is contributed by ajit.
# Python 3 implementation of the approach # Function to return the number# of set bits in ndef setBits(n): count = 0 while (n): n = n & (n - 1) count += 1 return count # Function to return the count# of required pairsdef countPairs(a, n): count = 0 for i in range(0, n - 1, 1): # Set bits for first element # of the pair setbits_x = setBits(a[i]) for j in range(i + 1, n, 1): # Set bits for second element # of the pair setbits_y = setBits(a[j]) # Set bits of the resultant number # which is the XOR of both the # elements of the pair setbits_xor_xy = setBits(a[i] ^ a[j]); # If the condition is satisfied if (setbits_x + setbits_y == setbits_xor_xy): # Increment the count count += 1 # Return the total count return count # Driver codeif __name__ == '__main__': a = [2, 3, 4, 5, 6] n = len(a) print(countPairs(a, n)) # This code is contributed by# Sanjit_Prasad
// C# implementation of the approachusing System;class GFG{ // Function to return the number// of set bits in nstatic int setBits(int n){ int count = 0; while (n > 0) { n = n & (n - 1); count++; } return count;} // Function to return the count of// required pairsstatic int countPairs(int []a, int n){ int count = 0; for (int i = 0; i < n - 1; i++) { // Set bits for first element // of the pair int setbits_x = setBits(a[i]); for (int j = i + 1; j < n; j++) { // Set bits for second element // of the pair int setbits_y = setBits(a[j]); // Set bits of the resultant number which is // the XOR of both the elements of the pair int setbits_xor_xy = setBits(a[i] ^ a[j]); // If the condition is satisfied if (setbits_x + setbits_y == setbits_xor_xy) // Increment the count count++; } } // Return the total count return count;} // Driver codepublic static void Main(){ int []a = { 2, 3, 4, 5, 6 }; int n = a.Length; Console.Write(countPairs(a, n));}} // This code is contributed// by Akanksha Rai
<?php// PHP implementation of the approach // Function to return the number// of set bits in nfunction setBits($n){ $count = 0; while ($n) { $n = $n & ($n - 1); $count++; } return $count;} // Function to return the count of// required pairsfunction countPairs(&$a, $n){ $count = 0; for ($i = 0; $i < $n - 1; $i++) { // Set bits for first element // of the pair $setbits_x = setBits($a[$i]); for ($j = $i + 1; $j < $n; $j++) { // Set bits for second element of the pair $setbits_y = setBits($a[$j]); // Set bits of the resultant number which is // the XOR of both the elements of the pair $setbits_xor_xy = setBits($a[$i] ^ $a[$j]); // If the condition is satisfied if ($setbits_x + $setbits_y == $setbits_xor_xy) // Increment the count $count++; } } // Return the total count return $count;} // Driver code$a = array(2, 3, 4, 5, 6 );$n = sizeof($a) / sizeof($a[0]);echo countPairs($a, $n); // This code is contributed by ita_c?>
<script> // Javascript implementation of the approach // Function to return the number// of set bits in nfunction setBits(n){ let count = 0; while (n > 0) { n = n & (n - 1); count++; } return count;} // Function to return the count of// required pairsfunction countPairs(a, n){ let count = 0; for(let i = 0; i < n - 1; i++) { // Set bits for first element // of the pair let setbits_x = setBits(a[i]); for(let j = i + 1; j < n; j++) { // Set bits for second element // of the pair let setbits_y = setBits(a[j]); // Set bits of the resultant number which is // the XOR of both the elements of the pair let setbits_xor_xy = setBits(a[i] ^ a[j]); // If the condition is satisfied if (setbits_x + setbits_y == setbits_xor_xy) // Increment the count count++; } } // Return the total count return count;} // Driver codelet a = [ 2, 3, 4, 5, 6 ];let n = a.length; document.write(countPairs(a, n)); // This code is contributed by unknown2108 </script>
3
Sanjit_Prasad
ukasp
Akanksha_Rai
jit_t
unknown2108
Bitwise-XOR
Algorithms
Arrays
Bit Magic
Mathematical
Arrays
Mathematical
Bit Magic
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
How to write a Pseudo Code?
Understanding Time Complexity with Simple Examples
Introduction to Algorithms
Arrays in Java
Arrays in C/C++
Maximum and minimum of an array using minimum number of comparisons
Write a program to reverse an array or string
Program for array rotation | [
{
"code": null,
"e": 26528,
"s": 26500,
"text": "\n14 Apr, 2021"
},
{
"code": null,
"e": 26767,
"s": 26528,
"text": "Given an array arr[], the task is to count all the valid pairs from the array. A pair (arr[i], arr[j]) is said to be valid if func( arr[i] ) + func( arr[j] ) = func( XOR(arr[i], arr[j]) ) where func(x) returns the number of set bits in x."
},
{
"code": null,
"e": 26778,
"s": 26767,
"text": "Examples: "
},
{
"code": null,
"e": 26871,
"s": 26778,
"text": "Input: arr[] = {2, 3, 4, 5, 6} Output: 3 (2, 4), (2, 5) and (3, 4) are the only valid pairs."
},
{
"code": null,
"e": 26918,
"s": 26871,
"text": "Input: arr[] = {12, 13, 34, 25, 6} Output: 4 "
},
{
"code": null,
"e": 27105,
"s": 26918,
"text": "Approach: Iterating every possible pair and check whether the pair satisfies the given condition. If the condition is satisfied then update count = count + 1. Print the count in the end."
},
{
"code": null,
"e": 27158,
"s": 27105,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27162,
"s": 27158,
"text": "C++"
},
{
"code": null,
"e": 27167,
"s": 27162,
"text": "Java"
},
{
"code": null,
"e": 27175,
"s": 27167,
"text": "Python3"
},
{
"code": null,
"e": 27178,
"s": 27175,
"text": "C#"
},
{
"code": null,
"e": 27182,
"s": 27178,
"text": "PHP"
},
{
"code": null,
"e": 27193,
"s": 27182,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the number// of set bits in nint setBits(int n){ int count = 0; while (n) { n = n & (n - 1); count++; } return count;} // Function to return the count of required pairsint countPairs(int a[], int n){ int count = 0; for (int i = 0; i < n - 1; i++) { // Set bits for first element of the pair int setbits_x = setBits(a[i]); for (int j = i + 1; j < n; j++) { // Set bits for second element of the pair int setbits_y = setBits(a[j]); // Set bits of the resultant number which is // the XOR of both the elements of the pair int setbits_xor_xy = setBits(a[i] ^ a[j]); // If the condition is satisfied if (setbits_x + setbits_y == setbits_xor_xy) // Increment the count count++; } } // Return the total count return count;} // Driver codeint main(){ int a[] = { 2, 3, 4, 5, 6 }; int n = sizeof(a) / sizeof(a[0]); cout << countPairs(a, n);}",
"e": 28326,
"s": 27193,
"text": null
},
{
"code": "// Java implementation of the approachimport java.io.*; class GFG{ // Function to return the number// of set bits in nstatic int setBits(int n){ int count = 0; while (n > 0) { n = n & (n - 1); count++; } return count;} // Function to return the count of// required pairsstatic int countPairs(int a[], int n){ int count = 0; for (int i = 0; i < n - 1; i++) { // Set bits for first element // of the pair int setbits_x = setBits(a[i]); for (int j = i + 1; j < n; j++) { // Set bits for second element // of the pair int setbits_y = setBits(a[j]); // Set bits of the resultant number which is // the XOR of both the elements of the pair int setbits_xor_xy = setBits(a[i] ^ a[j]); // If the condition is satisfied if (setbits_x + setbits_y == setbits_xor_xy) // Increment the count count++; } } // Return the total count return count;} // Driver code public static void main (String[] args) { int []a = { 2, 3, 4, 5, 6 }; int n = a.length; System.out.println(countPairs(a, n)); }} // This code is contributed by ajit.",
"e": 29595,
"s": 28326,
"text": null
},
{
"code": "# Python 3 implementation of the approach # Function to return the number# of set bits in ndef setBits(n): count = 0 while (n): n = n & (n - 1) count += 1 return count # Function to return the count# of required pairsdef countPairs(a, n): count = 0 for i in range(0, n - 1, 1): # Set bits for first element # of the pair setbits_x = setBits(a[i]) for j in range(i + 1, n, 1): # Set bits for second element # of the pair setbits_y = setBits(a[j]) # Set bits of the resultant number # which is the XOR of both the # elements of the pair setbits_xor_xy = setBits(a[i] ^ a[j]); # If the condition is satisfied if (setbits_x + setbits_y == setbits_xor_xy): # Increment the count count += 1 # Return the total count return count # Driver codeif __name__ == '__main__': a = [2, 3, 4, 5, 6] n = len(a) print(countPairs(a, n)) # This code is contributed by# Sanjit_Prasad",
"e": 30721,
"s": 29595,
"text": null
},
{
"code": "// C# implementation of the approachusing System;class GFG{ // Function to return the number// of set bits in nstatic int setBits(int n){ int count = 0; while (n > 0) { n = n & (n - 1); count++; } return count;} // Function to return the count of// required pairsstatic int countPairs(int []a, int n){ int count = 0; for (int i = 0; i < n - 1; i++) { // Set bits for first element // of the pair int setbits_x = setBits(a[i]); for (int j = i + 1; j < n; j++) { // Set bits for second element // of the pair int setbits_y = setBits(a[j]); // Set bits of the resultant number which is // the XOR of both the elements of the pair int setbits_xor_xy = setBits(a[i] ^ a[j]); // If the condition is satisfied if (setbits_x + setbits_y == setbits_xor_xy) // Increment the count count++; } } // Return the total count return count;} // Driver codepublic static void Main(){ int []a = { 2, 3, 4, 5, 6 }; int n = a.Length; Console.Write(countPairs(a, n));}} // This code is contributed// by Akanksha Rai",
"e": 31942,
"s": 30721,
"text": null
},
{
"code": "<?php// PHP implementation of the approach // Function to return the number// of set bits in nfunction setBits($n){ $count = 0; while ($n) { $n = $n & ($n - 1); $count++; } return $count;} // Function to return the count of// required pairsfunction countPairs(&$a, $n){ $count = 0; for ($i = 0; $i < $n - 1; $i++) { // Set bits for first element // of the pair $setbits_x = setBits($a[$i]); for ($j = $i + 1; $j < $n; $j++) { // Set bits for second element of the pair $setbits_y = setBits($a[$j]); // Set bits of the resultant number which is // the XOR of both the elements of the pair $setbits_xor_xy = setBits($a[$i] ^ $a[$j]); // If the condition is satisfied if ($setbits_x + $setbits_y == $setbits_xor_xy) // Increment the count $count++; } } // Return the total count return $count;} // Driver code$a = array(2, 3, 4, 5, 6 );$n = sizeof($a) / sizeof($a[0]);echo countPairs($a, $n); // This code is contributed by ita_c?>",
"e": 33091,
"s": 31942,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach // Function to return the number// of set bits in nfunction setBits(n){ let count = 0; while (n > 0) { n = n & (n - 1); count++; } return count;} // Function to return the count of// required pairsfunction countPairs(a, n){ let count = 0; for(let i = 0; i < n - 1; i++) { // Set bits for first element // of the pair let setbits_x = setBits(a[i]); for(let j = i + 1; j < n; j++) { // Set bits for second element // of the pair let setbits_y = setBits(a[j]); // Set bits of the resultant number which is // the XOR of both the elements of the pair let setbits_xor_xy = setBits(a[i] ^ a[j]); // If the condition is satisfied if (setbits_x + setbits_y == setbits_xor_xy) // Increment the count count++; } } // Return the total count return count;} // Driver codelet a = [ 2, 3, 4, 5, 6 ];let n = a.length; document.write(countPairs(a, n)); // This code is contributed by unknown2108 </script>",
"e": 34279,
"s": 33091,
"text": null
},
{
"code": null,
"e": 34281,
"s": 34279,
"text": "3"
},
{
"code": null,
"e": 34297,
"s": 34283,
"text": "Sanjit_Prasad"
},
{
"code": null,
"e": 34303,
"s": 34297,
"text": "ukasp"
},
{
"code": null,
"e": 34316,
"s": 34303,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 34322,
"s": 34316,
"text": "jit_t"
},
{
"code": null,
"e": 34334,
"s": 34322,
"text": "unknown2108"
},
{
"code": null,
"e": 34346,
"s": 34334,
"text": "Bitwise-XOR"
},
{
"code": null,
"e": 34357,
"s": 34346,
"text": "Algorithms"
},
{
"code": null,
"e": 34364,
"s": 34357,
"text": "Arrays"
},
{
"code": null,
"e": 34374,
"s": 34364,
"text": "Bit Magic"
},
{
"code": null,
"e": 34387,
"s": 34374,
"text": "Mathematical"
},
{
"code": null,
"e": 34394,
"s": 34387,
"text": "Arrays"
},
{
"code": null,
"e": 34407,
"s": 34394,
"text": "Mathematical"
},
{
"code": null,
"e": 34417,
"s": 34407,
"text": "Bit Magic"
},
{
"code": null,
"e": 34428,
"s": 34417,
"text": "Algorithms"
},
{
"code": null,
"e": 34526,
"s": 34428,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34575,
"s": 34526,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 34600,
"s": 34575,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 34628,
"s": 34600,
"text": "How to write a Pseudo Code?"
},
{
"code": null,
"e": 34679,
"s": 34628,
"text": "Understanding Time Complexity with Simple Examples"
},
{
"code": null,
"e": 34706,
"s": 34679,
"text": "Introduction to Algorithms"
},
{
"code": null,
"e": 34721,
"s": 34706,
"text": "Arrays in Java"
},
{
"code": null,
"e": 34737,
"s": 34721,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 34805,
"s": 34737,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 34851,
"s": 34805,
"text": "Write a program to reverse an array or string"
}
] |
Enumeration (or enum) in C - GeeksforGeeks | 20 Jul, 2021
Enumeration (or enum) is a user defined data type in C. It is mainly used to assign names to integral constants, the names make a program easy to read and maintain.
enum State {Working = 1, Failed = 0};
The keyword ‘enum’ is used to declare new enumeration types in C and C++. Following is an example of enum declaration.
// The name of enumeration is "flag" and the constant
// are the values of the flag. By default, the values
// of the constants are as follows:
// constant1 = 0, constant2 = 1, constant3 = 2 and
// so on.
enum flag{constant1, constant2, constant3, ....... };
Variables of type enum can also be defined. They can be defined in two ways:
// In both of the below cases, "day" is
// defined as the variable of type week.
enum week{Mon, Tue, Wed};
enum week day;
// Or
enum week{Mon, Tue, Wed}day;
// An example program to demonstrate working// of enum in C#include<stdio.h> enum week{Mon, Tue, Wed, Thur, Fri, Sat, Sun}; int main(){ enum week day; day = Wed; printf("%d",day); return 0;}
Output:
2
In the above example, we declared “day” as the variable and the value of “Wed” is allocated to day, which is 2. So as a result, 2 is printed.
Another example of enumeration is:
// Another example program to demonstrate working// of enum in C#include<stdio.h> enum year{Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec}; int main(){ int i; for (i=Jan; i<=Dec; i++) printf("%d ", i); return 0;}
Output:
0 1 2 3 4 5 6 7 8 9 10 11
In this example, the for loop will run from i = 0 to i = 11, as initially the value of i is Jan which is 0 and the value of Dec is 11.
Interesting facts about initialization of enum.1. Two enum names can have same value. For example, in the following C program both ‘Failed’ and ‘Freezed’ have same value 0.
#include <stdio.h>enum State {Working = 1, Failed = 0, Freezed = 0}; int main(){ printf("%d, %d, %d", Working, Failed, Freezed); return 0;}
Output:
1, 0, 0
2. If we do not explicitly assign values to enum names, the compiler by default assigns values starting from 0. For example, in the following C program, sunday gets value 0, monday gets 1, and so on.
#include <stdio.h>enum day {sunday, monday, tuesday, wednesday, thursday, friday, saturday}; int main(){ enum day d = thursday; printf("The day number stored in d is %d", d); return 0;}
Output:
The day number stored in d is 4
3. We can assign values to some name in any order. All unassigned names get value as value of previous name plus one.
#include <stdio.h>enum day {sunday = 1, monday, tuesday = 5, wednesday, thursday = 10, friday, saturday}; int main(){ printf("%d %d %d %d %d %d %d", sunday, monday, tuesday, wednesday, thursday, friday, saturday); return 0;}
Output:
1 2 5 6 10 11 12
4. The value assigned to enum names must be some integral constant, i.e., the value must be in range from minimum possible integer value to maximum possible integer value.
5. All enum constants must be unique in their scope. For example, the following program fails in compilation.
enum state {working, failed};enum result {failed, passed}; int main() { return 0; }
Output:
Compile Error: 'failed' has a previous declaration as 'state failed'
Exercise:Predict the output of following C programs
Program 1:
#include <stdio.h>enum day {sunday = 1, tuesday, wednesday, thursday, friday, saturday}; int main(){ enum day d = thursday; printf("The day number stored in d is %d", d); return 0;}
Program 2:
#include <stdio.h>enum State {WORKING = 0, FAILED, FREEZED};enum State currState = 2; enum State FindState() { return currState;} int main() { (FindState() == WORKING)? printf("WORKING"): printf("NOT WORKING"); return 0;}
Enum vs MacroWe can also use macros to define names constants. For example we can define ‘Working’ and ‘Failed’ using following macro.
#define Working 0#define Failed 1#define Freezed 2
There are multiple advantages of using enum over macro when many related named constants have integral values.a) Enums follow scope rules.b) Enum variables are automatically assigned values. Following is simpler
enum state {Working, Failed, Freezed};
Introduction part of this article is contributed by Piyush Vashistha. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
KartheekMudarakola
adnanirshad158
C Basics
C-Struct-Union-Enum
cpp-data-types
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
Function Pointer in C
Core Dump (Segmentation fault) in C/C++
Substring in C++
rand() and srand() in C/C++
fork() in C
std::string class in C++
Converting Strings to Numbers in C/C++
Command line arguments in C/C++ | [
{
"code": null,
"e": 25541,
"s": 25513,
"text": "\n20 Jul, 2021"
},
{
"code": null,
"e": 25706,
"s": 25541,
"text": "Enumeration (or enum) is a user defined data type in C. It is mainly used to assign names to integral constants, the names make a program easy to read and maintain."
},
{
"code": null,
"e": 25745,
"s": 25706,
"text": "enum State {Working = 1, Failed = 0}; "
},
{
"code": null,
"e": 25864,
"s": 25745,
"text": "The keyword ‘enum’ is used to declare new enumeration types in C and C++. Following is an example of enum declaration."
},
{
"code": null,
"e": 26125,
"s": 25864,
"text": "// The name of enumeration is \"flag\" and the constant\n// are the values of the flag. By default, the values\n// of the constants are as follows:\n// constant1 = 0, constant2 = 1, constant3 = 2 and \n// so on.\nenum flag{constant1, constant2, constant3, ....... };\n"
},
{
"code": null,
"e": 26202,
"s": 26125,
"text": "Variables of type enum can also be defined. They can be defined in two ways:"
},
{
"code": null,
"e": 26365,
"s": 26202,
"text": "// In both of the below cases, \"day\" is \n// defined as the variable of type week. \n\nenum week{Mon, Tue, Wed};\nenum week day;\n\n// Or\n\nenum week{Mon, Tue, Wed}day;\n"
},
{
"code": "// An example program to demonstrate working// of enum in C#include<stdio.h> enum week{Mon, Tue, Wed, Thur, Fri, Sat, Sun}; int main(){ enum week day; day = Wed; printf(\"%d\",day); return 0;} ",
"e": 26571,
"s": 26365,
"text": null
},
{
"code": null,
"e": 26579,
"s": 26571,
"text": "Output:"
},
{
"code": null,
"e": 26582,
"s": 26579,
"text": "2\n"
},
{
"code": null,
"e": 26724,
"s": 26582,
"text": "In the above example, we declared “day” as the variable and the value of “Wed” is allocated to day, which is 2. So as a result, 2 is printed."
},
{
"code": null,
"e": 26759,
"s": 26724,
"text": "Another example of enumeration is:"
},
{
"code": "// Another example program to demonstrate working// of enum in C#include<stdio.h> enum year{Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec}; int main(){ int i; for (i=Jan; i<=Dec; i++) printf(\"%d \", i); return 0;}",
"e": 27022,
"s": 26759,
"text": null
},
{
"code": null,
"e": 27030,
"s": 27022,
"text": "Output:"
},
{
"code": null,
"e": 27057,
"s": 27030,
"text": "0 1 2 3 4 5 6 7 8 9 10 11\n"
},
{
"code": null,
"e": 27192,
"s": 27057,
"text": "In this example, the for loop will run from i = 0 to i = 11, as initially the value of i is Jan which is 0 and the value of Dec is 11."
},
{
"code": null,
"e": 27368,
"s": 27195,
"text": "Interesting facts about initialization of enum.1. Two enum names can have same value. For example, in the following C program both ‘Failed’ and ‘Freezed’ have same value 0."
},
{
"code": "#include <stdio.h>enum State {Working = 1, Failed = 0, Freezed = 0}; int main(){ printf(\"%d, %d, %d\", Working, Failed, Freezed); return 0;}",
"e": 27513,
"s": 27368,
"text": null
},
{
"code": null,
"e": 27521,
"s": 27513,
"text": "Output:"
},
{
"code": null,
"e": 27529,
"s": 27521,
"text": "1, 0, 0"
},
{
"code": null,
"e": 27729,
"s": 27529,
"text": "2. If we do not explicitly assign values to enum names, the compiler by default assigns values starting from 0. For example, in the following C program, sunday gets value 0, monday gets 1, and so on."
},
{
"code": "#include <stdio.h>enum day {sunday, monday, tuesday, wednesday, thursday, friday, saturday}; int main(){ enum day d = thursday; printf(\"The day number stored in d is %d\", d); return 0;}",
"e": 27925,
"s": 27729,
"text": null
},
{
"code": null,
"e": 27933,
"s": 27925,
"text": "Output:"
},
{
"code": null,
"e": 27965,
"s": 27933,
"text": "The day number stored in d is 4"
},
{
"code": null,
"e": 28083,
"s": 27965,
"text": "3. We can assign values to some name in any order. All unassigned names get value as value of previous name plus one."
},
{
"code": "#include <stdio.h>enum day {sunday = 1, monday, tuesday = 5, wednesday, thursday = 10, friday, saturday}; int main(){ printf(\"%d %d %d %d %d %d %d\", sunday, monday, tuesday, wednesday, thursday, friday, saturday); return 0;}",
"e": 28335,
"s": 28083,
"text": null
},
{
"code": null,
"e": 28343,
"s": 28335,
"text": "Output:"
},
{
"code": null,
"e": 28360,
"s": 28343,
"text": "1 2 5 6 10 11 12"
},
{
"code": null,
"e": 28532,
"s": 28360,
"text": "4. The value assigned to enum names must be some integral constant, i.e., the value must be in range from minimum possible integer value to maximum possible integer value."
},
{
"code": null,
"e": 28642,
"s": 28532,
"text": "5. All enum constants must be unique in their scope. For example, the following program fails in compilation."
},
{
"code": "enum state {working, failed};enum result {failed, passed}; int main() { return 0; }",
"e": 28729,
"s": 28642,
"text": null
},
{
"code": null,
"e": 28737,
"s": 28729,
"text": "Output:"
},
{
"code": null,
"e": 28806,
"s": 28737,
"text": "Compile Error: 'failed' has a previous declaration as 'state failed'"
},
{
"code": null,
"e": 28858,
"s": 28806,
"text": "Exercise:Predict the output of following C programs"
},
{
"code": null,
"e": 28869,
"s": 28858,
"text": "Program 1:"
},
{
"code": "#include <stdio.h>enum day {sunday = 1, tuesday, wednesday, thursday, friday, saturday}; int main(){ enum day d = thursday; printf(\"The day number stored in d is %d\", d); return 0;}",
"e": 29061,
"s": 28869,
"text": null
},
{
"code": null,
"e": 29072,
"s": 29061,
"text": "Program 2:"
},
{
"code": "#include <stdio.h>enum State {WORKING = 0, FAILED, FREEZED};enum State currState = 2; enum State FindState() { return currState;} int main() { (FindState() == WORKING)? printf(\"WORKING\"): printf(\"NOT WORKING\"); return 0;}",
"e": 29303,
"s": 29072,
"text": null
},
{
"code": null,
"e": 29438,
"s": 29303,
"text": "Enum vs MacroWe can also use macros to define names constants. For example we can define ‘Working’ and ‘Failed’ using following macro."
},
{
"code": "#define Working 0#define Failed 1#define Freezed 2",
"e": 29489,
"s": 29438,
"text": null
},
{
"code": null,
"e": 29701,
"s": 29489,
"text": "There are multiple advantages of using enum over macro when many related named constants have integral values.a) Enums follow scope rules.b) Enum variables are automatically assigned values. Following is simpler"
},
{
"code": "enum state {Working, Failed, Freezed};",
"e": 29741,
"s": 29701,
"text": null
},
{
"code": null,
"e": 30062,
"s": 29741,
"text": "Introduction part of this article is contributed by Piyush Vashistha. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 30081,
"s": 30062,
"text": "KartheekMudarakola"
},
{
"code": null,
"e": 30096,
"s": 30081,
"text": "adnanirshad158"
},
{
"code": null,
"e": 30105,
"s": 30096,
"text": "C Basics"
},
{
"code": null,
"e": 30125,
"s": 30105,
"text": "C-Struct-Union-Enum"
},
{
"code": null,
"e": 30140,
"s": 30125,
"text": "cpp-data-types"
},
{
"code": null,
"e": 30151,
"s": 30140,
"text": "C Language"
},
{
"code": null,
"e": 30249,
"s": 30151,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30284,
"s": 30249,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 30330,
"s": 30284,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 30352,
"s": 30330,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 30392,
"s": 30352,
"text": "Core Dump (Segmentation fault) in C/C++"
},
{
"code": null,
"e": 30409,
"s": 30392,
"text": "Substring in C++"
},
{
"code": null,
"e": 30437,
"s": 30409,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 30449,
"s": 30437,
"text": "fork() in C"
},
{
"code": null,
"e": 30474,
"s": 30449,
"text": "std::string class in C++"
},
{
"code": null,
"e": 30513,
"s": 30474,
"text": "Converting Strings to Numbers in C/C++"
}
] |
Field equals() method in Java with Examples - GeeksforGeeks | 05 Nov, 2019
The equals() method of java.lang.reflect.Field is used to compare two field objects. This method compares two field objects and returns true if both objects are equal otherwise false. The two Field objects are considered equal if and only if when they were declared by the same class and have the same name and type. This method is very helpful at the time of debugging the object properties which are actually fields of a class in Java.
Syntax:
public boolean equals(Object obj)
Parameters: This method accepts one parameter obj which is the reference object to compare with this Field object.
Return value: This method returns true if both objects are equal otherwise false.
Below programs illustrate equals() method:Program 1:
// Java program to demonstrate the above method import java.lang.reflect.Field; public class GFG { public static void main(String[] args) throws NoSuchFieldException, SecurityException { // get the array of Field objects Field[] fields = User.class.getDeclaredFields(); Field fieldObj = User.class.getField("name"); // print element of field array // and compare it with fieldObj for (int i = 0; i < fields.length; i++) { // compare the fields with each other boolean isEquals = fields[i].equals(fieldObj); if (isEquals) { System.out.println( "Field -> [" + fields[i] + "] and" + " FieldObj -> [" + fieldObj + "] are equal."); } else { System.out.println( "Field -> [" + fields[i] + "] and" + " FieldObj -> [" + fieldObj + "] are not equal."); } } }} // User classclass User { public String name; public int age;}
Field -> [public java.lang.String User.name]andFieldObj -> [public java.lang.String User.name]are equal.
Field -> [public int User.age]andFieldObj -> [public java.lang.String User.name]are not equal.
Program 2:
// Java program to demonstrate the above method import java.lang.reflect.Field; public class GFG { public static void main(String[] args) throws NoSuchFieldException, SecurityException { // get the array of Field objects Field[] fields1 = Class.class.getDeclaredFields(); Field[] fields2 = Class.class.getDeclaredFields(); // print element of field array 1 and compare // it with fields array 2 for (int i = 0; i < fields1.length; i++) { for (int j = 0; j < fields2.length; j++) { // compare the fields with each other boolean isEquals = fields1[i].equals(fields2[j]); if (isEquals) { System.out.println( "Field -> [" + fields1[i] + "] and" + " FieldObj -> [" + fields2[j] + "] are equal."); } else { System.out.println( "Field -> [" + fields1[i] + "] and" + " FieldObj -> [" + fields2[j] + "] are not equal."); } } } }} // Object of Class which contains// noOfStudents and studentNamesclass Class { public int noOfStudents; public String[] studentNames;}
Field -> [public int Class.noOfStudents]andFieldObj -> [public int Class.noOfStudents]are equal.
Field -> [public int Class.noOfStudents]andFieldObj -> [public java.lang.String[] Class.studentNames]are not equal.
Field -> [public java.lang.String[] Class.studentNames]andFieldObj -> [public int Class.noOfStudents]are not equal.
Field -> [public java.lang.String[] Class.studentNames]andFieldObj -> [public java.lang.String[] Class.studentNames]are equal.
References: https://docs.oracle.com/javase/10/docs/api/java/lang/reflect/Field.html#equals(java.lang.Object)
shubham_singh
Java-Field
Java-Functions
java-lang-reflect-package
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": "\n05 Nov, 2019"
},
{
"code": null,
"e": 25663,
"s": 25225,
"text": "The equals() method of java.lang.reflect.Field is used to compare two field objects. This method compares two field objects and returns true if both objects are equal otherwise false. The two Field objects are considered equal if and only if when they were declared by the same class and have the same name and type. This method is very helpful at the time of debugging the object properties which are actually fields of a class in Java."
},
{
"code": null,
"e": 25671,
"s": 25663,
"text": "Syntax:"
},
{
"code": null,
"e": 25706,
"s": 25671,
"text": "public boolean equals(Object obj)\n"
},
{
"code": null,
"e": 25821,
"s": 25706,
"text": "Parameters: This method accepts one parameter obj which is the reference object to compare with this Field object."
},
{
"code": null,
"e": 25903,
"s": 25821,
"text": "Return value: This method returns true if both objects are equal otherwise false."
},
{
"code": null,
"e": 25956,
"s": 25903,
"text": "Below programs illustrate equals() method:Program 1:"
},
{
"code": "// Java program to demonstrate the above method import java.lang.reflect.Field; public class GFG { public static void main(String[] args) throws NoSuchFieldException, SecurityException { // get the array of Field objects Field[] fields = User.class.getDeclaredFields(); Field fieldObj = User.class.getField(\"name\"); // print element of field array // and compare it with fieldObj for (int i = 0; i < fields.length; i++) { // compare the fields with each other boolean isEquals = fields[i].equals(fieldObj); if (isEquals) { System.out.println( \"Field -> [\" + fields[i] + \"] and\" + \" FieldObj -> [\" + fieldObj + \"] are equal.\"); } else { System.out.println( \"Field -> [\" + fields[i] + \"] and\" + \" FieldObj -> [\" + fieldObj + \"] are not equal.\"); } } }} // User classclass User { public String name; public int age;}",
"e": 27191,
"s": 25956,
"text": null
},
{
"code": null,
"e": 27296,
"s": 27191,
"text": "Field -> [public java.lang.String User.name]andFieldObj -> [public java.lang.String User.name]are equal."
},
{
"code": null,
"e": 27391,
"s": 27296,
"text": "Field -> [public int User.age]andFieldObj -> [public java.lang.String User.name]are not equal."
},
{
"code": null,
"e": 27402,
"s": 27391,
"text": "Program 2:"
},
{
"code": "// Java program to demonstrate the above method import java.lang.reflect.Field; public class GFG { public static void main(String[] args) throws NoSuchFieldException, SecurityException { // get the array of Field objects Field[] fields1 = Class.class.getDeclaredFields(); Field[] fields2 = Class.class.getDeclaredFields(); // print element of field array 1 and compare // it with fields array 2 for (int i = 0; i < fields1.length; i++) { for (int j = 0; j < fields2.length; j++) { // compare the fields with each other boolean isEquals = fields1[i].equals(fields2[j]); if (isEquals) { System.out.println( \"Field -> [\" + fields1[i] + \"] and\" + \" FieldObj -> [\" + fields2[j] + \"] are equal.\"); } else { System.out.println( \"Field -> [\" + fields1[i] + \"] and\" + \" FieldObj -> [\" + fields2[j] + \"] are not equal.\"); } } } }} // Object of Class which contains// noOfStudents and studentNamesclass Class { public int noOfStudents; public String[] studentNames;}",
"e": 28879,
"s": 27402,
"text": null
},
{
"code": null,
"e": 28976,
"s": 28879,
"text": "Field -> [public int Class.noOfStudents]andFieldObj -> [public int Class.noOfStudents]are equal."
},
{
"code": null,
"e": 29092,
"s": 28976,
"text": "Field -> [public int Class.noOfStudents]andFieldObj -> [public java.lang.String[] Class.studentNames]are not equal."
},
{
"code": null,
"e": 29208,
"s": 29092,
"text": "Field -> [public java.lang.String[] Class.studentNames]andFieldObj -> [public int Class.noOfStudents]are not equal."
},
{
"code": null,
"e": 29335,
"s": 29208,
"text": "Field -> [public java.lang.String[] Class.studentNames]andFieldObj -> [public java.lang.String[] Class.studentNames]are equal."
},
{
"code": null,
"e": 29444,
"s": 29335,
"text": "References: https://docs.oracle.com/javase/10/docs/api/java/lang/reflect/Field.html#equals(java.lang.Object)"
},
{
"code": null,
"e": 29458,
"s": 29444,
"text": "shubham_singh"
},
{
"code": null,
"e": 29469,
"s": 29458,
"text": "Java-Field"
},
{
"code": null,
"e": 29484,
"s": 29469,
"text": "Java-Functions"
},
{
"code": null,
"e": 29510,
"s": 29484,
"text": "java-lang-reflect-package"
},
{
"code": null,
"e": 29515,
"s": 29510,
"text": "Java"
},
{
"code": null,
"e": 29520,
"s": 29515,
"text": "Java"
},
{
"code": null,
"e": 29618,
"s": 29520,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29633,
"s": 29618,
"text": "Stream In Java"
},
{
"code": null,
"e": 29654,
"s": 29633,
"text": "Constructors in Java"
},
{
"code": null,
"e": 29673,
"s": 29654,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 29703,
"s": 29673,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 29749,
"s": 29703,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 29766,
"s": 29749,
"text": "Generics in Java"
},
{
"code": null,
"e": 29787,
"s": 29766,
"text": "Introduction to Java"
},
{
"code": null,
"e": 29830,
"s": 29787,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 29866,
"s": 29830,
"text": "Internal Working of HashMap in Java"
}
] |
reflect.String() Function in Golang with Examples - GeeksforGeeks | 05 May, 2020
Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.String() Function in Golang is used to get the string v’s underlying value, as a string. To access this function, one needs to imports the reflect package in the program.
Syntax:
func (v Value) String() string
Parameters: This function does not accept any parameter.
Return Value: This function returns the string v’s underlying value, as a string.
Below examples illustrate the use of the above method in Golang:
Example 1:
// Golang program to illustrate// reflect.String() Function package main import ( "fmt" "reflect") // Main function func main() { var k = reflect.TypeOf(0) var e = reflect.TypeOf("") //use of String method fmt.Println(reflect.FuncOf([]reflect.Type{k}, []reflect.Type{e}, false).String())}
Output:
func(int) string
Example 2:
// Golang program to illustrate// reflect.String() Function package main import ( "fmt" "reflect") type Struct1 struct { Var1 string Var2 string Var3 float64 Var4 float64} // Main function func main() { NewMap := make(map[string]*Struct1) NewMap["abc"] = &Struct1{"abc", "def", 1.0, 2.0} subvalMetric := "Var1" for _, Value:= range NewMap { s := reflect.ValueOf(&Value).Elem() // use of String() method println(s.String()) println(s.Elem().String()) metric := s.Elem().FieldByName(subvalMetric).Interface() fmt.Println(metric) } }
Output:
<*main.Struct1 Value>
<main.Struct1 Value>
abc
Golang-reflect
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
strings.Replace() Function in Golang With Examples
6 Best Books to Learn Go Programming Language
Arrays in Go
fmt.Sprintf() Function in Golang With Examples
Golang Maps
Slices in Golang
Different Ways to Find the Type of Variable in Golang
Inheritance in GoLang
Interfaces in Golang
How to Trim a String in Golang? | [
{
"code": null,
"e": 25603,
"s": 25575,
"text": "\n05 May, 2020"
},
{
"code": null,
"e": 25961,
"s": 25603,
"text": "Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.String() Function in Golang is used to get the string v’s underlying value, as a string. To access this function, one needs to imports the reflect package in the program."
},
{
"code": null,
"e": 25969,
"s": 25961,
"text": "Syntax:"
},
{
"code": null,
"e": 26001,
"s": 25969,
"text": "func (v Value) String() string\n"
},
{
"code": null,
"e": 26058,
"s": 26001,
"text": "Parameters: This function does not accept any parameter."
},
{
"code": null,
"e": 26140,
"s": 26058,
"text": "Return Value: This function returns the string v’s underlying value, as a string."
},
{
"code": null,
"e": 26205,
"s": 26140,
"text": "Below examples illustrate the use of the above method in Golang:"
},
{
"code": null,
"e": 26216,
"s": 26205,
"text": "Example 1:"
},
{
"code": "// Golang program to illustrate// reflect.String() Function package main import ( \"fmt\" \"reflect\") // Main function func main() { var k = reflect.TypeOf(0) var e = reflect.TypeOf(\"\") //use of String method fmt.Println(reflect.FuncOf([]reflect.Type{k}, []reflect.Type{e}, false).String())}",
"e": 26554,
"s": 26216,
"text": null
},
{
"code": null,
"e": 26562,
"s": 26554,
"text": "Output:"
},
{
"code": null,
"e": 26580,
"s": 26562,
"text": "func(int) string\n"
},
{
"code": null,
"e": 26591,
"s": 26580,
"text": "Example 2:"
},
{
"code": "// Golang program to illustrate// reflect.String() Function package main import ( \"fmt\" \"reflect\") type Struct1 struct { Var1 string Var2 string Var3 float64 Var4 float64} // Main function func main() { NewMap := make(map[string]*Struct1) NewMap[\"abc\"] = &Struct1{\"abc\", \"def\", 1.0, 2.0} subvalMetric := \"Var1\" for _, Value:= range NewMap { s := reflect.ValueOf(&Value).Elem() // use of String() method println(s.String()) println(s.Elem().String()) metric := s.Elem().FieldByName(subvalMetric).Interface() fmt.Println(metric) } }",
"e": 27257,
"s": 26591,
"text": null
},
{
"code": null,
"e": 27265,
"s": 27257,
"text": "Output:"
},
{
"code": null,
"e": 27313,
"s": 27265,
"text": "<*main.Struct1 Value>\n<main.Struct1 Value>\nabc\n"
},
{
"code": null,
"e": 27328,
"s": 27313,
"text": "Golang-reflect"
},
{
"code": null,
"e": 27340,
"s": 27328,
"text": "Go Language"
},
{
"code": null,
"e": 27438,
"s": 27340,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27489,
"s": 27438,
"text": "strings.Replace() Function in Golang With Examples"
},
{
"code": null,
"e": 27535,
"s": 27489,
"text": "6 Best Books to Learn Go Programming Language"
},
{
"code": null,
"e": 27548,
"s": 27535,
"text": "Arrays in Go"
},
{
"code": null,
"e": 27595,
"s": 27548,
"text": "fmt.Sprintf() Function in Golang With Examples"
},
{
"code": null,
"e": 27607,
"s": 27595,
"text": "Golang Maps"
},
{
"code": null,
"e": 27624,
"s": 27607,
"text": "Slices in Golang"
},
{
"code": null,
"e": 27678,
"s": 27624,
"text": "Different Ways to Find the Type of Variable in Golang"
},
{
"code": null,
"e": 27700,
"s": 27678,
"text": "Inheritance in GoLang"
},
{
"code": null,
"e": 27721,
"s": 27700,
"text": "Interfaces in Golang"
}
] |
Output of C programs | Set 37 - GeeksforGeeks | 08 Aug, 2017
1.) What will be the output of the following code?
#include <stdio.h>int main(void){ int y, z; int x = scanf("%d %d", &y, &z); printf("%d", x); return 0;}
Input:
12 10
a)12b)2c)Syntax Errord)10
Answer : b
Explanation: scanf() returns the number of variables it successfully stored.
2. What will be the output of the following code?
#include <stdio.h>int main(void){ printf("%d", printf("geeksforgeeks")); return 0;}
a)Syntax Errorb)geeksforgeeksc)geeksforgeeks13d)13
Answer : c
Explanation : () returns the length of output(printed by printf) as integer.
3. What will be the output of the following code?
#include <stdio.h>int add(int a, int b){ if (a != 0 && b != 0) return printf("%*c%*c", a, '.', b, '.'); else return a != 0 ? a : b;}int main(){ int A = 0, B = 0; scanf("%d %d", &A, &B); printf("Required sum is %d", add(A, B)); return 0;}
Input:
22 10
a)42b)Compilation Errorc)Required sum is 32d)32
Answer : c
Explanation : printf() adds any numbers without using the addition operator .
4. What will be the output of the following code?
#include <stdio.h>int main(){ printf("%m"); return 0;}
a) Successb)Compilation Errorc)%md)None of the above.
Answer : a
Explanation : “%m” when used within printf() prints “Success”. The ‘%m’ conversion is a GNU C Library extension.
5. What will be the output of the following code?
#include <stdio.h>double m[] = { 7709179928849219.0, 771 };int main(){ m[1]-- ? m[0] *= 2, main() : printf((char*)m);}
a) C++Sucksb)Compilation Errorc)714d)770
Answer: a
Explanation :The number 7709179928849219.0 has the following binary representation as a 64-bit double:01000011 00111011 01100011 01110101 01010011 00101011 00101011 01000011+^^^^^^^ ^^^^—- ——– ——– ——– ——– ——– ——–+ shows the position of the sign; ^ of the exponent, and – of the mantissa (i.e. the value without the exponent).Since the representation uses binary exponent and mantissa, doubling the number increments the exponent by one. This program does it precisely 771 times, so the exponent which started at 1075 (decimal representation of 10000110011) becomes 1075 + 771 = 1846 at the end; binary representation of 1846 is 11100110110. The resultant pattern looks like this:01110011 01101011 01100011 01110101 01010011 00101011 00101011 01000011——– ——– ——– ——– ——– ——– ——– ——–0x73 ‘s’ 0x6B ‘k’ 0x63 ‘c’ 0x75 ‘u’ 0x53 ‘S’ 0x2B ‘+’ 0x2B ‘+’ 0x43 ‘C’This pattern corresponds to the string that we see printed, only backwards. At the same time, the second element of the array becomes zero, providing null terminator, making the string suitable for passing to printf().
6. What will be the output of the following code?
#include <stdio.h>int main(){ printf("geeksforgeeks"); brk(0);}
a)geeksforgeeksb)Compilation Errorc)program will not terminated)None of the above
Answer : a
Explanation : brk(0) terminates the program and acts like return statement.
This article is contributed by Nikita Tiwari. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
C-Output
Program Output
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Output of Java program | Set 18 (Overriding)
Output of Java Program | Set 11
Output of C++ programs | Set 34 (File Handling)
Different ways to copy a string in C/C++
Output of Java programs | Set 13 (Collections)
Output of Java Program | Set 3
Runtime Errors
Output of Java program | Set 28
Output of Java program | Set 5
Output of Java Programs | Set 12 | [
{
"code": null,
"e": 25573,
"s": 25545,
"text": "\n08 Aug, 2017"
},
{
"code": null,
"e": 25624,
"s": 25573,
"text": "1.) What will be the output of the following code?"
},
{
"code": "#include <stdio.h>int main(void){ int y, z; int x = scanf(\"%d %d\", &y, &z); printf(\"%d\", x); return 0;}",
"e": 25740,
"s": 25624,
"text": null
},
{
"code": null,
"e": 25747,
"s": 25740,
"text": "Input:"
},
{
"code": null,
"e": 25755,
"s": 25747,
"text": " 12 10\n"
},
{
"code": null,
"e": 25781,
"s": 25755,
"text": "a)12b)2c)Syntax Errord)10"
},
{
"code": null,
"e": 25792,
"s": 25781,
"text": "Answer : b"
},
{
"code": null,
"e": 25869,
"s": 25792,
"text": "Explanation: scanf() returns the number of variables it successfully stored."
},
{
"code": null,
"e": 25919,
"s": 25869,
"text": "2. What will be the output of the following code?"
},
{
"code": "#include <stdio.h>int main(void){ printf(\"%d\", printf(\"geeksforgeeks\")); return 0;}",
"e": 26009,
"s": 25919,
"text": null
},
{
"code": null,
"e": 26060,
"s": 26009,
"text": "a)Syntax Errorb)geeksforgeeksc)geeksforgeeks13d)13"
},
{
"code": null,
"e": 26071,
"s": 26060,
"text": "Answer : c"
},
{
"code": null,
"e": 26148,
"s": 26071,
"text": "Explanation : () returns the length of output(printed by printf) as integer."
},
{
"code": null,
"e": 26198,
"s": 26148,
"text": "3. What will be the output of the following code?"
},
{
"code": "#include <stdio.h>int add(int a, int b){ if (a != 0 && b != 0) return printf(\"%*c%*c\", a, '.', b, '.'); else return a != 0 ? a : b;}int main(){ int A = 0, B = 0; scanf(\"%d %d\", &A, &B); printf(\"Required sum is %d\", add(A, B)); return 0;}",
"e": 26468,
"s": 26198,
"text": null
},
{
"code": null,
"e": 26475,
"s": 26468,
"text": "Input:"
},
{
"code": null,
"e": 26481,
"s": 26475,
"text": "22 10"
},
{
"code": null,
"e": 26529,
"s": 26481,
"text": "a)42b)Compilation Errorc)Required sum is 32d)32"
},
{
"code": null,
"e": 26540,
"s": 26529,
"text": "Answer : c"
},
{
"code": null,
"e": 26618,
"s": 26540,
"text": "Explanation : printf() adds any numbers without using the addition operator ."
},
{
"code": null,
"e": 26668,
"s": 26618,
"text": "4. What will be the output of the following code?"
},
{
"code": "#include <stdio.h>int main(){ printf(\"%m\"); return 0;}",
"e": 26729,
"s": 26668,
"text": null
},
{
"code": null,
"e": 26783,
"s": 26729,
"text": "a) Successb)Compilation Errorc)%md)None of the above."
},
{
"code": null,
"e": 26794,
"s": 26783,
"text": "Answer : a"
},
{
"code": null,
"e": 26907,
"s": 26794,
"text": "Explanation : “%m” when used within printf() prints “Success”. The ‘%m’ conversion is a GNU C Library extension."
},
{
"code": null,
"e": 26957,
"s": 26907,
"text": "5. What will be the output of the following code?"
},
{
"code": "#include <stdio.h>double m[] = { 7709179928849219.0, 771 };int main(){ m[1]-- ? m[0] *= 2, main() : printf((char*)m);}",
"e": 27079,
"s": 26957,
"text": null
},
{
"code": null,
"e": 27120,
"s": 27079,
"text": "a) C++Sucksb)Compilation Errorc)714d)770"
},
{
"code": null,
"e": 27130,
"s": 27120,
"text": "Answer: a"
},
{
"code": null,
"e": 28201,
"s": 27130,
"text": "Explanation :The number 7709179928849219.0 has the following binary representation as a 64-bit double:01000011 00111011 01100011 01110101 01010011 00101011 00101011 01000011+^^^^^^^ ^^^^—- ——– ——– ——– ——– ——– ——–+ shows the position of the sign; ^ of the exponent, and – of the mantissa (i.e. the value without the exponent).Since the representation uses binary exponent and mantissa, doubling the number increments the exponent by one. This program does it precisely 771 times, so the exponent which started at 1075 (decimal representation of 10000110011) becomes 1075 + 771 = 1846 at the end; binary representation of 1846 is 11100110110. The resultant pattern looks like this:01110011 01101011 01100011 01110101 01010011 00101011 00101011 01000011——– ——– ——– ——– ——– ——– ——– ——–0x73 ‘s’ 0x6B ‘k’ 0x63 ‘c’ 0x75 ‘u’ 0x53 ‘S’ 0x2B ‘+’ 0x2B ‘+’ 0x43 ‘C’This pattern corresponds to the string that we see printed, only backwards. At the same time, the second element of the array becomes zero, providing null terminator, making the string suitable for passing to printf()."
},
{
"code": null,
"e": 28251,
"s": 28201,
"text": "6. What will be the output of the following code?"
},
{
"code": "#include <stdio.h>int main(){ printf(\"geeksforgeeks\"); brk(0);}",
"e": 28321,
"s": 28251,
"text": null
},
{
"code": null,
"e": 28403,
"s": 28321,
"text": "a)geeksforgeeksb)Compilation Errorc)program will not terminated)None of the above"
},
{
"code": null,
"e": 28415,
"s": 28403,
"text": "Answer : a"
},
{
"code": null,
"e": 28491,
"s": 28415,
"text": "Explanation : brk(0) terminates the program and acts like return statement."
},
{
"code": null,
"e": 28792,
"s": 28491,
"text": "This article is contributed by Nikita Tiwari. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 28917,
"s": 28792,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 28926,
"s": 28917,
"text": "C-Output"
},
{
"code": null,
"e": 28941,
"s": 28926,
"text": "Program Output"
},
{
"code": null,
"e": 29039,
"s": 28941,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29084,
"s": 29039,
"text": "Output of Java program | Set 18 (Overriding)"
},
{
"code": null,
"e": 29116,
"s": 29084,
"text": "Output of Java Program | Set 11"
},
{
"code": null,
"e": 29164,
"s": 29116,
"text": "Output of C++ programs | Set 34 (File Handling)"
},
{
"code": null,
"e": 29205,
"s": 29164,
"text": "Different ways to copy a string in C/C++"
},
{
"code": null,
"e": 29252,
"s": 29205,
"text": "Output of Java programs | Set 13 (Collections)"
},
{
"code": null,
"e": 29283,
"s": 29252,
"text": "Output of Java Program | Set 3"
},
{
"code": null,
"e": 29298,
"s": 29283,
"text": "Runtime Errors"
},
{
"code": null,
"e": 29330,
"s": 29298,
"text": "Output of Java program | Set 28"
},
{
"code": null,
"e": 29361,
"s": 29330,
"text": "Output of Java program | Set 5"
}
] |
Python | Pandas DatetimeIndex.year - GeeksforGeeks | 24 Dec, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas DatetimeIndex.year attribute outputs an Index object containing the value of years present in the Datetime object.
Syntax: DatetimeIndex.year
Return: Index containing years.
Example #1: Use DatetimeIndex.year attribute to find the years present in the DatetimeIndex.
# importing pandas as pdimport pandas as pd # Create the DatetimeIndex# Here the 'B' represents Business day frequencydidx = pd.DatetimeIndex(start ='2014-08-01 10:00', freq ='B', periods = 5, tz ='Asia/Calcutta') # Print the DatetimeIndexprint(didx)
Output :
Now we want to find all the year values present in the DatetimeIndex object.
# find all the years in the objectdidx.year
Output :As we can see in the output, the function has returned an Index object containing the year value of each entry in the DatetimeIndex object.&n bsp;Example #2: Use DatetimeIndex.year attribute to find the years present in the DatetimeIndex.
# importing pandas as pdimport pandas as pd # Create the DatetimeIndex# Here the 'AS' represents Year start frequencydidx = pd.DatetimeIndex(start ='2014-08-01 10:00', freq ='AS', periods = 5, tz ='Asia/Calcutta') # Print the DatetimeIndexprint(didx)
Output :
Now we want to find all the year values present in the DatetimeIndex object.
# find all the years in the objectdidx.year
Output :As we can see in the output, the function has returned an Index object containing the year value of each entry in the DatetimeIndex object.
Python pandas-datetimeIndex
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | 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": "\n24 Dec, 2018"
},
{
"code": null,
"e": 25769,
"s": 25555,
"text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier."
},
{
"code": null,
"e": 25891,
"s": 25769,
"text": "Pandas DatetimeIndex.year attribute outputs an Index object containing the value of years present in the Datetime object."
},
{
"code": null,
"e": 25918,
"s": 25891,
"text": "Syntax: DatetimeIndex.year"
},
{
"code": null,
"e": 25950,
"s": 25918,
"text": "Return: Index containing years."
},
{
"code": null,
"e": 26043,
"s": 25950,
"text": "Example #1: Use DatetimeIndex.year attribute to find the years present in the DatetimeIndex."
},
{
"code": "# importing pandas as pdimport pandas as pd # Create the DatetimeIndex# Here the 'B' represents Business day frequencydidx = pd.DatetimeIndex(start ='2014-08-01 10:00', freq ='B', periods = 5, tz ='Asia/Calcutta') # Print the DatetimeIndexprint(didx)",
"e": 26324,
"s": 26043,
"text": null
},
{
"code": null,
"e": 26333,
"s": 26324,
"text": "Output :"
},
{
"code": null,
"e": 26410,
"s": 26333,
"text": "Now we want to find all the year values present in the DatetimeIndex object."
},
{
"code": "# find all the years in the objectdidx.year",
"e": 26454,
"s": 26410,
"text": null
},
{
"code": null,
"e": 26701,
"s": 26454,
"text": "Output :As we can see in the output, the function has returned an Index object containing the year value of each entry in the DatetimeIndex object.&n bsp;Example #2: Use DatetimeIndex.year attribute to find the years present in the DatetimeIndex."
},
{
"code": "# importing pandas as pdimport pandas as pd # Create the DatetimeIndex# Here the 'AS' represents Year start frequencydidx = pd.DatetimeIndex(start ='2014-08-01 10:00', freq ='AS', periods = 5, tz ='Asia/Calcutta') # Print the DatetimeIndexprint(didx)",
"e": 26983,
"s": 26701,
"text": null
},
{
"code": null,
"e": 26992,
"s": 26983,
"text": "Output :"
},
{
"code": null,
"e": 27069,
"s": 26992,
"text": "Now we want to find all the year values present in the DatetimeIndex object."
},
{
"code": "# find all the years in the objectdidx.year",
"e": 27113,
"s": 27069,
"text": null
},
{
"code": null,
"e": 27261,
"s": 27113,
"text": "Output :As we can see in the output, the function has returned an Index object containing the year value of each entry in the DatetimeIndex object."
},
{
"code": null,
"e": 27289,
"s": 27261,
"text": "Python pandas-datetimeIndex"
},
{
"code": null,
"e": 27303,
"s": 27289,
"text": "Python-pandas"
},
{
"code": null,
"e": 27310,
"s": 27303,
"text": "Python"
},
{
"code": null,
"e": 27408,
"s": 27310,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27440,
"s": 27408,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27482,
"s": 27440,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27524,
"s": 27482,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27580,
"s": 27524,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27607,
"s": 27580,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27638,
"s": 27607,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27677,
"s": 27638,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27706,
"s": 27677,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 27728,
"s": 27706,
"text": "Defaultdict in Python"
}
] |
Check if four segments form a rectangle - GeeksforGeeks | 09 Mar, 2022
We are given four segments as a pair of coordinates of their end points. We need to tell whether those four line segments make a rectangle or not. Examples:
Input : segments[] = [(4, 2), (7, 5),
(2, 4), (4, 2),
(2, 4), (5, 7),
(5, 7), (7, 5)]
Output : Yes
Given these segment make a rectangle of length 3X2.
Input : segment[] = [(7, 0), (10, 0),
(7, 0), (7, 3),
(7, 3), (10, 2),
(10, 2), (10, 0)]
Output : Not
These segments do not make a rectangle.
Above examples are shown in below diagram.
This problem is mainly an extension of How to check if given four points form a square
Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution.
We can solve this problem by using properties of a rectangle. First, we check total unique end points of segments, if count of these points is not equal to 4 then the line segment can’t make a rectangle. Then we check distances between all pair of points, there should be at most 3 different distances, one for diagonal and two for sides and at the end we will check the relation among these three distances, for line segments to make a rectangle these distance should satisfy Pythagorean relation because sides and diagonal of rectangle makes a right angle triangle. If they satisfy mentioned conditions then we will flag polygon made by line segment as rectangle otherwise not.
CPP
// C++ program to check whether it is possible// to make a rectangle from 4 segments#include <bits/stdc++.h>using namespace std;#define N 4 // structure to represent a segmentstruct Segment{ int ax, ay; int bx, by;}; // Utility method to return square of distance// between two pointsint getDis(pair<int, int> a, pair<int, int> b){ return (a.first - b.first)*(a.first - b.first) + (a.second - b.second)*(a.second - b.second);} // method returns true if line Segments make// a rectanglebool isPossibleRectangle(Segment segments[]){ set< pair<int, int> > st; // putting all end points in a set to // count total unique points for (int i = 0; i < N; i++) { st.insert(make_pair(segments[i].ax, segments[i].ay)); st.insert(make_pair(segments[i].bx, segments[i].by)); } // If total unique points are not 4, then // they can't make a rectangle if (st.size() != 4) return false; // dist will store unique 'square of distances' set<int> dist; // calculating distance between all pair of // end points of line segments for (auto it1=st.begin(); it1!=st.end(); it1++) for (auto it2=st.begin(); it2!=st.end(); it2++) if (*it1 != *it2) dist.insert(getDis(*it1, *it2)); // if total unique distance are more than 3, // then line segment can't make a rectangle if (dist.size() > 3) return false; // copying distance into array. Note that set maintains // sorted order. int distance[3]; int i = 0; for (auto it = dist.begin(); it != dist.end(); it++) distance[i++] = *it; // If line seqments form a square if (dist.size() == 2) return (2*distance[0] == distance[1]); // distance of sides should satisfy pythagorean // theorem return (distance[0] + distance[1] == distance[2]);} // Driver code to test above methodsint main(){ Segment segments[] = { {4, 2, 7, 5}, {2, 4, 4, 2}, {2, 4, 5, 7}, {5, 7, 7, 5} }; (isPossibleRectangle(segments))?cout << "Yes\n":cout << "No\n";}
Output:
Yes
This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
harrypotter0
surinderdawra388
square-rectangle
Geometric
Mathematical
Mathematical
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convex Hull | Set 2 (Graham Scan)
Check whether a given point lies inside a triangle or not
Optimum location of point to minimize total distance
Closest Pair of Points | O(nlogn) Implementation
Given n line segments, find if any two segments intersect
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": 26701,
"s": 26673,
"text": "\n09 Mar, 2022"
},
{
"code": null,
"e": 26860,
"s": 26701,
"text": "We are given four segments as a pair of coordinates of their end points. We need to tell whether those four line segments make a rectangle or not. Examples: "
},
{
"code": null,
"e": 27331,
"s": 26860,
"text": "Input : segments[] = [(4, 2), (7, 5),\n (2, 4), (4, 2),\n (2, 4), (5, 7),\n (5, 7), (7, 5)]\nOutput : Yes\nGiven these segment make a rectangle of length 3X2.\n\nInput : segment[] = [(7, 0), (10, 0),\n (7, 0), (7, 3),\n (7, 3), (10, 2),\n (10, 2), (10, 0)]\nOutput : Not\nThese segments do not make a rectangle.\n\nAbove examples are shown in below diagram."
},
{
"code": null,
"e": 27418,
"s": 27331,
"text": "This problem is mainly an extension of How to check if given four points form a square"
},
{
"code": null,
"e": 27506,
"s": 27420,
"text": "Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution. "
},
{
"code": null,
"e": 28189,
"s": 27508,
"text": "We can solve this problem by using properties of a rectangle. First, we check total unique end points of segments, if count of these points is not equal to 4 then the line segment can’t make a rectangle. Then we check distances between all pair of points, there should be at most 3 different distances, one for diagonal and two for sides and at the end we will check the relation among these three distances, for line segments to make a rectangle these distance should satisfy Pythagorean relation because sides and diagonal of rectangle makes a right angle triangle. If they satisfy mentioned conditions then we will flag polygon made by line segment as rectangle otherwise not. "
},
{
"code": null,
"e": 28193,
"s": 28189,
"text": "CPP"
},
{
"code": "// C++ program to check whether it is possible// to make a rectangle from 4 segments#include <bits/stdc++.h>using namespace std;#define N 4 // structure to represent a segmentstruct Segment{ int ax, ay; int bx, by;}; // Utility method to return square of distance// between two pointsint getDis(pair<int, int> a, pair<int, int> b){ return (a.first - b.first)*(a.first - b.first) + (a.second - b.second)*(a.second - b.second);} // method returns true if line Segments make// a rectanglebool isPossibleRectangle(Segment segments[]){ set< pair<int, int> > st; // putting all end points in a set to // count total unique points for (int i = 0; i < N; i++) { st.insert(make_pair(segments[i].ax, segments[i].ay)); st.insert(make_pair(segments[i].bx, segments[i].by)); } // If total unique points are not 4, then // they can't make a rectangle if (st.size() != 4) return false; // dist will store unique 'square of distances' set<int> dist; // calculating distance between all pair of // end points of line segments for (auto it1=st.begin(); it1!=st.end(); it1++) for (auto it2=st.begin(); it2!=st.end(); it2++) if (*it1 != *it2) dist.insert(getDis(*it1, *it2)); // if total unique distance are more than 3, // then line segment can't make a rectangle if (dist.size() > 3) return false; // copying distance into array. Note that set maintains // sorted order. int distance[3]; int i = 0; for (auto it = dist.begin(); it != dist.end(); it++) distance[i++] = *it; // If line seqments form a square if (dist.size() == 2) return (2*distance[0] == distance[1]); // distance of sides should satisfy pythagorean // theorem return (distance[0] + distance[1] == distance[2]);} // Driver code to test above methodsint main(){ Segment segments[] = { {4, 2, 7, 5}, {2, 4, 4, 2}, {2, 4, 5, 7}, {5, 7, 7, 5} }; (isPossibleRectangle(segments))?cout << \"Yes\\n\":cout << \"No\\n\";}",
"e": 30265,
"s": 28193,
"text": null
},
{
"code": null,
"e": 30275,
"s": 30265,
"text": "Output: "
},
{
"code": null,
"e": 30279,
"s": 30275,
"text": "Yes"
},
{
"code": null,
"e": 30703,
"s": 30279,
"text": "This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 30716,
"s": 30703,
"text": "harrypotter0"
},
{
"code": null,
"e": 30733,
"s": 30716,
"text": "surinderdawra388"
},
{
"code": null,
"e": 30750,
"s": 30733,
"text": "square-rectangle"
},
{
"code": null,
"e": 30760,
"s": 30750,
"text": "Geometric"
},
{
"code": null,
"e": 30773,
"s": 30760,
"text": "Mathematical"
},
{
"code": null,
"e": 30786,
"s": 30773,
"text": "Mathematical"
},
{
"code": null,
"e": 30796,
"s": 30786,
"text": "Geometric"
},
{
"code": null,
"e": 30894,
"s": 30796,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30928,
"s": 30894,
"text": "Convex Hull | Set 2 (Graham Scan)"
},
{
"code": null,
"e": 30986,
"s": 30928,
"text": "Check whether a given point lies inside a triangle or not"
},
{
"code": null,
"e": 31039,
"s": 30986,
"text": "Optimum location of point to minimize total distance"
},
{
"code": null,
"e": 31088,
"s": 31039,
"text": "Closest Pair of Points | O(nlogn) Implementation"
},
{
"code": null,
"e": 31146,
"s": 31088,
"text": "Given n line segments, find if any two segments intersect"
},
{
"code": null,
"e": 31176,
"s": 31146,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 31236,
"s": 31176,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 31251,
"s": 31236,
"text": "C++ Data Types"
},
{
"code": null,
"e": 31294,
"s": 31251,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
ESLint - Pluggable JavaScript linter - GeeksforGeeks | 08 Sep, 2021
Before getting into ESlint first you should be aware of linting. It is the process of checking the code for any errors. A Linter is an automated tool that runs on a static piece of code to find any kind of discrepancy arising due to formatting or due to bad coding practices. Running a Linting tool over the source code helps to improve the quality and readability of the code.
ESLint: It is a JavaScript linting tool which is used for automatically detecting incorrect patterns found in ECMAScript/JavaScript code. It is used with the purpose of improving code quality, making code more consistent, and avoiding bugs. ESLint is written using Node.js to provide a fast runtime environment and easy installation via npm.The “ES” in ESLint stands for “EcmaScript”, which was created to standardize Javascript.
Prerequisites: Before installing or start working on ESLint, we have to make sure few things are available in our system.
Any Text Editor(e.g VS Code, Atom etc.)
NodeJS installed in your system:Installation of Node.js on WindowsInstallation of Node.js on Linux
Installation of Node.js on WindowsInstallation of Node.js on Linux
Installation of Node.js on Windows
Installation of Node.js on Linux
Installation:
We can install ESLint using npm(node package manager).npm install -g eslint
npm install -g eslint
We can set up a configuration file by below command.eslint --init
eslint --init
We can run ESLint on any file or directory by below command.eslint yourfile.js
eslint yourfile.js
Advantages of Using ESLint:
Static Analyser: ESLint can be easily integrated into most of the text editors like (VS Code, Sublime).ESLint allows developers to discover problems with their JavaScript code without even executing it. It analyses the static code quickly and can be integrated as part of the integration pipeline also.
Customizable: ESLint is easily customizable to suit the needs of the developers. The primary reason ESLint was created was to allow developers to create their own linting rules. One can write their own rules that work alongside the ESLint’s built-in rules.
Automatic Fix: ESLint not only identifies the issues but also fixes them automatically. The fixed feature of ESLint is pretty great and can auto-format/fix much of the code according to the ESLint configurations. We can find bugs and errors timely.
Configuration Rules: The ESLint comes with a large number of rules. We can modify those rules in our project by using configuration command or configuration files. To change the settings of any rule, we must set the rule ID equal to one of these values:
“off” or 0: To turn off the rule.
“warn” or 1: To turn on the rule as a warning (doesn’t affect exit code).
“error” or 2: To turn on the rule as an error (exit code is 1 when triggered).
Steps to set up ESLint in VSCode:
Step 1: Create a Javascript/React project
Step 2: Install eslint as an extension in the VS Code Editor.
Step 3: Install ESLint globally by running below command.npm install -g eslint
npm install -g eslint
Step 4: To initialize eslint in the project run below commandeslint --init
eslint --init
Step 5: Modify the eslint configuration file in your project by setting up rules.
ESLint rules:
priyankadalmia
aniruddhashriwant
JavaScript-Misc
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
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to apply style to parent if it has child with CSS?
How to execute PHP code using command line ?
Difference Between PUT and PATCH Request
REST API (Introduction)
How to redirect to another page in ReactJS ? | [
{
"code": null,
"e": 26169,
"s": 26141,
"text": "\n08 Sep, 2021"
},
{
"code": null,
"e": 26547,
"s": 26169,
"text": "Before getting into ESlint first you should be aware of linting. It is the process of checking the code for any errors. A Linter is an automated tool that runs on a static piece of code to find any kind of discrepancy arising due to formatting or due to bad coding practices. Running a Linting tool over the source code helps to improve the quality and readability of the code."
},
{
"code": null,
"e": 26977,
"s": 26547,
"text": "ESLint: It is a JavaScript linting tool which is used for automatically detecting incorrect patterns found in ECMAScript/JavaScript code. It is used with the purpose of improving code quality, making code more consistent, and avoiding bugs. ESLint is written using Node.js to provide a fast runtime environment and easy installation via npm.The “ES” in ESLint stands for “EcmaScript”, which was created to standardize Javascript."
},
{
"code": null,
"e": 27099,
"s": 26977,
"text": "Prerequisites: Before installing or start working on ESLint, we have to make sure few things are available in our system."
},
{
"code": null,
"e": 27139,
"s": 27099,
"text": "Any Text Editor(e.g VS Code, Atom etc.)"
},
{
"code": null,
"e": 27238,
"s": 27139,
"text": "NodeJS installed in your system:Installation of Node.js on WindowsInstallation of Node.js on Linux"
},
{
"code": null,
"e": 27305,
"s": 27238,
"text": "Installation of Node.js on WindowsInstallation of Node.js on Linux"
},
{
"code": null,
"e": 27340,
"s": 27305,
"text": "Installation of Node.js on Windows"
},
{
"code": null,
"e": 27373,
"s": 27340,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27387,
"s": 27373,
"text": "Installation:"
},
{
"code": null,
"e": 27463,
"s": 27387,
"text": "We can install ESLint using npm(node package manager).npm install -g eslint"
},
{
"code": null,
"e": 27485,
"s": 27463,
"text": "npm install -g eslint"
},
{
"code": null,
"e": 27551,
"s": 27485,
"text": "We can set up a configuration file by below command.eslint --init"
},
{
"code": null,
"e": 27565,
"s": 27551,
"text": "eslint --init"
},
{
"code": null,
"e": 27644,
"s": 27565,
"text": "We can run ESLint on any file or directory by below command.eslint yourfile.js"
},
{
"code": null,
"e": 27663,
"s": 27644,
"text": "eslint yourfile.js"
},
{
"code": null,
"e": 27691,
"s": 27663,
"text": "Advantages of Using ESLint:"
},
{
"code": null,
"e": 27994,
"s": 27691,
"text": "Static Analyser: ESLint can be easily integrated into most of the text editors like (VS Code, Sublime).ESLint allows developers to discover problems with their JavaScript code without even executing it. It analyses the static code quickly and can be integrated as part of the integration pipeline also."
},
{
"code": null,
"e": 28251,
"s": 27994,
"text": "Customizable: ESLint is easily customizable to suit the needs of the developers. The primary reason ESLint was created was to allow developers to create their own linting rules. One can write their own rules that work alongside the ESLint’s built-in rules."
},
{
"code": null,
"e": 28500,
"s": 28251,
"text": "Automatic Fix: ESLint not only identifies the issues but also fixes them automatically. The fixed feature of ESLint is pretty great and can auto-format/fix much of the code according to the ESLint configurations. We can find bugs and errors timely."
},
{
"code": null,
"e": 28754,
"s": 28500,
"text": "Configuration Rules: The ESLint comes with a large number of rules. We can modify those rules in our project by using configuration command or configuration files. To change the settings of any rule, we must set the rule ID equal to one of these values:"
},
{
"code": null,
"e": 28788,
"s": 28754,
"text": "“off” or 0: To turn off the rule."
},
{
"code": null,
"e": 28862,
"s": 28788,
"text": "“warn” or 1: To turn on the rule as a warning (doesn’t affect exit code)."
},
{
"code": null,
"e": 28941,
"s": 28862,
"text": "“error” or 2: To turn on the rule as an error (exit code is 1 when triggered)."
},
{
"code": null,
"e": 28975,
"s": 28941,
"text": "Steps to set up ESLint in VSCode:"
},
{
"code": null,
"e": 29017,
"s": 28975,
"text": "Step 1: Create a Javascript/React project"
},
{
"code": null,
"e": 29079,
"s": 29017,
"text": "Step 2: Install eslint as an extension in the VS Code Editor."
},
{
"code": null,
"e": 29158,
"s": 29079,
"text": "Step 3: Install ESLint globally by running below command.npm install -g eslint"
},
{
"code": null,
"e": 29180,
"s": 29158,
"text": "npm install -g eslint"
},
{
"code": null,
"e": 29255,
"s": 29180,
"text": "Step 4: To initialize eslint in the project run below commandeslint --init"
},
{
"code": null,
"e": 29269,
"s": 29255,
"text": "eslint --init"
},
{
"code": null,
"e": 29351,
"s": 29269,
"text": "Step 5: Modify the eslint configuration file in your project by setting up rules."
},
{
"code": null,
"e": 29365,
"s": 29351,
"text": "ESLint rules:"
},
{
"code": null,
"e": 29380,
"s": 29365,
"text": "priyankadalmia"
},
{
"code": null,
"e": 29398,
"s": 29380,
"text": "aniruddhashriwant"
},
{
"code": null,
"e": 29414,
"s": 29398,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 29431,
"s": 29414,
"text": "Web Technologies"
},
{
"code": null,
"e": 29529,
"s": 29431,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29569,
"s": 29529,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29614,
"s": 29569,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29657,
"s": 29614,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 29718,
"s": 29657,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29790,
"s": 29718,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 29845,
"s": 29790,
"text": "How to apply style to parent if it has child with CSS?"
},
{
"code": null,
"e": 29890,
"s": 29845,
"text": "How to execute PHP code using command line ?"
},
{
"code": null,
"e": 29931,
"s": 29890,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 29955,
"s": 29931,
"text": "REST API (Introduction)"
}
] |
PHP | include_once() and require_once() - GeeksforGeeks | 08 Mar, 2018
We already have learnt about file inclusion in PHP in the article PHP | (Include and Require). We have discussed about include() and require() functions for file inclusion in our previous article. In this article we will discuss about two more yet useful functions in PHP for file inclusion: include_once() and require_once() functions.
include_once() Function
The include_once() function can be used to include a PHP file in another one, when you may need to include the called file more than once. If it is found that the file has already been included, calling script is going to ignore further inclusions.
If a file named a.php is a php script calling b.php with include_once() function, and does not find b.php, a.php executes with a warning, excluding the part of the code written within b.php.
Syntax:
include_once('name of the called file with path');
Example:
// name of file is header.inc.php <?php echo "GEEKSFORGEEKS"; ?>
The above file is header.inc.php
The above file header.inc.php, is included twice with include_once() function in the following file index.php. But from the output, you will get that the second instance of inclusion is ignored since include_once() function ignores all the similar inclusions after the first one.
// name of file is index.php <?php include_once('header.inc.php'); include_once('header.inc.php'); ?>
Output:
GEEKSFORGEEKS
require_once() Function
require_once() function can be used to include a PHP file in another one, when you may need to include the called file more than once. If it is found that the file has already been included, calling script is going to ignore further inclusions.
If a.php is a php script calling b.php with require_once() function, and does not find b.php, a.php stops execution causing a fatal error.
Syntax:
require_once('name of the called file with path');
Example:
// name of file is header.inc.php <?php echo "GEEKSFORGEEKS"; ?>
The above file is header.inc.php
The above file header.inc.php, is included twice with require_once() function in the following file index.php. But from the output, you will get that the second instance of inclusion is ignored since require_once() function ignores all the similar inclusions after the first one.
// name of file is index.php <?php require_once('header.inc.php'); require_once('header.inc.php'); ?>
Output:
GEEKSFORGEEKS
include_once() vs require_once()
Both functions work as same and produce same output but if any error arises then differences come.
Example:
If we don’t have a file named header.inc.php, then in the case of the include_once(), the output will be shown with warnings about missing file, but at least the output will be shown from the index.php file.
In the case of the require_once(), if the file PHP file is missing, then a fatal error will arise and no output is shown and the execution halts.
PHP-basics
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to convert array to string in PHP ?
PHP | Converting string to Date and DateTime
How to pass JavaScript variables to PHP ?
Split a comma delimited string into an array in PHP
Download file from URL using PHP
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": 26050,
"s": 26022,
"text": "\n08 Mar, 2018"
},
{
"code": null,
"e": 26387,
"s": 26050,
"text": "We already have learnt about file inclusion in PHP in the article PHP | (Include and Require). We have discussed about include() and require() functions for file inclusion in our previous article. In this article we will discuss about two more yet useful functions in PHP for file inclusion: include_once() and require_once() functions."
},
{
"code": null,
"e": 26411,
"s": 26387,
"text": "include_once() Function"
},
{
"code": null,
"e": 26660,
"s": 26411,
"text": "The include_once() function can be used to include a PHP file in another one, when you may need to include the called file more than once. If it is found that the file has already been included, calling script is going to ignore further inclusions."
},
{
"code": null,
"e": 26851,
"s": 26660,
"text": "If a file named a.php is a php script calling b.php with include_once() function, and does not find b.php, a.php executes with a warning, excluding the part of the code written within b.php."
},
{
"code": null,
"e": 26859,
"s": 26851,
"text": "Syntax:"
},
{
"code": null,
"e": 26912,
"s": 26859,
"text": " include_once('name of the called file with path');\n"
},
{
"code": null,
"e": 26921,
"s": 26912,
"text": "Example:"
},
{
"code": "// name of file is header.inc.php <?php echo \"GEEKSFORGEEKS\"; ?>",
"e": 26989,
"s": 26921,
"text": null
},
{
"code": null,
"e": 27022,
"s": 26989,
"text": "The above file is header.inc.php"
},
{
"code": null,
"e": 27302,
"s": 27022,
"text": "The above file header.inc.php, is included twice with include_once() function in the following file index.php. But from the output, you will get that the second instance of inclusion is ignored since include_once() function ignores all the similar inclusions after the first one."
},
{
"code": "// name of file is index.php <?php include_once('header.inc.php'); include_once('header.inc.php'); ?>",
"e": 27408,
"s": 27302,
"text": null
},
{
"code": null,
"e": 27416,
"s": 27408,
"text": "Output:"
},
{
"code": null,
"e": 27430,
"s": 27416,
"text": "GEEKSFORGEEKS"
},
{
"code": null,
"e": 27454,
"s": 27430,
"text": "require_once() Function"
},
{
"code": null,
"e": 27699,
"s": 27454,
"text": "require_once() function can be used to include a PHP file in another one, when you may need to include the called file more than once. If it is found that the file has already been included, calling script is going to ignore further inclusions."
},
{
"code": null,
"e": 27838,
"s": 27699,
"text": "If a.php is a php script calling b.php with require_once() function, and does not find b.php, a.php stops execution causing a fatal error."
},
{
"code": null,
"e": 27846,
"s": 27838,
"text": "Syntax:"
},
{
"code": null,
"e": 27899,
"s": 27846,
"text": " require_once('name of the called file with path');\n"
},
{
"code": null,
"e": 27908,
"s": 27899,
"text": "Example:"
},
{
"code": "// name of file is header.inc.php <?php echo \"GEEKSFORGEEKS\"; ?>",
"e": 27976,
"s": 27908,
"text": null
},
{
"code": null,
"e": 28009,
"s": 27976,
"text": "The above file is header.inc.php"
},
{
"code": null,
"e": 28289,
"s": 28009,
"text": "The above file header.inc.php, is included twice with require_once() function in the following file index.php. But from the output, you will get that the second instance of inclusion is ignored since require_once() function ignores all the similar inclusions after the first one."
},
{
"code": "// name of file is index.php <?php require_once('header.inc.php'); require_once('header.inc.php'); ?>",
"e": 28395,
"s": 28289,
"text": null
},
{
"code": null,
"e": 28403,
"s": 28395,
"text": "Output:"
},
{
"code": null,
"e": 28417,
"s": 28403,
"text": "GEEKSFORGEEKS"
},
{
"code": null,
"e": 28450,
"s": 28417,
"text": "include_once() vs require_once()"
},
{
"code": null,
"e": 28549,
"s": 28450,
"text": "Both functions work as same and produce same output but if any error arises then differences come."
},
{
"code": null,
"e": 28558,
"s": 28549,
"text": "Example:"
},
{
"code": null,
"e": 28766,
"s": 28558,
"text": "If we don’t have a file named header.inc.php, then in the case of the include_once(), the output will be shown with warnings about missing file, but at least the output will be shown from the index.php file."
},
{
"code": null,
"e": 28912,
"s": 28766,
"text": "In the case of the require_once(), if the file PHP file is missing, then a fatal error will arise and no output is shown and the execution halts."
},
{
"code": null,
"e": 28923,
"s": 28912,
"text": "PHP-basics"
},
{
"code": null,
"e": 28936,
"s": 28923,
"text": "PHP-function"
},
{
"code": null,
"e": 28940,
"s": 28936,
"text": "PHP"
},
{
"code": null,
"e": 28957,
"s": 28940,
"text": "Web Technologies"
},
{
"code": null,
"e": 28961,
"s": 28957,
"text": "PHP"
},
{
"code": null,
"e": 29059,
"s": 28961,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29099,
"s": 29059,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 29144,
"s": 29099,
"text": "PHP | Converting string to Date and DateTime"
},
{
"code": null,
"e": 29186,
"s": 29144,
"text": "How to pass JavaScript variables to PHP ?"
},
{
"code": null,
"e": 29238,
"s": 29186,
"text": "Split a comma delimited string into an array in PHP"
},
{
"code": null,
"e": 29271,
"s": 29238,
"text": "Download file from URL using PHP"
},
{
"code": null,
"e": 29311,
"s": 29271,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29344,
"s": 29311,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29389,
"s": 29344,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29432,
"s": 29389,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Switch Expression in C# 8.0 - GeeksforGeeks | 11 Dec, 2019
The switch statement is a multiway branch statement. It provides an easy way to forward execution to different parts of code based on the value of the expression. So, with switch statement you always use some repetitive case and break keywords and also use default statement as shown in the below example:
Example:
// C# program to illustrate// switch case statementusing System; public class GFG { // Main Method public static void Main(String[] args) { int gitem = 8; switch (gitem) { case 2: Console.WriteLine("Hello"); break; case 4: Console.WriteLine("Bonjour"); break; case 6: Console.WriteLine("Konnichiwa"); break; case 8: Console.WriteLine("Namaste"); break; case 10: Console.WriteLine("Anyoung haseyo"); break; default: Console.WriteLine("No greeting found"); break; } }}
Output:
Namaste
This is the basic introduction of the switch statement. Now coming to the main topic, as we know that Microsoft has released the latest version of C# that is C# 8.0. In C# 8.0, the developers made some improvements in the switch statement and after improvements, the switch statement is converted into switch expression and the improvements are as follows:
The variable used in switch expression is now coming before the switch keyword.
Colon (:) and case keyword are replaced with arrows (=>). Which makes the code more compact and readable.
The default case is now replaced with a discard(_).
And the body of the switch is expression, not a statement.
Now, we modify the above example, according to the new improvements. These new improvements make our program more compact and easy to read as compared to the traditional method.
Example 1:
// C# program to illustrate// switch expressionusing System; public class GFG { // Main Method public static void Main(String[] args) { var gitem = 4; var res = gitem switch { 2 => "Hello", 4 => "Bonjour", 6 => "Namaste", 8 => "Anyoung haseyo", _ => "No greeting found", }; Console.WriteLine(res); }}
Output:
Bonjour
Example 2:
// C# program to illustrate // how to use string in// switch expressionusing System; public class GFG { // Main Method public static void Main(String[] args) { var sitem = "Second"; var res = sitem switch { "First" => "C#", "Second" => "Java", "Third" => "C++", "Fourth" => "Python", _ => "Not Language found !", }; Console.WriteLine("Favorite Language: {0} ", res); }}
Output:
Favorite Language: Java
CSharp-8.0
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Delegates
C# | Abstract Classes
Extension Method in C#
Introduction to .NET Framework
C# | String.IndexOf( ) Method | Set - 1
C# | Replace() Method
C# | Data Types
C# | Arrays
HashSet in C# with Examples
Common Language Runtime (CLR) in C# | [
{
"code": null,
"e": 25517,
"s": 25489,
"text": "\n11 Dec, 2019"
},
{
"code": null,
"e": 25823,
"s": 25517,
"text": "The switch statement is a multiway branch statement. It provides an easy way to forward execution to different parts of code based on the value of the expression. So, with switch statement you always use some repetitive case and break keywords and also use default statement as shown in the below example:"
},
{
"code": null,
"e": 25832,
"s": 25823,
"text": "Example:"
},
{
"code": "// C# program to illustrate// switch case statementusing System; public class GFG { // Main Method public static void Main(String[] args) { int gitem = 8; switch (gitem) { case 2: Console.WriteLine(\"Hello\"); break; case 4: Console.WriteLine(\"Bonjour\"); break; case 6: Console.WriteLine(\"Konnichiwa\"); break; case 8: Console.WriteLine(\"Namaste\"); break; case 10: Console.WriteLine(\"Anyoung haseyo\"); break; default: Console.WriteLine(\"No greeting found\"); break; } }}",
"e": 26523,
"s": 25832,
"text": null
},
{
"code": null,
"e": 26531,
"s": 26523,
"text": "Output:"
},
{
"code": null,
"e": 26540,
"s": 26531,
"text": "Namaste\n"
},
{
"code": null,
"e": 26897,
"s": 26540,
"text": "This is the basic introduction of the switch statement. Now coming to the main topic, as we know that Microsoft has released the latest version of C# that is C# 8.0. In C# 8.0, the developers made some improvements in the switch statement and after improvements, the switch statement is converted into switch expression and the improvements are as follows:"
},
{
"code": null,
"e": 26977,
"s": 26897,
"text": "The variable used in switch expression is now coming before the switch keyword."
},
{
"code": null,
"e": 27083,
"s": 26977,
"text": "Colon (:) and case keyword are replaced with arrows (=>). Which makes the code more compact and readable."
},
{
"code": null,
"e": 27135,
"s": 27083,
"text": "The default case is now replaced with a discard(_)."
},
{
"code": null,
"e": 27194,
"s": 27135,
"text": "And the body of the switch is expression, not a statement."
},
{
"code": null,
"e": 27372,
"s": 27194,
"text": "Now, we modify the above example, according to the new improvements. These new improvements make our program more compact and easy to read as compared to the traditional method."
},
{
"code": null,
"e": 27383,
"s": 27372,
"text": "Example 1:"
},
{
"code": "// C# program to illustrate// switch expressionusing System; public class GFG { // Main Method public static void Main(String[] args) { var gitem = 4; var res = gitem switch { 2 => \"Hello\", 4 => \"Bonjour\", 6 => \"Namaste\", 8 => \"Anyoung haseyo\", _ => \"No greeting found\", }; Console.WriteLine(res); }}",
"e": 27788,
"s": 27383,
"text": null
},
{
"code": null,
"e": 27796,
"s": 27788,
"text": "Output:"
},
{
"code": null,
"e": 27804,
"s": 27796,
"text": "Bonjour"
},
{
"code": null,
"e": 27815,
"s": 27804,
"text": "Example 2:"
},
{
"code": "// C# program to illustrate // how to use string in// switch expressionusing System; public class GFG { // Main Method public static void Main(String[] args) { var sitem = \"Second\"; var res = sitem switch { \"First\" => \"C#\", \"Second\" => \"Java\", \"Third\" => \"C++\", \"Fourth\" => \"Python\", _ => \"Not Language found !\", }; Console.WriteLine(\"Favorite Language: {0} \", res); }}",
"e": 28289,
"s": 27815,
"text": null
},
{
"code": null,
"e": 28297,
"s": 28289,
"text": "Output:"
},
{
"code": null,
"e": 28322,
"s": 28297,
"text": "Favorite Language: Java "
},
{
"code": null,
"e": 28333,
"s": 28322,
"text": "CSharp-8.0"
},
{
"code": null,
"e": 28336,
"s": 28333,
"text": "C#"
},
{
"code": null,
"e": 28434,
"s": 28336,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28449,
"s": 28434,
"text": "C# | Delegates"
},
{
"code": null,
"e": 28471,
"s": 28449,
"text": "C# | Abstract Classes"
},
{
"code": null,
"e": 28494,
"s": 28471,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 28525,
"s": 28494,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 28565,
"s": 28525,
"text": "C# | String.IndexOf( ) Method | Set - 1"
},
{
"code": null,
"e": 28587,
"s": 28565,
"text": "C# | Replace() Method"
},
{
"code": null,
"e": 28603,
"s": 28587,
"text": "C# | Data Types"
},
{
"code": null,
"e": 28615,
"s": 28603,
"text": "C# | Arrays"
},
{
"code": null,
"e": 28643,
"s": 28615,
"text": "HashSet in C# with Examples"
}
] |
C library function - strcat() | The C library function char *strcat(char *dest, const char *src) appends the string pointed to by src to the end of the string pointed to by dest.
Following is the declaration for strcat() function.
char *strcat(char *dest, const char *src)
dest − This is pointer to the destination array, which should contain a C string, and should be large enough to contain the concatenated resulting string.
dest − This is pointer to the destination array, which should contain a C string, and should be large enough to contain the concatenated resulting string.
src − This is the string to be appended. This should not overlap the destination.
src − This is the string to be appended. This should not overlap the destination.
This function returns a pointer to the resulting string dest.
The following example shows the usage of strcat() function.
#include <stdio.h>
#include <string.h>
int main () {
char src[50], dest[50];
strcpy(src, "This is source");
strcpy(dest, "This is destination");
strcat(dest, src);
printf("Final destination string : |%s|", dest);
return(0);
}
Let us compile and run the above program that will produce the following result −
Final destination string : |This is destinationThis is source|
12 Lectures
2 hours
Nishant Malik
12 Lectures
2.5 hours
Nishant Malik
48 Lectures
6.5 hours
Asif Hussain
12 Lectures
2 hours
Richa Maheshwari
20 Lectures
3.5 hours
Vandana Annavaram
44 Lectures
1 hours
Amit Diwan
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2154,
"s": 2007,
"text": "The C library function char *strcat(char *dest, const char *src) appends the string pointed to by src to the end of the string pointed to by dest."
},
{
"code": null,
"e": 2206,
"s": 2154,
"text": "Following is the declaration for strcat() function."
},
{
"code": null,
"e": 2248,
"s": 2206,
"text": "char *strcat(char *dest, const char *src)"
},
{
"code": null,
"e": 2403,
"s": 2248,
"text": "dest − This is pointer to the destination array, which should contain a C string, and should be large enough to contain the concatenated resulting string."
},
{
"code": null,
"e": 2558,
"s": 2403,
"text": "dest − This is pointer to the destination array, which should contain a C string, and should be large enough to contain the concatenated resulting string."
},
{
"code": null,
"e": 2640,
"s": 2558,
"text": "src − This is the string to be appended. This should not overlap the destination."
},
{
"code": null,
"e": 2722,
"s": 2640,
"text": "src − This is the string to be appended. This should not overlap the destination."
},
{
"code": null,
"e": 2784,
"s": 2722,
"text": "This function returns a pointer to the resulting string dest."
},
{
"code": null,
"e": 2844,
"s": 2784,
"text": "The following example shows the usage of strcat() function."
},
{
"code": null,
"e": 3097,
"s": 2844,
"text": "#include <stdio.h>\n#include <string.h>\n\nint main () {\n char src[50], dest[50];\n\n strcpy(src, \"This is source\");\n strcpy(dest, \"This is destination\");\n\n strcat(dest, src);\n\n printf(\"Final destination string : |%s|\", dest);\n \n return(0);\n}"
},
{
"code": null,
"e": 3179,
"s": 3097,
"text": "Let us compile and run the above program that will produce the following result −"
},
{
"code": null,
"e": 3243,
"s": 3179,
"text": "Final destination string : |This is destinationThis is source|\n"
},
{
"code": null,
"e": 3276,
"s": 3243,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3291,
"s": 3276,
"text": " Nishant Malik"
},
{
"code": null,
"e": 3326,
"s": 3291,
"text": "\n 12 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3341,
"s": 3326,
"text": " Nishant Malik"
},
{
"code": null,
"e": 3376,
"s": 3341,
"text": "\n 48 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 3390,
"s": 3376,
"text": " Asif Hussain"
},
{
"code": null,
"e": 3423,
"s": 3390,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3441,
"s": 3423,
"text": " Richa Maheshwari"
},
{
"code": null,
"e": 3476,
"s": 3441,
"text": "\n 20 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 3495,
"s": 3476,
"text": " Vandana Annavaram"
},
{
"code": null,
"e": 3528,
"s": 3495,
"text": "\n 44 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3540,
"s": 3528,
"text": " Amit Diwan"
},
{
"code": null,
"e": 3547,
"s": 3540,
"text": " Print"
},
{
"code": null,
"e": 3558,
"s": 3547,
"text": " Add Notes"
}
] |
Detecting arrow key presses in JavaScript? | To detect the arrow key when it is pressed, use onkeydown in JavaScript.
The button has key code. As you know the left arrow key has the code 37. The up arrow key
has the code 38 and right has the 39 and down has 40.
Following is the code −
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<body>
</body>
<script>
document.onkeydown = function (event) {
switch (event.keyCode) {
case 37:
console.log("Left key is pressed.");
break;
case 38:
console.log("Up key is pressed.");
break;
case 39:
console.log("Right key is pressed.");
break;
case 40:
console.log("Down key is pressed.");
break;
}
};
</script>
</html>
To run the above program, save the file name anyName.html(index.html). Right click on the file
and select the option “Open with live server” in VS Code editor.
Here, I have pressed the up arrow key. This will produce the following output on console − | [
{
"code": null,
"e": 1135,
"s": 1062,
"text": "To detect the arrow key when it is pressed, use onkeydown in JavaScript."
},
{
"code": null,
"e": 1279,
"s": 1135,
"text": "The button has key code. As you know the left arrow key has the code 37. The up arrow key\nhas the code 38 and right has the 39 and down has 40."
},
{
"code": null,
"e": 1303,
"s": 1279,
"text": "Following is the code −"
},
{
"code": null,
"e": 2172,
"s": 1303,
"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</head>\n<link rel=\"stylesheet\" href=\"//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css\">\n<script src=\"https://code.jquery.com/jquery-1.12.4.js\"></script>\n<script src=\"https://code.jquery.com/ui/1.12.1/jquery-ui.js\"></script>\n<body>\n</body>\n<script>\n document.onkeydown = function (event) {\n switch (event.keyCode) {\n case 37:\n console.log(\"Left key is pressed.\");\n break;\n case 38:\n console.log(\"Up key is pressed.\");\n break;\n case 39:\n console.log(\"Right key is pressed.\");\n break;\n case 40:\n console.log(\"Down key is pressed.\");\n break;\n }\n };\n</script>\n</html>"
},
{
"code": null,
"e": 2332,
"s": 2172,
"text": "To run the above program, save the file name anyName.html(index.html). Right click on the file\nand select the option “Open with live server” in VS Code editor."
},
{
"code": null,
"e": 2423,
"s": 2332,
"text": "Here, I have pressed the up arrow key. This will produce the following output on console −"
}
] |
How to check Android Phone Model programmatically using Kotlin? | This example demonstrates how to check Android Phone Model programmatically using kotlin.
Step 1 − Create a new project in Android Studio, go to File? New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:padding="8dp"
android:text="Tutorials Point"
android:textColor="@android:color/holo_green_dark"
android:textSize="48sp"
android:textStyle="bold" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:onClick="getModel"
android:text="Get Model"
android:textColor="@android:color/background_dark" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/button"
android:layout_centerHorizontal="true"
android:padding="8dp"
android:textColor="@android:color/holo_blue_dark"
android:textSize="24sp"
android:textStyle="bold" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.os.Build
import android.os.Bundle
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
lateinit var textView: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
textView = findViewById(R.id.textView)
}
fun getModel(view: View) {
textView.text = getPhoneModel()
}
private fun getPhoneModel(): String? {
return Build.MODEL
}
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.myapplication">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen | [
{
"code": null,
"e": 1152,
"s": 1062,
"text": "This example demonstrates how to check Android Phone Model programmatically using kotlin."
},
{
"code": null,
"e": 1280,
"s": 1152,
"text": "Step 1 − Create a new project in Android Studio, go to File? New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1345,
"s": 1280,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2665,
"s": 1345,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"50dp\"\n android:padding=\"8dp\"\n android:text=\"Tutorials Point\"\n android:textColor=\"@android:color/holo_green_dark\"\n android:textSize=\"48sp\"\n android:textStyle=\"bold\" />\n <Button\n android:id=\"@+id/button\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:onClick=\"getModel\"\n android:text=\"Get Model\"\n android:textColor=\"@android:color/background_dark\" />\n <TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@id/button\"\n android:layout_centerHorizontal=\"true\"\n android:padding=\"8dp\"\n android:textColor=\"@android:color/holo_blue_dark\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 2720,
"s": 2665,
"text": "Step 3 − Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 3316,
"s": 2720,
"text": "import android.os.Build\nimport android.os.Bundle\nimport android.view.View\nimport android.widget.TextView\nimport androidx.appcompat.app.AppCompatActivity\nclass MainActivity : AppCompatActivity() {\n lateinit var textView: TextView\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n textView = findViewById(R.id.textView)\n }\n fun getModel(view: View) {\n textView.text = getPhoneModel()\n }\n private fun getPhoneModel(): String? {\n return Build.MODEL\n }\n}"
},
{
"code": null,
"e": 3371,
"s": 3316,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 4052,
"s": 3371,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.myapplication\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" /> \n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 4400,
"s": 4052,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen"
}
] |
How to Create a Correlation Matrix with Too Many Variables in R | by Catherine Williams | Towards Data Science | I used the Kaggle House Prices Dataset which has 79 explanatory variables. In my analysis, I tried to look at correlations between all of the variables and realized there are just too many variables to make sense of any typical visual aid.
I tried several different packages and tools and decided that I can manipulate corrplot to do what I want the best. Without any manipulations, this is what the correlation matrix looks like. This is obviously a very unhelpful visualization. There are definitely ways to change this view built into the package, but none of them can really handle this many variables.
library(corrplot)df_cor <- cor(df)corrplot(df_cor)
With a lot of trial and error and skimming Stack Overflow, I was able to create a function to make this process much easier. First, it will convert all variables to numeric values (if not already). Then, it will drop duplicates and perfect correlations (correlations with itself). These are obviously not useful.
corr_simple <- function(data=df,sig=0.5){ #convert data to numeric in order to run correlations #convert to factor first to keep the integrity of the data - each value will become a number rather than turn into NA df_cor <- data %>% mutate_if(is.character, as.factor) df_cor <- df_cor %>% mutate_if(is.factor, as.numeric) #run a correlation and drop the insignificant ones corr <- cor(df_cor) #prepare to drop duplicates and correlations of 1 corr[lower.tri(corr,diag=TRUE)] <- NA #drop perfect correlations corr[corr == 1] <- NA #turn into a 3-column table corr <- as.data.frame(as.table(corr)) #remove the NA values from above corr <- na.omit(corr) #select significant values corr <- subset(corr, abs(Freq) > sig) #sort by highest correlation corr <- corr[order(-abs(corr$Freq)),] #print table print(corr) #turn corr back into matrix in order to plot with corrplot mtx_corr <- reshape2::acast(corr, Var1~Var2, value.var="Freq") #plot correlations visually corrplot(mtx_corr, is.corr=FALSE, tl.col="black", na.label=" ")}corr_simple()
Next, it will set up the data frame to see the raw correlations in a table since raw numbers can be helpful. The data frame is sorted by the highest correlation first.
In order to reduce the sheer quantity of variables (without having to manually pick and choose), Only variables above a specific significance level threshold are selected. It is set to 0.5 as the initial default.
After the table is produced, it will return the following, filtered out, correlation matrix chart. Only the correlations with a high enough significance level will have a colored circle. This further helps to cut out the noise if there are still a lot of remaining variables.
This ‘corr_simple’ function can be run again and again after some feature engineering, or with different significance levels. This really helps for faster analysis and to see only the relevant data. With more variables, it may be necessary to play with different significance levels and/or use more feature engineering to reduce the number of correlated variables, and then re-run the function until results are readable and useful. | [
{
"code": null,
"e": 412,
"s": 172,
"text": "I used the Kaggle House Prices Dataset which has 79 explanatory variables. In my analysis, I tried to look at correlations between all of the variables and realized there are just too many variables to make sense of any typical visual aid."
},
{
"code": null,
"e": 779,
"s": 412,
"text": "I tried several different packages and tools and decided that I can manipulate corrplot to do what I want the best. Without any manipulations, this is what the correlation matrix looks like. This is obviously a very unhelpful visualization. There are definitely ways to change this view built into the package, but none of them can really handle this many variables."
},
{
"code": null,
"e": 830,
"s": 779,
"text": "library(corrplot)df_cor <- cor(df)corrplot(df_cor)"
},
{
"code": null,
"e": 1143,
"s": 830,
"text": "With a lot of trial and error and skimming Stack Overflow, I was able to create a function to make this process much easier. First, it will convert all variables to numeric values (if not already). Then, it will drop duplicates and perfect correlations (correlations with itself). These are obviously not useful."
},
{
"code": null,
"e": 2218,
"s": 1143,
"text": "corr_simple <- function(data=df,sig=0.5){ #convert data to numeric in order to run correlations #convert to factor first to keep the integrity of the data - each value will become a number rather than turn into NA df_cor <- data %>% mutate_if(is.character, as.factor) df_cor <- df_cor %>% mutate_if(is.factor, as.numeric) #run a correlation and drop the insignificant ones corr <- cor(df_cor) #prepare to drop duplicates and correlations of 1 corr[lower.tri(corr,diag=TRUE)] <- NA #drop perfect correlations corr[corr == 1] <- NA #turn into a 3-column table corr <- as.data.frame(as.table(corr)) #remove the NA values from above corr <- na.omit(corr) #select significant values corr <- subset(corr, abs(Freq) > sig) #sort by highest correlation corr <- corr[order(-abs(corr$Freq)),] #print table print(corr) #turn corr back into matrix in order to plot with corrplot mtx_corr <- reshape2::acast(corr, Var1~Var2, value.var=\"Freq\") #plot correlations visually corrplot(mtx_corr, is.corr=FALSE, tl.col=\"black\", na.label=\" \")}corr_simple()"
},
{
"code": null,
"e": 2386,
"s": 2218,
"text": "Next, it will set up the data frame to see the raw correlations in a table since raw numbers can be helpful. The data frame is sorted by the highest correlation first."
},
{
"code": null,
"e": 2599,
"s": 2386,
"text": "In order to reduce the sheer quantity of variables (without having to manually pick and choose), Only variables above a specific significance level threshold are selected. It is set to 0.5 as the initial default."
},
{
"code": null,
"e": 2875,
"s": 2599,
"text": "After the table is produced, it will return the following, filtered out, correlation matrix chart. Only the correlations with a high enough significance level will have a colored circle. This further helps to cut out the noise if there are still a lot of remaining variables."
}
] |
How can we write JSON objects to a file in Java?
| The JSON is one of the widely used data-interchange formats and is a lightweight and language independent. The json.simple is a lightweight JSON processing library that can be used to write JSON files and it can be used to encode or decode JSON text and fully compliant with JSON specification(RFC4627). In order to read a JSON file, we need to download the json-simple.jar file and set the path to execute it.
import java.io.*;
import java.util.*;
import org.json.simple.*;
import org.json.simple.parser.*;
public class JSONObjectWriterToFileTest {
public static void main(String[] args) throws IOException {
JSONObject obj = new JSONObject();
obj.put("Name", "Adithya");
obj.put("Course", "MCA");
JSONArray subjects = new JSONArray();
subjects.add("Subject1: DBMS");
subjects.add("Subject2: JAVA");
subjects.add("Subject3: PYTHON");
obj.put("Subjects:", subjects);
try (FileWriter file = new FileWriter("/Users/User/Desktop/course1.json")) {
file.write(obj.toJSONString());
System.out.println("JSON Object write to a File successfully");
System.out.println("JSON Object: " + obj);
}
}
}
JSON Object write to a File successfully
JSON Object: {"Subjects:":["Subject1: DBMS","Subject2: JAVA","Subject3: PYTHON"],"Course":"MCA","Name":"Adithya"} | [
{
"code": null,
"e": 1473,
"s": 1062,
"text": "The JSON is one of the widely used data-interchange formats and is a lightweight and language independent. The json.simple is a lightweight JSON processing library that can be used to write JSON files and it can be used to encode or decode JSON text and fully compliant with JSON specification(RFC4627). In order to read a JSON file, we need to download the json-simple.jar file and set the path to execute it."
},
{
"code": null,
"e": 2244,
"s": 1473,
"text": "import java.io.*;\nimport java.util.*;\nimport org.json.simple.*;\nimport org.json.simple.parser.*;\npublic class JSONObjectWriterToFileTest {\n public static void main(String[] args) throws IOException {\n JSONObject obj = new JSONObject();\n obj.put(\"Name\", \"Adithya\");\n obj.put(\"Course\", \"MCA\");\n JSONArray subjects = new JSONArray();\n subjects.add(\"Subject1: DBMS\");\n subjects.add(\"Subject2: JAVA\");\n subjects.add(\"Subject3: PYTHON\");\n obj.put(\"Subjects:\", subjects);\n try (FileWriter file = new FileWriter(\"/Users/User/Desktop/course1.json\")) {\n file.write(obj.toJSONString());\n System.out.println(\"JSON Object write to a File successfully\");\n System.out.println(\"JSON Object: \" + obj);\n }\n }\n}"
},
{
"code": null,
"e": 2399,
"s": 2244,
"text": "JSON Object write to a File successfully\nJSON Object: {\"Subjects:\":[\"Subject1: DBMS\",\"Subject2: JAVA\",\"Subject3: PYTHON\"],\"Course\":\"MCA\",\"Name\":\"Adithya\"}"
}
] |
Twitter bot for Data Scientists. Ever wonder how to create your... | by Stephen Oni | Towards Data Science | Ever wonder how to create your @Getvideobot @threadreaderapp and the likes
Twitter is one of the most widely used social platforms. It’s used by individuals and organizations. It serves as a large pool of information for those whose information (data) drives their lives and work.
The existence of twitter API has provided unlimited creative access to the information shared and provided on the platform, due to this, different twitter bot has being created for a different purpose, and it has helped make twitter more of a better platform.
Going further than just making twitter platform interesting with the use of these bots, it can serve as a means to crowdsource data for data scientists.
In this article we will be learning how to create different twitter bot to crowdsource data for your data science project, like how to:
download images and videos by monitoring specific keywords.download media data by being referenced in a tweet.collecting tweet of a monitored user.Unrolling twitter thread in to a text file.storing data gather in aws s3.
download images and videos by monitoring specific keywords.
download media data by being referenced in a tweet.
collecting tweet of a monitored user.
Unrolling twitter thread in to a text file.
storing data gather in aws s3.
These various processes can help crowdsource data not just for NLP, but also for computer vision( since most people think twitter is most best for collecting data for Natural language processing).
In this article, I will assume you have Twitter API Authentication Credentials and also know how to use Tweepy. If not, check the reference below on how to obtain twitter API credentials and how to install tweepy and gain a little bit of introduction to it. But I will advise you follow through the article first, just to gain the application view, then go back to the reference.
Provided you have the twitter API credentials, the first thing to do is to create a config file, which sets up your authentication with twitter API.
A call to the function helps checks if the authentication is valid. You can replace the os.getenv() with the api keys directly, or you store the api key in your environment . The wait_on_rate_limit and wait_on_rate_limit_notify helps tweepy wait and print out a message when the rate limit is exceeded.
Download Media Data by Monitoring Specific Keywords
Data collection is the backbone of every data-driven project. The type of data being collected depends on the type of project being done. For example, for a computer vision project, it requires images or videos. Twitter can serve as a platform to curate such data in different ways. And one of the ways is monitoring a particular set of keywords related to the type of data you want for your project.
Let say you want to curate or gather data, involving Trump, a twitter bot can be created to always listen to every tweet mentioning Trump.
The Monitor bot is created using Twitter Stream service api interfaced by tweepy. This helps the bot to keep listen to different tweets across the Twitter platform. The Monitor class inherit from the tweepy.StreamListener and it contains two methods; on_status this helps to pass in the tweet and do whatever we want with the tweet passed in and on_error provide the actionable point in case an error is being encountered during the on_status process.
The tweet passed in on_status contains the JSON attribute of each tweet. Since in this example we need the media data. The json element of the tweet contains what will be called entities and the entities contain the media files and the embedded url in a tweet. For example
{u'hashtags': [{u'indices': [0, 12], u'text': u'NeurIPS2019'}], u'media': [{u'display_url': u'pic.twitter.com/GjpvEte86u', u'expanded_url': u'https://twitter.com/doomie/status/1206025007261876226/photo/1', u'features': {u'large': {u'faces': []}, u'medium': {u'faces': []}, u'orig': {u'faces': []}, u'small': {u'faces': []}}, u'id': 1206024997262618626, u'id_str': u'1206024997262618626', u'indices': [278, 301], u'media_url': u'http://pbs.twimg.com/media/ELypWGAUcAIpNTu.jpg', u'media_url_https': u'https://pbs.twimg.com/media/ELypWGAUcAIpNTu.jpg', u'sizes': {u'large': {u'h': 1536, u'resize': u'fit', u'w': 2048}, u'medium': {u'h': 900, u'resize': u'fit', u'w': 1200}, u'small': {u'h': 510, u'resize': u'fit', u'w': 680}, u'thumb': {u'h': 150, u'resize': u'crop', u'w': 150}}, u'type': u'photo', u'url': u'https://t.co/GjpvEte86u'}], u'symbols': [], u'urls': [], u'user_mentions': []}
the tweet.entities contains this keys and value items. since we will need the media files. For the image file, the media_url will be used to download the image in a tweet. and for the videos uploaded in the tweet will be downloaded using the expanded_url and for the videos embedded through a url, such as youtube videos. will be extracted from the urls , but in this tweet, it contains no urls, that's why the array is empty. But for a tweet which contains a url
{ .... u'urls': [{...,u'expanded_url':'youtube.com?...}]
Hence the video is downloaded by parsing in urls[0]['expanded_url'] .
Various python libraries or modules have been created to make the downloading of images and videos easy. To download images, a python package called wget is used. For youtube video download pytube is used and for twitter videos, twitter_dl is used. All of these libraries are great libraries, they make it easier to build this project. But for twitter-dl and pytube i make some changes to them due to the error I was encountering, but i think the new update should resolve that. So you can check my github to download them if you encounter any error.
To download these media files, we combine these libraries into a single file
Now we can combine this with the Monitor.py to start downloading media files
Download Media file When being Referenced to a Tweet
Sometimes instead of trying to monitor a specific keyword, we can let others help crowdsource data for us on twitter. The method involves letting people reference your twitter name under the tweet that contains the kind of data you want. The process is similar to that of the monitoring process just that we won’t be using streaming api, and it does not listen to all tweets except the one you are being mentioned in.
The mention function makes use of the api.mention , to fetch all the tweet you are being mentioned in. To prevent the api.Cursor from fetching all the tweets you are being mentioned in, since the time you join twitter, we use the since_id . To make sure it keeps fetching the newly tweet you are being mentioned in. First, we get the id of the tweet of your last mention.
tweety = []for tweet in tweepy.Cursor(api.mentions_timeline).items(): if len(tweety) > 1: break else: tweety.append(tweet)
And since the tweet is being fetched based on the newly created tweet. we only need that and then we index tweety to get the id of the tweet.
tweety[0].idoutput[]:1208298926627074049
And in mention() in the above code palette, we make use of max(tweet.id,new_since_id) This is used since for each new tweet, the id is always greater than the tweet id before it. that is new tweet id is higher than old tweet id.
Don’t forget that the tweet collected are not just text but json element, containing tweet attribute. For this bot, you are being referenced to a tweet, via a comment section. The main content you want is in the tweet the user reference you in via a comment. So the user is replying to a tweet.
In the tweet json element, it is possible to extract the id of the tweet the user replied to. We call this id in_reply_to_status_id. When a user is not replying to a tweet, the id is usually None . To create the bot, we first check if the reply status id is not None, then we process the tweet. Then we get the tweet from the status id using
status_id = tweet.in_reply_to_status_id tweet_u = api.get_status(status_id,tweet_mode='extended')
Then you can now print out the text contained within the tweet.
After this basic process, the remaining process is similar to that of the Monitor bot, if the media files are required. For the code above we can just store the text in a database. And such a process will still be required to create another bot called popularly know has Unrollthread which will be discussed before the end of this article.
To download media data
Collecting tweet of a Monitored User
A Twitter bot can be created to always track twitter feeds from a particular set of users, this can help curate data to create a language model base on a specific data and for various NLP data analysis. In retrospect to the Monitor specific keyword bot created at first, but for this process instead of subscribing to a keyword we subscribe to a user using their user id.
In the code, I specify the user id, the user id can be retrieved by; e.g
api.get_user("@_mytwtbot").id #specify the user screen name you want//1138739106031308800
Hence, you will always be the first to get the tweet created by this user.
Unrolling Twitter thread into a text file.
You’ve heard the unrolled thread bot on twitter, to always create a pdf format of a thread. We will be creating that. that can also help gather data for your data science project. The process is still the same with the Mention bot. It makes use of the reply status id, and it uses a recursive function to get all the tweets in a thread.
Storing Data gathered in AWS s3
Now that we’ve have different approaches to collect data, we need to be able to store them. Aws s3 provides one of the quick and easy ways of storing media files online if you don’t have a storage services online.
First, you install aws sdk, which is provided via boto3 a python library
pip install boto3
Then for boto3 to work and connect to your aws resources, you need aws credentials which can be obtained by creating an iam user permission, which then can be stored, in your computer home directory
touch ~/.aws/credentials
Then in the credentials, we store the necessary info
[default]aws_access_key_id = YOUR_ACCESS_KEY_IDaws_secret_access_key = YOUR_SECRET_ACCESS_KEY
Now to obtain the access keys;
First, visit the aws console and enter the iam resources
Follow the pictures in order of how it is arranged from left to right to set up an iam on aws. Once this is done you can download the csv as seen in the last image above, copy the credentials in it and paste in the ~/.aws/credentials
Once this is done we go ahead to create a bucket in aws S3.
Click on create bucket to create a bucket to store your files.
Then specify the name, the region you want and then click on create hence your bucket is created.
Since the bucket is created, we can always make a call to it using boto3:
import boto3s3 = boto3.client("s3")s3.upload_file(path,"bucket_name","name_to_store_file")
This the basic function we will be using to store the files on s3. the upload_file method takes in the path of the file to be uploaded e.g /home/documents/bot/video.mp4 and the bucket_name is name of the bucket you created, then the third argument is the name you want to store the file as on s3.
So with a little bit of modification to our download_t.py we can save the file on aws s3
After the files are being uploaded it can be viewed by clicking on the bucket
Now everything is set, we can now create a docker image and then deploy to aws. Check the reference below to learn how to deploy to aws.
But just one little addition after you’ve learnt how to deploy to aws from the reference link, you add the aws credentials alongside with the environmental variable
The additional thing to add to this, in order to be able to save the media files to aws s3
-e aws_access_key_id="sjbkjgkjhfyfyjfyjyfj" \-e aws_secret_access_key="1124knlkhk45nklhl" \fav-retweet-bot
Now as a data scientist we’ve learned a way to gather data from twitter and create a bot. Check out this to learn how to create a twitter bot using deep learning.
Download the repo containing the code from github
REFERENCE
This post heavily depends on the work of some team from realpython.com check here to learn how to generate twitter api and how to deploy to aws . | [
{
"code": null,
"e": 247,
"s": 172,
"text": "Ever wonder how to create your @Getvideobot @threadreaderapp and the likes"
},
{
"code": null,
"e": 453,
"s": 247,
"text": "Twitter is one of the most widely used social platforms. It’s used by individuals and organizations. It serves as a large pool of information for those whose information (data) drives their lives and work."
},
{
"code": null,
"e": 713,
"s": 453,
"text": "The existence of twitter API has provided unlimited creative access to the information shared and provided on the platform, due to this, different twitter bot has being created for a different purpose, and it has helped make twitter more of a better platform."
},
{
"code": null,
"e": 866,
"s": 713,
"text": "Going further than just making twitter platform interesting with the use of these bots, it can serve as a means to crowdsource data for data scientists."
},
{
"code": null,
"e": 1002,
"s": 866,
"text": "In this article we will be learning how to create different twitter bot to crowdsource data for your data science project, like how to:"
},
{
"code": null,
"e": 1223,
"s": 1002,
"text": "download images and videos by monitoring specific keywords.download media data by being referenced in a tweet.collecting tweet of a monitored user.Unrolling twitter thread in to a text file.storing data gather in aws s3."
},
{
"code": null,
"e": 1283,
"s": 1223,
"text": "download images and videos by monitoring specific keywords."
},
{
"code": null,
"e": 1335,
"s": 1283,
"text": "download media data by being referenced in a tweet."
},
{
"code": null,
"e": 1373,
"s": 1335,
"text": "collecting tweet of a monitored user."
},
{
"code": null,
"e": 1417,
"s": 1373,
"text": "Unrolling twitter thread in to a text file."
},
{
"code": null,
"e": 1448,
"s": 1417,
"text": "storing data gather in aws s3."
},
{
"code": null,
"e": 1645,
"s": 1448,
"text": "These various processes can help crowdsource data not just for NLP, but also for computer vision( since most people think twitter is most best for collecting data for Natural language processing)."
},
{
"code": null,
"e": 2025,
"s": 1645,
"text": "In this article, I will assume you have Twitter API Authentication Credentials and also know how to use Tweepy. If not, check the reference below on how to obtain twitter API credentials and how to install tweepy and gain a little bit of introduction to it. But I will advise you follow through the article first, just to gain the application view, then go back to the reference."
},
{
"code": null,
"e": 2174,
"s": 2025,
"text": "Provided you have the twitter API credentials, the first thing to do is to create a config file, which sets up your authentication with twitter API."
},
{
"code": null,
"e": 2477,
"s": 2174,
"text": "A call to the function helps checks if the authentication is valid. You can replace the os.getenv() with the api keys directly, or you store the api key in your environment . The wait_on_rate_limit and wait_on_rate_limit_notify helps tweepy wait and print out a message when the rate limit is exceeded."
},
{
"code": null,
"e": 2529,
"s": 2477,
"text": "Download Media Data by Monitoring Specific Keywords"
},
{
"code": null,
"e": 2930,
"s": 2529,
"text": "Data collection is the backbone of every data-driven project. The type of data being collected depends on the type of project being done. For example, for a computer vision project, it requires images or videos. Twitter can serve as a platform to curate such data in different ways. And one of the ways is monitoring a particular set of keywords related to the type of data you want for your project."
},
{
"code": null,
"e": 3069,
"s": 2930,
"text": "Let say you want to curate or gather data, involving Trump, a twitter bot can be created to always listen to every tweet mentioning Trump."
},
{
"code": null,
"e": 3521,
"s": 3069,
"text": "The Monitor bot is created using Twitter Stream service api interfaced by tweepy. This helps the bot to keep listen to different tweets across the Twitter platform. The Monitor class inherit from the tweepy.StreamListener and it contains two methods; on_status this helps to pass in the tweet and do whatever we want with the tweet passed in and on_error provide the actionable point in case an error is being encountered during the on_status process."
},
{
"code": null,
"e": 3794,
"s": 3521,
"text": "The tweet passed in on_status contains the JSON attribute of each tweet. Since in this example we need the media data. The json element of the tweet contains what will be called entities and the entities contain the media files and the embedded url in a tweet. For example"
},
{
"code": null,
"e": 4718,
"s": 3794,
"text": "{u'hashtags': [{u'indices': [0, 12], u'text': u'NeurIPS2019'}], u'media': [{u'display_url': u'pic.twitter.com/GjpvEte86u', u'expanded_url': u'https://twitter.com/doomie/status/1206025007261876226/photo/1', u'features': {u'large': {u'faces': []}, u'medium': {u'faces': []}, u'orig': {u'faces': []}, u'small': {u'faces': []}}, u'id': 1206024997262618626, u'id_str': u'1206024997262618626', u'indices': [278, 301], u'media_url': u'http://pbs.twimg.com/media/ELypWGAUcAIpNTu.jpg', u'media_url_https': u'https://pbs.twimg.com/media/ELypWGAUcAIpNTu.jpg', u'sizes': {u'large': {u'h': 1536, u'resize': u'fit', u'w': 2048}, u'medium': {u'h': 900, u'resize': u'fit', u'w': 1200}, u'small': {u'h': 510, u'resize': u'fit', u'w': 680}, u'thumb': {u'h': 150, u'resize': u'crop', u'w': 150}}, u'type': u'photo', u'url': u'https://t.co/GjpvEte86u'}], u'symbols': [], u'urls': [], u'user_mentions': []}"
},
{
"code": null,
"e": 5182,
"s": 4718,
"text": "the tweet.entities contains this keys and value items. since we will need the media files. For the image file, the media_url will be used to download the image in a tweet. and for the videos uploaded in the tweet will be downloaded using the expanded_url and for the videos embedded through a url, such as youtube videos. will be extracted from the urls , but in this tweet, it contains no urls, that's why the array is empty. But for a tweet which contains a url"
},
{
"code": null,
"e": 5240,
"s": 5182,
"text": "{ .... u'urls': [{...,u'expanded_url':'youtube.com?...}]"
},
{
"code": null,
"e": 5310,
"s": 5240,
"text": "Hence the video is downloaded by parsing in urls[0]['expanded_url'] ."
},
{
"code": null,
"e": 5861,
"s": 5310,
"text": "Various python libraries or modules have been created to make the downloading of images and videos easy. To download images, a python package called wget is used. For youtube video download pytube is used and for twitter videos, twitter_dl is used. All of these libraries are great libraries, they make it easier to build this project. But for twitter-dl and pytube i make some changes to them due to the error I was encountering, but i think the new update should resolve that. So you can check my github to download them if you encounter any error."
},
{
"code": null,
"e": 5938,
"s": 5861,
"text": "To download these media files, we combine these libraries into a single file"
},
{
"code": null,
"e": 6015,
"s": 5938,
"text": "Now we can combine this with the Monitor.py to start downloading media files"
},
{
"code": null,
"e": 6068,
"s": 6015,
"text": "Download Media file When being Referenced to a Tweet"
},
{
"code": null,
"e": 6486,
"s": 6068,
"text": "Sometimes instead of trying to monitor a specific keyword, we can let others help crowdsource data for us on twitter. The method involves letting people reference your twitter name under the tweet that contains the kind of data you want. The process is similar to that of the monitoring process just that we won’t be using streaming api, and it does not listen to all tweets except the one you are being mentioned in."
},
{
"code": null,
"e": 6858,
"s": 6486,
"text": "The mention function makes use of the api.mention , to fetch all the tweet you are being mentioned in. To prevent the api.Cursor from fetching all the tweets you are being mentioned in, since the time you join twitter, we use the since_id . To make sure it keeps fetching the newly tweet you are being mentioned in. First, we get the id of the tweet of your last mention."
},
{
"code": null,
"e": 7001,
"s": 6858,
"text": "tweety = []for tweet in tweepy.Cursor(api.mentions_timeline).items(): if len(tweety) > 1: break else: tweety.append(tweet)"
},
{
"code": null,
"e": 7143,
"s": 7001,
"text": "And since the tweet is being fetched based on the newly created tweet. we only need that and then we index tweety to get the id of the tweet."
},
{
"code": null,
"e": 7184,
"s": 7143,
"text": "tweety[0].idoutput[]:1208298926627074049"
},
{
"code": null,
"e": 7413,
"s": 7184,
"text": "And in mention() in the above code palette, we make use of max(tweet.id,new_since_id) This is used since for each new tweet, the id is always greater than the tweet id before it. that is new tweet id is higher than old tweet id."
},
{
"code": null,
"e": 7708,
"s": 7413,
"text": "Don’t forget that the tweet collected are not just text but json element, containing tweet attribute. For this bot, you are being referenced to a tweet, via a comment section. The main content you want is in the tweet the user reference you in via a comment. So the user is replying to a tweet."
},
{
"code": null,
"e": 8050,
"s": 7708,
"text": "In the tweet json element, it is possible to extract the id of the tweet the user replied to. We call this id in_reply_to_status_id. When a user is not replying to a tweet, the id is usually None . To create the bot, we first check if the reply status id is not None, then we process the tweet. Then we get the tweet from the status id using"
},
{
"code": null,
"e": 8182,
"s": 8050,
"text": "status_id = tweet.in_reply_to_status_id tweet_u = api.get_status(status_id,tweet_mode='extended')"
},
{
"code": null,
"e": 8246,
"s": 8182,
"text": "Then you can now print out the text contained within the tweet."
},
{
"code": null,
"e": 8586,
"s": 8246,
"text": "After this basic process, the remaining process is similar to that of the Monitor bot, if the media files are required. For the code above we can just store the text in a database. And such a process will still be required to create another bot called popularly know has Unrollthread which will be discussed before the end of this article."
},
{
"code": null,
"e": 8609,
"s": 8586,
"text": "To download media data"
},
{
"code": null,
"e": 8646,
"s": 8609,
"text": "Collecting tweet of a Monitored User"
},
{
"code": null,
"e": 9018,
"s": 8646,
"text": "A Twitter bot can be created to always track twitter feeds from a particular set of users, this can help curate data to create a language model base on a specific data and for various NLP data analysis. In retrospect to the Monitor specific keyword bot created at first, but for this process instead of subscribing to a keyword we subscribe to a user using their user id."
},
{
"code": null,
"e": 9091,
"s": 9018,
"text": "In the code, I specify the user id, the user id can be retrieved by; e.g"
},
{
"code": null,
"e": 9181,
"s": 9091,
"text": "api.get_user(\"@_mytwtbot\").id #specify the user screen name you want//1138739106031308800"
},
{
"code": null,
"e": 9256,
"s": 9181,
"text": "Hence, you will always be the first to get the tweet created by this user."
},
{
"code": null,
"e": 9299,
"s": 9256,
"text": "Unrolling Twitter thread into a text file."
},
{
"code": null,
"e": 9636,
"s": 9299,
"text": "You’ve heard the unrolled thread bot on twitter, to always create a pdf format of a thread. We will be creating that. that can also help gather data for your data science project. The process is still the same with the Mention bot. It makes use of the reply status id, and it uses a recursive function to get all the tweets in a thread."
},
{
"code": null,
"e": 9668,
"s": 9636,
"text": "Storing Data gathered in AWS s3"
},
{
"code": null,
"e": 9882,
"s": 9668,
"text": "Now that we’ve have different approaches to collect data, we need to be able to store them. Aws s3 provides one of the quick and easy ways of storing media files online if you don’t have a storage services online."
},
{
"code": null,
"e": 9955,
"s": 9882,
"text": "First, you install aws sdk, which is provided via boto3 a python library"
},
{
"code": null,
"e": 9973,
"s": 9955,
"text": "pip install boto3"
},
{
"code": null,
"e": 10172,
"s": 9973,
"text": "Then for boto3 to work and connect to your aws resources, you need aws credentials which can be obtained by creating an iam user permission, which then can be stored, in your computer home directory"
},
{
"code": null,
"e": 10197,
"s": 10172,
"text": "touch ~/.aws/credentials"
},
{
"code": null,
"e": 10250,
"s": 10197,
"text": "Then in the credentials, we store the necessary info"
},
{
"code": null,
"e": 10344,
"s": 10250,
"text": "[default]aws_access_key_id = YOUR_ACCESS_KEY_IDaws_secret_access_key = YOUR_SECRET_ACCESS_KEY"
},
{
"code": null,
"e": 10375,
"s": 10344,
"text": "Now to obtain the access keys;"
},
{
"code": null,
"e": 10432,
"s": 10375,
"text": "First, visit the aws console and enter the iam resources"
},
{
"code": null,
"e": 10666,
"s": 10432,
"text": "Follow the pictures in order of how it is arranged from left to right to set up an iam on aws. Once this is done you can download the csv as seen in the last image above, copy the credentials in it and paste in the ~/.aws/credentials"
},
{
"code": null,
"e": 10726,
"s": 10666,
"text": "Once this is done we go ahead to create a bucket in aws S3."
},
{
"code": null,
"e": 10789,
"s": 10726,
"text": "Click on create bucket to create a bucket to store your files."
},
{
"code": null,
"e": 10887,
"s": 10789,
"text": "Then specify the name, the region you want and then click on create hence your bucket is created."
},
{
"code": null,
"e": 10961,
"s": 10887,
"text": "Since the bucket is created, we can always make a call to it using boto3:"
},
{
"code": null,
"e": 11052,
"s": 10961,
"text": "import boto3s3 = boto3.client(\"s3\")s3.upload_file(path,\"bucket_name\",\"name_to_store_file\")"
},
{
"code": null,
"e": 11349,
"s": 11052,
"text": "This the basic function we will be using to store the files on s3. the upload_file method takes in the path of the file to be uploaded e.g /home/documents/bot/video.mp4 and the bucket_name is name of the bucket you created, then the third argument is the name you want to store the file as on s3."
},
{
"code": null,
"e": 11438,
"s": 11349,
"text": "So with a little bit of modification to our download_t.py we can save the file on aws s3"
},
{
"code": null,
"e": 11516,
"s": 11438,
"text": "After the files are being uploaded it can be viewed by clicking on the bucket"
},
{
"code": null,
"e": 11653,
"s": 11516,
"text": "Now everything is set, we can now create a docker image and then deploy to aws. Check the reference below to learn how to deploy to aws."
},
{
"code": null,
"e": 11818,
"s": 11653,
"text": "But just one little addition after you’ve learnt how to deploy to aws from the reference link, you add the aws credentials alongside with the environmental variable"
},
{
"code": null,
"e": 11909,
"s": 11818,
"text": "The additional thing to add to this, in order to be able to save the media files to aws s3"
},
{
"code": null,
"e": 12016,
"s": 11909,
"text": "-e aws_access_key_id=\"sjbkjgkjhfyfyjfyjyfj\" \\-e aws_secret_access_key=\"1124knlkhk45nklhl\" \\fav-retweet-bot"
},
{
"code": null,
"e": 12179,
"s": 12016,
"text": "Now as a data scientist we’ve learned a way to gather data from twitter and create a bot. Check out this to learn how to create a twitter bot using deep learning."
},
{
"code": null,
"e": 12229,
"s": 12179,
"text": "Download the repo containing the code from github"
},
{
"code": null,
"e": 12239,
"s": 12229,
"text": "REFERENCE"
}
] |
E-Mail Sentiment Analysis Using Python and Microsoft Azure — Part 1 | by Ben Prescott | Towards Data Science | What does our e-mail Sent Items folder say about our demeanor? Can we use this and other complementary data to possibly determine trends in happiness or sadness at work?
This is Part 1 of a multi-part article.
Admitting right off the bat, I’ll consider myself a “noob” when it comes to most things data related. I have a pretty extensive history in traditional datacenter and cloud infrastructure, but pretty fresh to working with data. Kaggle has pretty much been my best friend over the last 12 months.
With that said, I’ve been engulfing myself in as many studies as possible around where my skills are lacking — calculus refreshers, statistics, coding, data engineering concepts, etc. I’d like to think that one of the best ways to learn is to do, but to also document the process as I’m experiencing it. Also, making sure to keep it fun!
I have also included a link to the Notebook that I created while writing this story. Feel free to use and modify as you see fit!
For those of us who use e-mail regularly, we’ve all sent snarky emails a few times, or many times...or maybe every day.
“Per my last email...”
“Going forward, I would suggest...”
“This is complete and utter s**t!”
Do these look vaguely familiar? For many, it’s easy to either intentionally or unintentionally display your current state of emotion through email. You might be growing tired of having to explain the same situation multiple times, maybe your e-mail is a reflection of your increasing burnout, or maybe your car died this morning and you’re just having a bad day.
No matter what the cause, the history of our e-mails could actually provide a useful view into our attitude within an organization.
The remainder of this article will be focused on leveraging Jupyter Notebooks, the Microsoft Azure Text Analytics API to provide the horsepower, and using Python to explore, clean and present the sentiment analysis results.
Of course, I’ll also be blurring or sanitizing certain data just to make sure I still have a job after this. :)
The core environment will consist of the following:
Outlook Sent Items CSV Export
Azure Text Analytics API
Azure Notebooks (Jupyter Notebook)
For Python specifically, we’ll be using the following packages:
Numpy
Pandas
MatPlotLib
Azure AI Text Analytics
Now that we understand the basics of the tools we’ll be using, lets get to building!
We first need to deploy an API instance for us to target in the remainder of this article. Navigate to https://portal.azure.com and sign in. If you don’t have an account you can access free trials/credits by creating a subscription using one of the following:
Azure Pass: https://www.microsoftazurepass.com/
VS Dev Essentials: https://visualstudio.microsoft.com/dev-essentials/
Once we’re logged in we’ll need to search for Text Analytics API.
Click Create a resource.
Type Text Analytics. Hit enter.
Click Create.
Next, we need to enter details about the service and its pricing tier. Type a Name, Subscription (if you have more than 1 active), Location (would recommend picking one close to you), Pricing Tier (F0 is free and works fine for this), and a Resource Group for it to live in. If you don’t have one, click Create New and give it a name.
Once deployed, select All Resources from the left and click on your API resource. Then, click on Keys and Endpoint and copy the Endpoint and Key1 into a notepad or something for later use.
The next step is to grab a CSV export of your e-mail Sent Items. Considering we’re looking for our own personal sentiment scores, we’re only going to be concerned with our Sent Items.
Open Outlook
File → Open & Export → Import/Export
Export to a file
Comma Separated Values (CSV)
Select your Sent Items folder
Select an export location
Finish the export
Now that we have our CSV we need to start writing our code to explore and prepare our data for analysis. I would strongly recommend not opening the .csv file in Excel, as many of us refuse to organize or keep our mailbox clean. Instead, we’ll stick with loading it into a Pandas DataFrame.
We need to create a new Jupyter Notebook to work out of. I just called mine something simple like EmailSentiment.ipynb for now. If you don’t have Jupyter installed, and don’t want to use a hosted version, I would strongly suggest checking out Anaconda for a well-rounded package.
Now that we have our notebook we need to install the Azure Text Analytics API package for Python (if you don’t already have it).
!pip install azure-ai-textanalytics
We’re going to assume our dev environment already has Pandas and Numpy installed (both Anaconda and Azure Notebooks come with them available).
We can then continue to import the necessary packages. We’re also going to assign our Azure Text Analytics API key and endpoint information (from Step 1) into this cell.
import pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom matplotlib.pyplot import figurefrom azure.ai.textanalytics import TextAnalyticsClientfrom azure.core.credentials import AzureKeyCredential#Key and enpoint from Azure Text Analytics API servicekey = "f7c7c91cd70e493ea38521d1cbf698aa"endpoint = "https://mediumapi.cognitiveservices.azure.com/"
We also need to define some functions we’re going to use later in our notebook. For organization sake, I just added both to a cell so they’re in the same location in the notebook.
We need one function to provide authentication for the Text Analytics API, as well as one for the core sentiment analysis. We’re following code from the following Quickstart in the Microsoft documentation but will make some modifications to the core function to fit our specific needs.
While the auth function is straight forward, we need to modify the sentiment analysis function to iterate over a list of lists (compared to a single hard-coded string), only retrieving the overall score(we’ll explore sentiment score ranges in the next post), and incrementing a frequency table we’ll create later.
#Creating the Azure authentication functiondef authenticate_client(): ta_credential = AzureKeyCredential(key) text_analytics_client = TextAnalyticsClient(endpoint=endpoint, credential=ta_credential) return text_analytics_client#Core function for running sentiment analysis#Modified to fit our specific needs#Added global variables we'll use later in this notebookdef sentiment_analysis_example(client,list_name): global senti_results senti_results = {'Positive':0,'Neutral':0,'Negative':0,'Unknown':0} global senti_errors senti_errors = [] documents = list_name for row in documents: response = client.analyze_sentiment(documents = row)[0] try: if response.sentiment == "positive": senti_results['Positive'] += 1 elif response.sentiment == "neutral": senti_results['Neutral'] += 1 elif response.sentiment == "negative": senti_results['Negative'] +=1 else: senti_results['Unknown'] +=1 except: senti_errors.append(row) return(senti_results,senti_errors)#Assigning authentication function to objectclient = authenticate_client()
Now that we have our Azure API functions setup we’re ready to start exploring and preparing our dataset.
#Assign your filename to a variableemailFile = ‘BenSent.CSV’#Display the first 5 rows of our CSV to inspect#Notice encoding — this seemed to work for our CSVemail_data = pd.read_csv(emailFile,encoding=’ISO 8859–1')email_data.head()
If you run the above you should see something similar to the below output.
There are plenty of columns (useful or not) provided with the Outlook export, but you’ll find one critical data point missing — timestamps.
Unfortunately, Outlook doesn’t provide the ability to map the date/time property to the CSV export. For the sake of simplicity, we’re going to just analyze our dataset as a full batch. We’ll see how we can include dates in a follow-on post.
Based on the available data in this scenario, we’ll focus on what we’re saying to others in our e-mails and determining if it was a positive, neutral or negative sentiment overall. We’re going to need to create a separate object with just the content from the Body column. We’ll do this using Pandas.
#Assign Body column to new objectemail_body = email_data['Body']#Display top 5 rows and the overall length of the seriesprint(email_body.head())print('\n')print("Starting email count:",email_body.shape)
Here I’m using selection by column label considering we have those available to us. You can also use the column index, or whatever you prefer.
Now we can see we have just the body content, which is what we’ll use to perform sentiment analysis on. We’ll be closely monitoring the shape of our Series as we continue to clean this. We’re currently starting with 1675 rows.
Next, we’ll notice just from the first 5 rows that we have odd characters we don’t want to analyze, such as \ror \nand others. We’ll use a simple str.replace to remove these.
#Removing \r and \n characters from stringsemail_body = email_body.str.replace("\r","")email_body = email_body.str.replace("\n","")#Display top 5 rows and the overall length of the seriesprint(email_body.head())print('\n')print("Current e-mail count:",email_body.shape)
Next, we’re going to remove forwarded or trailing email threads where we don’t want to analyze a full email thread. An example is row index 3 where we see a date trailing my response in an e-mail thread.
I’ll clean these trailing e-mails by using what I know is automatically added to every sent item - my signature block. Using this as the target we can partition the data based on an identifying signature word(s) and trailing message into separate columns.
#Removing trailing email threads after start of my email signaturesplit_df = email_body.str.partition("Regards")print(split_df[0:3])print('\n')print("Current e-mail count:",split_df.shape)
From the shape and output, we can now see we have 3 different partitioned columns — one for the email body content, one for the identified signature block word (“Regards” in my case) and one for the trailing message.
We now need to drop these additional columns and focus back on our body text. We’re also going to remove rows that are identified to have no information.
#Removing extra fluff from partitioningclean_col = split_df.drop(columns=[1,2]) #1 contains "Regards", 2 contains trailing text#Removing rows with NaN - no dataclean_nan = clean_col.dropna()print("E-mail count before NaN removal:",clean_col.shape[0]) #Display before NaN removalprint("E-mail count after NaN removal:",clean_nan.shape[0]) #Display before NaN removal
We can see before partitioning we had 1,675 rows. We dropped the two columns containing the fluff including and after my signature. After removing rows with NaN we are down to 1,642 emails. We need to continue cleaning by removing PTO emails and forwarded message emails. We’ll also add a column name to our body text column.
#Updating the primary column with name EmailBodyclean_nan = clean_nan.rename(columns={0:"EmailBody"})#Remove emails with default out of office replyclean_pto = clean_nan[~clean_nan.EmailBody.str.contains("Hello,I am currently")]#Remove emails with a forwarded messagecleaned_df = clean_pto[~clean_pto.EmailBody.str.contains("---------- Forwarded message ---------")]print("E-mail count before removals:",clean_nan.shape[0]) #Pre PTO countprint("E-mail count after removing PTO messages:",clean_pto.shape[0]) #Post PTO countprint("E-mail count after also removing forwarded messages:",cleaned_df.shape[0]) #Post fwd removal
After checking the shape we can see we went from 1,642 rows to 1,460 rows, then finally to 1,399 rows. Keep in mind, we’re cleaning all of this to make sure our sentiment analysis returns as accurate information as possible.
If we print the cleaned_df Series we’ll see that we have rows that look to be empty. We need to make sure we remove those so that our analysis doesn’t error out. We’ll do this by using Pandas' df.replace and replace empty data with NaN.
#Considering we know we still have rows with no data, we'll replace the empty space with NaN#We can see all visible rows with nothing now show NaNcleaned_df['EmailBody'].replace(" ",np.nan,inplace=True)print(cleaned_df)
Now our empty rows will show NaN. We can now drop those rows by using pd.dropna() .
#We can now find all rows with NaN and drop them using pd.dropnacleaned_df = cleaned_df.dropna()print(cleaned_df)print('\n')print("E-mail count after dropping empty rows/rows with NaN:",cleaned_df.shape)
After removing our NaN rows were down to 1,288 rows. Feel free to continue exploring your data further to make sure you don’t have additional fluff that should be removed. While this won’t be perfect, we do want the results to be as legitimate as possible.
As for the last step, we’re going to convert our DataFrame into a list of lists that contains strings. We’ll use this to send to our API and return our results.
#Create an empty list to store values#Iterate over each row in the dataframe and append it to the listsenti_list = []for row in range((cleaned_df.shape[0])): senti_list.append(list(cleaned_df.iloc[row,:])) #Length of list matches length of old df print("E-mail count before error removal, ready for analysis:",len(senti_list))
We can print the length of the list of lists to make sure that it matches our DataFrame row count, which it does.
Now that we have a list of “meh, I kind of cleaned it” data, we can start to send the data to our Azure API, retrieve the results, and visualize our data.
We’re going to provide our newly created list as our list_name argument in our core sentiment analysis function. The function is written in a way to provide not just a frequency table of results, but also a list containing the rows themselves that may contain errors when analyzing.
This next part may take a while depending on how many rows are being sent to the API. You may also find yourself having to scale your API service. If that is the case I would suggest trimming your list down for practice purposes.
#Trigger the sentiment analysis function, passing in our list of listssentiment = sentiment_analysis_example(client,senti_list)
Once this is completed we can review the initial results.
print(senti_results)print("\n")print("Sentiment errors:",senti_errors)print("Error count:",len(senti_errors))
We can see two main things here: the overall sentiment results for our data and the rows that errored out when being analyzed. We can see we have a total of 11 rows not being analyzed and it seems to be because of varying white spaces.
We need to iterate over this list, iterate over our original dataset list of lists, and remove all lists containing these. We’ll also make a copy of our list of lists just so we have the historical version in case we need it in the future.
#Removing the errors from our list of lists#Assigning to a new variable so we have the unmodified originalsenti_cleaned = senti_listfor i in senti_errors: for row in senti_cleaned: if i == row: senti_cleaned.remove(row) print("E-mail count after removing error rows. Final used for analysis:",len(senti_cleaned))
We can see we’re down exactly 11 rows, which matches the count of errors. We can now re-run the analysis on our data copy to make sure we have no other errors.
#Triggering next run of analysis on the final datasetsentiment = sentiment_analysis_example(client,senti_cleaned)#Displaying the sentiment analysis resultsprint(senti_results)print("\n")print("Sentiment errors:",senti_errors)print("Error count:",len(senti_errors))
Reviewing the output we can verify we have no more errors (your mileage may vary) and are ready to move on to plotting our results.
Now that we have our results in a nice dictionary we can work on plotting them into nice graphs. For this article, we’ll be focused on two views: overall sentiment percentage by result and e-mail count of each sentiment type.
To do this we’re going to use the matplotlib.pyplotlibrary. We’ll be creating both a pie chart (to visualize the percentages) and a bar chart (to visualize the e-mail count by result). We’ll also do some formatting changes to the plots before showing them, such as: color changes, font changes, padding/spacing, display sizes, etc.
#Setting our Key/Value pairs from our resultskeys = senti_results.keys()values = senti_results.values()#Establishing some format changes for our chartsfigure(num=None, figsize=(8,8),dpi=80)colors = ['seagreen','lightsteelblue','indianred','silver']explode = (0.1, 0, 0, 0)plt.rcParams.update({'font.size': 12})#Creating the first plot (pie chart)plt.subplot(221)plt.pie(values,labels=keys,colors=colors, explode=explode,autopct='%1.1f%%',shadow=True,startangle=90)plt.title('Overall Sentiment Against 1,277 E-mails, by Percentage',bbox={'facecolor':'1','pad':8},y=1.10)#Creating the second plot (bar chart)plt.subplot(222)plt.title('E-mail Count by Sentiment Result',bbox={'facecolor':'1','pad':8},y=1.10)plt.bar(keys,values,width=.8,color=colors)#Adjusting the spacing/padding between subplotsplt.subplots_adjust(left=0.125, bottom=0.1, right=1.8, top=1.3, wspace=0.2, hspace=0.2)#Displaying the plotsplt.show()
Now we can see we have a nice visual representation of our data! While we still have a bunch of “Unknown” response types from our API, we can tell that overall we aren’t as negative in our responses as we may have thought.
In some follow-on posts, we’ll look to break out each e-mails individual rating scores for each category and group them. We’ll also look to bring in some other data to compare/contrast with what we’ve found so far.
Hopefully, this post was useful or fun and you learned something along the way. Keep in mind, I’m very new to this and would definitely appreciate your feedback! | [
{
"code": null,
"e": 341,
"s": 171,
"text": "What does our e-mail Sent Items folder say about our demeanor? Can we use this and other complementary data to possibly determine trends in happiness or sadness at work?"
},
{
"code": null,
"e": 381,
"s": 341,
"text": "This is Part 1 of a multi-part article."
},
{
"code": null,
"e": 676,
"s": 381,
"text": "Admitting right off the bat, I’ll consider myself a “noob” when it comes to most things data related. I have a pretty extensive history in traditional datacenter and cloud infrastructure, but pretty fresh to working with data. Kaggle has pretty much been my best friend over the last 12 months."
},
{
"code": null,
"e": 1014,
"s": 676,
"text": "With that said, I’ve been engulfing myself in as many studies as possible around where my skills are lacking — calculus refreshers, statistics, coding, data engineering concepts, etc. I’d like to think that one of the best ways to learn is to do, but to also document the process as I’m experiencing it. Also, making sure to keep it fun!"
},
{
"code": null,
"e": 1143,
"s": 1014,
"text": "I have also included a link to the Notebook that I created while writing this story. Feel free to use and modify as you see fit!"
},
{
"code": null,
"e": 1263,
"s": 1143,
"text": "For those of us who use e-mail regularly, we’ve all sent snarky emails a few times, or many times...or maybe every day."
},
{
"code": null,
"e": 1286,
"s": 1263,
"text": "“Per my last email...”"
},
{
"code": null,
"e": 1322,
"s": 1286,
"text": "“Going forward, I would suggest...”"
},
{
"code": null,
"e": 1357,
"s": 1322,
"text": "“This is complete and utter s**t!”"
},
{
"code": null,
"e": 1720,
"s": 1357,
"text": "Do these look vaguely familiar? For many, it’s easy to either intentionally or unintentionally display your current state of emotion through email. You might be growing tired of having to explain the same situation multiple times, maybe your e-mail is a reflection of your increasing burnout, or maybe your car died this morning and you’re just having a bad day."
},
{
"code": null,
"e": 1852,
"s": 1720,
"text": "No matter what the cause, the history of our e-mails could actually provide a useful view into our attitude within an organization."
},
{
"code": null,
"e": 2076,
"s": 1852,
"text": "The remainder of this article will be focused on leveraging Jupyter Notebooks, the Microsoft Azure Text Analytics API to provide the horsepower, and using Python to explore, clean and present the sentiment analysis results."
},
{
"code": null,
"e": 2188,
"s": 2076,
"text": "Of course, I’ll also be blurring or sanitizing certain data just to make sure I still have a job after this. :)"
},
{
"code": null,
"e": 2240,
"s": 2188,
"text": "The core environment will consist of the following:"
},
{
"code": null,
"e": 2270,
"s": 2240,
"text": "Outlook Sent Items CSV Export"
},
{
"code": null,
"e": 2295,
"s": 2270,
"text": "Azure Text Analytics API"
},
{
"code": null,
"e": 2330,
"s": 2295,
"text": "Azure Notebooks (Jupyter Notebook)"
},
{
"code": null,
"e": 2394,
"s": 2330,
"text": "For Python specifically, we’ll be using the following packages:"
},
{
"code": null,
"e": 2400,
"s": 2394,
"text": "Numpy"
},
{
"code": null,
"e": 2407,
"s": 2400,
"text": "Pandas"
},
{
"code": null,
"e": 2418,
"s": 2407,
"text": "MatPlotLib"
},
{
"code": null,
"e": 2442,
"s": 2418,
"text": "Azure AI Text Analytics"
},
{
"code": null,
"e": 2527,
"s": 2442,
"text": "Now that we understand the basics of the tools we’ll be using, lets get to building!"
},
{
"code": null,
"e": 2787,
"s": 2527,
"text": "We first need to deploy an API instance for us to target in the remainder of this article. Navigate to https://portal.azure.com and sign in. If you don’t have an account you can access free trials/credits by creating a subscription using one of the following:"
},
{
"code": null,
"e": 2835,
"s": 2787,
"text": "Azure Pass: https://www.microsoftazurepass.com/"
},
{
"code": null,
"e": 2905,
"s": 2835,
"text": "VS Dev Essentials: https://visualstudio.microsoft.com/dev-essentials/"
},
{
"code": null,
"e": 2971,
"s": 2905,
"text": "Once we’re logged in we’ll need to search for Text Analytics API."
},
{
"code": null,
"e": 2996,
"s": 2971,
"text": "Click Create a resource."
},
{
"code": null,
"e": 3028,
"s": 2996,
"text": "Type Text Analytics. Hit enter."
},
{
"code": null,
"e": 3042,
"s": 3028,
"text": "Click Create."
},
{
"code": null,
"e": 3377,
"s": 3042,
"text": "Next, we need to enter details about the service and its pricing tier. Type a Name, Subscription (if you have more than 1 active), Location (would recommend picking one close to you), Pricing Tier (F0 is free and works fine for this), and a Resource Group for it to live in. If you don’t have one, click Create New and give it a name."
},
{
"code": null,
"e": 3566,
"s": 3377,
"text": "Once deployed, select All Resources from the left and click on your API resource. Then, click on Keys and Endpoint and copy the Endpoint and Key1 into a notepad or something for later use."
},
{
"code": null,
"e": 3750,
"s": 3566,
"text": "The next step is to grab a CSV export of your e-mail Sent Items. Considering we’re looking for our own personal sentiment scores, we’re only going to be concerned with our Sent Items."
},
{
"code": null,
"e": 3763,
"s": 3750,
"text": "Open Outlook"
},
{
"code": null,
"e": 3800,
"s": 3763,
"text": "File → Open & Export → Import/Export"
},
{
"code": null,
"e": 3817,
"s": 3800,
"text": "Export to a file"
},
{
"code": null,
"e": 3846,
"s": 3817,
"text": "Comma Separated Values (CSV)"
},
{
"code": null,
"e": 3876,
"s": 3846,
"text": "Select your Sent Items folder"
},
{
"code": null,
"e": 3902,
"s": 3876,
"text": "Select an export location"
},
{
"code": null,
"e": 3920,
"s": 3902,
"text": "Finish the export"
},
{
"code": null,
"e": 4210,
"s": 3920,
"text": "Now that we have our CSV we need to start writing our code to explore and prepare our data for analysis. I would strongly recommend not opening the .csv file in Excel, as many of us refuse to organize or keep our mailbox clean. Instead, we’ll stick with loading it into a Pandas DataFrame."
},
{
"code": null,
"e": 4490,
"s": 4210,
"text": "We need to create a new Jupyter Notebook to work out of. I just called mine something simple like EmailSentiment.ipynb for now. If you don’t have Jupyter installed, and don’t want to use a hosted version, I would strongly suggest checking out Anaconda for a well-rounded package."
},
{
"code": null,
"e": 4619,
"s": 4490,
"text": "Now that we have our notebook we need to install the Azure Text Analytics API package for Python (if you don’t already have it)."
},
{
"code": null,
"e": 4655,
"s": 4619,
"text": "!pip install azure-ai-textanalytics"
},
{
"code": null,
"e": 4798,
"s": 4655,
"text": "We’re going to assume our dev environment already has Pandas and Numpy installed (both Anaconda and Azure Notebooks come with them available)."
},
{
"code": null,
"e": 4968,
"s": 4798,
"text": "We can then continue to import the necessary packages. We’re also going to assign our Azure Text Analytics API key and endpoint information (from Step 1) into this cell."
},
{
"code": null,
"e": 5333,
"s": 4968,
"text": "import pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom matplotlib.pyplot import figurefrom azure.ai.textanalytics import TextAnalyticsClientfrom azure.core.credentials import AzureKeyCredential#Key and enpoint from Azure Text Analytics API servicekey = \"f7c7c91cd70e493ea38521d1cbf698aa\"endpoint = \"https://mediumapi.cognitiveservices.azure.com/\""
},
{
"code": null,
"e": 5513,
"s": 5333,
"text": "We also need to define some functions we’re going to use later in our notebook. For organization sake, I just added both to a cell so they’re in the same location in the notebook."
},
{
"code": null,
"e": 5799,
"s": 5513,
"text": "We need one function to provide authentication for the Text Analytics API, as well as one for the core sentiment analysis. We’re following code from the following Quickstart in the Microsoft documentation but will make some modifications to the core function to fit our specific needs."
},
{
"code": null,
"e": 6113,
"s": 5799,
"text": "While the auth function is straight forward, we need to modify the sentiment analysis function to iterate over a list of lists (compared to a single hard-coded string), only retrieving the overall score(we’ll explore sentiment score ranges in the next post), and incrementing a frequency table we’ll create later."
},
{
"code": null,
"e": 7308,
"s": 6113,
"text": "#Creating the Azure authentication functiondef authenticate_client(): ta_credential = AzureKeyCredential(key) text_analytics_client = TextAnalyticsClient(endpoint=endpoint, credential=ta_credential) return text_analytics_client#Core function for running sentiment analysis#Modified to fit our specific needs#Added global variables we'll use later in this notebookdef sentiment_analysis_example(client,list_name): global senti_results senti_results = {'Positive':0,'Neutral':0,'Negative':0,'Unknown':0} global senti_errors senti_errors = [] documents = list_name for row in documents: response = client.analyze_sentiment(documents = row)[0] try: if response.sentiment == \"positive\": senti_results['Positive'] += 1 elif response.sentiment == \"neutral\": senti_results['Neutral'] += 1 elif response.sentiment == \"negative\": senti_results['Negative'] +=1 else: senti_results['Unknown'] +=1 except: senti_errors.append(row) return(senti_results,senti_errors)#Assigning authentication function to objectclient = authenticate_client()"
},
{
"code": null,
"e": 7413,
"s": 7308,
"text": "Now that we have our Azure API functions setup we’re ready to start exploring and preparing our dataset."
},
{
"code": null,
"e": 7645,
"s": 7413,
"text": "#Assign your filename to a variableemailFile = ‘BenSent.CSV’#Display the first 5 rows of our CSV to inspect#Notice encoding — this seemed to work for our CSVemail_data = pd.read_csv(emailFile,encoding=’ISO 8859–1')email_data.head()"
},
{
"code": null,
"e": 7720,
"s": 7645,
"text": "If you run the above you should see something similar to the below output."
},
{
"code": null,
"e": 7860,
"s": 7720,
"text": "There are plenty of columns (useful or not) provided with the Outlook export, but you’ll find one critical data point missing — timestamps."
},
{
"code": null,
"e": 8101,
"s": 7860,
"text": "Unfortunately, Outlook doesn’t provide the ability to map the date/time property to the CSV export. For the sake of simplicity, we’re going to just analyze our dataset as a full batch. We’ll see how we can include dates in a follow-on post."
},
{
"code": null,
"e": 8402,
"s": 8101,
"text": "Based on the available data in this scenario, we’ll focus on what we’re saying to others in our e-mails and determining if it was a positive, neutral or negative sentiment overall. We’re going to need to create a separate object with just the content from the Body column. We’ll do this using Pandas."
},
{
"code": null,
"e": 8605,
"s": 8402,
"text": "#Assign Body column to new objectemail_body = email_data['Body']#Display top 5 rows and the overall length of the seriesprint(email_body.head())print('\\n')print(\"Starting email count:\",email_body.shape)"
},
{
"code": null,
"e": 8748,
"s": 8605,
"text": "Here I’m using selection by column label considering we have those available to us. You can also use the column index, or whatever you prefer."
},
{
"code": null,
"e": 8975,
"s": 8748,
"text": "Now we can see we have just the body content, which is what we’ll use to perform sentiment analysis on. We’ll be closely monitoring the shape of our Series as we continue to clean this. We’re currently starting with 1675 rows."
},
{
"code": null,
"e": 9150,
"s": 8975,
"text": "Next, we’ll notice just from the first 5 rows that we have odd characters we don’t want to analyze, such as \\ror \\nand others. We’ll use a simple str.replace to remove these."
},
{
"code": null,
"e": 9420,
"s": 9150,
"text": "#Removing \\r and \\n characters from stringsemail_body = email_body.str.replace(\"\\r\",\"\")email_body = email_body.str.replace(\"\\n\",\"\")#Display top 5 rows and the overall length of the seriesprint(email_body.head())print('\\n')print(\"Current e-mail count:\",email_body.shape)"
},
{
"code": null,
"e": 9624,
"s": 9420,
"text": "Next, we’re going to remove forwarded or trailing email threads where we don’t want to analyze a full email thread. An example is row index 3 where we see a date trailing my response in an e-mail thread."
},
{
"code": null,
"e": 9880,
"s": 9624,
"text": "I’ll clean these trailing e-mails by using what I know is automatically added to every sent item - my signature block. Using this as the target we can partition the data based on an identifying signature word(s) and trailing message into separate columns."
},
{
"code": null,
"e": 10069,
"s": 9880,
"text": "#Removing trailing email threads after start of my email signaturesplit_df = email_body.str.partition(\"Regards\")print(split_df[0:3])print('\\n')print(\"Current e-mail count:\",split_df.shape)"
},
{
"code": null,
"e": 10286,
"s": 10069,
"text": "From the shape and output, we can now see we have 3 different partitioned columns — one for the email body content, one for the identified signature block word (“Regards” in my case) and one for the trailing message."
},
{
"code": null,
"e": 10440,
"s": 10286,
"text": "We now need to drop these additional columns and focus back on our body text. We’re also going to remove rows that are identified to have no information."
},
{
"code": null,
"e": 10806,
"s": 10440,
"text": "#Removing extra fluff from partitioningclean_col = split_df.drop(columns=[1,2]) #1 contains \"Regards\", 2 contains trailing text#Removing rows with NaN - no dataclean_nan = clean_col.dropna()print(\"E-mail count before NaN removal:\",clean_col.shape[0]) #Display before NaN removalprint(\"E-mail count after NaN removal:\",clean_nan.shape[0]) #Display before NaN removal"
},
{
"code": null,
"e": 11132,
"s": 10806,
"text": "We can see before partitioning we had 1,675 rows. We dropped the two columns containing the fluff including and after my signature. After removing rows with NaN we are down to 1,642 emails. We need to continue cleaning by removing PTO emails and forwarded message emails. We’ll also add a column name to our body text column."
},
{
"code": null,
"e": 11755,
"s": 11132,
"text": "#Updating the primary column with name EmailBodyclean_nan = clean_nan.rename(columns={0:\"EmailBody\"})#Remove emails with default out of office replyclean_pto = clean_nan[~clean_nan.EmailBody.str.contains(\"Hello,I am currently\")]#Remove emails with a forwarded messagecleaned_df = clean_pto[~clean_pto.EmailBody.str.contains(\"---------- Forwarded message ---------\")]print(\"E-mail count before removals:\",clean_nan.shape[0]) #Pre PTO countprint(\"E-mail count after removing PTO messages:\",clean_pto.shape[0]) #Post PTO countprint(\"E-mail count after also removing forwarded messages:\",cleaned_df.shape[0]) #Post fwd removal"
},
{
"code": null,
"e": 11980,
"s": 11755,
"text": "After checking the shape we can see we went from 1,642 rows to 1,460 rows, then finally to 1,399 rows. Keep in mind, we’re cleaning all of this to make sure our sentiment analysis returns as accurate information as possible."
},
{
"code": null,
"e": 12217,
"s": 11980,
"text": "If we print the cleaned_df Series we’ll see that we have rows that look to be empty. We need to make sure we remove those so that our analysis doesn’t error out. We’ll do this by using Pandas' df.replace and replace empty data with NaN."
},
{
"code": null,
"e": 12437,
"s": 12217,
"text": "#Considering we know we still have rows with no data, we'll replace the empty space with NaN#We can see all visible rows with nothing now show NaNcleaned_df['EmailBody'].replace(\" \",np.nan,inplace=True)print(cleaned_df)"
},
{
"code": null,
"e": 12521,
"s": 12437,
"text": "Now our empty rows will show NaN. We can now drop those rows by using pd.dropna() ."
},
{
"code": null,
"e": 12725,
"s": 12521,
"text": "#We can now find all rows with NaN and drop them using pd.dropnacleaned_df = cleaned_df.dropna()print(cleaned_df)print('\\n')print(\"E-mail count after dropping empty rows/rows with NaN:\",cleaned_df.shape)"
},
{
"code": null,
"e": 12982,
"s": 12725,
"text": "After removing our NaN rows were down to 1,288 rows. Feel free to continue exploring your data further to make sure you don’t have additional fluff that should be removed. While this won’t be perfect, we do want the results to be as legitimate as possible."
},
{
"code": null,
"e": 13143,
"s": 12982,
"text": "As for the last step, we’re going to convert our DataFrame into a list of lists that contains strings. We’ll use this to send to our API and return our results."
},
{
"code": null,
"e": 13476,
"s": 13143,
"text": "#Create an empty list to store values#Iterate over each row in the dataframe and append it to the listsenti_list = []for row in range((cleaned_df.shape[0])): senti_list.append(list(cleaned_df.iloc[row,:])) #Length of list matches length of old df print(\"E-mail count before error removal, ready for analysis:\",len(senti_list))"
},
{
"code": null,
"e": 13590,
"s": 13476,
"text": "We can print the length of the list of lists to make sure that it matches our DataFrame row count, which it does."
},
{
"code": null,
"e": 13745,
"s": 13590,
"text": "Now that we have a list of “meh, I kind of cleaned it” data, we can start to send the data to our Azure API, retrieve the results, and visualize our data."
},
{
"code": null,
"e": 14028,
"s": 13745,
"text": "We’re going to provide our newly created list as our list_name argument in our core sentiment analysis function. The function is written in a way to provide not just a frequency table of results, but also a list containing the rows themselves that may contain errors when analyzing."
},
{
"code": null,
"e": 14258,
"s": 14028,
"text": "This next part may take a while depending on how many rows are being sent to the API. You may also find yourself having to scale your API service. If that is the case I would suggest trimming your list down for practice purposes."
},
{
"code": null,
"e": 14386,
"s": 14258,
"text": "#Trigger the sentiment analysis function, passing in our list of listssentiment = sentiment_analysis_example(client,senti_list)"
},
{
"code": null,
"e": 14444,
"s": 14386,
"text": "Once this is completed we can review the initial results."
},
{
"code": null,
"e": 14554,
"s": 14444,
"text": "print(senti_results)print(\"\\n\")print(\"Sentiment errors:\",senti_errors)print(\"Error count:\",len(senti_errors))"
},
{
"code": null,
"e": 14790,
"s": 14554,
"text": "We can see two main things here: the overall sentiment results for our data and the rows that errored out when being analyzed. We can see we have a total of 11 rows not being analyzed and it seems to be because of varying white spaces."
},
{
"code": null,
"e": 15030,
"s": 14790,
"text": "We need to iterate over this list, iterate over our original dataset list of lists, and remove all lists containing these. We’ll also make a copy of our list of lists just so we have the historical version in case we need it in the future."
},
{
"code": null,
"e": 15375,
"s": 15030,
"text": "#Removing the errors from our list of lists#Assigning to a new variable so we have the unmodified originalsenti_cleaned = senti_listfor i in senti_errors: for row in senti_cleaned: if i == row: senti_cleaned.remove(row) print(\"E-mail count after removing error rows. Final used for analysis:\",len(senti_cleaned))"
},
{
"code": null,
"e": 15535,
"s": 15375,
"text": "We can see we’re down exactly 11 rows, which matches the count of errors. We can now re-run the analysis on our data copy to make sure we have no other errors."
},
{
"code": null,
"e": 15800,
"s": 15535,
"text": "#Triggering next run of analysis on the final datasetsentiment = sentiment_analysis_example(client,senti_cleaned)#Displaying the sentiment analysis resultsprint(senti_results)print(\"\\n\")print(\"Sentiment errors:\",senti_errors)print(\"Error count:\",len(senti_errors))"
},
{
"code": null,
"e": 15932,
"s": 15800,
"text": "Reviewing the output we can verify we have no more errors (your mileage may vary) and are ready to move on to plotting our results."
},
{
"code": null,
"e": 16158,
"s": 15932,
"text": "Now that we have our results in a nice dictionary we can work on plotting them into nice graphs. For this article, we’ll be focused on two views: overall sentiment percentage by result and e-mail count of each sentiment type."
},
{
"code": null,
"e": 16490,
"s": 16158,
"text": "To do this we’re going to use the matplotlib.pyplotlibrary. We’ll be creating both a pie chart (to visualize the percentages) and a bar chart (to visualize the e-mail count by result). We’ll also do some formatting changes to the plots before showing them, such as: color changes, font changes, padding/spacing, display sizes, etc."
},
{
"code": null,
"e": 17403,
"s": 16490,
"text": "#Setting our Key/Value pairs from our resultskeys = senti_results.keys()values = senti_results.values()#Establishing some format changes for our chartsfigure(num=None, figsize=(8,8),dpi=80)colors = ['seagreen','lightsteelblue','indianred','silver']explode = (0.1, 0, 0, 0)plt.rcParams.update({'font.size': 12})#Creating the first plot (pie chart)plt.subplot(221)plt.pie(values,labels=keys,colors=colors, explode=explode,autopct='%1.1f%%',shadow=True,startangle=90)plt.title('Overall Sentiment Against 1,277 E-mails, by Percentage',bbox={'facecolor':'1','pad':8},y=1.10)#Creating the second plot (bar chart)plt.subplot(222)plt.title('E-mail Count by Sentiment Result',bbox={'facecolor':'1','pad':8},y=1.10)plt.bar(keys,values,width=.8,color=colors)#Adjusting the spacing/padding between subplotsplt.subplots_adjust(left=0.125, bottom=0.1, right=1.8, top=1.3, wspace=0.2, hspace=0.2)#Displaying the plotsplt.show()"
},
{
"code": null,
"e": 17626,
"s": 17403,
"text": "Now we can see we have a nice visual representation of our data! While we still have a bunch of “Unknown” response types from our API, we can tell that overall we aren’t as negative in our responses as we may have thought."
},
{
"code": null,
"e": 17841,
"s": 17626,
"text": "In some follow-on posts, we’ll look to break out each e-mails individual rating scores for each category and group them. We’ll also look to bring in some other data to compare/contrast with what we’ve found so far."
}
] |
How to Install Sublime Text Editor on Ubuntu | Sublime Text is a cross-platform source code editor with a Python application programming interface (API). It natively supports many programming languages and markup languages, and its functionality can be extended by users with plugins, typically community-built and maintained under free-software licenses.
This article describes “How to install Sublime Text Editor on Ubuntu”
Editing files side by side.
Editing files side by side.
It supported all Platforms.
It supported all Platforms.
It provides functionality to find and replace with regular expressions.
It provides functionality to find and replace with regular expressions.
The Command Palette gives fast access to functionality.
The Command Palette gives fast access to functionality.
“Goto Anything,” quick navigation to files, symbols, or lines.
“Goto Anything,” quick navigation to files, symbols, or lines.
Python-based plugin API.
Python-based plugin API.
Compatible with many language grammars from TextMate.
Compatible with many language grammars from TextMate.
There are two version’s of Sublime Text is available to install, To install Sublime 2, use the following commands –
$ sudo add-apt-repository ppa:webupd8team/sublime-text-2
The sample output should be like this –
Sublime Text 2 packages - the .deb will automatically download the latest build from http://www.sublimetext.com/dev or beta from http://www.sublimetext.com/2 (Adobe Flash Player installer - style).
More info and feedback:
http://www.webupd8.org/2011/03/sublime-text-2-ubuntu-ppa.html
http://www.webupd8.org/2012/03/sublime-text-2-ppa-separate-development.html
More info: https://launchpad.net/~webupd8team/+archive/ubuntu/sublime-text-2
Press [ENTER] to continue or ctrl-c to cancel adding it
gpg: keyring `/tmp/tmpsv1jnez9/secring.gpg' created
gpg: keyring `/tmp/tmpsv1jnez9/pubring.gpg' created
gpg: requesting key EEA14886 from hkp server keyserver.ubuntu.com
gpg: /tmp/tmpsv1jnez9/trustdb.gpg: trustdb created
gpg: key EEA14886: public key "Launchpad VLC" imported
gpg: no ultimately trusted keys found
gpg: Total number processed: 1
gpg: imported: 1 (RSA: 1)
OK
To update package index, use the following command-
$ sudo apt-get update
The sample output should be like this-
Ign http://dl.google.com stable InRelease
Hit http://dl.google.com stable Release.gpg
Hit http://dl.google.com stable Release
Ign http://extras.ubuntu.com trusty InRelease
Get:1 http://security.ubuntu.com trusty-security InRelease [65.9 kB]
Hit http://dl.google.com stable/main amd64 Packages
Hit http://extras.ubuntu.com trusty Release.gpg
Hit http://extras.ubuntu.com trusty Release
Hit http://extras.ubuntu.com trusty/main Sources
Get:2 http://security.ubuntu.com trusty-security/main Sources [109 kB]
Hit http://extras.ubuntu.com trusty/main amd64 Packages
Get:3 http://ppa.launchpad.net trusty InRelease [15.5 kB]
Hit http://extras.ubuntu.com trusty/main i386 Packages
Get:4 http://security.ubuntu.com trusty-security/restricted Sources [4,035 B]
Hit http://ppa.launchpad.net trusty InRelease
Get:5 http://security.ubuntu.com trusty-security/universe Sources [34.0 kB]
Ign http://ppa.launchpad.net trusty InRelease
Ign http://in.archive.ubuntu.com trusty InRelease
Hit http://ppa.launchpad.net trusty InRelease
Get:6 http://security.ubuntu.com trusty-security/multiverse Sources [2,750 B]
Ign http://ppa.launchpad.net trusty InRelease
Get:7 http://security.ubuntu.com trusty-security/main amd64 Packages [444 kB]
Ign http://ppa.launchpad.net trusty InRelease
Get:8 http://ppa.launchpad.net trusty/main amd64 Packages [739 B]
Get:9 http://ppa.launchpad.net trusty/main i386 Packages [753 B]
Get:10 http://ppa.launchpad.net trusty/main Translation-en [357 B]
Ign http://extras.ubuntu.com trusty/main Translation-en_IN
Hit http://ppa.launchpad.net trusty/main amd64 Packages
Get:11 http://in.archive.ubuntu.com trusty-updates InRelease [65.9 kB]
Ign http://extras.ubuntu.com trusty/main Translation-en
Hit http://ppa.launchpad.net trusty/main i386 Packages
Hit http://ppa.launchpad.net trusty/main Translation-en
Get:12 http://security.ubuntu.com trusty-security/restricted amd64 Packages [13.0 kB]
Hit http://ppa.launchpad.net trusty Release.gpg
Get:13 http://security.ubuntu.com trusty-security/universe amd64 Packages [125 kB]
Hit http://ppa.launchpad.net trusty/main amd64 Packages
Hit http://ppa.launchpad.net trusty/main i386 Packages
Hit http://ppa.launchpad.net trusty/main Translation-en
Get:14 http://security.ubuntu.com trusty-security/multiverse amd64 Packages [4,991 B]
Hit http://ppa.launchpad.net trusty Release.gpg
Get:15 http://security.ubuntu.com trusty-security/main i386 Packages [417 kB]
Get:16 http://ppa.launchpad.net trusty Release.gpg [316 B]
Hit http://ppa.launchpad.net trusty Release
................................................................
To install Sublime Text Editor, use the follwoing command –
$ sudo apt-get install sublime-text
The sample output should be like this –
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following packages were automatically installed and are no longer required:
gtk2-engines-pixbuf libbs2b0 libopusfile0 libpyside1.2 libqmmp-misc
libqmmpui0 libshiboken1.2 libsidplayfp libtidy-0.99-0 linux-headers-4.2.0-27
linux-headers-4.2.0-27-generic linux-image-4.2.0-27-generic
linux-image-extra-4.2.0-27-generic linux-signed-image-4.2.0-27-generic
php7.0-opcache python-beautifulsoup python-feedparser python-html2text
python-magic python-oauth2 python-pyside.qtcore python-pyside.qtgui
python-pyside.qtnetwork python-pyside.qtwebkit python-pysqlite2 python-regex
python-sqlalchemy python-sqlalchemy-ext python-support python-unity-singlet
python-utidylib
Use 'apt-get autoremove' to remove them.
The following NEW packages will be installed:
sublime-text
0 upgraded, 1 newly
To install sublime 3, use the following commands-
$ sudo add-apt-repository ppa:webupd8team/sublime-text-3
$ sudo apt-get update
$ sudo apt-get install sublime-text-installer
To open sublime, use the following command –
$ subl
The sample output should be like this –
Congratulations! Now, you know “How to Install Sublime Text Editor on Ubuntu ”. We’ll learn more about these types of commands in our next Linux post. Keep reading! | [
{
"code": null,
"e": 1371,
"s": 1062,
"text": "Sublime Text is a cross-platform source code editor with a Python application programming interface (API). It natively supports many programming languages and markup languages, and its functionality can be extended by users with plugins, typically community-built and maintained under free-software licenses."
},
{
"code": null,
"e": 1441,
"s": 1371,
"text": "This article describes “How to install Sublime Text Editor on Ubuntu”"
},
{
"code": null,
"e": 1469,
"s": 1441,
"text": "Editing files side by side."
},
{
"code": null,
"e": 1497,
"s": 1469,
"text": "Editing files side by side."
},
{
"code": null,
"e": 1525,
"s": 1497,
"text": "It supported all Platforms."
},
{
"code": null,
"e": 1553,
"s": 1525,
"text": "It supported all Platforms."
},
{
"code": null,
"e": 1625,
"s": 1553,
"text": "It provides functionality to find and replace with regular expressions."
},
{
"code": null,
"e": 1697,
"s": 1625,
"text": "It provides functionality to find and replace with regular expressions."
},
{
"code": null,
"e": 1753,
"s": 1697,
"text": "The Command Palette gives fast access to functionality."
},
{
"code": null,
"e": 1809,
"s": 1753,
"text": "The Command Palette gives fast access to functionality."
},
{
"code": null,
"e": 1872,
"s": 1809,
"text": "“Goto Anything,” quick navigation to files, symbols, or lines."
},
{
"code": null,
"e": 1935,
"s": 1872,
"text": "“Goto Anything,” quick navigation to files, symbols, or lines."
},
{
"code": null,
"e": 1960,
"s": 1935,
"text": "Python-based plugin API."
},
{
"code": null,
"e": 1985,
"s": 1960,
"text": "Python-based plugin API."
},
{
"code": null,
"e": 2039,
"s": 1985,
"text": "Compatible with many language grammars from TextMate."
},
{
"code": null,
"e": 2093,
"s": 2039,
"text": "Compatible with many language grammars from TextMate."
},
{
"code": null,
"e": 2209,
"s": 2093,
"text": "There are two version’s of Sublime Text is available to install, To install Sublime 2, use the following commands –"
},
{
"code": null,
"e": 2266,
"s": 2209,
"text": "$ sudo add-apt-repository ppa:webupd8team/sublime-text-2"
},
{
"code": null,
"e": 2306,
"s": 2266,
"text": "The sample output should be like this –"
},
{
"code": null,
"e": 3193,
"s": 2306,
"text": "Sublime Text 2 packages - the .deb will automatically download the latest build from http://www.sublimetext.com/dev or beta from http://www.sublimetext.com/2 (Adobe Flash Player installer - style).\n\nMore info and feedback:\nhttp://www.webupd8.org/2011/03/sublime-text-2-ubuntu-ppa.html\nhttp://www.webupd8.org/2012/03/sublime-text-2-ppa-separate-development.html\n More info: https://launchpad.net/~webupd8team/+archive/ubuntu/sublime-text-2\nPress [ENTER] to continue or ctrl-c to cancel adding it\n\ngpg: keyring `/tmp/tmpsv1jnez9/secring.gpg' created\ngpg: keyring `/tmp/tmpsv1jnez9/pubring.gpg' created\ngpg: requesting key EEA14886 from hkp server keyserver.ubuntu.com\ngpg: /tmp/tmpsv1jnez9/trustdb.gpg: trustdb created\ngpg: key EEA14886: public key \"Launchpad VLC\" imported\ngpg: no ultimately trusted keys found\ngpg: Total number processed: 1\ngpg: imported: 1 (RSA: 1)\nOK"
},
{
"code": null,
"e": 3245,
"s": 3193,
"text": "To update package index, use the following command-"
},
{
"code": null,
"e": 3267,
"s": 3245,
"text": "$ sudo apt-get update"
},
{
"code": null,
"e": 3306,
"s": 3267,
"text": "The sample output should be like this-"
},
{
"code": null,
"e": 5885,
"s": 3306,
"text": "Ign http://dl.google.com stable InRelease\nHit http://dl.google.com stable Release.gpg\nHit http://dl.google.com stable Release\nIgn http://extras.ubuntu.com trusty InRelease\nGet:1 http://security.ubuntu.com trusty-security InRelease [65.9 kB]\nHit http://dl.google.com stable/main amd64 Packages\nHit http://extras.ubuntu.com trusty Release.gpg\nHit http://extras.ubuntu.com trusty Release\nHit http://extras.ubuntu.com trusty/main Sources\nGet:2 http://security.ubuntu.com trusty-security/main Sources [109 kB]\nHit http://extras.ubuntu.com trusty/main amd64 Packages\nGet:3 http://ppa.launchpad.net trusty InRelease [15.5 kB]\nHit http://extras.ubuntu.com trusty/main i386 Packages\nGet:4 http://security.ubuntu.com trusty-security/restricted Sources [4,035 B]\nHit http://ppa.launchpad.net trusty InRelease\nGet:5 http://security.ubuntu.com trusty-security/universe Sources [34.0 kB]\nIgn http://ppa.launchpad.net trusty InRelease\nIgn http://in.archive.ubuntu.com trusty InRelease\nHit http://ppa.launchpad.net trusty InRelease\nGet:6 http://security.ubuntu.com trusty-security/multiverse Sources [2,750 B]\nIgn http://ppa.launchpad.net trusty InRelease\nGet:7 http://security.ubuntu.com trusty-security/main amd64 Packages [444 kB]\nIgn http://ppa.launchpad.net trusty InRelease\nGet:8 http://ppa.launchpad.net trusty/main amd64 Packages [739 B]\nGet:9 http://ppa.launchpad.net trusty/main i386 Packages [753 B]\nGet:10 http://ppa.launchpad.net trusty/main Translation-en [357 B]\nIgn http://extras.ubuntu.com trusty/main Translation-en_IN\nHit http://ppa.launchpad.net trusty/main amd64 Packages\nGet:11 http://in.archive.ubuntu.com trusty-updates InRelease [65.9 kB]\nIgn http://extras.ubuntu.com trusty/main Translation-en\nHit http://ppa.launchpad.net trusty/main i386 Packages\nHit http://ppa.launchpad.net trusty/main Translation-en\nGet:12 http://security.ubuntu.com trusty-security/restricted amd64 Packages [13.0 kB]\nHit http://ppa.launchpad.net trusty Release.gpg\nGet:13 http://security.ubuntu.com trusty-security/universe amd64 Packages [125 kB]\nHit http://ppa.launchpad.net trusty/main amd64 Packages\nHit http://ppa.launchpad.net trusty/main i386 Packages\nHit http://ppa.launchpad.net trusty/main Translation-en\nGet:14 http://security.ubuntu.com trusty-security/multiverse amd64 Packages [4,991 B]\nHit http://ppa.launchpad.net trusty Release.gpg\nGet:15 http://security.ubuntu.com trusty-security/main i386 Packages [417 kB]\nGet:16 http://ppa.launchpad.net trusty Release.gpg [316 B]\nHit http://ppa.launchpad.net trusty Release\n................................................................"
},
{
"code": null,
"e": 5945,
"s": 5885,
"text": "To install Sublime Text Editor, use the follwoing command –"
},
{
"code": null,
"e": 5981,
"s": 5945,
"text": "$ sudo apt-get install sublime-text"
},
{
"code": null,
"e": 6021,
"s": 5981,
"text": "The sample output should be like this –"
},
{
"code": null,
"e": 6924,
"s": 6021,
"text": "Reading package lists... Done\nBuilding dependency tree\nReading state information... Done\nThe following packages were automatically installed and are no longer required:\n gtk2-engines-pixbuf libbs2b0 libopusfile0 libpyside1.2 libqmmp-misc\n libqmmpui0 libshiboken1.2 libsidplayfp libtidy-0.99-0 linux-headers-4.2.0-27\n linux-headers-4.2.0-27-generic linux-image-4.2.0-27-generic\n linux-image-extra-4.2.0-27-generic linux-signed-image-4.2.0-27-generic\n php7.0-opcache python-beautifulsoup python-feedparser python-html2text\n python-magic python-oauth2 python-pyside.qtcore python-pyside.qtgui\n python-pyside.qtnetwork python-pyside.qtwebkit python-pysqlite2 python-regex\n python-sqlalchemy python-sqlalchemy-ext python-support python-unity-singlet\n python-utidylib\nUse 'apt-get autoremove' to remove them.\nThe following NEW packages will be installed:\n sublime-text\n0 upgraded, 1 newly"
},
{
"code": null,
"e": 6974,
"s": 6924,
"text": "To install sublime 3, use the following commands-"
},
{
"code": null,
"e": 7099,
"s": 6974,
"text": "$ sudo add-apt-repository ppa:webupd8team/sublime-text-3\n$ sudo apt-get update\n$ sudo apt-get install sublime-text-installer"
},
{
"code": null,
"e": 7144,
"s": 7099,
"text": "To open sublime, use the following command –"
},
{
"code": null,
"e": 7151,
"s": 7144,
"text": "$ subl"
},
{
"code": null,
"e": 7191,
"s": 7151,
"text": "The sample output should be like this –"
},
{
"code": null,
"e": 7356,
"s": 7191,
"text": "Congratulations! Now, you know “How to Install Sublime Text Editor on Ubuntu ”. We’ll learn more about these types of commands in our next Linux post. Keep reading!"
}
] |
Delete statement in MS SQL Server - GeeksforGeeks | 06 Aug, 2020
A database contains many tables that have data stored in order. To delete the rows, the user needs to use a delete statement.
1. To DELETE a single record :
Syntax –
DELETE FROM table_name
WHERE condition;
Note –Take care when deleting records from a table. Note that the WHERE clause in the DELETE statement. This WHERE specifies which record(s) need to be deleted. If you exclude the WHERE clause, all records in the table would be deleted.
Example –A table named Student has multiple values inserted into it and we need to delete some value.
The following SQL statement deletes a row from “Student” table which has StudentName as ‘ABC’.
DELETE FROM student
WHERE StudentName = 'ABC';
Output –
(1 row(s) affected)
To check whether the value is actually deleted, the query is as follows :
select *
from student;
Output –
2. To DELETE all the records :It is possible to delete all rows from a table without deleting the table. This means that the table structure, attributes, and indexes are going to be intact.
Syntax –
DELETE FROM table_name;
Example –The following SQL statement deletes all rows from “Student” table, without deleting the table.
DELETE FROM student;
Output –
(3 row(s) affected)
To check whether the value is actually deleted, the query is as follows :
select *
from student;
DBMS-SQL
SQL-Server
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Second Normal Form (2NF)
Introduction of Relational Algebra in DBMS
KDD Process in Data Mining
Types of Functional dependencies in DBMS
Relational Model in DBMS
SQL | DDL, DQL, DML, DCL and TCL Commands
How to find Nth highest salary from a table
SQL | ALTER (RENAME)
How to Update Multiple Columns in Single Update Statement in SQL?
MySQL | Group_CONCAT() Function | [
{
"code": null,
"e": 24224,
"s": 24196,
"text": "\n06 Aug, 2020"
},
{
"code": null,
"e": 24350,
"s": 24224,
"text": "A database contains many tables that have data stored in order. To delete the rows, the user needs to use a delete statement."
},
{
"code": null,
"e": 24381,
"s": 24350,
"text": "1. To DELETE a single record :"
},
{
"code": null,
"e": 24390,
"s": 24381,
"text": "Syntax –"
},
{
"code": null,
"e": 24432,
"s": 24390,
"text": "DELETE FROM table_name \nWHERE condition; "
},
{
"code": null,
"e": 24669,
"s": 24432,
"text": "Note –Take care when deleting records from a table. Note that the WHERE clause in the DELETE statement. This WHERE specifies which record(s) need to be deleted. If you exclude the WHERE clause, all records in the table would be deleted."
},
{
"code": null,
"e": 24771,
"s": 24669,
"text": "Example –A table named Student has multiple values inserted into it and we need to delete some value."
},
{
"code": null,
"e": 24866,
"s": 24771,
"text": "The following SQL statement deletes a row from “Student” table which has StudentName as ‘ABC’."
},
{
"code": null,
"e": 24914,
"s": 24866,
"text": "DELETE FROM student \nWHERE StudentName = 'ABC';"
},
{
"code": null,
"e": 24923,
"s": 24914,
"text": "Output –"
},
{
"code": null,
"e": 24943,
"s": 24923,
"text": "(1 row(s) affected)"
},
{
"code": null,
"e": 25017,
"s": 24943,
"text": "To check whether the value is actually deleted, the query is as follows :"
},
{
"code": null,
"e": 25041,
"s": 25017,
"text": "select * \nfrom student;"
},
{
"code": null,
"e": 25050,
"s": 25041,
"text": "Output –"
},
{
"code": null,
"e": 25240,
"s": 25050,
"text": "2. To DELETE all the records :It is possible to delete all rows from a table without deleting the table. This means that the table structure, attributes, and indexes are going to be intact."
},
{
"code": null,
"e": 25249,
"s": 25240,
"text": "Syntax –"
},
{
"code": null,
"e": 25273,
"s": 25249,
"text": "DELETE FROM table_name;"
},
{
"code": null,
"e": 25377,
"s": 25273,
"text": "Example –The following SQL statement deletes all rows from “Student” table, without deleting the table."
},
{
"code": null,
"e": 25398,
"s": 25377,
"text": "DELETE FROM student;"
},
{
"code": null,
"e": 25407,
"s": 25398,
"text": "Output –"
},
{
"code": null,
"e": 25427,
"s": 25407,
"text": "(3 row(s) affected)"
},
{
"code": null,
"e": 25501,
"s": 25427,
"text": "To check whether the value is actually deleted, the query is as follows :"
},
{
"code": null,
"e": 25525,
"s": 25501,
"text": "select * \nfrom student;"
},
{
"code": null,
"e": 25534,
"s": 25525,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 25545,
"s": 25534,
"text": "SQL-Server"
},
{
"code": null,
"e": 25550,
"s": 25545,
"text": "DBMS"
},
{
"code": null,
"e": 25554,
"s": 25550,
"text": "SQL"
},
{
"code": null,
"e": 25559,
"s": 25554,
"text": "DBMS"
},
{
"code": null,
"e": 25563,
"s": 25559,
"text": "SQL"
},
{
"code": null,
"e": 25661,
"s": 25563,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25670,
"s": 25661,
"text": "Comments"
},
{
"code": null,
"e": 25683,
"s": 25670,
"text": "Old Comments"
},
{
"code": null,
"e": 25708,
"s": 25683,
"text": "Second Normal Form (2NF)"
},
{
"code": null,
"e": 25751,
"s": 25708,
"text": "Introduction of Relational Algebra in DBMS"
},
{
"code": null,
"e": 25778,
"s": 25751,
"text": "KDD Process in Data Mining"
},
{
"code": null,
"e": 25819,
"s": 25778,
"text": "Types of Functional dependencies in DBMS"
},
{
"code": null,
"e": 25844,
"s": 25819,
"text": "Relational Model in DBMS"
},
{
"code": null,
"e": 25886,
"s": 25844,
"text": "SQL | DDL, DQL, DML, DCL and TCL Commands"
},
{
"code": null,
"e": 25930,
"s": 25886,
"text": "How to find Nth highest salary from a table"
},
{
"code": null,
"e": 25951,
"s": 25930,
"text": "SQL | ALTER (RENAME)"
},
{
"code": null,
"e": 26017,
"s": 25951,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
}
] |
Angular Material - Virtual Repeat | The md-virtual-repeat-container is the scroll container for the md-virtual-repeat component.
The following table lists out the parameters and description of the different attributes of md-virtual-repeat-container.
md-top-index
Binds the index of the item that is at the top of the scroll container to $scope. It can both read and set the scroll position.
md-orient-horizontal
Determines whether the container should scroll horizontally (defaults to orientation and scrolling vertically).
md-auto-shrink
When present, the container will shrink to fit the number of items when that number is less than its original size.
md-auto-shrink-min
Minimum number of items that md-auto-shrink will shrink to (default: 0).
Virtual repeat is a substitute for ng-repeat to renders only enough html elements to fill the container and reuse them when the user scrolls.
The following table lists out the parameters and description of the different attributes of md-virtual-repeat.
md-item-size
The height or width of the repeated elements (which must be identical for each element). This is optional. This attempts to read the size from the dom if missing, but still assumes that all repeated nodes have same height or width.
md-extra-name
Evaluates to an additional name to which the current iterated item can be assigned on the repeated scope (needed for use in md-autocomplete).
md-on-demand
When present, treats the md-virtual-repeat argument as an object that can fetch rows rather than an array.This object must implement the following interface with two (2) methods −
getItemAtIndex − function(index) [object] - The item at that index or null if it is not yet loaded (it should start downloading the item in that case).
getItemAtIndex − function(index) [object] - The item at that index or null if it is not yet loaded (it should start downloading the item in that case).
getLength − function() [number] - The data length to which the repeater container should be sized. Ideally, when the count is known, this method should return it. Otherwise, return a higher number than the currently loaded items to produce an infinite-scroll behavior.
getLength − function() [number] - The data length to which the repeater container should be sized. Ideally, when the count is known, this method should return it. Otherwise, return a higher number than the currently loaded items to produce an infinite-scroll behavior.
The following example show the use of virtual repeat.
am_virtualrepeat.htm
<html lang = "en">
<head>
<link rel = "stylesheet"
href = "https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.css">
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.min.js"></script>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-aria.min.js"></script>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-messages.min.js"></script>
<script src = "https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.js"></script>
<link rel = "stylesheet" href = "https://fonts.googleapis.com/icon?family=Material+Icons">
<style>
.vrepeatContainer #horizontal-container {
height: 100px;
width: 830px;
}
.vrepeatContainer #vertical-container {
height: 292px;
width: 400px;
}
.vrepeatContainer .repeated-item-horizontal {
border-right: 1px solid #ddd;
box-sizing: border-box;
display: inline-block;
height: 84px;
padding-top: 35px;
text-align: center;
width: 50px;
}
.vrepeatContainer .repeated-item-vertical {
border-bottom: 1px solid #ddd;
box-sizing: border-box;
height: 40px;
padding-top: 10px;
}
.vrepeatContainer md-content {
margin: 16px;
}
.vrepeatContainer md-virtual-repeat-container {
border: solid 1px grey;
}
</style>
<script language = "javascript">
angular
.module('firstApplication', ['ngMaterial'])
.controller('vrepeatController', vrepeatController);
function vrepeatController ($scope) {
this.items = [];
for (var i = 0; i < 1000; i++) {
this.items.push(i);
}
}
</script>
</head>
<body ng-app = "firstApplication">
<div class = "vrepeatContainer" ng-controller = "vrepeatController as ctrl"
ng-cloak>
<md-content layout = "column">
<h2>Horizontal Repeat</h2>
<md-virtual-repeat-container id = "horizontal-container" md-orient-horizontal>
<div md-virtual-repeat = "item in ctrl.items"
class = "repeated-item-horizontal" flex>
{{item}}
</div>
</md-virtual-repeat-container>
<h2>Vertical Repeat</h2>
<md-virtual-repeat-container id = "vertical-container">
<div md-virtual-repeat = "item in ctrl.items"
class = "repeated-item-vertical" flex>
{{item}}
</div>
</md-virtual-repeat-container>
</md-content>
</div>
</body>
</html>
Verify the result.
16 Lectures
1.5 hours
Anadi Sharma
28 Lectures
2.5 hours
Anadi Sharma
11 Lectures
7.5 hours
SHIVPRASAD KOIRALA
16 Lectures
2.5 hours
Frahaan Hussain
69 Lectures
5 hours
Senol Atac
53 Lectures
3.5 hours
Senol Atac
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2283,
"s": 2190,
"text": "The md-virtual-repeat-container is the scroll container for the md-virtual-repeat component."
},
{
"code": null,
"e": 2404,
"s": 2283,
"text": "The following table lists out the parameters and description of the different attributes of md-virtual-repeat-container."
},
{
"code": null,
"e": 2417,
"s": 2404,
"text": "md-top-index"
},
{
"code": null,
"e": 2545,
"s": 2417,
"text": "Binds the index of the item that is at the top of the scroll container to $scope. It can both read and set the scroll position."
},
{
"code": null,
"e": 2566,
"s": 2545,
"text": "md-orient-horizontal"
},
{
"code": null,
"e": 2678,
"s": 2566,
"text": "Determines whether the container should scroll horizontally (defaults to orientation and scrolling vertically)."
},
{
"code": null,
"e": 2693,
"s": 2678,
"text": "md-auto-shrink"
},
{
"code": null,
"e": 2809,
"s": 2693,
"text": "When present, the container will shrink to fit the number of items when that number is less than its original size."
},
{
"code": null,
"e": 2828,
"s": 2809,
"text": "md-auto-shrink-min"
},
{
"code": null,
"e": 2901,
"s": 2828,
"text": "Minimum number of items that md-auto-shrink will shrink to (default: 0)."
},
{
"code": null,
"e": 3043,
"s": 2901,
"text": "Virtual repeat is a substitute for ng-repeat to renders only enough html elements to fill the container and reuse them when the user scrolls."
},
{
"code": null,
"e": 3155,
"s": 3043,
"text": "The following table lists out the parameters and description of the different attributes of md-virtual-repeat."
},
{
"code": null,
"e": 3168,
"s": 3155,
"text": "md-item-size"
},
{
"code": null,
"e": 3400,
"s": 3168,
"text": "The height or width of the repeated elements (which must be identical for each element). This is optional. This attempts to read the size from the dom if missing, but still assumes that all repeated nodes have same height or width."
},
{
"code": null,
"e": 3414,
"s": 3400,
"text": "md-extra-name"
},
{
"code": null,
"e": 3556,
"s": 3414,
"text": "Evaluates to an additional name to which the current iterated item can be assigned on the repeated scope (needed for use in md-autocomplete)."
},
{
"code": null,
"e": 3569,
"s": 3556,
"text": "md-on-demand"
},
{
"code": null,
"e": 3749,
"s": 3569,
"text": "When present, treats the md-virtual-repeat argument as an object that can fetch rows rather than an array.This object must implement the following interface with two (2) methods −"
},
{
"code": null,
"e": 3901,
"s": 3749,
"text": "getItemAtIndex − function(index) [object] - The item at that index or null if it is not yet loaded (it should start downloading the item in that case)."
},
{
"code": null,
"e": 4053,
"s": 3901,
"text": "getItemAtIndex − function(index) [object] - The item at that index or null if it is not yet loaded (it should start downloading the item in that case)."
},
{
"code": null,
"e": 4322,
"s": 4053,
"text": "getLength − function() [number] - The data length to which the repeater container should be sized. Ideally, when the count is known, this method should return it. Otherwise, return a higher number than the currently loaded items to produce an infinite-scroll behavior."
},
{
"code": null,
"e": 4591,
"s": 4322,
"text": "getLength − function() [number] - The data length to which the repeater container should be sized. Ideally, when the count is known, this method should return it. Otherwise, return a higher number than the currently loaded items to produce an infinite-scroll behavior."
},
{
"code": null,
"e": 4645,
"s": 4591,
"text": "The following example show the use of virtual repeat."
},
{
"code": null,
"e": 4666,
"s": 4645,
"text": "am_virtualrepeat.htm"
},
{
"code": null,
"e": 7767,
"s": 4666,
"text": "<html lang = \"en\">\n <head>\n <link rel = \"stylesheet\"\n href = \"https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.css\">\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js\"></script>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.min.js\"></script>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-aria.min.js\"></script>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-messages.min.js\"></script>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.js\"></script>\n <link rel = \"stylesheet\" href = \"https://fonts.googleapis.com/icon?family=Material+Icons\">\n \n <style>\n .vrepeatContainer #horizontal-container {\n height: 100px;\n width: 830px; \n }\n\n .vrepeatContainer #vertical-container {\n height: 292px;\n width: 400px; \n }\n\n .vrepeatContainer .repeated-item-horizontal {\n border-right: 1px solid #ddd;\n box-sizing: border-box;\n display: inline-block;\n height: 84px;\n padding-top: 35px;\n text-align: center;\n width: 50px; \n }\n\n .vrepeatContainer .repeated-item-vertical {\n border-bottom: 1px solid #ddd;\n box-sizing: border-box;\n height: 40px;\n padding-top: 10px;\n }\n\n .vrepeatContainer md-content {\n margin: 16px; \n }\n \n .vrepeatContainer md-virtual-repeat-container {\n border: solid 1px grey; \n }\t \n </style>\n \n <script language = \"javascript\">\n angular\n .module('firstApplication', ['ngMaterial'])\n .controller('vrepeatController', vrepeatController);\n \n function vrepeatController ($scope) { \n this.items = [];\n for (var i = 0; i < 1000; i++) {\n this.items.push(i);\n }\n }\t \n </script> \n </head>\n \n <body ng-app = \"firstApplication\"> \n <div class = \"vrepeatContainer\" ng-controller = \"vrepeatController as ctrl\"\n ng-cloak>\n <md-content layout = \"column\">\n <h2>Horizontal Repeat</h2>\n <md-virtual-repeat-container id = \"horizontal-container\" md-orient-horizontal>\n <div md-virtual-repeat = \"item in ctrl.items\"\n class = \"repeated-item-horizontal\" flex>\n {{item}}\n </div>\n </md-virtual-repeat-container>\n \n <h2>Vertical Repeat</h2>\n <md-virtual-repeat-container id = \"vertical-container\">\n <div md-virtual-repeat = \"item in ctrl.items\"\n class = \"repeated-item-vertical\" flex>\n {{item}}\n </div>\n </md-virtual-repeat-container>\n \n </md-content>\n </div>\n </body>\n</html>"
},
{
"code": null,
"e": 7786,
"s": 7767,
"text": "Verify the result."
},
{
"code": null,
"e": 7821,
"s": 7786,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 7835,
"s": 7821,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 7870,
"s": 7835,
"text": "\n 28 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 7884,
"s": 7870,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 7919,
"s": 7884,
"text": "\n 11 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 7939,
"s": 7919,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 7974,
"s": 7939,
"text": "\n 16 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 7991,
"s": 7974,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 8024,
"s": 7991,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 8036,
"s": 8024,
"text": " Senol Atac"
},
{
"code": null,
"e": 8071,
"s": 8036,
"text": "\n 53 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 8083,
"s": 8071,
"text": " Senol Atac"
},
{
"code": null,
"e": 8090,
"s": 8083,
"text": " Print"
},
{
"code": null,
"e": 8101,
"s": 8090,
"text": " Add Notes"
}
] |
How to round off a floating number using Python? | The round() function in Python's library rounds the number to given position. Following are some Examples.
>>> round(11.6912,2) # upto second decimal place
11.69
>>> round(11.6912,1) # upto first place after decimal point
11.7
>>> round(11.6912) # rounded to nearest integer
12
>>> round(11.6912,-1)#rounded to ten's place
10.0 | [
{
"code": null,
"e": 1169,
"s": 1062,
"text": "The round() function in Python's library rounds the number to given position. Following are some Examples."
},
{
"code": null,
"e": 1390,
"s": 1169,
"text": ">>> round(11.6912,2) # upto second decimal place\n11.69\n>>> round(11.6912,1) # upto first place after decimal point\n11.7\n>>> round(11.6912) # rounded to nearest integer\n12\n>>> round(11.6912,-1)#rounded to ten's place\n10.0"
}
] |
How to check if Location Services are enabled in Android App? | This example demonstrate about How to check if Location Services are enabled in Android App.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.java
<? xml version= "1.0" encoding= "utf-8" ?>
<RelativeLayout xmlns: android = "http://schemas.android.com/apk/res/android"
xmlns: tools = "http://schemas.android.com/tools"
android :layout_width= "match_parent"
android :layout_height= "match_parent"
android :layout_margin= "16dp"
tools :context= ".MainActivity" >
<Button
android :id= "@+id/button"
android :layout_width= "match_parent"
android :layout_height= "wrap_content"
android :text= "Enable Location" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
package app.tutorialspoint.com.sample ;
import android.content.Context ;
import android.content.DialogInterface ;
import android.content.Intent ;
import android.location.LocationManager ;
import android.os.Bundle ;
import android.provider.Settings ;
import android.support.v7.app.AlertDialog ;
import android.support.v7.app.AppCompatActivity ;
import android.view.View ;
import android.widget.Button ;
import android.widget.TextView ;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate (Bundle savedInstanceState) {
super .onCreate(savedInstanceState) ;
setContentView(R.layout. activity_main ) ;
Button button = findViewById(R.id. button ) ;
button.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick (View v) {
locationEnabled() ;
}
}) ;
}
private void locationEnabled () {
LocationManager lm = (LocationManager)
getSystemService(Context. LOCATION_SERVICE ) ;
boolean gps_enabled = false;
boolean network_enabled = false;
try {
gps_enabled = lm.isProviderEnabled(LocationManager. GPS_PROVIDER ) ;
} catch (Exception e) {
e.printStackTrace() ;
}
try {
network_enabled = lm.isProviderEnabled(LocationManager. NETWORK_PROVIDER ) ;
} catch (Exception e) {
e.printStackTrace() ;
}
if (!gps_enabled && !network_enabled) {
new AlertDialog.Builder(MainActivity. this )
.setMessage( "GPS Enable" )
.setPositiveButton( "Settings" , new
DialogInterface.OnClickListener() {
@Override
public void onClick (DialogInterface paramDialogInterface , int paramInt) {
startActivity( new Intent(Settings. ACTION_LOCATION_SOURCE_SETTINGS )) ;
}
})
.setNegativeButton( "Cancel" , null )
.show() ;
}
}
}
Step 4 − Add the following code to androidManifest.xml
<? xml version= "1.0" encoding= "utf-8" ?>
<manifest xmlns: android = "http://schemas.android.com/apk/res/android"
package= "app.tutorialspoint.com.sample" >
<uses-permission android :name= "android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android :name= "android.permission.ACCESS_COARSE_LOCATION" />
<application
android :allowBackup= "true"
android :icon= "@mipmap/ic_launcher"
android :label= "@string/app_name"
android :roundIcon= "@mipmap/ic_launcher_round"
android :supportsRtl= "true"
android :theme= "@style/AppTheme" >
<activity android :name= ".MainActivity" >
<intent-filter>
<action android :name= "android.intent.action.MAIN" />
<category android :name= "android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen – | [
{
"code": null,
"e": 1155,
"s": 1062,
"text": "This example demonstrate about How to check if Location Services are enabled in Android App."
},
{
"code": null,
"e": 1284,
"s": 1155,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1349,
"s": 1284,
"text": "Step 2 − Add the following code to res/layout/activity_main.java"
},
{
"code": null,
"e": 1870,
"s": 1349,
"text": "<? xml version= \"1.0\" encoding= \"utf-8\" ?>\n<RelativeLayout xmlns: android = \"http://schemas.android.com/apk/res/android\"\n xmlns: tools = \"http://schemas.android.com/tools\"\n android :layout_width= \"match_parent\"\n android :layout_height= \"match_parent\"\n android :layout_margin= \"16dp\"\n tools :context= \".MainActivity\" >\n <Button\n android :id= \"@+id/button\"\n android :layout_width= \"match_parent\"\n android :layout_height= \"wrap_content\"\n android :text= \"Enable Location\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 1927,
"s": 1870,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 3879,
"s": 1927,
"text": "package app.tutorialspoint.com.sample ;\nimport android.content.Context ;\nimport android.content.DialogInterface ;\nimport android.content.Intent ;\nimport android.location.LocationManager ;\nimport android.os.Bundle ;\nimport android.provider.Settings ;\nimport android.support.v7.app.AlertDialog ;\nimport android.support.v7.app.AppCompatActivity ;\nimport android.view.View ;\nimport android.widget.Button ;\nimport android.widget.TextView ;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate (Bundle savedInstanceState) {\n super .onCreate(savedInstanceState) ;\n setContentView(R.layout. activity_main ) ;\n Button button = findViewById(R.id. button ) ;\n button.setOnClickListener( new View.OnClickListener() {\n @Override\n public void onClick (View v) {\n locationEnabled() ;\n }\n }) ;\n }\n private void locationEnabled () {\n LocationManager lm = (LocationManager)\n getSystemService(Context. LOCATION_SERVICE ) ;\n boolean gps_enabled = false;\n boolean network_enabled = false;\n try {\n gps_enabled = lm.isProviderEnabled(LocationManager. GPS_PROVIDER ) ;\n } catch (Exception e) {\n e.printStackTrace() ;\n }\n try {\n network_enabled = lm.isProviderEnabled(LocationManager. NETWORK_PROVIDER ) ;\n } catch (Exception e) {\n e.printStackTrace() ;\n }\n if (!gps_enabled && !network_enabled) {\n new AlertDialog.Builder(MainActivity. this )\n .setMessage( \"GPS Enable\" )\n .setPositiveButton( \"Settings\" , new\n DialogInterface.OnClickListener() {\n @Override\n public void onClick (DialogInterface paramDialogInterface , int paramInt) {\n startActivity( new Intent(Settings. ACTION_LOCATION_SOURCE_SETTINGS )) ;\n }\n })\n .setNegativeButton( \"Cancel\" , null )\n .show() ;\n }\n }\n}"
},
{
"code": null,
"e": 3934,
"s": 3879,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 4813,
"s": 3934,
"text": "<? xml version= \"1.0\" encoding= \"utf-8\" ?>\n<manifest xmlns: android = \"http://schemas.android.com/apk/res/android\"\n package= \"app.tutorialspoint.com.sample\" >\n <uses-permission android :name= \"android.permission.ACCESS_FINE_LOCATION\" />\n <uses-permission android :name= \"android.permission.ACCESS_COARSE_LOCATION\" />\n <application\n android :allowBackup= \"true\"\n android :icon= \"@mipmap/ic_launcher\"\n android :label= \"@string/app_name\"\n android :roundIcon= \"@mipmap/ic_launcher_round\"\n android :supportsRtl= \"true\"\n android :theme= \"@style/AppTheme\" >\n <activity android :name= \".MainActivity\" >\n <intent-filter>\n <action android :name= \"android.intent.action.MAIN\" />\n <category android :name= \"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 5160,
"s": 4813,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –"
}
] |
Removing Negatives from Array in JavaScript | Given an array arr of multiple values. For example −
[-3,5,1,3,2,10]
We are required to write a function that removes any negative values in the array. Once the
function finishes its execution the array should be composed of just positive numbers.
We are required to do this without creating a temporary array and only using pop method to
remove any values in the array.
Therefore, let’s write the code for this function −
The code for this will be −
// strip all negatives off the end
while (x.length && x[x.length - 1] < 0) {
x.pop();
}
for (var i = x.length - 1; i >= 0; i--) {
if (x[i] < 0) {
// replace this element with the last element (guaranteed to be
positive)
x[i] = x[x.length - 1];
x.pop();
}
}
The output in the console will be −
[ 1, 8, 9 ] | [
{
"code": null,
"e": 1115,
"s": 1062,
"text": "Given an array arr of multiple values. For example −"
},
{
"code": null,
"e": 1131,
"s": 1115,
"text": "[-3,5,1,3,2,10]"
},
{
"code": null,
"e": 1310,
"s": 1131,
"text": "We are required to write a function that removes any negative values in the array. Once the\nfunction finishes its execution the array should be composed of just positive numbers."
},
{
"code": null,
"e": 1433,
"s": 1310,
"text": "We are required to do this without creating a temporary array and only using pop method to\nremove any values in the array."
},
{
"code": null,
"e": 1485,
"s": 1433,
"text": "Therefore, let’s write the code for this function −"
},
{
"code": null,
"e": 1513,
"s": 1485,
"text": "The code for this will be −"
},
{
"code": null,
"e": 1803,
"s": 1513,
"text": "// strip all negatives off the end\nwhile (x.length && x[x.length - 1] < 0) {\n x.pop();\n}\nfor (var i = x.length - 1; i >= 0; i--) {\n if (x[i] < 0) {\n // replace this element with the last element (guaranteed to be\n positive)\n x[i] = x[x.length - 1];\n x.pop();\n }\n}"
},
{
"code": null,
"e": 1839,
"s": 1803,
"text": "The output in the console will be −"
},
{
"code": null,
"e": 1851,
"s": 1839,
"text": "[ 1, 8, 9 ]"
}
] |
Flutter – CircleAvatar Widget | 22 Feb, 2022
CircleAvatar widget comes built-in with the flutter SDK. It is simply a circle in which we can add background color, background image, or just some text. It usually represents a user with his image or with his initials. Although we can make a similar widget from the ground up, this widget comes in handy in the fast development of an application.
const CircleAvatar(
{Key key,
Widget child,
Color backgroundColor,
ImageProvider<Object> backgroundImage,
void onBackgroundImageError(
dynamic exception,
StackTrace stackTrace
),
Color foregroundColor,
double radius,
double minRadius,
double maxRadius}
)
Properties Of CircleAvatar Widget:
backgroundColor: This property takes in Color class (final) as the parameter. This property decides the background color of the circle and by default, it is set to ThemeData.primaryColorLight.
backgroundImage: This property holds ImageProvider<T extends Object> class (final) as the parameter. This property applies a background image to the CircleAvatar widget.
child: The child property takes the widget to be placed below the CircleAvatar widget inside the widget tree or the widget to be displayed inside the circle.
foregroundColor: This property holds the Color class (final) as the parameter value. It decides the default color of the text inside the CircleAvatar.
maxRadius: This property takes in a double value to decide the maximum size the CircleAvatar can get to.
minRadius: This minRadius property also takes in a double value as the parameter and it decided the minimum size of the CircleAvatar.
onBackgroundImageError: This property controls what to do if the background image is missing due to some reason.
radius: The radius property also holds a double value as the parameter to decide the size of CircleAvatar in terms if its radius.
Syntax:
void Function(
dynamic exception,
StackTrace stackTrace
) onBackgroundImageError
Example 1: In this example, we have shown a green circle, holding some text.
main.dart
Dart
import 'package:flutter/material.dart'; void main() { runApp( MaterialApp( home: Scaffold( appBar: AppBar( title: Text('GeeksforGeeks'), backgroundColor: Colors.greenAccent[400], leading: IconButton( icon: Icon(Icons.menu), tooltip: 'Menu', onPressed: () {}, ), //IconButton actions: <Widget>[ IconButton( icon: Icon(Icons.comment), tooltip: 'Comment', onPressed: () {}, ), //IconButton ], //<Widget>[] ), //AppBar body: Center( child: CircleAvatar( backgroundColor: Colors.greenAccent[400], radius: 100, child: Text( 'GeeksForGeeks', style: TextStyle(fontSize: 25, color: Colors.white), ), //Text ), //CircleAvatar ), //Center ), //Scaffold debugShowCheckedModeBanner: false, ), //MaterialApp );}
Output:
Note: We can also use foregroundColor property to assign default text color instead of doing it in TextStyle.
...
foregroundColor: Colors.white,
...
Explanation: In the CircularAvatar widget we have set the radius to be 100, back backgroundColor as greenAccent[400]. CircleAvatar takes Text widget as a child. The text is ‘GeeksforGeeks’. And we have also style text a bit by giving it a font-size of 25 and text-color white.
Example 2: Here we have added an image in CircleAvatar from the internet.
// Code snippet of CircleAvatar
...
body: Center(
child: CircleAvatar(
backgroundImage: NetworkImage(
"https://pbs.twimg.com/profile_images/1304985167476523008/QNHrwL2q_400x400.jpg"),
radius: 100,
), //CircleAvatar
...
Output:
Explanation: In this example, we have set an image inside the CircleAvatar widget using the backgroundImage property. The image is geekforgeeks logo whose address is provided inside the NetworkImages’s argument. And at last, we have assigned 100 as value to the radius of the CircleAvatar.
Example 3: In this example, we have added a border around the CircleAvatar.
// Code snippet of CircleAvatar
...
body: Center(
child: CircleAvatar(
backgroundColor: Colors.green,
radius: 115,
child: CircleAvatar(
backgroundColor: Colors.greenAccent[100],
radius: 110,
child: CircleAvatar(
backgroundImage: NetworkImage(
"https://pbs.twimg.com/profile_images/1304985167476523008/QNHrwL2q_400x400.jpg"), //NetworkImage
radius: 100,
), //CircleAvatar
), //CircleAvatar
), //CircleAvatar
), //Center
...
Output:
Explanation: Here we have added two borders around the NetworkImage that we added in the previous example. Essentially what we have down is we have wrapped the CircleAvatar which contains an image and has a radius of 100 px, with two more CircleAvatar widgets of a bigger size. Now, the top-most CircleAvatar is given a background of green color and a border-radius of 115 px. And in the CircleAvatar below that, we have set backgroundColor as greenAccent[400] and the radius for it is 110 px.
So, this is how we can use CircleAvatar widget in flutter and for full code of these examples, you can click here.
simranarora5sos
arorakashish0911
android
Flutter
Flutter-widgets
Android
Dart
Flutter
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Android SDK and it's Components
Android RecyclerView in Kotlin
Android Project folder Structure
Broadcast Receiver in Android With Example
Flutter - Custom Bottom Navigation Bar
Flutter - DropDownButton Widget
Flutter - Custom Bottom Navigation Bar
Flutter - Asset Image
Splash Screen in Flutter
Flutter - Checkbox Widget | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 Feb, 2022"
},
{
"code": null,
"e": 400,
"s": 52,
"text": "CircleAvatar widget comes built-in with the flutter SDK. It is simply a circle in which we can add background color, background image, or just some text. It usually represents a user with his image or with his initials. Although we can make a similar widget from the ground up, this widget comes in handy in the fast development of an application."
},
{
"code": null,
"e": 655,
"s": 400,
"text": "const CircleAvatar(\n{Key key,\nWidget child,\nColor backgroundColor,\nImageProvider<Object> backgroundImage,\nvoid onBackgroundImageError(\ndynamic exception,\nStackTrace stackTrace\n),\nColor foregroundColor,\ndouble radius,\ndouble minRadius,\ndouble maxRadius}\n)"
},
{
"code": null,
"e": 690,
"s": 655,
"text": "Properties Of CircleAvatar Widget:"
},
{
"code": null,
"e": 883,
"s": 690,
"text": "backgroundColor: This property takes in Color class (final) as the parameter. This property decides the background color of the circle and by default, it is set to ThemeData.primaryColorLight."
},
{
"code": null,
"e": 1053,
"s": 883,
"text": "backgroundImage: This property holds ImageProvider<T extends Object> class (final) as the parameter. This property applies a background image to the CircleAvatar widget."
},
{
"code": null,
"e": 1211,
"s": 1053,
"text": "child: The child property takes the widget to be placed below the CircleAvatar widget inside the widget tree or the widget to be displayed inside the circle."
},
{
"code": null,
"e": 1362,
"s": 1211,
"text": "foregroundColor: This property holds the Color class (final) as the parameter value. It decides the default color of the text inside the CircleAvatar."
},
{
"code": null,
"e": 1467,
"s": 1362,
"text": "maxRadius: This property takes in a double value to decide the maximum size the CircleAvatar can get to."
},
{
"code": null,
"e": 1601,
"s": 1467,
"text": "minRadius: This minRadius property also takes in a double value as the parameter and it decided the minimum size of the CircleAvatar."
},
{
"code": null,
"e": 1714,
"s": 1601,
"text": "onBackgroundImageError: This property controls what to do if the background image is missing due to some reason."
},
{
"code": null,
"e": 1844,
"s": 1714,
"text": "radius: The radius property also holds a double value as the parameter to decide the size of CircleAvatar in terms if its radius."
},
{
"code": null,
"e": 1852,
"s": 1844,
"text": "Syntax:"
},
{
"code": null,
"e": 1933,
"s": 1852,
"text": "void Function(\ndynamic exception,\nStackTrace stackTrace\n) onBackgroundImageError"
},
{
"code": null,
"e": 2010,
"s": 1933,
"text": "Example 1: In this example, we have shown a green circle, holding some text."
},
{
"code": null,
"e": 2020,
"s": 2010,
"text": "main.dart"
},
{
"code": null,
"e": 2025,
"s": 2020,
"text": "Dart"
},
{
"code": "import 'package:flutter/material.dart'; void main() { runApp( MaterialApp( home: Scaffold( appBar: AppBar( title: Text('GeeksforGeeks'), backgroundColor: Colors.greenAccent[400], leading: IconButton( icon: Icon(Icons.menu), tooltip: 'Menu', onPressed: () {}, ), //IconButton actions: <Widget>[ IconButton( icon: Icon(Icons.comment), tooltip: 'Comment', onPressed: () {}, ), //IconButton ], //<Widget>[] ), //AppBar body: Center( child: CircleAvatar( backgroundColor: Colors.greenAccent[400], radius: 100, child: Text( 'GeeksForGeeks', style: TextStyle(fontSize: 25, color: Colors.white), ), //Text ), //CircleAvatar ), //Center ), //Scaffold debugShowCheckedModeBanner: false, ), //MaterialApp );}",
"e": 3010,
"s": 2025,
"text": null
},
{
"code": null,
"e": 3021,
"s": 3012,
"text": "Output: "
},
{
"code": null,
"e": 3131,
"s": 3021,
"text": "Note: We can also use foregroundColor property to assign default text color instead of doing it in TextStyle."
},
{
"code": null,
"e": 3176,
"s": 3131,
"text": " ...\nforegroundColor: Colors.white,\n ..."
},
{
"code": null,
"e": 3453,
"s": 3176,
"text": "Explanation: In the CircularAvatar widget we have set the radius to be 100, back backgroundColor as greenAccent[400]. CircleAvatar takes Text widget as a child. The text is ‘GeeksforGeeks’. And we have also style text a bit by giving it a font-size of 25 and text-color white."
},
{
"code": null,
"e": 3528,
"s": 3453,
"text": "Example 2: Here we have added an image in CircleAvatar from the internet. "
},
{
"code": null,
"e": 3846,
"s": 3528,
"text": " // Code snippet of CircleAvatar\n ... \n body: Center(\n child: CircleAvatar(\n backgroundImage: NetworkImage(\n \"https://pbs.twimg.com/profile_images/1304985167476523008/QNHrwL2q_400x400.jpg\"),\n radius: 100,\n ), //CircleAvatar\n ..."
},
{
"code": null,
"e": 3854,
"s": 3846,
"text": "Output:"
},
{
"code": null,
"e": 4144,
"s": 3854,
"text": "Explanation: In this example, we have set an image inside the CircleAvatar widget using the backgroundImage property. The image is geekforgeeks logo whose address is provided inside the NetworkImages’s argument. And at last, we have assigned 100 as value to the radius of the CircleAvatar."
},
{
"code": null,
"e": 4221,
"s": 4144,
"text": "Example 3: In this example, we have added a border around the CircleAvatar. "
},
{
"code": null,
"e": 4862,
"s": 4221,
"text": " // Code snippet of CircleAvatar\n ...\n body: Center(\n child: CircleAvatar(\n backgroundColor: Colors.green,\n radius: 115,\n child: CircleAvatar(\n backgroundColor: Colors.greenAccent[100],\n radius: 110,\n child: CircleAvatar(\n backgroundImage: NetworkImage(\n \"https://pbs.twimg.com/profile_images/1304985167476523008/QNHrwL2q_400x400.jpg\"), //NetworkImage\n radius: 100,\n ), //CircleAvatar\n ), //CircleAvatar\n ), //CircleAvatar\n ), //Center\n ..."
},
{
"code": null,
"e": 4870,
"s": 4862,
"text": "Output:"
},
{
"code": null,
"e": 5364,
"s": 4870,
"text": "Explanation: Here we have added two borders around the NetworkImage that we added in the previous example. Essentially what we have down is we have wrapped the CircleAvatar which contains an image and has a radius of 100 px, with two more CircleAvatar widgets of a bigger size. Now, the top-most CircleAvatar is given a background of green color and a border-radius of 115 px. And in the CircleAvatar below that, we have set backgroundColor as greenAccent[400] and the radius for it is 110 px."
},
{
"code": null,
"e": 5479,
"s": 5364,
"text": "So, this is how we can use CircleAvatar widget in flutter and for full code of these examples, you can click here."
},
{
"code": null,
"e": 5495,
"s": 5479,
"text": "simranarora5sos"
},
{
"code": null,
"e": 5512,
"s": 5495,
"text": "arorakashish0911"
},
{
"code": null,
"e": 5520,
"s": 5512,
"text": "android"
},
{
"code": null,
"e": 5528,
"s": 5520,
"text": "Flutter"
},
{
"code": null,
"e": 5544,
"s": 5528,
"text": "Flutter-widgets"
},
{
"code": null,
"e": 5552,
"s": 5544,
"text": "Android"
},
{
"code": null,
"e": 5557,
"s": 5552,
"text": "Dart"
},
{
"code": null,
"e": 5565,
"s": 5557,
"text": "Flutter"
},
{
"code": null,
"e": 5573,
"s": 5565,
"text": "Android"
},
{
"code": null,
"e": 5671,
"s": 5573,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5703,
"s": 5671,
"text": "Android SDK and it's Components"
},
{
"code": null,
"e": 5734,
"s": 5703,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 5767,
"s": 5734,
"text": "Android Project folder Structure"
},
{
"code": null,
"e": 5810,
"s": 5767,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 5849,
"s": 5810,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 5881,
"s": 5849,
"text": "Flutter - DropDownButton Widget"
},
{
"code": null,
"e": 5920,
"s": 5881,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 5942,
"s": 5920,
"text": "Flutter - Asset Image"
},
{
"code": null,
"e": 5967,
"s": 5942,
"text": "Splash Screen in Flutter"
}
] |
How to delete an item or object from the array using ng-click ? | 10 Jun, 2020
The task is to delete the item from the list when the button is clicked. This all should be done by using ng-click. This is done by using the splice() method. The syntax for the method is given below.
Syntax for splice() function:
array.splice(indexno, noofitems(n), item-1, item-2, ..., item-n)
Example for splice() function:
const topics = ['Array', 'String', 'Vector'];let removed=topics.splice(1, 1);
Output:
['Array', 'Vector']
The keywords in syntax are explained here:
indexno: This is required quantity. Definition is integer that specifies at what position to add/remove items.If it is negative means to specify the position from the end of the array.
noofitems(n): This is optional quantity. This indicates a number of items to be removed. If it is set to 0, no items will be removed.
item-1, ...item-n:This is also optional quantity. This indicates new item(s) to be added to the array
Example: Let us focus on example more. Here we will try to prove the delete operation via example. Here student names are given who have an account on GeeksForGeeks. We will try to delete one of the names from the array of student_names.
<!DOCTYPE html> <html> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"> </script> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <script> var app = angular.module("studentNames", []); </script> <div ng-app="studentNames" ng-init="names= ['Madhavi', 'Shivay', 'Priya']"> <ul> <li ng-repeat="x in names track by $index">{{x}} <span ng-click="names.splice($index, 1)"> <strong>x</strong</span> </li> </ul> <input ng-model="addItem"> <button ng-click="names.push(addItem)">Add</button></div> <p>Click the small x given in front of name to remove an item from the name list.</p> </body></html>
Output:Before Click:
After click:
AngularJS-Directives
AngularJS-Function
Picked
AngularJS
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": "\n10 Jun, 2020"
},
{
"code": null,
"e": 229,
"s": 28,
"text": "The task is to delete the item from the list when the button is clicked. This all should be done by using ng-click. This is done by using the splice() method. The syntax for the method is given below."
},
{
"code": null,
"e": 259,
"s": 229,
"text": "Syntax for splice() function:"
},
{
"code": null,
"e": 325,
"s": 259,
"text": "array.splice(indexno, noofitems(n), item-1, item-2, ..., item-n)\n"
},
{
"code": null,
"e": 356,
"s": 325,
"text": "Example for splice() function:"
},
{
"code": "const topics = ['Array', 'String', 'Vector'];let removed=topics.splice(1, 1);",
"e": 434,
"s": 356,
"text": null
},
{
"code": null,
"e": 442,
"s": 434,
"text": "Output:"
},
{
"code": null,
"e": 463,
"s": 442,
"text": "['Array', 'Vector']\n"
},
{
"code": null,
"e": 506,
"s": 463,
"text": "The keywords in syntax are explained here:"
},
{
"code": null,
"e": 691,
"s": 506,
"text": "indexno: This is required quantity. Definition is integer that specifies at what position to add/remove items.If it is negative means to specify the position from the end of the array."
},
{
"code": null,
"e": 825,
"s": 691,
"text": "noofitems(n): This is optional quantity. This indicates a number of items to be removed. If it is set to 0, no items will be removed."
},
{
"code": null,
"e": 927,
"s": 825,
"text": "item-1, ...item-n:This is also optional quantity. This indicates new item(s) to be added to the array"
},
{
"code": null,
"e": 1165,
"s": 927,
"text": "Example: Let us focus on example more. Here we will try to prove the delete operation via example. Here student names are given who have an account on GeeksForGeeks. We will try to delete one of the names from the array of student_names."
},
{
"code": "<!DOCTYPE html> <html> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js\"> </script> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <script> var app = angular.module(\"studentNames\", []); </script> <div ng-app=\"studentNames\" ng-init=\"names= ['Madhavi', 'Shivay', 'Priya']\"> <ul> <li ng-repeat=\"x in names track by $index\">{{x}} <span ng-click=\"names.splice($index, 1)\"> <strong>x</strong</span> </li> </ul> <input ng-model=\"addItem\"> <button ng-click=\"names.push(addItem)\">Add</button></div> <p>Click the small x given in front of name to remove an item from the name list.</p> </body></html>",
"e": 1895,
"s": 1165,
"text": null
},
{
"code": null,
"e": 1916,
"s": 1895,
"text": "Output:Before Click:"
},
{
"code": null,
"e": 1929,
"s": 1916,
"text": "After click:"
},
{
"code": null,
"e": 1950,
"s": 1929,
"text": "AngularJS-Directives"
},
{
"code": null,
"e": 1969,
"s": 1950,
"text": "AngularJS-Function"
},
{
"code": null,
"e": 1976,
"s": 1969,
"text": "Picked"
},
{
"code": null,
"e": 1986,
"s": 1976,
"text": "AngularJS"
},
{
"code": null,
"e": 2003,
"s": 1986,
"text": "Web Technologies"
}
] |
R-CNN | Region Based CNNs | 01 Mar, 2020
Since Convolution Neural Network (CNN) with a fully connected layer is not able to deal with the frequency of occurrence and multi objects. So, one way could be that we use a sliding window brute force search to select a region and apply the CNN model on that, but the problem of this approach is that the same object can be represented in an image with different sizes and different aspect ratio. While considering these factors we have a lot of region proposals and if we apply deep learning (CNN) on all those regions that would computationally very expensive.
R-CNN architecture
Ross Girshick et al.in 2013 proposed an architecture called R-CNN (Region-based CNN) to deal with this challenge of object detection. This R-CNN architecture uses the selective search algorithm that generates approximately 2000 region proposals. These 2000 region proposals are then provided to CNN architecture that computes CNN features. These features are then passed in an SVM model to classify the object present in the region proposal. An extra step is to perform a bounding box regressor to localize the objects present in the image more precisely.
Region Proposals:Region proposals are simply the smaller regions of the image that possibly contains the objects we are searching for in the input image. To reduce the region proposals in the R-CNN uses a greedy algorithm called selective search.
Region Proposals generation using selective search ( Image Source: link)
Selective Search :Selective search is a greedy algorithm that combines smaller segmented regions to generate region proposal. This algorithm takes an image as input and output generate region proposals on it. This algorithm has the advantage over random proposal generation is that it limits the number of proposals to approximately 2000 and these region proposals have a high recall.
Algorithm:
Generate initial sub-segmentation of input image.Combine similar bounding boxes into larger ones recursivelUse these larger boxes to generate region proposals for object detection.
Generate initial sub-segmentation of input image.
Combine similar bounding boxes into larger ones recursivel
Use these larger boxes to generate region proposals for object detection.
In Step 2 similarities are considered based on colour similarity, texture similarity, region size, etc. We have discussed the selective search algorithm in great detail in this article.
CNN architecture of R-CNN :After that these regions are warped into the single square of regions of dimension as required by the CNN model. The CNN model that we used here is a pre-trained AlexNet model, which is the state of the art CNN model at that time for image classification Let’s look at AlexNet architecture here.
Here the input of AlexNet is (227, 227, 3). So, if the region proposals are small and large then we need to resize that region proposal to given dimensions.
From the above architecture, we remove the last softmax layer to get (1, 4096) feature vector. We pass this feature vector into SVM and bounding box regressor.
SVM (Support Vector Machine):The feature vector generated by CNN is then consumed by the binary SVM which is trained on each class independently. This SVM model takes feature vector generated in previous CNN architecture and outputs a confidence score of the presence of an object in that region. However, there is an issue for training with SVM is that we required AlexNet feature vectors for training SVM class. So, we could not train AlexNet and SVM independently in paralleled manner. This challenge is resolved in future versions of R-CNN (Fast R-CNN, Faster R-CNN etc.).
Bounding Box Regressor:In order to precisely locate the bounding box in the image., we used a scale-invariant linear regression model called bounding box regressor. For training this model we take as predicted and Ground truth pairs of four dimensions of localization. These dimensions are (x, y, w, h) where x and y are the pixel coordinates of center of bounding box respectively. w and h represents the width and height of bounding boxes. This method increases Mean Average precision (mAP) of the result by 3-4%.
Output:Now we have region proposals that are classified for every class label. In order to deal with the extra bounding box generated by the above model into the image, we use an algorithm called Non- maximum suppression.It works in 3 steps:
Discard those objects where the confidence score is less than a certain threshold value( say 0.5).
Select the region which has the highest probability among candidates regions for object as predicted region.
In the final step we discard those regions which has IoU (intersection Over Union) with predicted region over 0.5.
After that we can obtain output by plotting these bounding boxes on input image and labeling objects that are present in bounding boxes.Results:The R-CNN gives Mean Average Precision (mAPs) of 53.7% on VOC 2010 dataset. On 200-class ILSVRC 2013 object detection dataset it gives mAP of 31.4% which is large improvement from previous best 24.3%. However, this architecture is very slow to train and takes ~ 49 sec to generate test results on a single image of VOC 2007 dataset.
Challenges of R-CNN:
Selective Search algorithm is very rigid and there is no learning happens in that. This sometimes leads to bad region proposals generation for object detection.
Since there are approximately 2000 candidate proposals. It takes a lot of time to train the network. Also we need to train multiple steps separately (CNN architecture, SVM model, bounding box regressor). So, This makes it very slow to implement.
R-CNN can not be used in real time because it takes approximately 50 sec to test an image with bounding box regressor.
Since we need to save feature maps of all the region proposals. It also increases the amount of disk memory required during training.
References:
R-CNN paper
Selective Search paper
Artificial Intelligence
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Mar, 2020"
},
{
"code": null,
"e": 592,
"s": 28,
"text": "Since Convolution Neural Network (CNN) with a fully connected layer is not able to deal with the frequency of occurrence and multi objects. So, one way could be that we use a sliding window brute force search to select a region and apply the CNN model on that, but the problem of this approach is that the same object can be represented in an image with different sizes and different aspect ratio. While considering these factors we have a lot of region proposals and if we apply deep learning (CNN) on all those regions that would computationally very expensive."
},
{
"code": null,
"e": 611,
"s": 592,
"text": "R-CNN architecture"
},
{
"code": null,
"e": 1167,
"s": 611,
"text": "Ross Girshick et al.in 2013 proposed an architecture called R-CNN (Region-based CNN) to deal with this challenge of object detection. This R-CNN architecture uses the selective search algorithm that generates approximately 2000 region proposals. These 2000 region proposals are then provided to CNN architecture that computes CNN features. These features are then passed in an SVM model to classify the object present in the region proposal. An extra step is to perform a bounding box regressor to localize the objects present in the image more precisely."
},
{
"code": null,
"e": 1414,
"s": 1167,
"text": "Region Proposals:Region proposals are simply the smaller regions of the image that possibly contains the objects we are searching for in the input image. To reduce the region proposals in the R-CNN uses a greedy algorithm called selective search."
},
{
"code": null,
"e": 1488,
"s": 1414,
"text": " Region Proposals generation using selective search ( Image Source: link)"
},
{
"code": null,
"e": 1873,
"s": 1488,
"text": "Selective Search :Selective search is a greedy algorithm that combines smaller segmented regions to generate region proposal. This algorithm takes an image as input and output generate region proposals on it. This algorithm has the advantage over random proposal generation is that it limits the number of proposals to approximately 2000 and these region proposals have a high recall."
},
{
"code": null,
"e": 1884,
"s": 1873,
"text": "Algorithm:"
},
{
"code": null,
"e": 2065,
"s": 1884,
"text": "Generate initial sub-segmentation of input image.Combine similar bounding boxes into larger ones recursivelUse these larger boxes to generate region proposals for object detection."
},
{
"code": null,
"e": 2115,
"s": 2065,
"text": "Generate initial sub-segmentation of input image."
},
{
"code": null,
"e": 2174,
"s": 2115,
"text": "Combine similar bounding boxes into larger ones recursivel"
},
{
"code": null,
"e": 2248,
"s": 2174,
"text": "Use these larger boxes to generate region proposals for object detection."
},
{
"code": null,
"e": 2434,
"s": 2248,
"text": "In Step 2 similarities are considered based on colour similarity, texture similarity, region size, etc. We have discussed the selective search algorithm in great detail in this article."
},
{
"code": null,
"e": 2757,
"s": 2434,
"text": "CNN architecture of R-CNN :After that these regions are warped into the single square of regions of dimension as required by the CNN model. The CNN model that we used here is a pre-trained AlexNet model, which is the state of the art CNN model at that time for image classification Let’s look at AlexNet architecture here."
},
{
"code": null,
"e": 2914,
"s": 2757,
"text": "Here the input of AlexNet is (227, 227, 3). So, if the region proposals are small and large then we need to resize that region proposal to given dimensions."
},
{
"code": null,
"e": 3074,
"s": 2914,
"text": "From the above architecture, we remove the last softmax layer to get (1, 4096) feature vector. We pass this feature vector into SVM and bounding box regressor."
},
{
"code": null,
"e": 3653,
"s": 3076,
"text": "SVM (Support Vector Machine):The feature vector generated by CNN is then consumed by the binary SVM which is trained on each class independently. This SVM model takes feature vector generated in previous CNN architecture and outputs a confidence score of the presence of an object in that region. However, there is an issue for training with SVM is that we required AlexNet feature vectors for training SVM class. So, we could not train AlexNet and SVM independently in paralleled manner. This challenge is resolved in future versions of R-CNN (Fast R-CNN, Faster R-CNN etc.)."
},
{
"code": null,
"e": 4169,
"s": 3653,
"text": "Bounding Box Regressor:In order to precisely locate the bounding box in the image., we used a scale-invariant linear regression model called bounding box regressor. For training this model we take as predicted and Ground truth pairs of four dimensions of localization. These dimensions are (x, y, w, h) where x and y are the pixel coordinates of center of bounding box respectively. w and h represents the width and height of bounding boxes. This method increases Mean Average precision (mAP) of the result by 3-4%."
},
{
"code": null,
"e": 4411,
"s": 4169,
"text": "Output:Now we have region proposals that are classified for every class label. In order to deal with the extra bounding box generated by the above model into the image, we use an algorithm called Non- maximum suppression.It works in 3 steps:"
},
{
"code": null,
"e": 4510,
"s": 4411,
"text": "Discard those objects where the confidence score is less than a certain threshold value( say 0.5)."
},
{
"code": null,
"e": 4619,
"s": 4510,
"text": "Select the region which has the highest probability among candidates regions for object as predicted region."
},
{
"code": null,
"e": 4734,
"s": 4619,
"text": "In the final step we discard those regions which has IoU (intersection Over Union) with predicted region over 0.5."
},
{
"code": null,
"e": 5211,
"s": 4734,
"text": "After that we can obtain output by plotting these bounding boxes on input image and labeling objects that are present in bounding boxes.Results:The R-CNN gives Mean Average Precision (mAPs) of 53.7% on VOC 2010 dataset. On 200-class ILSVRC 2013 object detection dataset it gives mAP of 31.4% which is large improvement from previous best 24.3%. However, this architecture is very slow to train and takes ~ 49 sec to generate test results on a single image of VOC 2007 dataset."
},
{
"code": null,
"e": 5232,
"s": 5211,
"text": "Challenges of R-CNN:"
},
{
"code": null,
"e": 5393,
"s": 5232,
"text": "Selective Search algorithm is very rigid and there is no learning happens in that. This sometimes leads to bad region proposals generation for object detection."
},
{
"code": null,
"e": 5639,
"s": 5393,
"text": "Since there are approximately 2000 candidate proposals. It takes a lot of time to train the network. Also we need to train multiple steps separately (CNN architecture, SVM model, bounding box regressor). So, This makes it very slow to implement."
},
{
"code": null,
"e": 5758,
"s": 5639,
"text": "R-CNN can not be used in real time because it takes approximately 50 sec to test an image with bounding box regressor."
},
{
"code": null,
"e": 5892,
"s": 5758,
"text": "Since we need to save feature maps of all the region proposals. It also increases the amount of disk memory required during training."
},
{
"code": null,
"e": 5904,
"s": 5892,
"text": "References:"
},
{
"code": null,
"e": 5916,
"s": 5904,
"text": "R-CNN paper"
},
{
"code": null,
"e": 5939,
"s": 5916,
"text": "Selective Search paper"
},
{
"code": null,
"e": 5963,
"s": 5939,
"text": "Artificial Intelligence"
},
{
"code": null,
"e": 5980,
"s": 5963,
"text": "Machine Learning"
},
{
"code": null,
"e": 5987,
"s": 5980,
"text": "Python"
},
{
"code": null,
"e": 6004,
"s": 5987,
"text": "Machine Learning"
}
] |
java.io.UnsupportedEncodingException in Java with Examples | 16 Sep, 2021
The java.io.UnsupportedEncodingException occurs when an unsupported character encoding scheme is used in java strings or bytes. The java String getBytes method converts the requested string to bytes in the specified encoding format. If java does not support the encoding format, the method String getBytes throws java.io.UnsupportedEncodingException with the encoding format given.
The character encoding is used to determine how the raw binary is to be interpreted to a character. The default encoding for English Windows systems in CP1252. Other languages and systems can use a different default encoding. The UTF-8 encoding scheme is generally used as a character encoding scheme. In java, String.getBytes() and StringCoding.encode() methods are used to interpret between raw bytes and java strings.
Class Viewer
java.lang.Object
java.lang.Throwable
java.lang.Exception
java.io.IOException
java.io.UnsupportedEncodingException
Remember: It does implement Serializable interfaces.
Syntax:
public class UnsupportedEncodingException
extends IOException
The Character Encoding is not supported. Further moving ahead let us do go through the constructors of this class which are s follows:
UnsupportedEncodingException(): Constructs an UnsupportedEncodingException without a detail message.UnsupportedEncodingException(String s): Constructs an UnsupportedEncodingException with a detailed message.
UnsupportedEncodingException(): Constructs an UnsupportedEncodingException without a detail message.
UnsupportedEncodingException(String s): Constructs an UnsupportedEncodingException with a detailed message.
Implementation:
Now let us find a way out in order to how to reproduce this issue as stated UnsupportedEncodingException in java. We will carry over with the help of an example provided below that will be throw java.io.UnsupportedEncodingException. The “UTF” encoding scheme is an invalid encoding scheme name. It is because java can not interpret the string to bytes if the encoding scheme is unknown or not supported. Java will throw java.io. UnsupportedEncodingException if an unknown or unsupported encoding method is identified.
Example
Java
// Java Program to Illustrate UnsupportedEncodingException // Main class// StringGetBytesclass GFG { // Main driver method public static void main(String[] args) throws Exception { // Custom input string String str = "GeeksforGeeks"; // Declaring a byte array byte[] bytes; bytes = str.getBytes("UTF"); // Now here we are trying printing // given string and corresponding output string System.out.println("Given String : " + str); System.out.println("Output bytes : " + bytes); }}
Output:
Now we are well versed with the exception and have discussed why does it occur. Now let us figure a way out to get rid iff from this exception by proposing the solution to it. The java supported encoding scheme name should be provided in String.getBytes method. Do go through the set of provided methods been up here before proceeding further.
Hence, the CharsetEncoder class should be used when more control over the encoding process is required. The String.getBytes method returns with an array of bytes.
Example
Java
// Java Program to Resolve UnsupportedEncodingException // Main class// StringGetBytespublic class GFG { // Main driver method public static void main(String[] args) throws Exception { // Custom input string String str = "GeeksforGeeks"; byte[] bytes; // Getting output bytes via help of getBytes() // method bytes = str.getBytes("UTF-16"); // Print and display input string and // corresponding UTF16 string System.out.println("Given String : " + str); System.out.println("Output bytes : " + bytes); }}
Given String : GeeksforGeeks
Output bytes : [B@7cc355be
Java-Exceptions
Picked
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Sep, 2021"
},
{
"code": null,
"e": 410,
"s": 28,
"text": "The java.io.UnsupportedEncodingException occurs when an unsupported character encoding scheme is used in java strings or bytes. The java String getBytes method converts the requested string to bytes in the specified encoding format. If java does not support the encoding format, the method String getBytes throws java.io.UnsupportedEncodingException with the encoding format given."
},
{
"code": null,
"e": 831,
"s": 410,
"text": "The character encoding is used to determine how the raw binary is to be interpreted to a character. The default encoding for English Windows systems in CP1252. Other languages and systems can use a different default encoding. The UTF-8 encoding scheme is generally used as a character encoding scheme. In java, String.getBytes() and StringCoding.encode() methods are used to interpret between raw bytes and java strings."
},
{
"code": null,
"e": 844,
"s": 831,
"text": "Class Viewer"
},
{
"code": null,
"e": 998,
"s": 844,
"text": "java.lang.Object\n java.lang.Throwable\n java.lang.Exception\n java.io.IOException\n java.io.UnsupportedEncodingException"
},
{
"code": null,
"e": 1051,
"s": 998,
"text": "Remember: It does implement Serializable interfaces."
},
{
"code": null,
"e": 1060,
"s": 1051,
"text": "Syntax: "
},
{
"code": null,
"e": 1122,
"s": 1060,
"text": "public class UnsupportedEncodingException\nextends IOException"
},
{
"code": null,
"e": 1257,
"s": 1122,
"text": "The Character Encoding is not supported. Further moving ahead let us do go through the constructors of this class which are s follows:"
},
{
"code": null,
"e": 1467,
"s": 1257,
"text": " UnsupportedEncodingException(): Constructs an UnsupportedEncodingException without a detail message.UnsupportedEncodingException(String s): Constructs an UnsupportedEncodingException with a detailed message. "
},
{
"code": null,
"e": 1569,
"s": 1467,
"text": " UnsupportedEncodingException(): Constructs an UnsupportedEncodingException without a detail message."
},
{
"code": null,
"e": 1678,
"s": 1569,
"text": "UnsupportedEncodingException(String s): Constructs an UnsupportedEncodingException with a detailed message. "
},
{
"code": null,
"e": 1694,
"s": 1678,
"text": "Implementation:"
},
{
"code": null,
"e": 2212,
"s": 1694,
"text": "Now let us find a way out in order to how to reproduce this issue as stated UnsupportedEncodingException in java. We will carry over with the help of an example provided below that will be throw java.io.UnsupportedEncodingException. The “UTF” encoding scheme is an invalid encoding scheme name. It is because java can not interpret the string to bytes if the encoding scheme is unknown or not supported. Java will throw java.io. UnsupportedEncodingException if an unknown or unsupported encoding method is identified."
},
{
"code": null,
"e": 2220,
"s": 2212,
"text": "Example"
},
{
"code": null,
"e": 2225,
"s": 2220,
"text": "Java"
},
{
"code": "// Java Program to Illustrate UnsupportedEncodingException // Main class// StringGetBytesclass GFG { // Main driver method public static void main(String[] args) throws Exception { // Custom input string String str = \"GeeksforGeeks\"; // Declaring a byte array byte[] bytes; bytes = str.getBytes(\"UTF\"); // Now here we are trying printing // given string and corresponding output string System.out.println(\"Given String : \" + str); System.out.println(\"Output bytes : \" + bytes); }}",
"e": 2793,
"s": 2225,
"text": null
},
{
"code": null,
"e": 2802,
"s": 2793,
"text": "Output: "
},
{
"code": null,
"e": 3147,
"s": 2802,
"text": "Now we are well versed with the exception and have discussed why does it occur. Now let us figure a way out to get rid iff from this exception by proposing the solution to it. The java supported encoding scheme name should be provided in String.getBytes method. Do go through the set of provided methods been up here before proceeding further. "
},
{
"code": null,
"e": 3310,
"s": 3147,
"text": "Hence, the CharsetEncoder class should be used when more control over the encoding process is required. The String.getBytes method returns with an array of bytes."
},
{
"code": null,
"e": 3318,
"s": 3310,
"text": "Example"
},
{
"code": null,
"e": 3323,
"s": 3318,
"text": "Java"
},
{
"code": "// Java Program to Resolve UnsupportedEncodingException // Main class// StringGetBytespublic class GFG { // Main driver method public static void main(String[] args) throws Exception { // Custom input string String str = \"GeeksforGeeks\"; byte[] bytes; // Getting output bytes via help of getBytes() // method bytes = str.getBytes(\"UTF-16\"); // Print and display input string and // corresponding UTF16 string System.out.println(\"Given String : \" + str); System.out.println(\"Output bytes : \" + bytes); }}",
"e": 3921,
"s": 3323,
"text": null
},
{
"code": null,
"e": 3981,
"s": 3921,
"text": "Given String : GeeksforGeeks\nOutput bytes : [B@7cc355be\n"
},
{
"code": null,
"e": 3997,
"s": 3981,
"text": "Java-Exceptions"
},
{
"code": null,
"e": 4004,
"s": 3997,
"text": "Picked"
},
{
"code": null,
"e": 4009,
"s": 4004,
"text": "Java"
},
{
"code": null,
"e": 4014,
"s": 4009,
"text": "Java"
}
] |
Find the sum of the first half and second half elements of an array | 25 May, 2022
Given an array arr of size N. The task is to find the sum of the first half (N/2) elements and second half elements (N – N/2) of an array.Examples:
Input : arr[] = {20, 30, 60, 10, 25, 15, 40} Output : 110, 90 Sum of first N/2 elements 20 + 30 + 60 is 110Input : arr[] = {50, 35, 20, 15} Output : 85, 35
Approach: Initialize SumFirst and SumSecond as 0. Traverse the given array and add elements in SumFirst if the current index is less than N/2 otherwise add in SumSecond.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to find the sum of the first half// elements and second half elements of an array#include <bits/stdc++.h>using namespace std; // Function to find the sum of the first half// elements and second half elements of an arrayvoid sum_of_elements(int arr[], int n){ int sumfirst = 0, sumsecond = 0; for (int i = 0; i < n; i++) { // Add elements in first half sum if (i < n / 2) sumfirst += arr[i]; // Add elements in the second half sum else sumsecond += arr[i]; } cout << "Sum of first half elements is " << sumfirst << endl; cout << "Sum of second half elements is " << sumsecond << endl;} // Driver Codeint main(){ int arr[] = { 20, 30, 60, 10, 25, 15, 40 }; int n = sizeof(arr) / sizeof(arr[0]); // Function call sum_of_elements(arr, n); return 0;}
// Java program to count pairs// whose sum divisible by 'K'import java.util.*; class GFG{ public static void sum_of_elements(int []arr, int n){ int sumfirst = 0, sumsecond = 0; for (int i = 0; i < n; i++) { // Add elements in first half sum if (i < n / 2) { sumfirst += arr[i]; } // Add elements in the second half sum else { sumsecond += arr[i]; } } System.out.println("Sum of first half elements is " + sumfirst); System.out.println("Sum of second half elements is " + sumsecond);} // Driver codepublic static void main(String[] args){ int []arr = { 20, 30, 60, 10, 25, 15, 40 }; int n = arr.length; // Function call sum_of_elements(arr, n);}} // This code is contributed by Princi Singh
# Python3 program to find the sum of# the first half elements and# second half elements of an array # Function to find the sum of # the first half elements and# second half elements of an arraydef sum_of_elements(arr, n): sumfirst = 0; sumsecond = 0; for i in range(n): # Add elements in first half sum if (i < n // 2): sumfirst += arr[i]; # Add elements in the second half sum else: sumsecond += arr[i]; print("Sum of first half elements is", sumfirst, end = "\n"); print("Sum of second half elements is", sumsecond, end = "\n"); # Driver Codearr = [20, 30, 60, 10, 25, 15, 40]; n = len(arr); # Function callsum_of_elements(arr, n); # This code is contributed# by Akanksha Rai
// C# program to count pairs// whose sum divisible by 'K'using System; class GFG{ public static void sum_of_elements(int []arr, int n) { int sumfirst = 0, sumsecond = 0; for (int i = 0; i < n; i++) { // Add elements in first half sum if (i < n / 2) { sumfirst += arr[i]; } // Add elements in the second half sum else { sumsecond += arr[i]; } } Console.WriteLine("Sum of first half elements is " + sumfirst); Console.WriteLine("Sum of second half elements is " + sumsecond);} // Driver codestatic public void Main (){ int []arr = { 20, 30, 60, 10, 25, 15, 40 }; int n = arr.Length; // Function call sum_of_elements(arr, n);}} // This code is contributed by nidhiva
<script> // Javascript program to count pairs// whose sum divisible by 'K' function sum_of_elements(arr , n) { var sumfirst = 0, sumsecond = 0; for (i = 0; i < n; i++) { // Add elements in first half sum if (i < parseInt(n / 2)) { sumfirst += arr[i]; } // Add elements in the second half sum else { sumsecond += arr[i]; } } document.write( "Sum of first half elements is " + sumfirst+"<br/>" ); document.write( "Sum of second half elements is " + sumsecond+"<br/>" ); } // Driver code var arr = [ 20, 30, 60, 10, 25, 15, 40 ]; var n = arr.length; // Function call sum_of_elements(arr, n); // This code contributed by umadevi9616 </script>
Sum of first half elements is 110
Sum of second half elements is 90
Time complexity: O(N), as we are using a loop to traverse the array.Auxiliary Space: O(1), as we are not using any extra space.
nidhiva
princi singh
Akanksha_Rai
subhammahato348
umadevi9616
anikakapoor
rohitsingh07052
school-programming
Arrays
Mathematical
Arrays
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n25 May, 2022"
},
{
"code": null,
"e": 202,
"s": 53,
"text": "Given an array arr of size N. The task is to find the sum of the first half (N/2) elements and second half elements (N – N/2) of an array.Examples: "
},
{
"code": null,
"e": 358,
"s": 202,
"text": "Input : arr[] = {20, 30, 60, 10, 25, 15, 40} Output : 110, 90 Sum of first N/2 elements 20 + 30 + 60 is 110Input : arr[] = {50, 35, 20, 15} Output : 85, 35"
},
{
"code": null,
"e": 579,
"s": 358,
"text": "Approach: Initialize SumFirst and SumSecond as 0. Traverse the given array and add elements in SumFirst if the current index is less than N/2 otherwise add in SumSecond.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 583,
"s": 579,
"text": "C++"
},
{
"code": null,
"e": 588,
"s": 583,
"text": "Java"
},
{
"code": null,
"e": 596,
"s": 588,
"text": "Python3"
},
{
"code": null,
"e": 599,
"s": 596,
"text": "C#"
},
{
"code": null,
"e": 610,
"s": 599,
"text": "Javascript"
},
{
"code": "// C++ program to find the sum of the first half// elements and second half elements of an array#include <bits/stdc++.h>using namespace std; // Function to find the sum of the first half// elements and second half elements of an arrayvoid sum_of_elements(int arr[], int n){ int sumfirst = 0, sumsecond = 0; for (int i = 0; i < n; i++) { // Add elements in first half sum if (i < n / 2) sumfirst += arr[i]; // Add elements in the second half sum else sumsecond += arr[i]; } cout << \"Sum of first half elements is \" << sumfirst << endl; cout << \"Sum of second half elements is \" << sumsecond << endl;} // Driver Codeint main(){ int arr[] = { 20, 30, 60, 10, 25, 15, 40 }; int n = sizeof(arr) / sizeof(arr[0]); // Function call sum_of_elements(arr, n); return 0;}",
"e": 1526,
"s": 610,
"text": null
},
{
"code": "// Java program to count pairs// whose sum divisible by 'K'import java.util.*; class GFG{ public static void sum_of_elements(int []arr, int n){ int sumfirst = 0, sumsecond = 0; for (int i = 0; i < n; i++) { // Add elements in first half sum if (i < n / 2) { sumfirst += arr[i]; } // Add elements in the second half sum else { sumsecond += arr[i]; } } System.out.println(\"Sum of first half elements is \" + sumfirst); System.out.println(\"Sum of second half elements is \" + sumsecond);} // Driver codepublic static void main(String[] args){ int []arr = { 20, 30, 60, 10, 25, 15, 40 }; int n = arr.length; // Function call sum_of_elements(arr, n);}} // This code is contributed by Princi Singh",
"e": 2483,
"s": 1526,
"text": null
},
{
"code": "# Python3 program to find the sum of# the first half elements and# second half elements of an array # Function to find the sum of # the first half elements and# second half elements of an arraydef sum_of_elements(arr, n): sumfirst = 0; sumsecond = 0; for i in range(n): # Add elements in first half sum if (i < n // 2): sumfirst += arr[i]; # Add elements in the second half sum else: sumsecond += arr[i]; print(\"Sum of first half elements is\", sumfirst, end = \"\\n\"); print(\"Sum of second half elements is\", sumsecond, end = \"\\n\"); # Driver Codearr = [20, 30, 60, 10, 25, 15, 40]; n = len(arr); # Function callsum_of_elements(arr, n); # This code is contributed# by Akanksha Rai",
"e": 3289,
"s": 2483,
"text": null
},
{
"code": "// C# program to count pairs// whose sum divisible by 'K'using System; class GFG{ public static void sum_of_elements(int []arr, int n) { int sumfirst = 0, sumsecond = 0; for (int i = 0; i < n; i++) { // Add elements in first half sum if (i < n / 2) { sumfirst += arr[i]; } // Add elements in the second half sum else { sumsecond += arr[i]; } } Console.WriteLine(\"Sum of first half elements is \" + sumfirst); Console.WriteLine(\"Sum of second half elements is \" + sumsecond);} // Driver codestatic public void Main (){ int []arr = { 20, 30, 60, 10, 25, 15, 40 }; int n = arr.Length; // Function call sum_of_elements(arr, n);}} // This code is contributed by nidhiva",
"e": 4234,
"s": 3289,
"text": null
},
{
"code": "<script> // Javascript program to count pairs// whose sum divisible by 'K' function sum_of_elements(arr , n) { var sumfirst = 0, sumsecond = 0; for (i = 0; i < n; i++) { // Add elements in first half sum if (i < parseInt(n / 2)) { sumfirst += arr[i]; } // Add elements in the second half sum else { sumsecond += arr[i]; } } document.write( \"Sum of first half elements is \" + sumfirst+\"<br/>\" ); document.write( \"Sum of second half elements is \" + sumsecond+\"<br/>\" ); } // Driver code var arr = [ 20, 30, 60, 10, 25, 15, 40 ]; var n = arr.length; // Function call sum_of_elements(arr, n); // This code contributed by umadevi9616 </script>",
"e": 5089,
"s": 4234,
"text": null
},
{
"code": null,
"e": 5157,
"s": 5089,
"text": "Sum of first half elements is 110\nSum of second half elements is 90"
},
{
"code": null,
"e": 5287,
"s": 5159,
"text": "Time complexity: O(N), as we are using a loop to traverse the array.Auxiliary Space: O(1), as we are not using any extra space."
},
{
"code": null,
"e": 5295,
"s": 5287,
"text": "nidhiva"
},
{
"code": null,
"e": 5308,
"s": 5295,
"text": "princi singh"
},
{
"code": null,
"e": 5321,
"s": 5308,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 5337,
"s": 5321,
"text": "subhammahato348"
},
{
"code": null,
"e": 5349,
"s": 5337,
"text": "umadevi9616"
},
{
"code": null,
"e": 5361,
"s": 5349,
"text": "anikakapoor"
},
{
"code": null,
"e": 5377,
"s": 5361,
"text": "rohitsingh07052"
},
{
"code": null,
"e": 5396,
"s": 5377,
"text": "school-programming"
},
{
"code": null,
"e": 5403,
"s": 5396,
"text": "Arrays"
},
{
"code": null,
"e": 5416,
"s": 5403,
"text": "Mathematical"
},
{
"code": null,
"e": 5423,
"s": 5416,
"text": "Arrays"
},
{
"code": null,
"e": 5436,
"s": 5423,
"text": "Mathematical"
}
] |
Recurrent Neural Networks Explanation | 06 Oct, 2021
Today, different Machine Learning techniques are used to handle different types of data. One of the most difficult types of data to handle and the forecast is sequential data. Sequential data is different from other types of data in the sense that while all the features of a typical dataset can be assumed to be order-independent, this cannot be assumed for a sequential dataset. To handle such type of data, the concept of Recurrent Neural Networks was conceived. It is different from other Artificial Neural Networks in its structure. While other networks “travel” in a linear direction during the feed-forward process or the back-propagation process, the Recurrent Network follows a recurrence relation instead of a feed-forward pass and uses Back-Propagation through time to learn.
The Recurrent Neural Network consists of multiple fixed activation function units, one for each time step. Each unit has an internal state which is called the hidden state of the unit. This hidden state signifies the past knowledge that the network currently holds at a given time step. This hidden state is updated at every time step to signify the change in the knowledge of the network about the past. The hidden state is updated using the following recurrence relation:-
[Tex]- The new hidden state[/Tex]
[Tex]- The old hidden state[/Tex]
[Tex]- The current input[/Tex]
[Tex]- The fixed function with trainable weights[/Tex]
Note: Typically, to understand the concepts of a Recurrent Neural Network, it is often illustrated in its unrolled form and this norm will be followed in this post.
At each time step, the new hidden state is calculated using the recurrence relation as given above. This new generated hidden state is used to generate indeed a new hidden state and so on.
The basic work-flow of a Recurrent Neural Network is as follows:-
Note that is the initial hidden state of the network. Typically, it is a vector of zeros, but it can have other values also. One method is to encode the presumptions about the data into the initial hidden state of the network. For example, for a problem to determine the tone of a speech given by a renowned person, the person’s past speeches’ tones may be encoded into the initial hidden state. Another technique is to make the initial hidden state a trainable parameter. Although these techniques add little nuances to the network, initializing the hidden state vector to zeros is typically an effective choice.
Working of each Recurrent Unit:
Take input the previously hidden state vector and the current input vector. Note that since the hidden state and current input are treated as vectors, each element in the vector is placed in a different dimension which is orthogonal to the other dimensions. Thus each element when multiplied by another element only gives a non-zero value when the elements involved are non-zero and the elements are in the same dimension.Element-wise multiplies the hidden state vector by the hidden state weights and similarly performs the element-wise multiplication of the current input vector and the current input weights. This generates the parameterized hidden state vector and the current input vector. Note that weights for different vectors are stored in the trainable weight matrix.Perform the vector addition of the two parameterized vectors and then calculate the element-wise hyperbolic tangent to generate the new hidden state vector.
Take input the previously hidden state vector and the current input vector. Note that since the hidden state and current input are treated as vectors, each element in the vector is placed in a different dimension which is orthogonal to the other dimensions. Thus each element when multiplied by another element only gives a non-zero value when the elements involved are non-zero and the elements are in the same dimension.
Note that since the hidden state and current input are treated as vectors, each element in the vector is placed in a different dimension which is orthogonal to the other dimensions. Thus each element when multiplied by another element only gives a non-zero value when the elements involved are non-zero and the elements are in the same dimension.
Element-wise multiplies the hidden state vector by the hidden state weights and similarly performs the element-wise multiplication of the current input vector and the current input weights. This generates the parameterized hidden state vector and the current input vector. Note that weights for different vectors are stored in the trainable weight matrix.
Note that weights for different vectors are stored in the trainable weight matrix.
Perform the vector addition of the two parameterized vectors and then calculate the element-wise hyperbolic tangent to generate the new hidden state vector.
During the training of the recurrent network, the network also generates an output at each time step. This output is used to train the network using gradient descent.
The Back-Propagation involved is similar to the one used in a typical Artificial Neural Network with some minor changes. These changes are noted as:-
Let the predicted output of the network at any time step be and the actual output be . Then the error at each time step is given by:-
The total error is given by the summation of the errors at all the time steps.
Similarly, the value can be calculated as the summation of gradients at each time step.
Using the chain rule of calculus and using the fact that the output at a time step t is a function of the current hidden state of the recurrent unit, the following expression arises:-
Note that the weight matrix W used in the above expression is different for the input vector and hidden state vector and is only used in this manner for notational convenience.
Thus the following expression arises:-
Thus, Back-Propagation Through Time only differs from a typical Back-Propagation in the fact the errors at each time step are summed up to calculate the total error.
Although the basic Recurrent Neural Network is fairly effective, it can suffer from a significant problem. For deep networks, The Back-Propagation process can lead to the following issues:-
Vanishing Gradients: This occurs when the gradients become very small and tend towards zero.
Exploding Gradients: This occurs when the gradients become too large due to back-propagation.
The problem of Exploding Gradients may be solved by using a hack – By putting a threshold on the gradients being passed back in time. But this solution is not seen as a solution to the problem and may also reduce the efficiency of the network. To deal with such problems, two main variants of Recurrent Neural Networks were developed – Long Short Term Memory Networks and Gated Recurrent Unit Networks.
saurabh1990aror
23620uday2021
Neural Network
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Oct, 2021"
},
{
"code": null,
"e": 816,
"s": 28,
"text": "Today, different Machine Learning techniques are used to handle different types of data. One of the most difficult types of data to handle and the forecast is sequential data. Sequential data is different from other types of data in the sense that while all the features of a typical dataset can be assumed to be order-independent, this cannot be assumed for a sequential dataset. To handle such type of data, the concept of Recurrent Neural Networks was conceived. It is different from other Artificial Neural Networks in its structure. While other networks “travel” in a linear direction during the feed-forward process or the back-propagation process, the Recurrent Network follows a recurrence relation instead of a feed-forward pass and uses Back-Propagation through time to learn. "
},
{
"code": null,
"e": 1292,
"s": 816,
"text": "The Recurrent Neural Network consists of multiple fixed activation function units, one for each time step. Each unit has an internal state which is called the hidden state of the unit. This hidden state signifies the past knowledge that the network currently holds at a given time step. This hidden state is updated at every time step to signify the change in the knowledge of the network about the past. The hidden state is updated using the following recurrence relation:- "
},
{
"code": null,
"e": 1448,
"s": 1294,
"text": "[Tex]- The new hidden state[/Tex]\n[Tex]- The old hidden state[/Tex]\n[Tex]- The current input[/Tex]\n[Tex]- The fixed function with trainable weights[/Tex]"
},
{
"code": null,
"e": 1614,
"s": 1448,
"text": "Note: Typically, to understand the concepts of a Recurrent Neural Network, it is often illustrated in its unrolled form and this norm will be followed in this post. "
},
{
"code": null,
"e": 1804,
"s": 1614,
"text": "At each time step, the new hidden state is calculated using the recurrence relation as given above. This new generated hidden state is used to generate indeed a new hidden state and so on. "
},
{
"code": null,
"e": 1871,
"s": 1804,
"text": "The basic work-flow of a Recurrent Neural Network is as follows:- "
},
{
"code": null,
"e": 2488,
"s": 1873,
"text": "Note that is the initial hidden state of the network. Typically, it is a vector of zeros, but it can have other values also. One method is to encode the presumptions about the data into the initial hidden state of the network. For example, for a problem to determine the tone of a speech given by a renowned person, the person’s past speeches’ tones may be encoded into the initial hidden state. Another technique is to make the initial hidden state a trainable parameter. Although these techniques add little nuances to the network, initializing the hidden state vector to zeros is typically an effective choice. "
},
{
"code": null,
"e": 2522,
"s": 2488,
"text": "Working of each Recurrent Unit: "
},
{
"code": null,
"e": 3456,
"s": 2522,
"text": "Take input the previously hidden state vector and the current input vector. Note that since the hidden state and current input are treated as vectors, each element in the vector is placed in a different dimension which is orthogonal to the other dimensions. Thus each element when multiplied by another element only gives a non-zero value when the elements involved are non-zero and the elements are in the same dimension.Element-wise multiplies the hidden state vector by the hidden state weights and similarly performs the element-wise multiplication of the current input vector and the current input weights. This generates the parameterized hidden state vector and the current input vector. Note that weights for different vectors are stored in the trainable weight matrix.Perform the vector addition of the two parameterized vectors and then calculate the element-wise hyperbolic tangent to generate the new hidden state vector."
},
{
"code": null,
"e": 3879,
"s": 3456,
"text": "Take input the previously hidden state vector and the current input vector. Note that since the hidden state and current input are treated as vectors, each element in the vector is placed in a different dimension which is orthogonal to the other dimensions. Thus each element when multiplied by another element only gives a non-zero value when the elements involved are non-zero and the elements are in the same dimension."
},
{
"code": null,
"e": 4226,
"s": 3879,
"text": "Note that since the hidden state and current input are treated as vectors, each element in the vector is placed in a different dimension which is orthogonal to the other dimensions. Thus each element when multiplied by another element only gives a non-zero value when the elements involved are non-zero and the elements are in the same dimension."
},
{
"code": null,
"e": 4582,
"s": 4226,
"text": "Element-wise multiplies the hidden state vector by the hidden state weights and similarly performs the element-wise multiplication of the current input vector and the current input weights. This generates the parameterized hidden state vector and the current input vector. Note that weights for different vectors are stored in the trainable weight matrix."
},
{
"code": null,
"e": 4665,
"s": 4582,
"text": "Note that weights for different vectors are stored in the trainable weight matrix."
},
{
"code": null,
"e": 4822,
"s": 4665,
"text": "Perform the vector addition of the two parameterized vectors and then calculate the element-wise hyperbolic tangent to generate the new hidden state vector."
},
{
"code": null,
"e": 4992,
"s": 4824,
"text": "During the training of the recurrent network, the network also generates an output at each time step. This output is used to train the network using gradient descent. "
},
{
"code": null,
"e": 5145,
"s": 4994,
"text": "The Back-Propagation involved is similar to the one used in a typical Artificial Neural Network with some minor changes. These changes are noted as:- "
},
{
"code": null,
"e": 5280,
"s": 5145,
"text": "Let the predicted output of the network at any time step be and the actual output be . Then the error at each time step is given by:- "
},
{
"code": null,
"e": 5360,
"s": 5280,
"text": "The total error is given by the summation of the errors at all the time steps. "
},
{
"code": null,
"e": 5449,
"s": 5360,
"text": "Similarly, the value can be calculated as the summation of gradients at each time step. "
},
{
"code": null,
"e": 5634,
"s": 5449,
"text": "Using the chain rule of calculus and using the fact that the output at a time step t is a function of the current hidden state of the recurrent unit, the following expression arises:- "
},
{
"code": null,
"e": 5812,
"s": 5634,
"text": "Note that the weight matrix W used in the above expression is different for the input vector and hidden state vector and is only used in this manner for notational convenience. "
},
{
"code": null,
"e": 5852,
"s": 5812,
"text": "Thus the following expression arises:- "
},
{
"code": null,
"e": 6019,
"s": 5852,
"text": "Thus, Back-Propagation Through Time only differs from a typical Back-Propagation in the fact the errors at each time step are summed up to calculate the total error. "
},
{
"code": null,
"e": 6213,
"s": 6021,
"text": "Although the basic Recurrent Neural Network is fairly effective, it can suffer from a significant problem. For deep networks, The Back-Propagation process can lead to the following issues:- "
},
{
"code": null,
"e": 6306,
"s": 6213,
"text": "Vanishing Gradients: This occurs when the gradients become very small and tend towards zero."
},
{
"code": null,
"e": 6400,
"s": 6306,
"text": "Exploding Gradients: This occurs when the gradients become too large due to back-propagation."
},
{
"code": null,
"e": 6804,
"s": 6400,
"text": "The problem of Exploding Gradients may be solved by using a hack – By putting a threshold on the gradients being passed back in time. But this solution is not seen as a solution to the problem and may also reduce the efficiency of the network. To deal with such problems, two main variants of Recurrent Neural Networks were developed – Long Short Term Memory Networks and Gated Recurrent Unit Networks. "
},
{
"code": null,
"e": 6820,
"s": 6804,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 6834,
"s": 6820,
"text": "23620uday2021"
},
{
"code": null,
"e": 6849,
"s": 6834,
"text": "Neural Network"
},
{
"code": null,
"e": 6866,
"s": 6849,
"text": "Machine Learning"
},
{
"code": null,
"e": 6873,
"s": 6866,
"text": "Python"
},
{
"code": null,
"e": 6890,
"s": 6873,
"text": "Machine Learning"
}
] |
Program to Print a New Line in C# | World
Stay
Safe
C#
C# Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 1551,
"s": 1511,
"text": "World\nStay\nSafe\n"
},
{
"code": null,
"e": 1554,
"s": 1551,
"text": "C#"
},
{
"code": null,
"e": 1566,
"s": 1554,
"text": "C# Programs"
}
] |
Subset sum queries using bitset | 06 Jul, 2022
Given an array arr[] and a number of queries, where in each query we have to check whether a subset whose sum is equal to given number exists in the array or not.
Examples:
Input : arr[] = {1, 2, 3};
query[] = {5, 3, 8}
Output : Yes, Yes, No
There is a subset with sum 5, subset is {2, 3}
There is a subset with sum 3, subset is {1, 2}
There is no subset with sum 8.
Input : arr[] = {4, 1, 5};
query[] = {7, 9}
Output : No, Yes
There is no subset with sum 7.
There is a subset with sum 9, subset is {4, 5}
The idea is to use bitset container in C++. Using bitset, we can precalculate the existence all the subset sums in an array in O(n) and answer subsequent queries in just O(1). We basically use an array of bits bit[] to represent the subset sum of elements in the array. Size of bit[] should be at least sum of all array elements plus 1 to answer all queries. We keep of bit[x] as 1 if x is a subset sum of given array, else false. Note that indexing is assumed to begin with 0.
For every element arr[i] of input array,
we do following
// bit[x] will be 1 if x is a subset
// sum of arr[], else 0
bit = bit | (bit << arr[i])
How does this work?
Let us consider arr[] = {3, 1, 5}, we need
to whether a subset sum of x exists or not,
where 0 ≤ x ≤ Σarri.
We create a bitset bit[10] and reset all the
bits to 0, i.e., we make it 0000000000.
Set the 0th bit, because a subset sum of 0
exists in every array.
Now, the bit array is 0000000001
Apply the above technique for all the elements
of the array :
Current bitset = 0000000001
After doing "bit = bit | (bit << 3)",
bitset becomes 0000001001
After doing "bit | (bit << 1)",
bitset becomes 0000011011
After doing "bit | (bit << 5)",
bitset becomes 1101111011
Finally, we have the bit array as 1101111011, so, if bit[x] is 1 then a subset sum of x exists otherwise not. We can clearly observe that a subset sum of all the numbers from 0 to 9 except 2 and 7 exists in the array.
Implementation:
CPP
// C++ program to answer subset sum queries using bitset#include <bits/stdc++.h>using namespace std; // Maximum allowed query value# define MAXSUM 10000 // function to check whether a subset sum equal to n// exists in the array or not.void processQueries(int query[], int nq, bitset<MAXSUM> bit){ // One by one process subset sum queries for (int i=0; i<nq; i++) { int x = query[i]; // If x is beyond size of bit[] if (x >= MAXSUM) { cout << "NA, "; continue; } // Else if x is a subset sum, then x'th bit // must be set bit[x]? cout << "Yes, " : cout << "No, "; }} // function to store all the subset sums in bit vectorvoid preprocess(bitset<MAXSUM> &bit, int arr[], int n){ // set all the bits to 0 bit.reset(); // set the 0th bit because subset sum of 0 exists bit[0] = 1; // Process all array elements one by one for (int i = 0; i < n; ++i) // Do OR of following two // 1) All previous sums. We keep previous value // of bit. // 2) arr[i] added to every previous sum. We // move all previous indexes arr[i] ahead. bit |= (bit << arr[i]);} // Driver programint main(){ int arr[] = {3, 1, 5}; int query[] = {8, 7}; int n = sizeof(arr) / sizeof(arr[0]); int nq = sizeof(query) / sizeof(query[0]); // a vector of MAXSUM number of bits bitset<MAXSUM> bit; preprocess(bit, arr, n); processQueries(query, nq, bit); return 0;}
Yes, No,
Time complexity : O(n) for pre-calculating and O(1) for subsequent queries, where n is the number of elements in the array.Auxiliary Space: O(n)
This article is contributed by Avinash Kumar Saw. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
ranjanrohit840
hardikkoriintern
CPP-bitset
subset
Arrays
Bit Magic
Arrays
Bit Magic
subset
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n06 Jul, 2022"
},
{
"code": null,
"e": 218,
"s": 54,
"text": "Given an array arr[] and a number of queries, where in each query we have to check whether a subset whose sum is equal to given number exists in the array or not. "
},
{
"code": null,
"e": 228,
"s": 218,
"text": "Examples:"
},
{
"code": null,
"e": 582,
"s": 228,
"text": "Input : arr[] = {1, 2, 3};\n query[] = {5, 3, 8} \nOutput : Yes, Yes, No\nThere is a subset with sum 5, subset is {2, 3}\nThere is a subset with sum 3, subset is {1, 2}\nThere is no subset with sum 8.\n\nInput : arr[] = {4, 1, 5};\n query[] = {7, 9}\nOutput : No, Yes\nThere is no subset with sum 7.\nThere is a subset with sum 9, subset is {4, 5}"
},
{
"code": null,
"e": 1060,
"s": 582,
"text": "The idea is to use bitset container in C++. Using bitset, we can precalculate the existence all the subset sums in an array in O(n) and answer subsequent queries in just O(1). We basically use an array of bits bit[] to represent the subset sum of elements in the array. Size of bit[] should be at least sum of all array elements plus 1 to answer all queries. We keep of bit[x] as 1 if x is a subset sum of given array, else false. Note that indexing is assumed to begin with 0."
},
{
"code": null,
"e": 1207,
"s": 1060,
"text": "For every element arr[i] of input array,\nwe do following\n\n// bit[x] will be 1 if x is a subset\n// sum of arr[], else 0\nbit = bit | (bit << arr[i])"
},
{
"code": null,
"e": 1227,
"s": 1207,
"text": "How does this work?"
},
{
"code": null,
"e": 1818,
"s": 1227,
"text": "Let us consider arr[] = {3, 1, 5}, we need \nto whether a subset sum of x exists or not, \nwhere 0 ≤ x ≤ Σarri.\n\nWe create a bitset bit[10] and reset all the \nbits to 0, i.e., we make it 0000000000.\n\nSet the 0th bit, because a subset sum of 0 \nexists in every array.\nNow, the bit array is 0000000001\n\nApply the above technique for all the elements\nof the array :\nCurrent bitset = 0000000001\n\nAfter doing \"bit = bit | (bit << 3)\", \nbitset becomes 0000001001\n\n\nAfter doing \"bit | (bit << 1)\", \nbitset becomes 0000011011\n\n\nAfter doing \"bit | (bit << 5)\", \nbitset becomes 1101111011 "
},
{
"code": null,
"e": 2037,
"s": 1818,
"text": "Finally, we have the bit array as 1101111011, so, if bit[x] is 1 then a subset sum of x exists otherwise not. We can clearly observe that a subset sum of all the numbers from 0 to 9 except 2 and 7 exists in the array. "
},
{
"code": null,
"e": 2053,
"s": 2037,
"text": "Implementation:"
},
{
"code": null,
"e": 2057,
"s": 2053,
"text": "CPP"
},
{
"code": "// C++ program to answer subset sum queries using bitset#include <bits/stdc++.h>using namespace std; // Maximum allowed query value# define MAXSUM 10000 // function to check whether a subset sum equal to n// exists in the array or not.void processQueries(int query[], int nq, bitset<MAXSUM> bit){ // One by one process subset sum queries for (int i=0; i<nq; i++) { int x = query[i]; // If x is beyond size of bit[] if (x >= MAXSUM) { cout << \"NA, \"; continue; } // Else if x is a subset sum, then x'th bit // must be set bit[x]? cout << \"Yes, \" : cout << \"No, \"; }} // function to store all the subset sums in bit vectorvoid preprocess(bitset<MAXSUM> &bit, int arr[], int n){ // set all the bits to 0 bit.reset(); // set the 0th bit because subset sum of 0 exists bit[0] = 1; // Process all array elements one by one for (int i = 0; i < n; ++i) // Do OR of following two // 1) All previous sums. We keep previous value // of bit. // 2) arr[i] added to every previous sum. We // move all previous indexes arr[i] ahead. bit |= (bit << arr[i]);} // Driver programint main(){ int arr[] = {3, 1, 5}; int query[] = {8, 7}; int n = sizeof(arr) / sizeof(arr[0]); int nq = sizeof(query) / sizeof(query[0]); // a vector of MAXSUM number of bits bitset<MAXSUM> bit; preprocess(bit, arr, n); processQueries(query, nq, bit); return 0;}",
"e": 3397,
"s": 2057,
"text": null
},
{
"code": null,
"e": 3407,
"s": 3397,
"text": "Yes, No, "
},
{
"code": null,
"e": 3552,
"s": 3407,
"text": "Time complexity : O(n) for pre-calculating and O(1) for subsequent queries, where n is the number of elements in the array.Auxiliary Space: O(n)"
},
{
"code": null,
"e": 3853,
"s": 3552,
"text": "This article is contributed by Avinash Kumar Saw. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 3868,
"s": 3853,
"text": "ranjanrohit840"
},
{
"code": null,
"e": 3885,
"s": 3868,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 3896,
"s": 3885,
"text": "CPP-bitset"
},
{
"code": null,
"e": 3903,
"s": 3896,
"text": "subset"
},
{
"code": null,
"e": 3910,
"s": 3903,
"text": "Arrays"
},
{
"code": null,
"e": 3920,
"s": 3910,
"text": "Bit Magic"
},
{
"code": null,
"e": 3927,
"s": 3920,
"text": "Arrays"
},
{
"code": null,
"e": 3937,
"s": 3927,
"text": "Bit Magic"
},
{
"code": null,
"e": 3944,
"s": 3937,
"text": "subset"
}
] |
Difference between Half adder and full adder | 21 Jun, 2022
1. Half Adder : Half Adder is a combinational logic circuit which is designed by connecting one EX-OR gate and one AND gate. The half adder circuit has two inputs: A and B, which add two input digits and generates a carry and a sum.
The output obtained from the EX-OR gate is the sum of the two numbers while that obtained by AND gate is the carry. There will be no forwarding of carry addition because there is no logic gate to process that. Thus, this is called the Half Adder circuit.
Logical Expression :
Sum = A XOR B
Carry = A AND B
Truth Table :
2. Full Adder: Full Adder is the circuit that consists of two EX-OR gates, two AND gates, and one OR gate. Full Adder is the adder that adds three inputs and produces two outputs which consist of two EX-OR gates, two AND gates, and one OR gate. The first two inputs are A and B and the third input is an input carry as C-IN. The output carry is designated as C-OUT and the normal output is designated as S which is SUM.
The equation obtained by the EX-OR gate is the sum of the binary digits. While the output obtained by AND gate is the carry obtained by addition.
Truth Table:
Logical Expression :
SUM = (A XOR B) XOR Cin = (A ⊕ B) ⊕ Cin
CARRY-OUT = A AND B OR Cin(A XOR B) = A.B + Cin(A ⊕ B)
krishshewani7
annieahujaweb2020
Difference Between
Digital Electronics & Logic Design
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n21 Jun, 2022"
},
{
"code": null,
"e": 287,
"s": 52,
"text": "1. Half Adder : Half Adder is a combinational logic circuit which is designed by connecting one EX-OR gate and one AND gate. The half adder circuit has two inputs: A and B, which add two input digits and generates a carry and a sum. "
},
{
"code": null,
"e": 543,
"s": 287,
"text": "The output obtained from the EX-OR gate is the sum of the two numbers while that obtained by AND gate is the carry. There will be no forwarding of carry addition because there is no logic gate to process that. Thus, this is called the Half Adder circuit. "
},
{
"code": null,
"e": 564,
"s": 543,
"text": "Logical Expression :"
},
{
"code": null,
"e": 595,
"s": 564,
"text": "Sum = A XOR B\nCarry = A AND B "
},
{
"code": null,
"e": 609,
"s": 595,
"text": "Truth Table :"
},
{
"code": null,
"e": 1032,
"s": 612,
"text": "2. Full Adder: Full Adder is the circuit that consists of two EX-OR gates, two AND gates, and one OR gate. Full Adder is the adder that adds three inputs and produces two outputs which consist of two EX-OR gates, two AND gates, and one OR gate. The first two inputs are A and B and the third input is an input carry as C-IN. The output carry is designated as C-OUT and the normal output is designated as S which is SUM."
},
{
"code": null,
"e": 1182,
"s": 1035,
"text": "The equation obtained by the EX-OR gate is the sum of the binary digits. While the output obtained by AND gate is the carry obtained by addition. "
},
{
"code": null,
"e": 1195,
"s": 1182,
"text": "Truth Table:"
},
{
"code": null,
"e": 1219,
"s": 1198,
"text": "Logical Expression :"
},
{
"code": null,
"e": 1315,
"s": 1219,
"text": "SUM = (A XOR B) XOR Cin = (A ⊕ B) ⊕ Cin\nCARRY-OUT = A AND B OR Cin(A XOR B) = A.B + Cin(A ⊕ B) "
},
{
"code": null,
"e": 1329,
"s": 1315,
"text": "krishshewani7"
},
{
"code": null,
"e": 1347,
"s": 1329,
"text": "annieahujaweb2020"
},
{
"code": null,
"e": 1366,
"s": 1347,
"text": "Difference Between"
},
{
"code": null,
"e": 1401,
"s": 1366,
"text": "Digital Electronics & Logic Design"
},
{
"code": null,
"e": 1409,
"s": 1401,
"text": "GATE CS"
}
] |
Subsets and Splits