title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
PostgreSQL – SMALLINT Integer Data Type
|
28 Aug, 2020
PostgreSQL allows a type of integer type namely SMALLINT. It requires 2 bytes of storage size and can store integers in the range of -37, 767 to 32, 767. It comes in handy for storing data like the age of people, the number of pages in a book, etc.
Syntax: variable_name SMALLINT
Now let’s look into some examples of use cases of SMALLINT integer type.Example 1:In this example we will create a table that stores the number of pages in a book by using the below commands:
CREATE TABLE books (
book_id SERIAL PRIMARY KEY,
title VARCHAR (255) NOT NULL,
pages SMALLINT NOT NULL CHECK (pages > 0)
);
Now let’s add some data to the table using the below command:
INSERT INTO books(title, pages)
VALUES
('Jumanji', 600),
('Insurgent', 7530),
('Nottingham', 8657),
('Dracula', 3000);
Now let’s check our inserted data using the below commands:
SELECT * FROM books;
Output:
Example 2:In this example we will create a table that stores the ages of students by using the below commands:
CREATE TABLE student_age(
student_id SERIAL PRIMARY KEY,
first_name VARCHAR (255) NOT NULL,
last_name VARCHAR (255) NOT NULL,
age SMALLINT NOT NULL CHECK (age > 0)
);
Now let’s add some data to the table using the below command:
INSERT INTO student_age(first_name, last_name, age)
VALUES
('Raju', 'Kumar', 25),
('Nikhil', 'Aggarwal', 21),
('Baccha', 'Yadav', 45),
('Geeta', 'Devi', 30);
Now let’s check our inserted data using the below commands:
SELECT * FROM student_age;
Output:
postgreSQL-dataTypes
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - IF Statement
PostgreSQL - For Loops
PostgreSQL - LIMIT with OFFSET clause
PostgreSQL - SELECT
PostgreSQL - REPLACE Function
PostgreSQL - GROUP BY clause
PostgreSQL - Create Database
PostgreSQL Tutorial
PostgreSQL - FETCH clause
PostgreSQL - INSERT
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Aug, 2020"
},
{
"code": null,
"e": 277,
"s": 28,
"text": "PostgreSQL allows a type of integer type namely SMALLINT. It requires 2 bytes of storage size and can store integers in the range of -37, 767 to 32, 767. It comes in handy for storing data like the age of people, the number of pages in a book, etc."
},
{
"code": null,
"e": 308,
"s": 277,
"text": "Syntax: variable_name SMALLINT"
},
{
"code": null,
"e": 500,
"s": 308,
"text": "Now let’s look into some examples of use cases of SMALLINT integer type.Example 1:In this example we will create a table that stores the number of pages in a book by using the below commands:"
},
{
"code": null,
"e": 636,
"s": 500,
"text": "CREATE TABLE books (\n book_id SERIAL PRIMARY KEY,\n title VARCHAR (255) NOT NULL,\n pages SMALLINT NOT NULL CHECK (pages > 0)\n);"
},
{
"code": null,
"e": 698,
"s": 636,
"text": "Now let’s add some data to the table using the below command:"
},
{
"code": null,
"e": 836,
"s": 698,
"text": "INSERT INTO books(title, pages)\nVALUES\n ('Jumanji', 600),\n ('Insurgent', 7530), \n ('Nottingham', 8657), \n ('Dracula', 3000);"
},
{
"code": null,
"e": 896,
"s": 836,
"text": "Now let’s check our inserted data using the below commands:"
},
{
"code": null,
"e": 917,
"s": 896,
"text": "SELECT * FROM books;"
},
{
"code": null,
"e": 925,
"s": 917,
"text": "Output:"
},
{
"code": null,
"e": 1036,
"s": 925,
"text": "Example 2:In this example we will create a table that stores the ages of students by using the below commands:"
},
{
"code": null,
"e": 1219,
"s": 1036,
"text": "CREATE TABLE student_age(\n student_id SERIAL PRIMARY KEY,\n first_name VARCHAR (255) NOT NULL,\n last_name VARCHAR (255) NOT NULL,\n age SMALLINT NOT NULL CHECK (age > 0)\n);"
},
{
"code": null,
"e": 1281,
"s": 1219,
"text": "Now let’s add some data to the table using the below command:"
},
{
"code": null,
"e": 1458,
"s": 1281,
"text": "INSERT INTO student_age(first_name, last_name, age)\nVALUES\n ('Raju', 'Kumar', 25),\n ('Nikhil', 'Aggarwal', 21), \n ('Baccha', 'Yadav', 45), \n ('Geeta', 'Devi', 30);"
},
{
"code": null,
"e": 1518,
"s": 1458,
"text": "Now let’s check our inserted data using the below commands:"
},
{
"code": null,
"e": 1545,
"s": 1518,
"text": "SELECT * FROM student_age;"
},
{
"code": null,
"e": 1553,
"s": 1545,
"text": "Output:"
},
{
"code": null,
"e": 1574,
"s": 1553,
"text": "postgreSQL-dataTypes"
},
{
"code": null,
"e": 1585,
"s": 1574,
"text": "PostgreSQL"
},
{
"code": null,
"e": 1683,
"s": 1585,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1709,
"s": 1683,
"text": "PostgreSQL - IF Statement"
},
{
"code": null,
"e": 1732,
"s": 1709,
"text": "PostgreSQL - For Loops"
},
{
"code": null,
"e": 1770,
"s": 1732,
"text": "PostgreSQL - LIMIT with OFFSET clause"
},
{
"code": null,
"e": 1790,
"s": 1770,
"text": "PostgreSQL - SELECT"
},
{
"code": null,
"e": 1820,
"s": 1790,
"text": "PostgreSQL - REPLACE Function"
},
{
"code": null,
"e": 1849,
"s": 1820,
"text": "PostgreSQL - GROUP BY clause"
},
{
"code": null,
"e": 1878,
"s": 1849,
"text": "PostgreSQL - Create Database"
},
{
"code": null,
"e": 1898,
"s": 1878,
"text": "PostgreSQL Tutorial"
},
{
"code": null,
"e": 1924,
"s": 1898,
"text": "PostgreSQL - FETCH clause"
}
] |
How to initialize a list in a single line in Java with a specified value?
|
16 Dec, 2019
Given a value N, the task is to create a List having this value N in a single line in Java.
Examples:
Input: N = 5
Output: [5]
Input: N = GeeksForGeeks
Output: [GeeksForGeeks]
Approach:
Get the value N
Create an array with this value N
Create a List with this array as an argument in the constructor
Below is the implementation of the above approach:
// Java program to initialize a list// in a single line with a specified value import java.io.*;import java.util.*; class GFG { // Function to create a List // with the specified value public static <T> List<T> createList(T N) { // Currently only one value is taken int size = 1; // Create an array of size 1 T arr[] = (T[]) new Object[1]; // Add the specified value in the array arr[0] = N; // System.out.println(Arrays.toString(arr)); List<T> list = Arrays.asList(arr); // return the created list return list; } // Driver code public static void main(String[] args) { int N = 1024; System.out.println("List with element " + N + ": " + createList(N)); String str = "GeeksForGeeks"; System.out.println("List with element " + str + ": " + createList(str)); }}
Output:
List with element 1024: [1024]
List with element GeeksForGeeks: [GeeksForGeeks]
Java-List-Programs
Java Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Factory method design pattern in Java
Java Program to Remove Duplicate Elements From the Array
Iterate through List in Java
Java program to count the occurrence of each character in a string using Hashmap
How to Iterate HashMap in Java?
Remove first and last character of a string in Java
Program to print ASCII Value of a character
Iterate Over the Characters of a String in Java
Traverse Through a HashMap in Java
How to Convert Char to String in Java?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Dec, 2019"
},
{
"code": null,
"e": 120,
"s": 28,
"text": "Given a value N, the task is to create a List having this value N in a single line in Java."
},
{
"code": null,
"e": 130,
"s": 120,
"text": "Examples:"
},
{
"code": null,
"e": 206,
"s": 130,
"text": "Input: N = 5\nOutput: [5]\n\nInput: N = GeeksForGeeks\nOutput: [GeeksForGeeks]\n"
},
{
"code": null,
"e": 216,
"s": 206,
"text": "Approach:"
},
{
"code": null,
"e": 232,
"s": 216,
"text": "Get the value N"
},
{
"code": null,
"e": 266,
"s": 232,
"text": "Create an array with this value N"
},
{
"code": null,
"e": 330,
"s": 266,
"text": "Create a List with this array as an argument in the constructor"
},
{
"code": null,
"e": 381,
"s": 330,
"text": "Below is the implementation of the above approach:"
},
{
"code": "// Java program to initialize a list// in a single line with a specified value import java.io.*;import java.util.*; class GFG { // Function to create a List // with the specified value public static <T> List<T> createList(T N) { // Currently only one value is taken int size = 1; // Create an array of size 1 T arr[] = (T[]) new Object[1]; // Add the specified value in the array arr[0] = N; // System.out.println(Arrays.toString(arr)); List<T> list = Arrays.asList(arr); // return the created list return list; } // Driver code public static void main(String[] args) { int N = 1024; System.out.println(\"List with element \" + N + \": \" + createList(N)); String str = \"GeeksForGeeks\"; System.out.println(\"List with element \" + str + \": \" + createList(str)); }}",
"e": 1389,
"s": 381,
"text": null
},
{
"code": null,
"e": 1397,
"s": 1389,
"text": "Output:"
},
{
"code": null,
"e": 1478,
"s": 1397,
"text": "List with element 1024: [1024]\nList with element GeeksForGeeks: [GeeksForGeeks]\n"
},
{
"code": null,
"e": 1497,
"s": 1478,
"text": "Java-List-Programs"
},
{
"code": null,
"e": 1511,
"s": 1497,
"text": "Java Programs"
},
{
"code": null,
"e": 1609,
"s": 1511,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1647,
"s": 1609,
"text": "Factory method design pattern in Java"
},
{
"code": null,
"e": 1704,
"s": 1647,
"text": "Java Program to Remove Duplicate Elements From the Array"
},
{
"code": null,
"e": 1733,
"s": 1704,
"text": "Iterate through List in Java"
},
{
"code": null,
"e": 1814,
"s": 1733,
"text": "Java program to count the occurrence of each character in a string using Hashmap"
},
{
"code": null,
"e": 1846,
"s": 1814,
"text": "How to Iterate HashMap in Java?"
},
{
"code": null,
"e": 1898,
"s": 1846,
"text": "Remove first and last character of a string in Java"
},
{
"code": null,
"e": 1942,
"s": 1898,
"text": "Program to print ASCII Value of a character"
},
{
"code": null,
"e": 1990,
"s": 1942,
"text": "Iterate Over the Characters of a String in Java"
},
{
"code": null,
"e": 2025,
"s": 1990,
"text": "Traverse Through a HashMap in Java"
}
] |
Smallest divisor D of N such that gcd(D, M) is greater than 1
|
16 Jun, 2022
Given two positive integers N and M., The task is to find the smallest divisor D of N such that gcd(D, M) > 1. If there are no such divisors, then print -1. Examples:
Input: N = 8, M = 10 Output: 2Input: N = 8, M = 1 Output: -1
A naive approach is to iterate for every factor and calculate the gcd of the factor and M. If it exceeds M, then we have the answer. Time Complexity: O(N * log max(N, M))An efficient approach is to iterate till sqrt(n) and check for gcd(i, m). If gcd(i, m) > 1, then we print and break it, else we check for gcd(n/i, m) and store the minimum of them. Below is the implementation of the above approach.
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Function to find the minimum divisorint findMinimum(int n, int m){ int mini = m; // Iterate for all factors of N for (int i = 1; i * i <= n; i++) { if (n % i == 0) { int sec = n / i; // Check for gcd > 1 if (__gcd(m, i) > 1) { return i; } // Check for gcd > 1 else if (__gcd(sec, m) > 1) { mini = min(sec, mini); } } } // If gcd is m itself if (mini == m) return -1; else return mini;}// Drivers codeint main(){ int n = 8, m = 10; cout << findMinimum(n, m); return 0;}
// Java implementation of the above approachclass GFG{ static int __gcd(int a, int b){ if (b == 0) return a; return __gcd(b, a % b); } // Function to find the minimum divisorstatic int findMinimum(int n, int m){ int mini = m; // Iterate for all factors of N for (int i = 1; i * i <= n; i++) { if (n % i == 0) { int sec = n / i; // Check for gcd > 1 if (__gcd(m, i) > 1) { return i; } // Check for gcd > 1 else if (__gcd(sec, m) > 1) { mini = Math.min(sec, mini); } } } // If gcd is m itself if (mini == m) return -1; else return mini;} // Driver codepublic static void main (String[] args){ int n = 8, m = 10; System.out.println(findMinimum(n, m));}} // This code is contributed by chandan_jnu
# Python3 implementation of the above approachimport math # Function to find the minimum divisordef findMinimum(n, m): mini, i = m, 1 # Iterate for all factors of N while i * i <= n: if n % i == 0: sec = n // i # Check for gcd > 1 if math.gcd(m, i) > 1: return i # Check for gcd > 1 elif math.gcd(sec, m) > 1: mini = min(sec, mini) i += 1 # If gcd is m itself if mini == m: return -1 else: return mini # Drivers codeif __name__ == "__main__": n, m = 8, 10 print(findMinimum(n, m)) # This code is contributed by Rituraj Jain
// C# implementation of the above approachusing System; class GFG{ static int __gcd(int a, int b){ if (b == 0) return a; return __gcd(b, a % b); } // Function to find the minimum divisorstatic int findMinimum(int n, int m){ int mini = m; // Iterate for all factors of N for (int i = 1; i * i <= n; i++) { if (n % i == 0) { int sec = n / i; // Check for gcd > 1 if (__gcd(m, i) > 1) { return i; } // Check for gcd > 1 else if (__gcd(sec, m) > 1) { mini = Math.Min(sec, mini); } } } // If gcd is m itself if (mini == m) return -1; else return mini;} // Driver codestatic void Main(){ int n = 8, m = 10; Console.WriteLine(findMinimum(n, m));}} // This code is contributed by chandan_jnu
<?php// PHP implementation of the above approachfunction __gcd($a, $b){ if ($b == 0) return $a; return __gcd($b, $a % $b); } // Function to find the minimum divisorfunction findMinimum($n, $m){ $mini = $m; // Iterate for all factors of N for ($i = 1; $i * $i <= $n; $i++) { if ($n % $i == 0) { $sec = $n / $i; // Check for gcd > 1 if (__gcd($m, $i) > 1) { return $i; } // Check for gcd > 1 else if (__gcd($sec, $m) > 1) { $mini = min($sec, $mini); } } } // If gcd is m itself if ($mini == $m) return -1; else return $mini;} // Driver code$n = 8; $m = 10;echo(findMinimum($n, $m)); // This code is contributed by Code_Mech.
<script>// javascript implementation of the above approach function __gcd(a , b) { if (b == 0) return a; return __gcd(b, a % b); } // Function to find the minimum divisor function findMinimum(n , m) { var mini = m; // Iterate for all factors of N for (var i = 1; i * i <= n; i++) { if (n % i == 0) { var sec = n / i; // Check for gcd > 1 if (__gcd(m, i) > 1) { return i; } // Check for gcd > 1 else if (__gcd(sec, m) > 1) { mini = Math.min(sec, mini); } } } // If gcd is m itself if (mini == m) return -1; else return mini; } // Driver code var n = 8, m = 10; document.write(findMinimum(n, m)); // This code is contributed by todaysgaurav</script>
2
Time Complexity: O(sqrt(N) * log max(N, M)), as we are using a loop to traverse sqrt(N) times and we are using the inbuilt GCD function in each traversal which costs logN time. Where N and M are the two integers provided.Auxiliary Space: O(1), as we are not using any extra space.
rituraj_jain
Chandan_Kumar
Code_Mech
todaysgaurav
rohitsingh57
divisors
GCD-LCM
Competitive Programming
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Jun, 2022"
},
{
"code": null,
"e": 197,
"s": 28,
"text": "Given two positive integers N and M., The task is to find the smallest divisor D of N such that gcd(D, M) > 1. If there are no such divisors, then print -1. Examples: "
},
{
"code": null,
"e": 259,
"s": 197,
"text": "Input: N = 8, M = 10 Output: 2Input: N = 8, M = 1 Output: -1 "
},
{
"code": null,
"e": 662,
"s": 259,
"text": "A naive approach is to iterate for every factor and calculate the gcd of the factor and M. If it exceeds M, then we have the answer. Time Complexity: O(N * log max(N, M))An efficient approach is to iterate till sqrt(n) and check for gcd(i, m). If gcd(i, m) > 1, then we print and break it, else we check for gcd(n/i, m) and store the minimum of them. Below is the implementation of the above approach. "
},
{
"code": null,
"e": 666,
"s": 662,
"text": "C++"
},
{
"code": null,
"e": 671,
"s": 666,
"text": "Java"
},
{
"code": null,
"e": 679,
"s": 671,
"text": "Python3"
},
{
"code": null,
"e": 682,
"s": 679,
"text": "C#"
},
{
"code": null,
"e": 686,
"s": 682,
"text": "PHP"
},
{
"code": null,
"e": 697,
"s": 686,
"text": "Javascript"
},
{
"code": "// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Function to find the minimum divisorint findMinimum(int n, int m){ int mini = m; // Iterate for all factors of N for (int i = 1; i * i <= n; i++) { if (n % i == 0) { int sec = n / i; // Check for gcd > 1 if (__gcd(m, i) > 1) { return i; } // Check for gcd > 1 else if (__gcd(sec, m) > 1) { mini = min(sec, mini); } } } // If gcd is m itself if (mini == m) return -1; else return mini;}// Drivers codeint main(){ int n = 8, m = 10; cout << findMinimum(n, m); return 0;}",
"e": 1426,
"s": 697,
"text": null
},
{
"code": "// Java implementation of the above approachclass GFG{ static int __gcd(int a, int b){ if (b == 0) return a; return __gcd(b, a % b); } // Function to find the minimum divisorstatic int findMinimum(int n, int m){ int mini = m; // Iterate for all factors of N for (int i = 1; i * i <= n; i++) { if (n % i == 0) { int sec = n / i; // Check for gcd > 1 if (__gcd(m, i) > 1) { return i; } // Check for gcd > 1 else if (__gcd(sec, m) > 1) { mini = Math.min(sec, mini); } } } // If gcd is m itself if (mini == m) return -1; else return mini;} // Driver codepublic static void main (String[] args){ int n = 8, m = 10; System.out.println(findMinimum(n, m));}} // This code is contributed by chandan_jnu",
"e": 2335,
"s": 1426,
"text": null
},
{
"code": "# Python3 implementation of the above approachimport math # Function to find the minimum divisordef findMinimum(n, m): mini, i = m, 1 # Iterate for all factors of N while i * i <= n: if n % i == 0: sec = n // i # Check for gcd > 1 if math.gcd(m, i) > 1: return i # Check for gcd > 1 elif math.gcd(sec, m) > 1: mini = min(sec, mini) i += 1 # If gcd is m itself if mini == m: return -1 else: return mini # Drivers codeif __name__ == \"__main__\": n, m = 8, 10 print(findMinimum(n, m)) # This code is contributed by Rituraj Jain",
"e": 3019,
"s": 2335,
"text": null
},
{
"code": "// C# implementation of the above approachusing System; class GFG{ static int __gcd(int a, int b){ if (b == 0) return a; return __gcd(b, a % b); } // Function to find the minimum divisorstatic int findMinimum(int n, int m){ int mini = m; // Iterate for all factors of N for (int i = 1; i * i <= n; i++) { if (n % i == 0) { int sec = n / i; // Check for gcd > 1 if (__gcd(m, i) > 1) { return i; } // Check for gcd > 1 else if (__gcd(sec, m) > 1) { mini = Math.Min(sec, mini); } } } // If gcd is m itself if (mini == m) return -1; else return mini;} // Driver codestatic void Main(){ int n = 8, m = 10; Console.WriteLine(findMinimum(n, m));}} // This code is contributed by chandan_jnu",
"e": 3918,
"s": 3019,
"text": null
},
{
"code": "<?php// PHP implementation of the above approachfunction __gcd($a, $b){ if ($b == 0) return $a; return __gcd($b, $a % $b); } // Function to find the minimum divisorfunction findMinimum($n, $m){ $mini = $m; // Iterate for all factors of N for ($i = 1; $i * $i <= $n; $i++) { if ($n % $i == 0) { $sec = $n / $i; // Check for gcd > 1 if (__gcd($m, $i) > 1) { return $i; } // Check for gcd > 1 else if (__gcd($sec, $m) > 1) { $mini = min($sec, $mini); } } } // If gcd is m itself if ($mini == $m) return -1; else return $mini;} // Driver code$n = 8; $m = 10;echo(findMinimum($n, $m)); // This code is contributed by Code_Mech.",
"e": 4750,
"s": 3918,
"text": null
},
{
"code": "<script>// javascript implementation of the above approach function __gcd(a , b) { if (b == 0) return a; return __gcd(b, a % b); } // Function to find the minimum divisor function findMinimum(n , m) { var mini = m; // Iterate for all factors of N for (var i = 1; i * i <= n; i++) { if (n % i == 0) { var sec = n / i; // Check for gcd > 1 if (__gcd(m, i) > 1) { return i; } // Check for gcd > 1 else if (__gcd(sec, m) > 1) { mini = Math.min(sec, mini); } } } // If gcd is m itself if (mini == m) return -1; else return mini; } // Driver code var n = 8, m = 10; document.write(findMinimum(n, m)); // This code is contributed by todaysgaurav</script>",
"e": 5702,
"s": 4750,
"text": null
},
{
"code": null,
"e": 5704,
"s": 5702,
"text": "2"
},
{
"code": null,
"e": 5988,
"s": 5706,
"text": "Time Complexity: O(sqrt(N) * log max(N, M)), as we are using a loop to traverse sqrt(N) times and we are using the inbuilt GCD function in each traversal which costs logN time. Where N and M are the two integers provided.Auxiliary Space: O(1), as we are not using any extra space."
},
{
"code": null,
"e": 6001,
"s": 5988,
"text": "rituraj_jain"
},
{
"code": null,
"e": 6015,
"s": 6001,
"text": "Chandan_Kumar"
},
{
"code": null,
"e": 6025,
"s": 6015,
"text": "Code_Mech"
},
{
"code": null,
"e": 6038,
"s": 6025,
"text": "todaysgaurav"
},
{
"code": null,
"e": 6051,
"s": 6038,
"text": "rohitsingh57"
},
{
"code": null,
"e": 6060,
"s": 6051,
"text": "divisors"
},
{
"code": null,
"e": 6068,
"s": 6060,
"text": "GCD-LCM"
},
{
"code": null,
"e": 6092,
"s": 6068,
"text": "Competitive Programming"
},
{
"code": null,
"e": 6105,
"s": 6092,
"text": "Mathematical"
},
{
"code": null,
"e": 6118,
"s": 6105,
"text": "Mathematical"
}
] |
Python | Frequency of each character in String
|
22 Nov, 2018
Given a string, the task is to find the frequencies of all the characters in that string and return a dictionary with key as the character and its value as its frequency in the given string.
Method #1 : Naive method
Simply iterate through the string and form a key in dictionary of newly occurred element or if element is already occurred, increase its value by 1.
# Python3 code to demonstrate # each occurrence frequency using # naive method # initializing string test_str = "GeeksforGeeks" # using naive method to get count # of each element in string all_freq = {} for i in test_str: if i in all_freq: all_freq[i] += 1 else: all_freq[i] = 1 # printing result print ("Count of all characters in GeeksforGeeks is :\n " + str(all_freq))
Output :
Count of all characters in GeeksforGeeks is :
{'r': 1, 'e': 4, 'k': 2, 'G': 2, 's': 2, 'f': 1, 'o': 1}
Method #2 : Using collections.Counter()
The most suggested method that could be used to find all occurrences is this method, this actually gets all element frequency and could also be used to print single element frequency if required.
# Python3 code to demonstrate # each occurrence frequency using # collections.Counter()from collections import Counter # initializing string test_str = "GeeksforGeeks" # using collections.Counter() to get # count of each element in string res = Counter(test_str) # printing result print ("Count of all characters in GeeksforGeeks is :\n " + str(res))
Output :
Count of all characters in GeeksforGeeks is :
Counter({'e': 4, 's': 2, 'k': 2, 'G': 2, 'o': 1, 'r': 1, 'f': 1})
Method #3 : Using dict.get()
get() method is used to check the previously occurring character in string, if its new, it assigns 0 as initial and appends 1 to it, else appends 1 to previously holded value of that element in dictionary.
# Python3 code to demonstrate # each occurrence frequency using # dict.get() # initializing string test_str = "GeeksforGeeks" # using dict.get() to get count # of each element in string res = {} for keys in test_str: res[keys] = res.get(keys, 0) + 1 # printing result print ("Count of all characters in GeeksforGeeks is : \n" + str(res))
Output :
Count of all characters in GeeksforGeeks is :
{'k': 2, 'e': 4, 's': 2, 'G': 2, 'f': 1, 'r': 1, 'o': 1}
Method #4 : Using set() + count()
count() coupled with set() can also achieve this task, in this we just iterate over the set converted string and get the count of each character in original string and assign that element with that value counted using count().
# Python3 code to demonstrate # each occurrence frequency using # set() + count() # initializing string test_str = "GeeksforGeeks" # using set() + count() to get count # of each element in string res = {i : test_str.count(i) for i in set(test_str)} # printing result print ("The count of all characters in GeeksforGeeks is :\n " + str(res))
Output :
Count of all characters in GeeksforGeeks is :
{'G': 2, 's': 2, 'k': 2, 'e': 4, 'o': 1, 'r': 1, 'f': 1}
Python string-programs
python-string
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": 52,
"s": 24,
"text": "\n22 Nov, 2018"
},
{
"code": null,
"e": 243,
"s": 52,
"text": "Given a string, the task is to find the frequencies of all the characters in that string and return a dictionary with key as the character and its value as its frequency in the given string."
},
{
"code": null,
"e": 268,
"s": 243,
"text": "Method #1 : Naive method"
},
{
"code": null,
"e": 417,
"s": 268,
"text": "Simply iterate through the string and form a key in dictionary of newly occurred element or if element is already occurred, increase its value by 1."
},
{
"code": "# Python3 code to demonstrate # each occurrence frequency using # naive method # initializing string test_str = \"GeeksforGeeks\" # using naive method to get count # of each element in string all_freq = {} for i in test_str: if i in all_freq: all_freq[i] += 1 else: all_freq[i] = 1 # printing result print (\"Count of all characters in GeeksforGeeks is :\\n \" + str(all_freq))",
"e": 855,
"s": 417,
"text": null
},
{
"code": null,
"e": 864,
"s": 855,
"text": "Output :"
},
{
"code": null,
"e": 969,
"s": 864,
"text": "Count of all characters in GeeksforGeeks is :\n {'r': 1, 'e': 4, 'k': 2, 'G': 2, 's': 2, 'f': 1, 'o': 1}\n"
},
{
"code": null,
"e": 1011,
"s": 971,
"text": "Method #2 : Using collections.Counter()"
},
{
"code": null,
"e": 1207,
"s": 1011,
"text": "The most suggested method that could be used to find all occurrences is this method, this actually gets all element frequency and could also be used to print single element frequency if required."
},
{
"code": "# Python3 code to demonstrate # each occurrence frequency using # collections.Counter()from collections import Counter # initializing string test_str = \"GeeksforGeeks\" # using collections.Counter() to get # count of each element in string res = Counter(test_str) # printing result print (\"Count of all characters in GeeksforGeeks is :\\n \" + str(res))",
"e": 1604,
"s": 1207,
"text": null
},
{
"code": null,
"e": 1613,
"s": 1604,
"text": "Output :"
},
{
"code": null,
"e": 1727,
"s": 1613,
"text": "Count of all characters in GeeksforGeeks is : \nCounter({'e': 4, 's': 2, 'k': 2, 'G': 2, 'o': 1, 'r': 1, 'f': 1})\n"
},
{
"code": null,
"e": 1758,
"s": 1729,
"text": "Method #3 : Using dict.get()"
},
{
"code": null,
"e": 1964,
"s": 1758,
"text": "get() method is used to check the previously occurring character in string, if its new, it assigns 0 as initial and appends 1 to it, else appends 1 to previously holded value of that element in dictionary."
},
{
"code": "# Python3 code to demonstrate # each occurrence frequency using # dict.get() # initializing string test_str = \"GeeksforGeeks\" # using dict.get() to get count # of each element in string res = {} for keys in test_str: res[keys] = res.get(keys, 0) + 1 # printing result print (\"Count of all characters in GeeksforGeeks is : \\n\" + str(res))",
"e": 2354,
"s": 1964,
"text": null
},
{
"code": null,
"e": 2363,
"s": 2354,
"text": "Output :"
},
{
"code": null,
"e": 2468,
"s": 2363,
"text": "Count of all characters in GeeksforGeeks is :\n {'k': 2, 'e': 4, 's': 2, 'G': 2, 'f': 1, 'r': 1, 'o': 1}\n"
},
{
"code": null,
"e": 2504,
"s": 2470,
"text": "Method #4 : Using set() + count()"
},
{
"code": null,
"e": 2731,
"s": 2504,
"text": "count() coupled with set() can also achieve this task, in this we just iterate over the set converted string and get the count of each character in original string and assign that element with that value counted using count()."
},
{
"code": "# Python3 code to demonstrate # each occurrence frequency using # set() + count() # initializing string test_str = \"GeeksforGeeks\" # using set() + count() to get count # of each element in string res = {i : test_str.count(i) for i in set(test_str)} # printing result print (\"The count of all characters in GeeksforGeeks is :\\n \" + str(res))",
"e": 3122,
"s": 2731,
"text": null
},
{
"code": null,
"e": 3131,
"s": 3122,
"text": "Output :"
},
{
"code": null,
"e": 3236,
"s": 3131,
"text": "Count of all characters in GeeksforGeeks is :\n {'G': 2, 's': 2, 'k': 2, 'e': 4, 'o': 1, 'r': 1, 'f': 1}\n"
},
{
"code": null,
"e": 3259,
"s": 3236,
"text": "Python string-programs"
},
{
"code": null,
"e": 3273,
"s": 3259,
"text": "python-string"
},
{
"code": null,
"e": 3280,
"s": 3273,
"text": "Python"
},
{
"code": null,
"e": 3378,
"s": 3280,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3410,
"s": 3378,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3439,
"s": 3410,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3466,
"s": 3439,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3502,
"s": 3466,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 3533,
"s": 3502,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 3570,
"s": 3533,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 3593,
"s": 3570,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 3649,
"s": 3593,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 3670,
"s": 3649,
"text": "Python OOPs Concepts"
}
] |
Rotate each ring of matrix anticlockwise by K elements
|
06 Jul, 2022
Given a matrix of order M*N and a value K, the task is to rotate each ring of the matrix anticlockwise by K elements. If in any ring elements are less than and equal K then don’t rotate it.
Examples:
Input : k = 3
mat[4][4] = {{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}}
Output: 4 8 12 16
3 10 6 15
2 11 7 14
1 5 9 13
Input : k = 2
mat[3][4] = {{1, 2, 3, 4},
{10, 11, 12, 5},
{9, 8, 7, 6}}
Output: 3 4 5 6
2 11 12 7
1 10 9 8
The idea is to traverse matrix in spiral form. Here is the algorithm to solve this problem :
Make an auxiliary array temp[] of size M*N.
Start traversing matrix in spiral form and store elements of current ring in temp[] array. While storing the elements in temp, keep track of starting and ending positions of current ring.
For every ring that is being stored in temp[], rotate that subarray temp[]
Repeat this process for each ring of matrix.
In last traverse matrix again spirally and copy elements of temp[] array to matrix.
Below is C++ implementation of above steps.
CPP
// C++ program to rotate individual rings by k in// spiral order traversal.#include<bits/stdc++.h>#define MAX 100using namespace std; // Fills temp array into mat[][] using spiral order// traversal.void fillSpiral(int mat[][MAX], int m, int n, int temp[]){ int i, k = 0, l = 0; /* k - starting row index m - ending row index l - starting column index n - ending column index */ int tIdx = 0; // Index in temp array while (k < m && l < n) { /* first row from the remaining rows */ for (int i = l; i < n; ++i) mat[k][i] = temp[tIdx++]; k++; /* last column from the remaining columns */ for (int i = k; i < m; ++i) mat[i][n-1] = temp[tIdx++]; n--; /* last row from the remaining rows */ if (k < m) { for (int i = n-1; i >= l; --i) mat[m-1][i] = temp[tIdx++]; m--; } /* first column from the remaining columns */ if (l < n) { for (int i = m-1; i >= k; --i) mat[i][l] = temp[tIdx++]; l++; } }} // Function to spirally traverse matrix and// rotate each ring of matrix by K elements// mat[][] --> matrix of elements// M --> number of rows// N --> number of columnsvoid spiralRotate(int mat[][MAX], int M, int N, int k){ // Create a temporary array to store the result int temp[M*N]; /* s - starting row index m - ending row index l - starting column index n - ending column index; */ int m = M, n = N, s = 0, l = 0; int *start = temp; // Start position of current ring int tIdx = 0; // Index in temp while (s < m && l < n) { // Initialize end position of current ring int *end = start; // copy the first row from the remaining rows for (int i = l; i < n; ++i) { temp[tIdx++] = mat[s][i]; end++; } s++; // copy the last column from the remaining columns for (int i = s; i < m; ++i) { temp[tIdx++] = mat[i][n-1]; end++; } n--; // copy the last row from the remaining rows if (s < m) { for (int i = n-1; i >= l; --i) { temp[tIdx++] = mat[m-1][i]; end++; } m--; } /* copy the first column from the remaining columns */ if (l < n) { for (int i = m-1; i >= s; --i) { temp[tIdx++] = mat[i][l]; end++; } l++; } // if elements in current ring greater than // k then rotate elements of current ring if (end-start > k) { // Rotate current ring using reversal // algorithm for rotation reverse(start, start+k); reverse(start+k, end); reverse(start, end); // Reset start for next ring start = end; } } // Fill temp array in original matrix. fillSpiral(mat, M, N, temp);} // Driver program to run the caseint main(){ // Your C++ Code int M = 4, N = 4, k = 3; int mat[][MAX]= {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16} }; spiralRotate(mat, M, N, k); // print modified matrix for (int i=0; i<M; i++) { for (int j=0; j<N; j++) cout << mat[i][j] << " "; cout << endl; } return 0;}
4 8 12 16
3 10 6 15
2 11 7 14
1 5 9 13
Time Complexity : O(M*N) as we are using nested loops to traverse the matrix.Auxiliary space : O(M*N) as we are using extra space for matrix.
This article is contributed by Shashank Mishra ( Gullu ). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
sagartomar9927
surinderdawra388
simmytarika5
rahulsharma9
rohitsingh57
hardikkoriintern
rotation
spiral
Matrix
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Matrix Chain Multiplication | DP-8
Program to find largest element in an array
Rat in a Maze | Backtracking-2
Sudoku | Backtracking-7
The Celebrity Problem
Find the number of islands | Set 1 (Using DFS)
Rotate a matrix by 90 degree in clockwise direction without using any extra space
Count all possible paths from top left to bottom right of a mXn matrix
Unique paths in a Grid with Obstacles
Printing all solutions in N-Queen Problem
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n06 Jul, 2022"
},
{
"code": null,
"e": 243,
"s": 52,
"text": "Given a matrix of order M*N and a value K, the task is to rotate each ring of the matrix anticlockwise by K elements. If in any ring elements are less than and equal K then don’t rotate it. "
},
{
"code": null,
"e": 254,
"s": 243,
"text": "Examples: "
},
{
"code": null,
"e": 663,
"s": 254,
"text": "Input : k = 3\n mat[4][4] = {{1, 2, 3, 4},\n {5, 6, 7, 8},\n {9, 10, 11, 12},\n {13, 14, 15, 16}}\nOutput: 4 8 12 16\n 3 10 6 15\n 2 11 7 14\n 1 5 9 13\n\nInput : k = 2\n mat[3][4] = {{1, 2, 3, 4},\n {10, 11, 12, 5},\n {9, 8, 7, 6}}\nOutput: 3 4 5 6\n 2 11 12 7\n 1 10 9 8"
},
{
"code": null,
"e": 757,
"s": 663,
"text": "The idea is to traverse matrix in spiral form. Here is the algorithm to solve this problem : "
},
{
"code": null,
"e": 801,
"s": 757,
"text": "Make an auxiliary array temp[] of size M*N."
},
{
"code": null,
"e": 989,
"s": 801,
"text": "Start traversing matrix in spiral form and store elements of current ring in temp[] array. While storing the elements in temp, keep track of starting and ending positions of current ring."
},
{
"code": null,
"e": 1064,
"s": 989,
"text": "For every ring that is being stored in temp[], rotate that subarray temp[]"
},
{
"code": null,
"e": 1109,
"s": 1064,
"text": "Repeat this process for each ring of matrix."
},
{
"code": null,
"e": 1193,
"s": 1109,
"text": "In last traverse matrix again spirally and copy elements of temp[] array to matrix."
},
{
"code": null,
"e": 1237,
"s": 1193,
"text": "Below is C++ implementation of above steps."
},
{
"code": null,
"e": 1241,
"s": 1237,
"text": "CPP"
},
{
"code": "// C++ program to rotate individual rings by k in// spiral order traversal.#include<bits/stdc++.h>#define MAX 100using namespace std; // Fills temp array into mat[][] using spiral order// traversal.void fillSpiral(int mat[][MAX], int m, int n, int temp[]){ int i, k = 0, l = 0; /* k - starting row index m - ending row index l - starting column index n - ending column index */ int tIdx = 0; // Index in temp array while (k < m && l < n) { /* first row from the remaining rows */ for (int i = l; i < n; ++i) mat[k][i] = temp[tIdx++]; k++; /* last column from the remaining columns */ for (int i = k; i < m; ++i) mat[i][n-1] = temp[tIdx++]; n--; /* last row from the remaining rows */ if (k < m) { for (int i = n-1; i >= l; --i) mat[m-1][i] = temp[tIdx++]; m--; } /* first column from the remaining columns */ if (l < n) { for (int i = m-1; i >= k; --i) mat[i][l] = temp[tIdx++]; l++; } }} // Function to spirally traverse matrix and// rotate each ring of matrix by K elements// mat[][] --> matrix of elements// M --> number of rows// N --> number of columnsvoid spiralRotate(int mat[][MAX], int M, int N, int k){ // Create a temporary array to store the result int temp[M*N]; /* s - starting row index m - ending row index l - starting column index n - ending column index; */ int m = M, n = N, s = 0, l = 0; int *start = temp; // Start position of current ring int tIdx = 0; // Index in temp while (s < m && l < n) { // Initialize end position of current ring int *end = start; // copy the first row from the remaining rows for (int i = l; i < n; ++i) { temp[tIdx++] = mat[s][i]; end++; } s++; // copy the last column from the remaining columns for (int i = s; i < m; ++i) { temp[tIdx++] = mat[i][n-1]; end++; } n--; // copy the last row from the remaining rows if (s < m) { for (int i = n-1; i >= l; --i) { temp[tIdx++] = mat[m-1][i]; end++; } m--; } /* copy the first column from the remaining columns */ if (l < n) { for (int i = m-1; i >= s; --i) { temp[tIdx++] = mat[i][l]; end++; } l++; } // if elements in current ring greater than // k then rotate elements of current ring if (end-start > k) { // Rotate current ring using reversal // algorithm for rotation reverse(start, start+k); reverse(start+k, end); reverse(start, end); // Reset start for next ring start = end; } } // Fill temp array in original matrix. fillSpiral(mat, M, N, temp);} // Driver program to run the caseint main(){ // Your C++ Code int M = 4, N = 4, k = 3; int mat[][MAX]= {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16} }; spiralRotate(mat, M, N, k); // print modified matrix for (int i=0; i<M; i++) { for (int j=0; j<N; j++) cout << mat[i][j] << \" \"; cout << endl; } return 0;}",
"e": 4806,
"s": 1241,
"text": null
},
{
"code": null,
"e": 4850,
"s": 4806,
"text": "4 8 12 16 \n3 10 6 15 \n2 11 7 14 \n1 5 9 13 \n"
},
{
"code": null,
"e": 4994,
"s": 4850,
"text": "Time Complexity : O(M*N) as we are using nested loops to traverse the matrix.Auxiliary space : O(M*N) as we are using extra space for matrix."
},
{
"code": null,
"e": 5304,
"s": 4994,
"text": "This article is contributed by Shashank Mishra ( Gullu ). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. "
},
{
"code": null,
"e": 5319,
"s": 5304,
"text": "sagartomar9927"
},
{
"code": null,
"e": 5336,
"s": 5319,
"text": "surinderdawra388"
},
{
"code": null,
"e": 5349,
"s": 5336,
"text": "simmytarika5"
},
{
"code": null,
"e": 5362,
"s": 5349,
"text": "rahulsharma9"
},
{
"code": null,
"e": 5375,
"s": 5362,
"text": "rohitsingh57"
},
{
"code": null,
"e": 5392,
"s": 5375,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 5401,
"s": 5392,
"text": "rotation"
},
{
"code": null,
"e": 5408,
"s": 5401,
"text": "spiral"
},
{
"code": null,
"e": 5415,
"s": 5408,
"text": "Matrix"
},
{
"code": null,
"e": 5422,
"s": 5415,
"text": "Matrix"
},
{
"code": null,
"e": 5520,
"s": 5422,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5555,
"s": 5520,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 5599,
"s": 5555,
"text": "Program to find largest element in an array"
},
{
"code": null,
"e": 5630,
"s": 5599,
"text": "Rat in a Maze | Backtracking-2"
},
{
"code": null,
"e": 5654,
"s": 5630,
"text": "Sudoku | Backtracking-7"
},
{
"code": null,
"e": 5676,
"s": 5654,
"text": "The Celebrity Problem"
},
{
"code": null,
"e": 5723,
"s": 5676,
"text": "Find the number of islands | Set 1 (Using DFS)"
},
{
"code": null,
"e": 5805,
"s": 5723,
"text": "Rotate a matrix by 90 degree in clockwise direction without using any extra space"
},
{
"code": null,
"e": 5876,
"s": 5805,
"text": "Count all possible paths from top left to bottom right of a mXn matrix"
},
{
"code": null,
"e": 5914,
"s": 5876,
"text": "Unique paths in a Grid with Obstacles"
}
] |
MongoDB – Greater than Operator $gt
|
27 Mar, 2020
MongoDB provides different types of comparison operators and greater than operator($gt) is one of them. This operator is used to select those documents where the value of the field is greater than(>) the given value. You can use this operator in methods (like, find, update, etc.) according to your requirements.
Syntax:
{field: {$gt: value}}
In the following examples, we are working with:
Database: GeeksforGeeksCollection: employeeDocument: four documents that contain the details of the employees in the form of field-value pairs.
Example #1:In this example, we are selecting those documents where the value of the salary field is greater than 35000.
Example #2:In this example, we are selecting only those documents where the age of the employee is greater than 23. Or in other words, in this example, we are specifying conditions on the field in the embedded document using dot notation.
Example #3:In this example, we are selecting only those documents where the points array is greater than the specified array.
Example #4:In this example, we are updating the salary of those employees whose experience year is greater than 2 years. Or in other words, set the value of the salary field to 49000 of those documents whose experienceYear field value is greater than 2.
MongoDB
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Monte Carlo Tree Search (MCTS)
Copying Files to and from Docker Containers
Basics of API Testing Using Postman
Markov Decision Process
Getting Started with System Design
Principal Component Analysis with Python
How to create a REST API using Java Spring Boot
Monolithic vs Microservices architecture
Fuzzy Logic | Introduction
Mounting a Volume Inside Docker Container
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Mar, 2020"
},
{
"code": null,
"e": 341,
"s": 28,
"text": "MongoDB provides different types of comparison operators and greater than operator($gt) is one of them. This operator is used to select those documents where the value of the field is greater than(>) the given value. You can use this operator in methods (like, find, update, etc.) according to your requirements."
},
{
"code": null,
"e": 349,
"s": 341,
"text": "Syntax:"
},
{
"code": null,
"e": 371,
"s": 349,
"text": "{field: {$gt: value}}"
},
{
"code": null,
"e": 419,
"s": 371,
"text": "In the following examples, we are working with:"
},
{
"code": null,
"e": 563,
"s": 419,
"text": "Database: GeeksforGeeksCollection: employeeDocument: four documents that contain the details of the employees in the form of field-value pairs."
},
{
"code": null,
"e": 684,
"s": 563,
"text": " Example #1:In this example, we are selecting those documents where the value of the salary field is greater than 35000."
},
{
"code": null,
"e": 924,
"s": 684,
"text": " Example #2:In this example, we are selecting only those documents where the age of the employee is greater than 23. Or in other words, in this example, we are specifying conditions on the field in the embedded document using dot notation."
},
{
"code": null,
"e": 1051,
"s": 924,
"text": " Example #3:In this example, we are selecting only those documents where the points array is greater than the specified array."
},
{
"code": null,
"e": 1306,
"s": 1051,
"text": " Example #4:In this example, we are updating the salary of those employees whose experience year is greater than 2 years. Or in other words, set the value of the salary field to 49000 of those documents whose experienceYear field value is greater than 2."
},
{
"code": null,
"e": 1314,
"s": 1306,
"text": "MongoDB"
},
{
"code": null,
"e": 1340,
"s": 1314,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 1438,
"s": 1340,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1474,
"s": 1438,
"text": "ML | Monte Carlo Tree Search (MCTS)"
},
{
"code": null,
"e": 1518,
"s": 1474,
"text": "Copying Files to and from Docker Containers"
},
{
"code": null,
"e": 1554,
"s": 1518,
"text": "Basics of API Testing Using Postman"
},
{
"code": null,
"e": 1578,
"s": 1554,
"text": "Markov Decision Process"
},
{
"code": null,
"e": 1613,
"s": 1578,
"text": "Getting Started with System Design"
},
{
"code": null,
"e": 1654,
"s": 1613,
"text": "Principal Component Analysis with Python"
},
{
"code": null,
"e": 1702,
"s": 1654,
"text": "How to create a REST API using Java Spring Boot"
},
{
"code": null,
"e": 1743,
"s": 1702,
"text": "Monolithic vs Microservices architecture"
},
{
"code": null,
"e": 1770,
"s": 1743,
"text": "Fuzzy Logic | Introduction"
}
] |
factorial() in Python
|
11 Oct, 2017
Not many people know, but python offers a direct function that can compute the factorial of a number without writing the whole code for computing factorial.
Naive method to compute factorial
# Python code to demonstrate naive method# to compute factorialn = 23fact = 1 for i in range(1,n+1): fact = fact * i print ("The factorial of 23 is : ",end="")print (fact)
Output :
The factorial of 23 is : 25852016738884976640000
Using math.factorial()
This method is defined in “math” module of python. Because it has C type internal implementation, it is fast.
math.factorial(x)
Parameters :
x : The number whose factorial has to be computed.
Return value :
Returns the factorial of desired number.
Exceptions :
Raises Value error if number is negative or non-integral.
# Python code to demonstrate math.factorial()import math print ("The factorial of 23 is : ", end="")print (math.factorial(23))
Output :
The factorial of 23 is : 25852016738884976640000
Exceptions in math.factorial()
If give number is Negative :# Python code to demonstrate math.factorial()# Exceptions ( negative number ) import math print ("The factorial of -5 is : ",end="") # raises exceptionprint (math.factorial(-5))Output :The factorial of -5 is :
Runtime Error :Traceback (most recent call last):
File "/home/f29a45b132fac802d76b5817dfaeb137.py", line 9, in
print (math.factorial(-5))
ValueError: factorial() not defined for negative values
# Python code to demonstrate math.factorial()# Exceptions ( negative number ) import math print ("The factorial of -5 is : ",end="") # raises exceptionprint (math.factorial(-5))
Output :
The factorial of -5 is :
Runtime Error :
Traceback (most recent call last):
File "/home/f29a45b132fac802d76b5817dfaeb137.py", line 9, in
print (math.factorial(-5))
ValueError: factorial() not defined for negative values
If given number is Non – Integral Value :# Python code to demonstrate math.factorial()# Exceptions ( Non-Integral number ) import math print ("The factorial of 5.6 is : ",end="") # raises exceptionprint (math.factorial(5.6))Output :The factorial of 5.6 is :
Runtime Error :Traceback (most recent call last):
File "/home/3987966b8ca9cbde2904ad47dfdec124.py", line 9, in
print (math.factorial(5.6))
ValueError: factorial() only accepts integral values
# Python code to demonstrate math.factorial()# Exceptions ( Non-Integral number ) import math print ("The factorial of 5.6 is : ",end="") # raises exceptionprint (math.factorial(5.6))
Output :
The factorial of 5.6 is :
Runtime Error :
Traceback (most recent call last):
File "/home/3987966b8ca9cbde2904ad47dfdec124.py", line 9, in
print (math.factorial(5.6))
ValueError: factorial() only accepts integral values
This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Python-Library
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n11 Oct, 2017"
},
{
"code": null,
"e": 209,
"s": 52,
"text": "Not many people know, but python offers a direct function that can compute the factorial of a number without writing the whole code for computing factorial."
},
{
"code": null,
"e": 243,
"s": 209,
"text": "Naive method to compute factorial"
},
{
"code": "# Python code to demonstrate naive method# to compute factorialn = 23fact = 1 for i in range(1,n+1): fact = fact * i print (\"The factorial of 23 is : \",end=\"\")print (fact)",
"e": 424,
"s": 243,
"text": null
},
{
"code": null,
"e": 433,
"s": 424,
"text": "Output :"
},
{
"code": null,
"e": 483,
"s": 433,
"text": "The factorial of 23 is : 25852016738884976640000\n"
},
{
"code": null,
"e": 506,
"s": 483,
"text": "Using math.factorial()"
},
{
"code": null,
"e": 616,
"s": 506,
"text": "This method is defined in “math” module of python. Because it has C type internal implementation, it is fast."
},
{
"code": null,
"e": 827,
"s": 616,
"text": "math.factorial(x)\nParameters :\nx : The number whose factorial has to be computed.\nReturn value :\nReturns the factorial of desired number.\nExceptions : \nRaises Value error if number is negative or non-integral.\n"
},
{
"code": "# Python code to demonstrate math.factorial()import math print (\"The factorial of 23 is : \", end=\"\")print (math.factorial(23))",
"e": 955,
"s": 827,
"text": null
},
{
"code": null,
"e": 964,
"s": 955,
"text": "Output :"
},
{
"code": null,
"e": 1014,
"s": 964,
"text": "The factorial of 23 is : 25852016738884976640000\n"
},
{
"code": null,
"e": 1045,
"s": 1014,
"text": "Exceptions in math.factorial()"
},
{
"code": null,
"e": 1489,
"s": 1045,
"text": "If give number is Negative :# Python code to demonstrate math.factorial()# Exceptions ( negative number ) import math print (\"The factorial of -5 is : \",end=\"\") # raises exceptionprint (math.factorial(-5))Output :The factorial of -5 is : \nRuntime Error :Traceback (most recent call last):\n File \"/home/f29a45b132fac802d76b5817dfaeb137.py\", line 9, in \n print (math.factorial(-5))\nValueError: factorial() not defined for negative values\n"
},
{
"code": "# Python code to demonstrate math.factorial()# Exceptions ( negative number ) import math print (\"The factorial of -5 is : \",end=\"\") # raises exceptionprint (math.factorial(-5))",
"e": 1670,
"s": 1489,
"text": null
},
{
"code": null,
"e": 1679,
"s": 1670,
"text": "Output :"
},
{
"code": null,
"e": 1706,
"s": 1679,
"text": "The factorial of -5 is : \n"
},
{
"code": null,
"e": 1722,
"s": 1706,
"text": "Runtime Error :"
},
{
"code": null,
"e": 1909,
"s": 1722,
"text": "Traceback (most recent call last):\n File \"/home/f29a45b132fac802d76b5817dfaeb137.py\", line 9, in \n print (math.factorial(-5))\nValueError: factorial() not defined for negative values\n"
},
{
"code": null,
"e": 2371,
"s": 1909,
"text": "If given number is Non – Integral Value :# Python code to demonstrate math.factorial()# Exceptions ( Non-Integral number ) import math print (\"The factorial of 5.6 is : \",end=\"\") # raises exceptionprint (math.factorial(5.6))Output :The factorial of 5.6 is : \nRuntime Error :Traceback (most recent call last):\n File \"/home/3987966b8ca9cbde2904ad47dfdec124.py\", line 9, in \n print (math.factorial(5.6))\nValueError: factorial() only accepts integral values\n"
},
{
"code": "# Python code to demonstrate math.factorial()# Exceptions ( Non-Integral number ) import math print (\"The factorial of 5.6 is : \",end=\"\") # raises exceptionprint (math.factorial(5.6))",
"e": 2558,
"s": 2371,
"text": null
},
{
"code": null,
"e": 2567,
"s": 2558,
"text": "Output :"
},
{
"code": null,
"e": 2595,
"s": 2567,
"text": "The factorial of 5.6 is : \n"
},
{
"code": null,
"e": 2611,
"s": 2595,
"text": "Runtime Error :"
},
{
"code": null,
"e": 2796,
"s": 2611,
"text": "Traceback (most recent call last):\n File \"/home/3987966b8ca9cbde2904ad47dfdec124.py\", line 9, in \n print (math.factorial(5.6))\nValueError: factorial() only accepts integral values\n"
},
{
"code": null,
"e": 3097,
"s": 2796,
"text": "This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 3222,
"s": 3097,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 3237,
"s": 3222,
"text": "Python-Library"
},
{
"code": null,
"e": 3244,
"s": 3237,
"text": "Python"
}
] |
GATE | GATE-CS-2016 (Set 1) | Question 56
|
07 Sep, 2021
Consider the following Syntax Directed Translation Scheme (SDTS), with non-terminals {S, A} and terminals {a, b}}.
Using the above SDTS, the output printed by a bottom-up parser, for the input aab is(A) 1 3 2(B) 2 2 3(C) 2 3 1(D) Syntax ErrorAnswer: (C)Explanation: Bottom up parser builds the parse tree from bottom to up, i.e from the given string to the starting symbol. The given string is aab and starting symbol is S.
so the process is to start from aab and reach S.
=>aab ( given string)=>aSb (after reduction by S->a, and hence print 2)=>aA (after reduction by A->Sb, and hence print 3)=>S (after reduction by S->aA, and hence print 1)
As we reach the starting symbol from the string, the string belongs to the language of the grammar.
Another way to do the same thing is :- bottom up parser does the parsing by RMD in reverse.
RMD is as follows:
=>S=> aA (hence, print 1)=> aSb (hence, print 3)=> aab (hence, print 2)
If we take in Reverse it will print : 231
PYQ - Parsing and SDT (Continued) with Joyojyoti Acharya | GeeksforGeeks GATE - YouTubeGeeksforGeeks GATE Computer Science17.5K subscribersPYQ - Parsing and SDT (Continued) with Joyojyoti Acharya | GeeksforGeeks GATEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0024:50 / 44:16•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=9LF8Bby1Qhc" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
GATE-CS-2016 (Set 1)
GATE-GATE-CS-2016 (Set 1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n07 Sep, 2021"
},
{
"code": null,
"e": 169,
"s": 54,
"text": "Consider the following Syntax Directed Translation Scheme (SDTS), with non-terminals {S, A} and terminals {a, b}}."
},
{
"code": null,
"e": 478,
"s": 169,
"text": "Using the above SDTS, the output printed by a bottom-up parser, for the input aab is(A) 1 3 2(B) 2 2 3(C) 2 3 1(D) Syntax ErrorAnswer: (C)Explanation: Bottom up parser builds the parse tree from bottom to up, i.e from the given string to the starting symbol. The given string is aab and starting symbol is S."
},
{
"code": null,
"e": 527,
"s": 478,
"text": "so the process is to start from aab and reach S."
},
{
"code": null,
"e": 698,
"s": 527,
"text": "=>aab ( given string)=>aSb (after reduction by S->a, and hence print 2)=>aA (after reduction by A->Sb, and hence print 3)=>S (after reduction by S->aA, and hence print 1)"
},
{
"code": null,
"e": 798,
"s": 698,
"text": "As we reach the starting symbol from the string, the string belongs to the language of the grammar."
},
{
"code": null,
"e": 890,
"s": 798,
"text": "Another way to do the same thing is :- bottom up parser does the parsing by RMD in reverse."
},
{
"code": null,
"e": 909,
"s": 890,
"text": "RMD is as follows:"
},
{
"code": null,
"e": 981,
"s": 909,
"text": "=>S=> aA (hence, print 1)=> aSb (hence, print 3)=> aab (hence, print 2)"
},
{
"code": null,
"e": 1023,
"s": 981,
"text": "If we take in Reverse it will print : 231"
},
{
"code": null,
"e": 2009,
"s": 1023,
"text": "PYQ - Parsing and SDT (Continued) with Joyojyoti Acharya | GeeksforGeeks GATE - YouTubeGeeksforGeeks GATE Computer Science17.5K subscribersPYQ - Parsing and SDT (Continued) with Joyojyoti Acharya | GeeksforGeeks GATEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0024:50 / 44:16•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=9LF8Bby1Qhc\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question"
},
{
"code": null,
"e": 2030,
"s": 2009,
"text": "GATE-CS-2016 (Set 1)"
},
{
"code": null,
"e": 2056,
"s": 2030,
"text": "GATE-GATE-CS-2016 (Set 1)"
},
{
"code": null,
"e": 2061,
"s": 2056,
"text": "GATE"
}
] |
Feature Extraction Techniques – NLP
|
03 Jun, 2022
This article focuses on basic feature extraction techniques in NLP to analyse the similarities between pieces of text. Natural Language Processing (NLP) is a branch of computer science and machine learning that deals with training computers to process a large amount of human (natural) language data. Briefly, NLP is the ability of computers to understand human language. Need of feature extraction techniques Machine Learning algorithms learn from a pre-defined set of features from the training data to produce output for the test data. But the main problem in working with language processing is that machine learning algorithms cannot work on the raw text directly. So, we need some feature extraction techniques to convert text into a matrix(or vector) of features. Some of the most popular methods of feature extraction are :
Bag-of-Words
TF-IDF
Bag of Words: Bag-of-Words is one of the most fundamental methods to transform tokens into a set of features. The BoW model is used in document classification, where each word is used as a feature for training the classifier. For example, in a task of review based sentiment analysis, the presence of words like ‘fabulous’, ‘excellent’ indicates a positive review, while words like ‘annoying’, ‘poor’ point to a negative review . There are 3 steps while creating a BoW model :
The first step is text-preprocessing which involves:converting the entire text into lower case characters.removing all punctuations and unnecessary symbols.The second step is to create a vocabulary of all unique words from the corpus. Let’s suppose, we have a hotel review text. Let’s consider 3 of these reviews, which are as follows :
The first step is text-preprocessing which involves:converting the entire text into lower case characters.removing all punctuations and unnecessary symbols.
converting the entire text into lower case characters.removing all punctuations and unnecessary symbols.
converting the entire text into lower case characters.
removing all punctuations and unnecessary symbols.
The second step is to create a vocabulary of all unique words from the corpus. Let’s suppose, we have a hotel review text. Let’s consider 3 of these reviews, which are as follows :
good movienot a good moviedid not like
good movie
not a good movie
did not like
Now, we consider all the unique words from the above set of reviews to create a vocabulary, which is going to be as follows :
Now, we consider all the unique words from the above set of reviews to create a vocabulary, which is going to be as follows :
{good, movie, not, a, did, like}
In the third step, we create a matrix of features by assigning a separate column for each word, while each row corresponds to a review. This process is known as Text Vectorization. Each entry in the matrix signifies the presence(or absence) of the word in the review. We put 1 if the word is present in the review, and 0 if it is not present.
In the third step, we create a matrix of features by assigning a separate column for each word, while each row corresponds to a review. This process is known as Text Vectorization. Each entry in the matrix signifies the presence(or absence) of the word in the review. We put 1 if the word is present in the review, and 0 if it is not present.
For the above example, the matrix of features will be as follows :
A major drawback in using this model is that the order of occurrence of words is lost, as we create a vector of tokens in randomised order.However, we can solve this problem by considering N-grams(mostly bigrams) instead of individual words(i.e. unigrams). This can preserve local ordering of words. If we consider all possible bigrams from the given reviews, the above table would look like:
However, this table will come out to be very large, as there can be a lot of possible bigrams by considering all possible consecutive word pairs. Also, using N-grams can result in a huge sparse(has a lot of 0’s) matrix, if the size of the vocabulary is large, making the computation really complex!! Thus, we have to remove a few N-grams based on their frequency. Like, we can always remove high-frequency N-grams, because they appear in almost all documents. These high-frequency N-grams are generally articles, determiners, etc. most commonly called as StopWords. Similarly, we can also remove low frequency N-grams because these are really rare(i.e. generally appear in 1 or 2 reviews)!! These types of N-grams are generally typos(or typing mistakes). Generally, medium frequency N-grams are considered as the most ideal. However, there are some N-grams which are really rare in our corpus but can highlight a specific issue. Let’s suppose, there is a review that says – “Wi-Fi breaks often”. Here, the N-gram ‘Wi-Fi breaks can’t be too frequent, but it highlights a major problem that needs to be looked upon. Our BoW model would not capture such N-grams since its frequency is really low. To solve this type of problem, we need another model i.e. TF-IDF Vectorizer, which we will study next. Code : Python code for creating a BoW model is:
Python3
# Creating the Bag of Words modelword2count = {}for data in dataset: words = nltk.word_tokenize(data) for word in words: if word not in word2count.keys(): word2count[word] = 1 else: word2count[word] += 1
TF-IDF Vectorizer : TF-IDF stands for term frequency-inverse document frequency. It highlights a specific issue which might not be too frequent in our corpus but holds great importance. The TF–IFD value increases proportionally to the number of times a word appears in the document and decreases with the number of documents in the corpus that contain the word. It is composed of 2 sub-parts, which are :
Term Frequency (TF)Inverse Document Frequency (IDF)
Term Frequency (TF)
Inverse Document Frequency (IDF)
Term Frequency(TF) : Term frequency specifies how frequently a term appears in the entire document.It can be thought of as the probability of finding a word within the document.It calculates the number of times a word occurs in a review , with respect to the total number of words in the review .It is formulated as:
A different scheme for calculating tf is log normalization. And it is formulated as:
where, is the frequency of the term t in document D. Inverse Document Frequency(IDF) : The inverse document frequency is a measure of whether a term is rare or frequent across the documents in the entire corpus. It highlights those words which occur in very few documents across the corpus, or in simple language, the words that are rare have high IDF score. IDF is a log normalised value, that is obtained by dividing the total number of documents in the corpus by the number of documents containing the term , and taking the logarithm of the overall term.
where, is the frequency of the term t in document D. is the total number of documents in the corpus. is the count of documents in the corpus, which contains the term t. Since the ratio inside the IDF’s log function has to be always greater than or equal to 1, so the value of IDF (and thus tf–idf) is greater than or equal to 0.When a term appears in large number of documents, the ratio inside the logarithm approaches 1, and the IDF is closer to 0. Term Frequency-Inverse Document Frequency(TF-IDF) TF-IDF is the product of TF and IDF. It is formulated as:
A high TF-IDF score is obtained by a term that has a high frequency in a document, and low document frequency in the corpus. For a word that appears in almost all documents, the IDF value approaches 0, making the tf-idf also come closer to 0.TF-IDF value is high when both IDF and TF values are high i.e the word is rare in the whole document but frequent in a document. Let’s take the same example to understand this better:
good movienot a good moviedid not like
good movie
not a good movie
did not like
In this example, each sentence is a separate document. Considering the bigram model, we calculate the TF-IDF values for each bigram :
Here, we observe that the bigram did not is rare(i.e. appears in only one document), as compared to other tokens, and thus has a higher tf-idf score. Code : Using the python in-built function TfidfVectorizer to calculate tf-idf score for any corpus
Python3
# calculating tf-idf valuesfrom sklearn.feature_extraction.text import TfidfVectorizerimport pandas as pd texts = {"good movie", "not a good movie", "did not like"} tfidf = TfidfVectorizer(min_df = 2, max_df = 0.5, ngram_range = (1, 2))features = tfidf.fit_transform(texts) pd.Dataframe{ features.todense(), columns = tfidf.get_feature_names()}
On a concluding note, we can say that though Bag-of-Words is one of the most fundamental methods in feature extraction and text vectorization, it fails to capture certain issues in the text. However, this problem is solved by TF-IDF Vectorizer, which also is a feature extraction method, that captures some of the major issues which are not too frequent in the entire corpus.
nikhatkhan11
Natural-language-processing
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": "\n03 Jun, 2022"
},
{
"code": null,
"e": 860,
"s": 28,
"text": "This article focuses on basic feature extraction techniques in NLP to analyse the similarities between pieces of text. Natural Language Processing (NLP) is a branch of computer science and machine learning that deals with training computers to process a large amount of human (natural) language data. Briefly, NLP is the ability of computers to understand human language. Need of feature extraction techniques Machine Learning algorithms learn from a pre-defined set of features from the training data to produce output for the test data. But the main problem in working with language processing is that machine learning algorithms cannot work on the raw text directly. So, we need some feature extraction techniques to convert text into a matrix(or vector) of features. Some of the most popular methods of feature extraction are :"
},
{
"code": null,
"e": 873,
"s": 860,
"text": "Bag-of-Words"
},
{
"code": null,
"e": 880,
"s": 873,
"text": "TF-IDF"
},
{
"code": null,
"e": 1357,
"s": 880,
"text": "Bag of Words: Bag-of-Words is one of the most fundamental methods to transform tokens into a set of features. The BoW model is used in document classification, where each word is used as a feature for training the classifier. For example, in a task of review based sentiment analysis, the presence of words like ‘fabulous’, ‘excellent’ indicates a positive review, while words like ‘annoying’, ‘poor’ point to a negative review . There are 3 steps while creating a BoW model :"
},
{
"code": null,
"e": 1694,
"s": 1357,
"text": "The first step is text-preprocessing which involves:converting the entire text into lower case characters.removing all punctuations and unnecessary symbols.The second step is to create a vocabulary of all unique words from the corpus. Let’s suppose, we have a hotel review text. Let’s consider 3 of these reviews, which are as follows :"
},
{
"code": null,
"e": 1851,
"s": 1694,
"text": "The first step is text-preprocessing which involves:converting the entire text into lower case characters.removing all punctuations and unnecessary symbols."
},
{
"code": null,
"e": 1956,
"s": 1851,
"text": "converting the entire text into lower case characters.removing all punctuations and unnecessary symbols."
},
{
"code": null,
"e": 2011,
"s": 1956,
"text": "converting the entire text into lower case characters."
},
{
"code": null,
"e": 2062,
"s": 2011,
"text": "removing all punctuations and unnecessary symbols."
},
{
"code": null,
"e": 2243,
"s": 2062,
"text": "The second step is to create a vocabulary of all unique words from the corpus. Let’s suppose, we have a hotel review text. Let’s consider 3 of these reviews, which are as follows :"
},
{
"code": null,
"e": 2282,
"s": 2243,
"text": "good movienot a good moviedid not like"
},
{
"code": null,
"e": 2293,
"s": 2282,
"text": "good movie"
},
{
"code": null,
"e": 2310,
"s": 2293,
"text": "not a good movie"
},
{
"code": null,
"e": 2323,
"s": 2310,
"text": "did not like"
},
{
"code": null,
"e": 2449,
"s": 2323,
"text": "Now, we consider all the unique words from the above set of reviews to create a vocabulary, which is going to be as follows :"
},
{
"code": null,
"e": 2575,
"s": 2449,
"text": "Now, we consider all the unique words from the above set of reviews to create a vocabulary, which is going to be as follows :"
},
{
"code": null,
"e": 2608,
"s": 2575,
"text": "{good, movie, not, a, did, like}"
},
{
"code": null,
"e": 2951,
"s": 2608,
"text": "In the third step, we create a matrix of features by assigning a separate column for each word, while each row corresponds to a review. This process is known as Text Vectorization. Each entry in the matrix signifies the presence(or absence) of the word in the review. We put 1 if the word is present in the review, and 0 if it is not present."
},
{
"code": null,
"e": 3294,
"s": 2951,
"text": "In the third step, we create a matrix of features by assigning a separate column for each word, while each row corresponds to a review. This process is known as Text Vectorization. Each entry in the matrix signifies the presence(or absence) of the word in the review. We put 1 if the word is present in the review, and 0 if it is not present."
},
{
"code": null,
"e": 3361,
"s": 3294,
"text": "For the above example, the matrix of features will be as follows :"
},
{
"code": null,
"e": 3754,
"s": 3361,
"text": "A major drawback in using this model is that the order of occurrence of words is lost, as we create a vector of tokens in randomised order.However, we can solve this problem by considering N-grams(mostly bigrams) instead of individual words(i.e. unigrams). This can preserve local ordering of words. If we consider all possible bigrams from the given reviews, the above table would look like:"
},
{
"code": null,
"e": 5100,
"s": 3754,
"text": "However, this table will come out to be very large, as there can be a lot of possible bigrams by considering all possible consecutive word pairs. Also, using N-grams can result in a huge sparse(has a lot of 0’s) matrix, if the size of the vocabulary is large, making the computation really complex!! Thus, we have to remove a few N-grams based on their frequency. Like, we can always remove high-frequency N-grams, because they appear in almost all documents. These high-frequency N-grams are generally articles, determiners, etc. most commonly called as StopWords. Similarly, we can also remove low frequency N-grams because these are really rare(i.e. generally appear in 1 or 2 reviews)!! These types of N-grams are generally typos(or typing mistakes). Generally, medium frequency N-grams are considered as the most ideal. However, there are some N-grams which are really rare in our corpus but can highlight a specific issue. Let’s suppose, there is a review that says – “Wi-Fi breaks often”. Here, the N-gram ‘Wi-Fi breaks can’t be too frequent, but it highlights a major problem that needs to be looked upon. Our BoW model would not capture such N-grams since its frequency is really low. To solve this type of problem, we need another model i.e. TF-IDF Vectorizer, which we will study next. Code : Python code for creating a BoW model is: "
},
{
"code": null,
"e": 5108,
"s": 5100,
"text": "Python3"
},
{
"code": "# Creating the Bag of Words modelword2count = {}for data in dataset: words = nltk.word_tokenize(data) for word in words: if word not in word2count.keys(): word2count[word] = 1 else: word2count[word] += 1",
"e": 5354,
"s": 5108,
"text": null
},
{
"code": null,
"e": 5759,
"s": 5354,
"text": "TF-IDF Vectorizer : TF-IDF stands for term frequency-inverse document frequency. It highlights a specific issue which might not be too frequent in our corpus but holds great importance. The TF–IFD value increases proportionally to the number of times a word appears in the document and decreases with the number of documents in the corpus that contain the word. It is composed of 2 sub-parts, which are :"
},
{
"code": null,
"e": 5811,
"s": 5759,
"text": "Term Frequency (TF)Inverse Document Frequency (IDF)"
},
{
"code": null,
"e": 5831,
"s": 5811,
"text": "Term Frequency (TF)"
},
{
"code": null,
"e": 5864,
"s": 5831,
"text": "Inverse Document Frequency (IDF)"
},
{
"code": null,
"e": 6182,
"s": 5864,
"text": "Term Frequency(TF) : Term frequency specifies how frequently a term appears in the entire document.It can be thought of as the probability of finding a word within the document.It calculates the number of times a word occurs in a review , with respect to the total number of words in the review .It is formulated as: "
},
{
"code": null,
"e": 6273,
"s": 6187,
"text": "A different scheme for calculating tf is log normalization. And it is formulated as: "
},
{
"code": null,
"e": 6837,
"s": 6278,
"text": "where, is the frequency of the term t in document D. Inverse Document Frequency(IDF) : The inverse document frequency is a measure of whether a term is rare or frequent across the documents in the entire corpus. It highlights those words which occur in very few documents across the corpus, or in simple language, the words that are rare have high IDF score. IDF is a log normalised value, that is obtained by dividing the total number of documents in the corpus by the number of documents containing the term , and taking the logarithm of the overall term. "
},
{
"code": null,
"e": 7402,
"s": 6842,
"text": "where, is the frequency of the term t in document D. is the total number of documents in the corpus. is the count of documents in the corpus, which contains the term t. Since the ratio inside the IDF’s log function has to be always greater than or equal to 1, so the value of IDF (and thus tf–idf) is greater than or equal to 0.When a term appears in large number of documents, the ratio inside the logarithm approaches 1, and the IDF is closer to 0. Term Frequency-Inverse Document Frequency(TF-IDF) TF-IDF is the product of TF and IDF. It is formulated as: "
},
{
"code": null,
"e": 7833,
"s": 7407,
"text": "A high TF-IDF score is obtained by a term that has a high frequency in a document, and low document frequency in the corpus. For a word that appears in almost all documents, the IDF value approaches 0, making the tf-idf also come closer to 0.TF-IDF value is high when both IDF and TF values are high i.e the word is rare in the whole document but frequent in a document. Let’s take the same example to understand this better:"
},
{
"code": null,
"e": 7872,
"s": 7833,
"text": "good movienot a good moviedid not like"
},
{
"code": null,
"e": 7883,
"s": 7872,
"text": "good movie"
},
{
"code": null,
"e": 7900,
"s": 7883,
"text": "not a good movie"
},
{
"code": null,
"e": 7913,
"s": 7900,
"text": "did not like"
},
{
"code": null,
"e": 8047,
"s": 7913,
"text": "In this example, each sentence is a separate document. Considering the bigram model, we calculate the TF-IDF values for each bigram :"
},
{
"code": null,
"e": 8297,
"s": 8047,
"text": "Here, we observe that the bigram did not is rare(i.e. appears in only one document), as compared to other tokens, and thus has a higher tf-idf score. Code : Using the python in-built function TfidfVectorizer to calculate tf-idf score for any corpus "
},
{
"code": null,
"e": 8305,
"s": 8297,
"text": "Python3"
},
{
"code": "# calculating tf-idf valuesfrom sklearn.feature_extraction.text import TfidfVectorizerimport pandas as pd texts = {\"good movie\", \"not a good movie\", \"did not like\"} tfidf = TfidfVectorizer(min_df = 2, max_df = 0.5, ngram_range = (1, 2))features = tfidf.fit_transform(texts) pd.Dataframe{ features.todense(), columns = tfidf.get_feature_names()}",
"e": 8658,
"s": 8305,
"text": null
},
{
"code": null,
"e": 9034,
"s": 8658,
"text": "On a concluding note, we can say that though Bag-of-Words is one of the most fundamental methods in feature extraction and text vectorization, it fails to capture certain issues in the text. However, this problem is solved by TF-IDF Vectorizer, which also is a feature extraction method, that captures some of the major issues which are not too frequent in the entire corpus."
},
{
"code": null,
"e": 9047,
"s": 9034,
"text": "nikhatkhan11"
},
{
"code": null,
"e": 9075,
"s": 9047,
"text": "Natural-language-processing"
},
{
"code": null,
"e": 9092,
"s": 9075,
"text": "Machine Learning"
},
{
"code": null,
"e": 9099,
"s": 9092,
"text": "Python"
},
{
"code": null,
"e": 9116,
"s": 9099,
"text": "Machine Learning"
}
] |
Skip List | Set 3 (Searching and Deletion)
|
14 Jun, 2022
In previous article Skip List | Set 2 (Insertion) we discussed the structure of skip nodes and how to insert an element in the skip list. In this article we will discuss how to search and delete an element from skip list.
Searching an element in Skip list
Searching an element is very similar to approach for searching a spot for inserting an element in Skip list. The basic idea is if –
Key of next node is less than search key then we keep on moving forward on the same level.Key of next node is greater than the key to be inserted then we store the pointer to current node i at update[i] and move one level down and continue our search.
Key of next node is less than search key then we keep on moving forward on the same level.
Key of next node is greater than the key to be inserted then we store the pointer to current node i at update[i] and move one level down and continue our search.
At the lowest level (0), if the element next to the rightmost element (update[0]) has key equal to the search key, then we have found key otherwise failure. Following is the pseudo code for searching element –
Search(list, searchKey)
x := list -> header
-- loop invariant: x -> key level downto 0 do
while x -> forward[i] -> key forward[i]
x := x -> forward[0]
if x -> key = searchKey then return x -> value
else return failure
Consider this example where we want to search for key 17-
Deleting an element from the Skip list
Deletion of an element k is preceded by locating element in the Skip list using above mentioned search algorithm. Once the element is located, rearrangement of pointers is done to remove element form list just like we do in singly linked list. We start from lowest level and do rearrangement until element next to update[i] is not k. After deletion of element there could be levels with no elements, so we will remove these levels as well by decrementing the level of Skip list. Following is the pseudo code for deletion –
Delete(list, searchKey)
local update[0..MaxLevel+1]
x := list -> header
for i := list -> level downto 0 do
while x -> forward[i] -> key forward[i]
update[i] := x
x := x -> forward[0]
if x -> key = searchKey then
for i := 0 to list -> level do
if update[i] -> forward[i] ≠ x then break
update[i] -> forward[i] := x -> forward[i]
free(x)
while list -> level > 0 and list -> header -> forward[list -> level] = NIL do
list -> level := list -> level – 1
Consider this example where we want to delete element 6 – Here at level 3, there is no element (arrow in red) after deleting element 6. So we will decrement level of skip list by 1. Following is the code for searching and deleting element from Skip List –
C++
Python
// C++ code for searching and deleting element in skip list #include <bits/stdc++.h>using namespace std; // Class to implement nodeclass Node{public: int key; // Array to hold pointers to node of different level Node **forward; Node(int, int);}; Node::Node(int key, int level){ this->key = key; // Allocate memory to forward forward = new Node*[level+1]; // Fill forward array with 0(NULL) memset(forward, 0, sizeof(Node*)*(level+1));}; // Class for Skip listclass SkipList{ // Maximum level for this skip list int MAXLVL; // P is the fraction of the nodes with level // i pointers also having level i+1 pointers float P; // current level of skip list int level; // pointer to header node Node *header;public: SkipList(int, float); int randomLevel(); Node* createNode(int, int); void insertElement(int); void deleteElement(int); void searchElement(int); void displayList();}; SkipList::SkipList(int MAXLVL, float P){ this->MAXLVL = MAXLVL; this->P = P; level = 0; // create header node and initialize key to -1 header = new Node(-1, MAXLVL);}; // create random level for nodeint SkipList::randomLevel(){ float r = (float)rand()/RAND_MAX; int lvl = 0; while(r < P && lvl < MAXLVL) { lvl++; r = (float)rand()/RAND_MAX; } return lvl;}; // create new nodeNode* SkipList::createNode(int key, int level){ Node *n = new Node(key, level); return n;}; // Insert given key in skip listvoid SkipList::insertElement(int key){ Node *current = header; // create update array and initialize it Node *update[MAXLVL+1]; memset(update, 0, sizeof(Node*)*(MAXLVL+1)); /* start from highest level of skip list move the current pointer forward while key is greater than key of node next to current Otherwise inserted current in update and move one level down and continue search */ for(int i = level; i >= 0; i--) { while(current->forward[i] != NULL && current->forward[i]->key < key) current = current->forward[i]; update[i] = current; } /* reached level 0 and forward pointer to right, which is desired position to insert key. */ current = current->forward[0]; /* if current is NULL that means we have reached to end of the level or current's key is not equal to key to insert that means we have to insert node between update[0] and current node */ if (current == NULL || current->key != key) { // Generate a random level for node int rlevel = randomLevel(); /* If random level is greater than list's current level (node with highest level inserted in list so far), initialize update value with pointer to header for further use */ if(rlevel > level) { for(int i=level+1;i<rlevel+1;i++) update[i] = header; // Update the list current level level = rlevel; } // create new node with random level generated Node* n = createNode(key, rlevel); // insert node by rearranging pointers for(int i=0;i<=rlevel;i++) { n->forward[i] = update[i]->forward[i]; update[i]->forward[i] = n; } cout<<"Successfully Inserted key "<<key<<"\n"; }}; // Delete element from skip listvoid SkipList::deleteElement(int key){ Node *current = header; // create update array and initialize it Node *update[MAXLVL+1]; memset(update, 0, sizeof(Node*)*(MAXLVL+1)); /* start from highest level of skip list move the current pointer forward while key is greater than key of node next to current Otherwise inserted current in update and move one level down and continue search */ for(int i = level; i >= 0; i--) { while(current->forward[i] != NULL && current->forward[i]->key < key) current = current->forward[i]; update[i] = current; } /* reached level 0 and forward pointer to right, which is possibly our desired node.*/ current = current->forward[0]; // If current node is target node if(current != NULL and current->key == key) { /* start from lowest level and rearrange pointers just like we do in singly linked list to remove target node */ for(int i=0;i<=level;i++) { /* If at level i, next node is not target node, break the loop, no need to move further level */ if(update[i]->forward[i] != current) break; update[i]->forward[i] = current->forward[i]; } // Remove levels having no elements while(level>0 && header->forward[level] == 0) level--; cout<<"Successfully deleted key "<<key<<"\n"; }}; // Search for element in skip listvoid SkipList::searchElement(int key){ Node *current = header; /* start from highest level of skip list move the current pointer forward while key is greater than key of node next to current Otherwise inserted current in update and move one level down and continue search */ for(int i = level; i >= 0; i--) { while(current->forward[i] && current->forward[i]->key < key) current = current->forward[i]; } /* reached level 0 and advance pointer to right, which is possibly our desired node*/ current = current->forward[0]; // If current node have key equal to // search key, we have found our target node if(current and current->key == key) cout<<"Found key: "<<key<<"\n";}; // Display skip list level wisevoid SkipList::displayList(){ cout<<"\n*****Skip List*****"<<"\n"; for(int i=0;i<=level;i++) { Node *node = header->forward[i]; cout<<"Level "<<i<<": "; while(node != NULL) { cout<<node->key<<" "; node = node->forward[i]; } cout<<"\n"; }}; // Driver to test above codeint main(){ // Seed random number generator srand((unsigned)time(0)); // create SkipList object with MAXLVL and P SkipList lst(3, 0.5); lst.insertElement(3); lst.insertElement(6); lst.insertElement(7); lst.insertElement(9); lst.insertElement(12); lst.insertElement(19); lst.insertElement(17); lst.insertElement(26); lst.insertElement(21); lst.insertElement(25); lst.displayList(); //Search for node 19 lst.searchElement(19); //Delete node 19 lst.deleteElement(19); lst.displayList();}
# Python3 code for searching and deleting element in skip list import random class Node(object): ''' Class to implement node ''' def __init__(self, key, level): self.key = key # list to hold references to node of different level self.forward = [None]*(level+1) class SkipList(object): ''' Class for Skip list ''' def __init__(self, max_lvl, P): # Maximum level for this skip list self.MAXLVL = max_lvl # P is the fraction of the nodes with level # i references also having level i+1 references self.P = P # create header node and initialize key to -1 self.header = self.createNode(self.MAXLVL, -1) # current level of skip list self.level = 0 # create new node def createNode(self, lvl, key): n = Node(key, lvl) return n # create random level for node def randomLevel(self): lvl = 0 while random.random()<self.P and \ lvl<self.MAXLVL:lvl += 1 return lvl # insert given key in skip list def insertElement(self, key): # create update array and initialize it update = [None]*(self.MAXLVL+1) current = self.header ''' start from highest level of skip list move the current reference forward while key is greater than key of node next to current Otherwise inserted current in update and move one level down and continue search ''' for i in range(self.level, -1, -1): while current.forward[i] and \ current.forward[i].key < key: current = current.forward[i] update[i] = current ''' reached level 0 and forward reference to right, which is desired position to insert key. ''' current = current.forward[0] ''' if current is NULL that means we have reached to end of the level or current's key is not equal to key to insert that means we have to insert node between update[0] and current node ''' if current == None or current.key != key: # Generate a random level for node rlevel = self.randomLevel() ''' If random level is greater than list's current level (node with highest level inserted in list so far), initialize update value with reference to header for further use ''' if rlevel > self.level: for i in range(self.level+1, rlevel+1): update[i] = self.header self.level = rlevel # create new node with random level generated n = self.createNode(rlevel, key) # insert node by rearranging references for i in range(rlevel+1): n.forward[i] = update[i].forward[i] update[i].forward[i] = n print("Successfully inserted key {}".format(key)) def deleteElement(self, search_key): # create update array and initialize it update = [None]*(self.MAXLVL+1) current = self.header ''' start from highest level of skip list move the current reference forward while key is greater than key of node next to current Otherwise inserted current in update and move one level down and continue search ''' for i in range(self.level, -1, -1): while(current.forward[i] and \ current.forward[i].key < search_key): current = current.forward[i] update[i] = current ''' reached level 0 and advance reference to right, which is possibly our desired node ''' current = current.forward[0] # If current node is target node if current != None and current.key == search_key: ''' start from lowest level and rearrange references just like we do in singly linked list to remove target node ''' for i in range(self.level+1): ''' If at level i, next node is not target node, break the loop, no need to move further level ''' if update[i].forward[i] != current: break update[i].forward[i] = current.forward[i] # Remove levels having no elements while(self.level>0 and\ self.header.forward[self.level] == None): self.level -= 1 print("Successfully deleted {}".format(search_key)) def searchElement(self, key): current = self.header ''' start from highest level of skip list move the current reference forward while key is greater than key of node next to current Otherwise inserted current in update and move one level down and continue search ''' for i in range(self.level, -1, -1): while(current.forward[i] and\ current.forward[i].key < key): current = current.forward[i] # reached level 0 and advance reference to # right, which is possibly our desired node current = current.forward[0] # If current node have key equal to # search key, we have found our target node if current and current.key == key: print("Found key ", key) # Display skip list level wise def displayList(self): print("\n*****Skip List******") head = self.header for lvl in range(self.level+1): print("Level {}: ".format(lvl), end=" ") node = head.forward[lvl] while(node != None): print(node.key, end=" ") node = node.forward[lvl] print("") # Driver to test above codedef main(): lst = SkipList(3, 0.5) lst.insertElement(3) lst.insertElement(6) lst.insertElement(7) lst.insertElement(9) lst.insertElement(12) lst.insertElement(19) lst.insertElement(17) lst.insertElement(26) lst.insertElement(21) lst.insertElement(25) lst.displayList() # Search for node 19 lst.searchElement(19) # Delete node 19 lst.deleteElement(19) lst.displayList() main()
Output:
Successfully Inserted key 3
Successfully Inserted key 6
Successfully Inserted key 7
Successfully Inserted key 9
Successfully Inserted key 12
Successfully Inserted key 19
Successfully Inserted key 17
Successfully Inserted key 26
Successfully Inserted key 21
Successfully Inserted key 25
*****Skip List*****
Level 0: 3 6 7 9 12 17 19 21 25 26
Level 1: 3 17 19 21 26
Level 2: 17 19 21
Found key: 19
Successfully deleted key 19
*****Skip List*****
Level 0: 3 6 7 9 12 17 21 25 26
Level 1: 3 17 21 26
Level 2: 17 21
Time complexity of both searching and deletion is same – Time complexity Worst case:
Access – O(n)
Search – O(n)
Insert – O(n)
Space – O(nlogn
Delete – O(n)
References ftp://ftp.cs.umd.edu/pub/skipLists/skiplists.pdf This article is contributed by Atul Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
surinderdawra388
guptavivek0503
Advanced Data Structure
Linked List
Linked List
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n14 Jun, 2022"
},
{
"code": null,
"e": 274,
"s": 52,
"text": "In previous article Skip List | Set 2 (Insertion) we discussed the structure of skip nodes and how to insert an element in the skip list. In this article we will discuss how to search and delete an element from skip list."
},
{
"code": null,
"e": 308,
"s": 274,
"text": "Searching an element in Skip list"
},
{
"code": null,
"e": 440,
"s": 308,
"text": "Searching an element is very similar to approach for searching a spot for inserting an element in Skip list. The basic idea is if –"
},
{
"code": null,
"e": 692,
"s": 440,
"text": "Key of next node is less than search key then we keep on moving forward on the same level.Key of next node is greater than the key to be inserted then we store the pointer to current node i at update[i] and move one level down and continue our search."
},
{
"code": null,
"e": 783,
"s": 692,
"text": "Key of next node is less than search key then we keep on moving forward on the same level."
},
{
"code": null,
"e": 945,
"s": 783,
"text": "Key of next node is greater than the key to be inserted then we store the pointer to current node i at update[i] and move one level down and continue our search."
},
{
"code": null,
"e": 1155,
"s": 945,
"text": "At the lowest level (0), if the element next to the rightmost element (update[0]) has key equal to the search key, then we have found key otherwise failure. Following is the pseudo code for searching element –"
},
{
"code": null,
"e": 1379,
"s": 1155,
"text": "Search(list, searchKey)\nx := list -> header\n-- loop invariant: x -> key level downto 0 do\n while x -> forward[i] -> key forward[i]\nx := x -> forward[0]\nif x -> key = searchKey then return x -> value\nelse return failure"
},
{
"code": null,
"e": 1438,
"s": 1379,
"text": "Consider this example where we want to search for key 17- "
},
{
"code": null,
"e": 1477,
"s": 1438,
"text": "Deleting an element from the Skip list"
},
{
"code": null,
"e": 2000,
"s": 1477,
"text": "Deletion of an element k is preceded by locating element in the Skip list using above mentioned search algorithm. Once the element is located, rearrangement of pointers is done to remove element form list just like we do in singly linked list. We start from lowest level and do rearrangement until element next to update[i] is not k. After deletion of element there could be levels with no elements, so we will remove these levels as well by decrementing the level of Skip list. Following is the pseudo code for deletion –"
},
{
"code": null,
"e": 2495,
"s": 2000,
"text": "Delete(list, searchKey)\nlocal update[0..MaxLevel+1]\nx := list -> header\nfor i := list -> level downto 0 do\n while x -> forward[i] -> key forward[i]\n update[i] := x\nx := x -> forward[0]\nif x -> key = searchKey then\n for i := 0 to list -> level do\n if update[i] -> forward[i] ≠ x then break\n update[i] -> forward[i] := x -> forward[i]\n free(x)\n while list -> level > 0 and list -> header -> forward[list -> level] = NIL do\n list -> level := list -> level – 1"
},
{
"code": null,
"e": 2753,
"s": 2495,
"text": "Consider this example where we want to delete element 6 – Here at level 3, there is no element (arrow in red) after deleting element 6. So we will decrement level of skip list by 1. Following is the code for searching and deleting element from Skip List – "
},
{
"code": null,
"e": 2757,
"s": 2753,
"text": "C++"
},
{
"code": null,
"e": 2764,
"s": 2757,
"text": "Python"
},
{
"code": "// C++ code for searching and deleting element in skip list #include <bits/stdc++.h>using namespace std; // Class to implement nodeclass Node{public: int key; // Array to hold pointers to node of different level Node **forward; Node(int, int);}; Node::Node(int key, int level){ this->key = key; // Allocate memory to forward forward = new Node*[level+1]; // Fill forward array with 0(NULL) memset(forward, 0, sizeof(Node*)*(level+1));}; // Class for Skip listclass SkipList{ // Maximum level for this skip list int MAXLVL; // P is the fraction of the nodes with level // i pointers also having level i+1 pointers float P; // current level of skip list int level; // pointer to header node Node *header;public: SkipList(int, float); int randomLevel(); Node* createNode(int, int); void insertElement(int); void deleteElement(int); void searchElement(int); void displayList();}; SkipList::SkipList(int MAXLVL, float P){ this->MAXLVL = MAXLVL; this->P = P; level = 0; // create header node and initialize key to -1 header = new Node(-1, MAXLVL);}; // create random level for nodeint SkipList::randomLevel(){ float r = (float)rand()/RAND_MAX; int lvl = 0; while(r < P && lvl < MAXLVL) { lvl++; r = (float)rand()/RAND_MAX; } return lvl;}; // create new nodeNode* SkipList::createNode(int key, int level){ Node *n = new Node(key, level); return n;}; // Insert given key in skip listvoid SkipList::insertElement(int key){ Node *current = header; // create update array and initialize it Node *update[MAXLVL+1]; memset(update, 0, sizeof(Node*)*(MAXLVL+1)); /* start from highest level of skip list move the current pointer forward while key is greater than key of node next to current Otherwise inserted current in update and move one level down and continue search */ for(int i = level; i >= 0; i--) { while(current->forward[i] != NULL && current->forward[i]->key < key) current = current->forward[i]; update[i] = current; } /* reached level 0 and forward pointer to right, which is desired position to insert key. */ current = current->forward[0]; /* if current is NULL that means we have reached to end of the level or current's key is not equal to key to insert that means we have to insert node between update[0] and current node */ if (current == NULL || current->key != key) { // Generate a random level for node int rlevel = randomLevel(); /* If random level is greater than list's current level (node with highest level inserted in list so far), initialize update value with pointer to header for further use */ if(rlevel > level) { for(int i=level+1;i<rlevel+1;i++) update[i] = header; // Update the list current level level = rlevel; } // create new node with random level generated Node* n = createNode(key, rlevel); // insert node by rearranging pointers for(int i=0;i<=rlevel;i++) { n->forward[i] = update[i]->forward[i]; update[i]->forward[i] = n; } cout<<\"Successfully Inserted key \"<<key<<\"\\n\"; }}; // Delete element from skip listvoid SkipList::deleteElement(int key){ Node *current = header; // create update array and initialize it Node *update[MAXLVL+1]; memset(update, 0, sizeof(Node*)*(MAXLVL+1)); /* start from highest level of skip list move the current pointer forward while key is greater than key of node next to current Otherwise inserted current in update and move one level down and continue search */ for(int i = level; i >= 0; i--) { while(current->forward[i] != NULL && current->forward[i]->key < key) current = current->forward[i]; update[i] = current; } /* reached level 0 and forward pointer to right, which is possibly our desired node.*/ current = current->forward[0]; // If current node is target node if(current != NULL and current->key == key) { /* start from lowest level and rearrange pointers just like we do in singly linked list to remove target node */ for(int i=0;i<=level;i++) { /* If at level i, next node is not target node, break the loop, no need to move further level */ if(update[i]->forward[i] != current) break; update[i]->forward[i] = current->forward[i]; } // Remove levels having no elements while(level>0 && header->forward[level] == 0) level--; cout<<\"Successfully deleted key \"<<key<<\"\\n\"; }}; // Search for element in skip listvoid SkipList::searchElement(int key){ Node *current = header; /* start from highest level of skip list move the current pointer forward while key is greater than key of node next to current Otherwise inserted current in update and move one level down and continue search */ for(int i = level; i >= 0; i--) { while(current->forward[i] && current->forward[i]->key < key) current = current->forward[i]; } /* reached level 0 and advance pointer to right, which is possibly our desired node*/ current = current->forward[0]; // If current node have key equal to // search key, we have found our target node if(current and current->key == key) cout<<\"Found key: \"<<key<<\"\\n\";}; // Display skip list level wisevoid SkipList::displayList(){ cout<<\"\\n*****Skip List*****\"<<\"\\n\"; for(int i=0;i<=level;i++) { Node *node = header->forward[i]; cout<<\"Level \"<<i<<\": \"; while(node != NULL) { cout<<node->key<<\" \"; node = node->forward[i]; } cout<<\"\\n\"; }}; // Driver to test above codeint main(){ // Seed random number generator srand((unsigned)time(0)); // create SkipList object with MAXLVL and P SkipList lst(3, 0.5); lst.insertElement(3); lst.insertElement(6); lst.insertElement(7); lst.insertElement(9); lst.insertElement(12); lst.insertElement(19); lst.insertElement(17); lst.insertElement(26); lst.insertElement(21); lst.insertElement(25); lst.displayList(); //Search for node 19 lst.searchElement(19); //Delete node 19 lst.deleteElement(19); lst.displayList();}",
"e": 9433,
"s": 2764,
"text": null
},
{
"code": "# Python3 code for searching and deleting element in skip list import random class Node(object): ''' Class to implement node ''' def __init__(self, key, level): self.key = key # list to hold references to node of different level self.forward = [None]*(level+1) class SkipList(object): ''' Class for Skip list ''' def __init__(self, max_lvl, P): # Maximum level for this skip list self.MAXLVL = max_lvl # P is the fraction of the nodes with level # i references also having level i+1 references self.P = P # create header node and initialize key to -1 self.header = self.createNode(self.MAXLVL, -1) # current level of skip list self.level = 0 # create new node def createNode(self, lvl, key): n = Node(key, lvl) return n # create random level for node def randomLevel(self): lvl = 0 while random.random()<self.P and \\ lvl<self.MAXLVL:lvl += 1 return lvl # insert given key in skip list def insertElement(self, key): # create update array and initialize it update = [None]*(self.MAXLVL+1) current = self.header ''' start from highest level of skip list move the current reference forward while key is greater than key of node next to current Otherwise inserted current in update and move one level down and continue search ''' for i in range(self.level, -1, -1): while current.forward[i] and \\ current.forward[i].key < key: current = current.forward[i] update[i] = current ''' reached level 0 and forward reference to right, which is desired position to insert key. ''' current = current.forward[0] ''' if current is NULL that means we have reached to end of the level or current's key is not equal to key to insert that means we have to insert node between update[0] and current node ''' if current == None or current.key != key: # Generate a random level for node rlevel = self.randomLevel() ''' If random level is greater than list's current level (node with highest level inserted in list so far), initialize update value with reference to header for further use ''' if rlevel > self.level: for i in range(self.level+1, rlevel+1): update[i] = self.header self.level = rlevel # create new node with random level generated n = self.createNode(rlevel, key) # insert node by rearranging references for i in range(rlevel+1): n.forward[i] = update[i].forward[i] update[i].forward[i] = n print(\"Successfully inserted key {}\".format(key)) def deleteElement(self, search_key): # create update array and initialize it update = [None]*(self.MAXLVL+1) current = self.header ''' start from highest level of skip list move the current reference forward while key is greater than key of node next to current Otherwise inserted current in update and move one level down and continue search ''' for i in range(self.level, -1, -1): while(current.forward[i] and \\ current.forward[i].key < search_key): current = current.forward[i] update[i] = current ''' reached level 0 and advance reference to right, which is possibly our desired node ''' current = current.forward[0] # If current node is target node if current != None and current.key == search_key: ''' start from lowest level and rearrange references just like we do in singly linked list to remove target node ''' for i in range(self.level+1): ''' If at level i, next node is not target node, break the loop, no need to move further level ''' if update[i].forward[i] != current: break update[i].forward[i] = current.forward[i] # Remove levels having no elements while(self.level>0 and\\ self.header.forward[self.level] == None): self.level -= 1 print(\"Successfully deleted {}\".format(search_key)) def searchElement(self, key): current = self.header ''' start from highest level of skip list move the current reference forward while key is greater than key of node next to current Otherwise inserted current in update and move one level down and continue search ''' for i in range(self.level, -1, -1): while(current.forward[i] and\\ current.forward[i].key < key): current = current.forward[i] # reached level 0 and advance reference to # right, which is possibly our desired node current = current.forward[0] # If current node have key equal to # search key, we have found our target node if current and current.key == key: print(\"Found key \", key) # Display skip list level wise def displayList(self): print(\"\\n*****Skip List******\") head = self.header for lvl in range(self.level+1): print(\"Level {}: \".format(lvl), end=\" \") node = head.forward[lvl] while(node != None): print(node.key, end=\" \") node = node.forward[lvl] print(\"\") # Driver to test above codedef main(): lst = SkipList(3, 0.5) lst.insertElement(3) lst.insertElement(6) lst.insertElement(7) lst.insertElement(9) lst.insertElement(12) lst.insertElement(19) lst.insertElement(17) lst.insertElement(26) lst.insertElement(21) lst.insertElement(25) lst.displayList() # Search for node 19 lst.searchElement(19) # Delete node 19 lst.deleteElement(19) lst.displayList() main()",
"e": 15734,
"s": 9433,
"text": null
},
{
"code": null,
"e": 15742,
"s": 15734,
"text": "Output:"
},
{
"code": null,
"e": 16261,
"s": 15742,
"text": "Successfully Inserted key 3\nSuccessfully Inserted key 6\nSuccessfully Inserted key 7\nSuccessfully Inserted key 9\nSuccessfully Inserted key 12\nSuccessfully Inserted key 19\nSuccessfully Inserted key 17\nSuccessfully Inserted key 26\nSuccessfully Inserted key 21\nSuccessfully Inserted key 25\n\n*****Skip List*****\nLevel 0: 3 6 7 9 12 17 19 21 25 26 \nLevel 1: 3 17 19 21 26 \nLevel 2: 17 19 21 \nFound key: 19\nSuccessfully deleted key 19\n\n*****Skip List*****\nLevel 0: 3 6 7 9 12 17 21 25 26 \nLevel 1: 3 17 21 26 \nLevel 2: 17 21 "
},
{
"code": null,
"e": 16346,
"s": 16261,
"text": "Time complexity of both searching and deletion is same – Time complexity Worst case:"
},
{
"code": null,
"e": 16360,
"s": 16346,
"text": "Access – O(n)"
},
{
"code": null,
"e": 16374,
"s": 16360,
"text": "Search – O(n)"
},
{
"code": null,
"e": 16388,
"s": 16374,
"text": "Insert – O(n)"
},
{
"code": null,
"e": 16404,
"s": 16388,
"text": "Space – O(nlogn"
},
{
"code": null,
"e": 16418,
"s": 16404,
"text": "Delete – O(n)"
},
{
"code": null,
"e": 16897,
"s": 16418,
"text": "References ftp://ftp.cs.umd.edu/pub/skipLists/skiplists.pdf This article is contributed by Atul Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 16914,
"s": 16897,
"text": "surinderdawra388"
},
{
"code": null,
"e": 16929,
"s": 16914,
"text": "guptavivek0503"
},
{
"code": null,
"e": 16953,
"s": 16929,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 16965,
"s": 16953,
"text": "Linked List"
},
{
"code": null,
"e": 16977,
"s": 16965,
"text": "Linked List"
}
] |
How to Create Buttons Inside a Widget in Android?
|
08 Sep, 2020
How to Create a Basic Widget of an Android App?
How to Create a Dynamic Widget of an Android App?
A Widget is a mini version of an Application, that provides a ground for the user to navigate through it or use its features from the Home Screen or Lock Screen. Widgets contain elements according to the features it provides. Widgets, as previously termed a mini version of the Application, is capable of displaying similar elements that of an Application, through this article, let’s demonstrate the implementation of Buttons and correspondingly how they can be used for certain functionalities. Here is a preview of the same:
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.
Step 2: Add the App Widget to the Project
Right-Click on the app, move the cursor to new, find the “Widget” option at the end, select it.
Specify the required properties for the widget such as min.width and height, config file and preferred language, etc, and proceed. Files are automatically generated.
Step 3: What to program? Where to program?
In our application, since we wish to display two Buttons named “Activity1” & “Activity2“, we need to declare them inside the new_app_widget.xml file which is inside the Layouts in the Resources folder.The entire programming (back-end) is done in the newly created NewAppWidget.kt, Kotlin Class File in the Main Source Folder. Here, we construct the Buttons. Since these Buttons will redirect the users to different activities, we need to create two Empty Activities, we name them “Activity1” and “Activity2” respectively.These Activities serve as Pending Intents since they initialize only when the user clicks on one of the buttons.Changes are made to Activity 1 and Activity 2 front-end files to represent their names.Just refer to the below codes and the corresponding comments given below.
In our application, since we wish to display two Buttons named “Activity1” & “Activity2“, we need to declare them inside the new_app_widget.xml file which is inside the Layouts in the Resources folder.
The entire programming (back-end) is done in the newly created NewAppWidget.kt, Kotlin Class File in the Main Source Folder. Here, we construct the Buttons. Since these Buttons will redirect the users to different activities, we need to create two Empty Activities, we name them “Activity1” and “Activity2” respectively.
These Activities serve as Pending Intents since they initialize only when the user clicks on one of the buttons.
Changes are made to Activity 1 and Activity 2 front-end files to represent their names.
Just refer to the below codes and the corresponding comments given below.
new_app_widget.xml and NewAppWidget.kt files
XML
Kotlin
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#0F9D58" android:padding="@dimen/widget_margin"> <!-- Button 1 --> <Button android:id="@+id/btn1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Activity1" android:layout_centerInParent="true" /> <!-- Button 2 --> <Button android:id="@+id/btn2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Activity2" android:layout_centerHorizontal="true" android:layout_below="@id/btn1" /> </RelativeLayout>
package org.geeksforgeeks.widget_buttons import android.app.PendingIntentimport android.appwidget.AppWidgetManagerimport android.appwidget.AppWidgetProviderimport android.content.Contextimport android.content.Intentimport android.widget.RemoteViews // Implementation of App Widget functionalityclass NewAppWidget : AppWidgetProvider() { override fun onUpdate( context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray ) { // There may be multiple widgets active, so update all of them for (appWidgetId in appWidgetIds) { updateAppWidget(context, appWidgetManager, appWidgetId) } } // Enter relevant functionality for when // the first widget is created override fun onEnabled(context: Context) { } // Enter relevant functionality for when // the last widget is disabled override fun onDisabled(context: Context) { } } internal fun updateAppWidget( context: Context, appWidgetManager: AppWidgetManager, appWidgetId: Int) /////////////////////////////Start Coding Here///////////////////////////////////////{ // Create a pending Intent for Activity 1 val i1 : PendingIntent = Intent(context,Activity1::class.java).let { intent -> PendingIntent.getActivity(context, 0, intent, 0) } // Create a pending Intent for Activity 2 val i2 : PendingIntent = Intent(context,Activity2::class.java).let { intent -> PendingIntent.getActivity(context, 0, intent, 0) } // Construct the RemoteViews object val views = RemoteViews(context.packageName, R.layout.new_app_widget) // Button 1 onClick Function .apply{setOnClickPendingIntent(R.id.btn1,i1)} // Button 2 onClick Function .apply { setOnClickPendingIntent(R.id.btn2,i2) } // Instruct the widget manager to update the widget appWidgetManager.updateAppWidget(appWidgetId, views)}/////////////////////////////Code Ends Here///////////////////////////////////////
activity_1.xml, Activity1.kt, activity_2.xml, Activity2.kt files
In both, the XML files add only a TextView, and in the Kotlin files, we have added nothing. The users may write their own code as their requirements inside those files.
XML
Kotlin
XML
Kotlin
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".Activity1"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Activity 1" android:layout_centerInParent="true" /> </RelativeLayout>
package org.geeksforgeeks.widget_buttons import androidx.appcompat.app.AppCompatActivityimport android.os.Bundle class Activity1 : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_1) }}
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".Activity2"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Activity 2" android:layout_centerInParent="true" /> </RelativeLayout>
package org.geeksforgeeks.widget_buttons import androidx.appcompat.app.AppCompatActivityimport android.os.Bundle class Activity2 : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_2) }}
activity_main.xml, MainActivity.kt files
There is nothing to do inside the activity_main.xml, MainActivity.kt files. The users may write their own code as their requirements inside those files.
XML
Kotlin
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
package org.geeksforgeeks.widget_buttons import androidx.appcompat.app.AppCompatActivityimport android.os.Bundle class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) }}
android
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Add Views Dynamically and Store Data in Arraylist in Android?
Android SDK and it's Components
Flutter - Custom Bottom Navigation Bar
How to Communicate Between Fragments in Android?
Retrofit with Kotlin Coroutine in Android
How to Add Views Dynamically and Store Data in Arraylist in Android?
Android UI Layouts
Kotlin Array
How to Communicate Between Fragments in Android?
Retrofit with Kotlin Coroutine in Android
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Sep, 2020"
},
{
"code": null,
"e": 76,
"s": 28,
"text": "How to Create a Basic Widget of an Android App?"
},
{
"code": null,
"e": 126,
"s": 76,
"text": "How to Create a Dynamic Widget of an Android App?"
},
{
"code": null,
"e": 654,
"s": 126,
"text": "A Widget is a mini version of an Application, that provides a ground for the user to navigate through it or use its features from the Home Screen or Lock Screen. Widgets contain elements according to the features it provides. Widgets, as previously termed a mini version of the Application, is capable of displaying similar elements that of an Application, through this article, let’s demonstrate the implementation of Buttons and correspondingly how they can be used for certain functionalities. Here is a preview of the same:"
},
{
"code": null,
"e": 683,
"s": 654,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 847,
"s": 683,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language."
},
{
"code": null,
"e": 889,
"s": 847,
"text": "Step 2: Add the App Widget to the Project"
},
{
"code": null,
"e": 985,
"s": 889,
"text": "Right-Click on the app, move the cursor to new, find the “Widget” option at the end, select it."
},
{
"code": null,
"e": 1151,
"s": 985,
"text": "Specify the required properties for the widget such as min.width and height, config file and preferred language, etc, and proceed. Files are automatically generated."
},
{
"code": null,
"e": 1194,
"s": 1151,
"text": "Step 3: What to program? Where to program?"
},
{
"code": null,
"e": 1988,
"s": 1194,
"text": "In our application, since we wish to display two Buttons named “Activity1” & “Activity2“, we need to declare them inside the new_app_widget.xml file which is inside the Layouts in the Resources folder.The entire programming (back-end) is done in the newly created NewAppWidget.kt, Kotlin Class File in the Main Source Folder. Here, we construct the Buttons. Since these Buttons will redirect the users to different activities, we need to create two Empty Activities, we name them “Activity1” and “Activity2” respectively.These Activities serve as Pending Intents since they initialize only when the user clicks on one of the buttons.Changes are made to Activity 1 and Activity 2 front-end files to represent their names.Just refer to the below codes and the corresponding comments given below."
},
{
"code": null,
"e": 2190,
"s": 1988,
"text": "In our application, since we wish to display two Buttons named “Activity1” & “Activity2“, we need to declare them inside the new_app_widget.xml file which is inside the Layouts in the Resources folder."
},
{
"code": null,
"e": 2511,
"s": 2190,
"text": "The entire programming (back-end) is done in the newly created NewAppWidget.kt, Kotlin Class File in the Main Source Folder. Here, we construct the Buttons. Since these Buttons will redirect the users to different activities, we need to create two Empty Activities, we name them “Activity1” and “Activity2” respectively."
},
{
"code": null,
"e": 2624,
"s": 2511,
"text": "These Activities serve as Pending Intents since they initialize only when the user clicks on one of the buttons."
},
{
"code": null,
"e": 2712,
"s": 2624,
"text": "Changes are made to Activity 1 and Activity 2 front-end files to represent their names."
},
{
"code": null,
"e": 2786,
"s": 2712,
"text": "Just refer to the below codes and the corresponding comments given below."
},
{
"code": null,
"e": 2831,
"s": 2786,
"text": "new_app_widget.xml and NewAppWidget.kt files"
},
{
"code": null,
"e": 2835,
"s": 2831,
"text": "XML"
},
{
"code": null,
"e": 2842,
"s": 2835,
"text": "Kotlin"
},
{
"code": "<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:background=\"#0F9D58\" android:padding=\"@dimen/widget_margin\"> <!-- Button 1 --> <Button android:id=\"@+id/btn1\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Activity1\" android:layout_centerInParent=\"true\" /> <!-- Button 2 --> <Button android:id=\"@+id/btn2\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Activity2\" android:layout_centerHorizontal=\"true\" android:layout_below=\"@id/btn1\" /> </RelativeLayout>",
"e": 3611,
"s": 2842,
"text": null
},
{
"code": "package org.geeksforgeeks.widget_buttons import android.app.PendingIntentimport android.appwidget.AppWidgetManagerimport android.appwidget.AppWidgetProviderimport android.content.Contextimport android.content.Intentimport android.widget.RemoteViews // Implementation of App Widget functionalityclass NewAppWidget : AppWidgetProvider() { override fun onUpdate( context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray ) { // There may be multiple widgets active, so update all of them for (appWidgetId in appWidgetIds) { updateAppWidget(context, appWidgetManager, appWidgetId) } } // Enter relevant functionality for when // the first widget is created override fun onEnabled(context: Context) { } // Enter relevant functionality for when // the last widget is disabled override fun onDisabled(context: Context) { } } internal fun updateAppWidget( context: Context, appWidgetManager: AppWidgetManager, appWidgetId: Int) /////////////////////////////Start Coding Here///////////////////////////////////////{ // Create a pending Intent for Activity 1 val i1 : PendingIntent = Intent(context,Activity1::class.java).let { intent -> PendingIntent.getActivity(context, 0, intent, 0) } // Create a pending Intent for Activity 2 val i2 : PendingIntent = Intent(context,Activity2::class.java).let { intent -> PendingIntent.getActivity(context, 0, intent, 0) } // Construct the RemoteViews object val views = RemoteViews(context.packageName, R.layout.new_app_widget) // Button 1 onClick Function .apply{setOnClickPendingIntent(R.id.btn1,i1)} // Button 2 onClick Function .apply { setOnClickPendingIntent(R.id.btn2,i2) } // Instruct the widget manager to update the widget appWidgetManager.updateAppWidget(appWidgetId, views)}/////////////////////////////Code Ends Here///////////////////////////////////////",
"e": 5635,
"s": 3611,
"text": null
},
{
"code": null,
"e": 5700,
"s": 5635,
"text": "activity_1.xml, Activity1.kt, activity_2.xml, Activity2.kt files"
},
{
"code": null,
"e": 5869,
"s": 5700,
"text": "In both, the XML files add only a TextView, and in the Kotlin files, we have added nothing. The users may write their own code as their requirements inside those files."
},
{
"code": null,
"e": 5873,
"s": 5869,
"text": "XML"
},
{
"code": null,
"e": 5880,
"s": 5873,
"text": "Kotlin"
},
{
"code": null,
"e": 5884,
"s": 5880,
"text": "XML"
},
{
"code": null,
"e": 5891,
"s": 5884,
"text": "Kotlin"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".Activity1\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Activity 1\" android:layout_centerInParent=\"true\" /> </RelativeLayout>",
"e": 6431,
"s": 5891,
"text": null
},
{
"code": "package org.geeksforgeeks.widget_buttons import androidx.appcompat.app.AppCompatActivityimport android.os.Bundle class Activity1 : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_1) }}",
"e": 6733,
"s": 6431,
"text": null
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".Activity2\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Activity 2\" android:layout_centerInParent=\"true\" /> </RelativeLayout>",
"e": 7273,
"s": 6733,
"text": null
},
{
"code": "package org.geeksforgeeks.widget_buttons import androidx.appcompat.app.AppCompatActivityimport android.os.Bundle class Activity2 : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_2) }}",
"e": 7575,
"s": 7273,
"text": null
},
{
"code": null,
"e": 7616,
"s": 7575,
"text": "activity_main.xml, MainActivity.kt files"
},
{
"code": null,
"e": 7769,
"s": 7616,
"text": "There is nothing to do inside the activity_main.xml, MainActivity.kt files. The users may write their own code as their requirements inside those files."
},
{
"code": null,
"e": 7773,
"s": 7769,
"text": "XML"
},
{
"code": null,
"e": 7780,
"s": 7773,
"text": "Kotlin"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Hello World!\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintRight_toRightOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> </androidx.constraintlayout.widget.ConstraintLayout>",
"e": 8552,
"s": 7780,
"text": null
},
{
"code": "package org.geeksforgeeks.widget_buttons import androidx.appcompat.app.AppCompatActivityimport android.os.Bundle class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) }}",
"e": 8860,
"s": 8552,
"text": null
},
{
"code": null,
"e": 8868,
"s": 8860,
"text": "android"
},
{
"code": null,
"e": 8876,
"s": 8868,
"text": "Android"
},
{
"code": null,
"e": 8883,
"s": 8876,
"text": "Kotlin"
},
{
"code": null,
"e": 8891,
"s": 8883,
"text": "Android"
},
{
"code": null,
"e": 8989,
"s": 8891,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9058,
"s": 8989,
"text": "How to Add Views Dynamically and Store Data in Arraylist in Android?"
},
{
"code": null,
"e": 9090,
"s": 9058,
"text": "Android SDK and it's Components"
},
{
"code": null,
"e": 9129,
"s": 9090,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 9178,
"s": 9129,
"text": "How to Communicate Between Fragments in Android?"
},
{
"code": null,
"e": 9220,
"s": 9178,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 9289,
"s": 9220,
"text": "How to Add Views Dynamically and Store Data in Arraylist in Android?"
},
{
"code": null,
"e": 9308,
"s": 9289,
"text": "Android UI Layouts"
},
{
"code": null,
"e": 9321,
"s": 9308,
"text": "Kotlin Array"
},
{
"code": null,
"e": 9370,
"s": 9321,
"text": "How to Communicate Between Fragments in Android?"
}
] |
Creating a Rainbow using Graphics Programming in C
|
13 Aug, 2019
In Turbo C graphics we use graphics.h functions to draw different shapes(like circle, rectangle etc), display text(any message) in different format(different fonts and colors). By using graphics.h we can make programs, animations and also games. These can be useful for beginners.
Functions Used :
delay(n): A function from dos.h header file is responsible for holding of the program for a while depending upon given value n.
setcolor(n): A function from graphics.h header file which set the color of pointer(cursor).
arc(x,y,a1,a2,r): A function from graphics.h header file which draw an arc with (x,y) as centre (a2-a1) as angle and r as radius.
Implementation:
// A C program to make a rainbow. This program would only// work in Turbo C compiler in DOS compatible machine#include<stdio.h>#include<graphics.h>#include<dos.h> // function for making of rainbowvoid rainbow(){ // auto detection int gdriver = DETECT,gmode; int x, y, i; // initialize graphics mode(passed three arguments to // initgraph function) // &gdriver is the address of gdriver variable, &gmode is // the address of gmode and // "C:\\Turboc3\\BGI" is the directory path where BGI files are stored initgraph(&gdriver,&gmode,"C:\\Turboc3\\BGI"); x = getmaxx() / 2;//finding centre x-ordinate of screen y = getmaxy() / 2;//finding centre y-ordinate of screen for (i=30; i<200; i++) { // delay function under dos.h for holding the // function for some time delay(100); // selecting color for making of rainbow setcolor(i/10); // making of arc with fixed centre and increasing radius arc(x, y, 0, 180, i-10); }}// driver programint main(){ rainbow(); return 0;}
Reference:http://www.xcnotes.com/graphics-in-c-language/draw-rainbow-in-c
This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
MuhammedYasir
C-Library
computer-graphics
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Function Pointer in C
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
Different Methods to Reverse a String in C++
std::string class in C++
Unordered Sets in C++ Standard Template Library
rand() and srand() in C/C++
Enumeration (or enum) in C
What is the purpose of a function prototype?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Aug, 2019"
},
{
"code": null,
"e": 309,
"s": 28,
"text": "In Turbo C graphics we use graphics.h functions to draw different shapes(like circle, rectangle etc), display text(any message) in different format(different fonts and colors). By using graphics.h we can make programs, animations and also games. These can be useful for beginners."
},
{
"code": null,
"e": 326,
"s": 309,
"text": "Functions Used :"
},
{
"code": null,
"e": 454,
"s": 326,
"text": "delay(n): A function from dos.h header file is responsible for holding of the program for a while depending upon given value n."
},
{
"code": null,
"e": 546,
"s": 454,
"text": "setcolor(n): A function from graphics.h header file which set the color of pointer(cursor)."
},
{
"code": null,
"e": 676,
"s": 546,
"text": "arc(x,y,a1,a2,r): A function from graphics.h header file which draw an arc with (x,y) as centre (a2-a1) as angle and r as radius."
},
{
"code": null,
"e": 692,
"s": 676,
"text": "Implementation:"
},
{
"code": "// A C program to make a rainbow. This program would only// work in Turbo C compiler in DOS compatible machine#include<stdio.h>#include<graphics.h>#include<dos.h> // function for making of rainbowvoid rainbow(){ // auto detection int gdriver = DETECT,gmode; int x, y, i; // initialize graphics mode(passed three arguments to // initgraph function) // &gdriver is the address of gdriver variable, &gmode is // the address of gmode and // \"C:\\\\Turboc3\\\\BGI\" is the directory path where BGI files are stored initgraph(&gdriver,&gmode,\"C:\\\\Turboc3\\\\BGI\"); x = getmaxx() / 2;//finding centre x-ordinate of screen y = getmaxy() / 2;//finding centre y-ordinate of screen for (i=30; i<200; i++) { // delay function under dos.h for holding the // function for some time delay(100); // selecting color for making of rainbow setcolor(i/10); // making of arc with fixed centre and increasing radius arc(x, y, 0, 180, i-10); }}// driver programint main(){ rainbow(); return 0;}",
"e": 1767,
"s": 692,
"text": null
},
{
"code": null,
"e": 1841,
"s": 1767,
"text": "Reference:http://www.xcnotes.com/graphics-in-c-language/draw-rainbow-in-c"
},
{
"code": null,
"e": 2156,
"s": 1841,
"text": "This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 2281,
"s": 2156,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 2295,
"s": 2281,
"text": "MuhammedYasir"
},
{
"code": null,
"e": 2305,
"s": 2295,
"text": "C-Library"
},
{
"code": null,
"e": 2323,
"s": 2305,
"text": "computer-graphics"
},
{
"code": null,
"e": 2334,
"s": 2323,
"text": "C Language"
},
{
"code": null,
"e": 2432,
"s": 2334,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2449,
"s": 2432,
"text": "Substring in C++"
},
{
"code": null,
"e": 2471,
"s": 2449,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 2506,
"s": 2471,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 2552,
"s": 2506,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 2597,
"s": 2552,
"text": "Different Methods to Reverse a String in C++"
},
{
"code": null,
"e": 2622,
"s": 2597,
"text": "std::string class in C++"
},
{
"code": null,
"e": 2670,
"s": 2622,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 2698,
"s": 2670,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 2725,
"s": 2698,
"text": "Enumeration (or enum) in C"
}
] |
GATE | GATE-IT-2004 | Question 8
|
19 Nov, 2018
What is the minimum number of NAND gates required to implement a 2-input EXCLUSIVE-OR function without using any other logic gate?(A) 3(B) 4(C) 5(D) 6Answer: (B)Explanation:
Pic Courtesy: http://www.electronics-tutorials.ws/logic/logic_7.html
Other way around:
x XOR y = x’y+xy’ = x’y+xy’+xx’+yy’ = (x+y) (x’+y’)
Using NAND gates
F= (x+y)(xy)’ = x. (xy)’ + y. (xy)’
Taking compliment
F’= ( x. (xy)’ + y. (xy)’ )’ = (x. (xy)’)’. (y. (xy)’)
Compliment again
F=( (x. (xy)’)’. (y. (xy)’) )’
So Answer is BQuiz of this Question
GATE IT 2004
GATE-GATE IT 2004
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Nov, 2018"
},
{
"code": null,
"e": 203,
"s": 28,
"text": "What is the minimum number of NAND gates required to implement a 2-input EXCLUSIVE-OR function without using any other logic gate?(A) 3(B) 4(C) 5(D) 6Answer: (B)Explanation: "
},
{
"code": null,
"e": 272,
"s": 203,
"text": "Pic Courtesy: http://www.electronics-tutorials.ws/logic/logic_7.html"
},
{
"code": null,
"e": 290,
"s": 272,
"text": "Other way around:"
},
{
"code": null,
"e": 342,
"s": 290,
"text": "x XOR y = x’y+xy’ = x’y+xy’+xx’+yy’ = (x+y) (x’+y’)"
},
{
"code": null,
"e": 359,
"s": 342,
"text": "Using NAND gates"
},
{
"code": null,
"e": 395,
"s": 359,
"text": "F= (x+y)(xy)’ = x. (xy)’ + y. (xy)’"
},
{
"code": null,
"e": 413,
"s": 395,
"text": "Taking compliment"
},
{
"code": null,
"e": 468,
"s": 413,
"text": "F’= ( x. (xy)’ + y. (xy)’ )’ = (x. (xy)’)’. (y. (xy)’)"
},
{
"code": null,
"e": 485,
"s": 468,
"text": "Compliment again"
},
{
"code": null,
"e": 516,
"s": 485,
"text": "F=( (x. (xy)’)’. (y. (xy)’) )’"
},
{
"code": null,
"e": 552,
"s": 516,
"text": "So Answer is BQuiz of this Question"
},
{
"code": null,
"e": 565,
"s": 552,
"text": "GATE IT 2004"
},
{
"code": null,
"e": 583,
"s": 565,
"text": "GATE-GATE IT 2004"
},
{
"code": null,
"e": 588,
"s": 583,
"text": "GATE"
}
] |
How to make a PyGame Window?
|
24 Feb, 2021
PyGame is a free and open-source cross-platform library for game development in Python. It was officially written by Pete Shinners to replace PySDL it is suitable for the creation of client-side applications and acts as standalone executables. In this article, we are going to see how to make Pygame window in Python.
Command to install pygame on Windows-based system :
pip install pygame
Steps to make a pygame window:
Import pygame module
Create a pygame window object using pygame.display.set_mode() method. It requires two parameters that define the width and height of the window.
Window properties can be altered such as the title of the window can be set using the set_caption() method. The background color can be changed by filling the screen object using a 3 tuple of integers ranging from 0 to 255 and representing the RGB values respectively.
Display the window using the flip() method. Once this method is called, the code reaches its end and the program terminates.
To keep the window visible without terminating abruptly, an infinite loop can be added to the code. However, the program will not quit even if the user wants. The user has to forcibly end the program by using CTRL+C in the command line.
To display the window for as long as the user does not choose to close it, pygame.event.get() method is used. This method returns a list of events. To stop the window from displaying, one has to loop through and check whether the event has a type quit. If found, one can easily exit from the loop.
Example:
Python3
# import the pygame moduleimport pygame # Define the background colour# using RGB color coding.background_colour = (234, 212, 252) # Define the dimensions of# screen object(width,height)screen = pygame.display.set_mode((300, 300)) # Set the caption of the screenpygame.display.set_caption('Geeksforgeeks') # Fill the background colour to the screenscreen.fill(background_colour) # Update the display using flippygame.display.flip() # Variable to keep our game loop runningrunning = True # game loopwhile running: # for loop through the event queue for event in pygame.event.get(): # Check for QUIT event if event.type == pygame.QUIT: running = False
Output:
Picked
Python-PyGame
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Feb, 2021"
},
{
"code": null,
"e": 346,
"s": 28,
"text": "PyGame is a free and open-source cross-platform library for game development in Python. It was officially written by Pete Shinners to replace PySDL it is suitable for the creation of client-side applications and acts as standalone executables. In this article, we are going to see how to make Pygame window in Python."
},
{
"code": null,
"e": 400,
"s": 346,
"text": "Command to install pygame on Windows-based system : "
},
{
"code": null,
"e": 419,
"s": 400,
"text": "pip install pygame"
},
{
"code": null,
"e": 450,
"s": 419,
"text": "Steps to make a pygame window:"
},
{
"code": null,
"e": 471,
"s": 450,
"text": "Import pygame module"
},
{
"code": null,
"e": 616,
"s": 471,
"text": "Create a pygame window object using pygame.display.set_mode() method. It requires two parameters that define the width and height of the window."
},
{
"code": null,
"e": 885,
"s": 616,
"text": "Window properties can be altered such as the title of the window can be set using the set_caption() method. The background color can be changed by filling the screen object using a 3 tuple of integers ranging from 0 to 255 and representing the RGB values respectively."
},
{
"code": null,
"e": 1010,
"s": 885,
"text": "Display the window using the flip() method. Once this method is called, the code reaches its end and the program terminates."
},
{
"code": null,
"e": 1247,
"s": 1010,
"text": "To keep the window visible without terminating abruptly, an infinite loop can be added to the code. However, the program will not quit even if the user wants. The user has to forcibly end the program by using CTRL+C in the command line."
},
{
"code": null,
"e": 1545,
"s": 1247,
"text": "To display the window for as long as the user does not choose to close it, pygame.event.get() method is used. This method returns a list of events. To stop the window from displaying, one has to loop through and check whether the event has a type quit. If found, one can easily exit from the loop."
},
{
"code": null,
"e": 1554,
"s": 1545,
"text": "Example:"
},
{
"code": null,
"e": 1562,
"s": 1554,
"text": "Python3"
},
{
"code": "# import the pygame moduleimport pygame # Define the background colour# using RGB color coding.background_colour = (234, 212, 252) # Define the dimensions of# screen object(width,height)screen = pygame.display.set_mode((300, 300)) # Set the caption of the screenpygame.display.set_caption('Geeksforgeeks') # Fill the background colour to the screenscreen.fill(background_colour) # Update the display using flippygame.display.flip() # Variable to keep our game loop runningrunning = True # game loopwhile running: # for loop through the event queue for event in pygame.event.get(): # Check for QUIT event if event.type == pygame.QUIT: running = False",
"e": 2264,
"s": 1562,
"text": null
},
{
"code": null,
"e": 2273,
"s": 2264,
"text": "Output: "
},
{
"code": null,
"e": 2280,
"s": 2273,
"text": "Picked"
},
{
"code": null,
"e": 2294,
"s": 2280,
"text": "Python-PyGame"
},
{
"code": null,
"e": 2301,
"s": 2294,
"text": "Python"
}
] |
D3.js band.bandwidth() Function
|
26 Jul, 2021
The band.bandwidth() function in d3.js is used to find the width of each band.
Syntax:
band.bandwidth()
Parameters: This function does not accept any parameter.
Return Values: This function returns the width of each band.
Example 1:
HTML
<!DOCTYPE html><html lang = "en"> <head> <meta charset = "UTF-8" /> <meta name = "viewport" path1tent = "width=device-width, initial-scale = 1.0"/> <script src = "https://d3js.org/d3.v4.min.js"> </script></head> <body> <script> // Creating the band scale with // specified domain and range. var A = d3.scaleBand() .domain([10, 20, 30, 40, 50]) .range([0, 10]); // Applying bandwidth() Function let gfg = A.bandwidth(); // Printing the Output console.log("Bandwidth Of A: ",gfg); </script></body> </html>
Output:
Bandwidth Of A: 2
Example 2:
HTML
<!DOCTYPE html><html lang = "en"> <head> <meta charset = "UTF-8" /> <meta name = "viewport" path1tent = "width=device-width, initial-scale = 1.0"/> <script src = "https://d3js.org/d3.v4.min.js"> </script></head> <body> <script> // Creating the band scale with // specified domain and range. var B = d3.scaleBand() .domain(["one", "two", "three", "four"]) .range([0, 60]); // Applying bandwidth() Function let gfg = B.bandwidth(); // Printing the Output console.log("Bandwidth Of each band in B: ",gfg); </script></body> </html>
Output:
Bandwidth Of each band in B: 15
surinderdawra388
D3.js
JavaScript
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": "\n26 Jul, 2021"
},
{
"code": null,
"e": 107,
"s": 28,
"text": "The band.bandwidth() function in d3.js is used to find the width of each band."
},
{
"code": null,
"e": 115,
"s": 107,
"text": "Syntax:"
},
{
"code": null,
"e": 132,
"s": 115,
"text": "band.bandwidth()"
},
{
"code": null,
"e": 189,
"s": 132,
"text": "Parameters: This function does not accept any parameter."
},
{
"code": null,
"e": 250,
"s": 189,
"text": "Return Values: This function returns the width of each band."
},
{
"code": null,
"e": 261,
"s": 250,
"text": "Example 1:"
},
{
"code": null,
"e": 266,
"s": 261,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang = \"en\"> <head> <meta charset = \"UTF-8\" /> <meta name = \"viewport\" path1tent = \"width=device-width, initial-scale = 1.0\"/> <script src = \"https://d3js.org/d3.v4.min.js\"> </script></head> <body> <script> // Creating the band scale with // specified domain and range. var A = d3.scaleBand() .domain([10, 20, 30, 40, 50]) .range([0, 10]); // Applying bandwidth() Function let gfg = A.bandwidth(); // Printing the Output console.log(\"Bandwidth Of A: \",gfg); </script></body> </html>",
"e": 914,
"s": 266,
"text": null
},
{
"code": null,
"e": 922,
"s": 914,
"text": "Output:"
},
{
"code": null,
"e": 941,
"s": 922,
"text": "Bandwidth Of A: 2"
},
{
"code": null,
"e": 953,
"s": 941,
"text": "Example 2: "
},
{
"code": null,
"e": 958,
"s": 953,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang = \"en\"> <head> <meta charset = \"UTF-8\" /> <meta name = \"viewport\" path1tent = \"width=device-width, initial-scale = 1.0\"/> <script src = \"https://d3js.org/d3.v4.min.js\"> </script></head> <body> <script> // Creating the band scale with // specified domain and range. var B = d3.scaleBand() .domain([\"one\", \"two\", \"three\", \"four\"]) .range([0, 60]); // Applying bandwidth() Function let gfg = B.bandwidth(); // Printing the Output console.log(\"Bandwidth Of each band in B: \",gfg); </script></body> </html>",
"e": 1619,
"s": 958,
"text": null
},
{
"code": null,
"e": 1630,
"s": 1619,
"text": " Output: "
},
{
"code": null,
"e": 1663,
"s": 1630,
"text": "Bandwidth Of each band in B: 15"
},
{
"code": null,
"e": 1680,
"s": 1663,
"text": "surinderdawra388"
},
{
"code": null,
"e": 1686,
"s": 1680,
"text": "D3.js"
},
{
"code": null,
"e": 1697,
"s": 1686,
"text": "JavaScript"
},
{
"code": null,
"e": 1714,
"s": 1697,
"text": "Web Technologies"
}
] |
PyQt5 – How to add border on QLabel ?
|
26 Mar, 2020
When we create Label in PyQt5, we can see that there are no borders like there exist in Push Buttons, in this article we will see how to add border to the Label.
In order to add border to the Label we will use label.setStyleSheet() method, this will add the border to the label, also we can set the thickness as well as color of the border.
Syntax : label.setStyleSheet(“border: 1px solid black;”)
Argument : It takes string as a argument.
Action performed : This will create a border on label with thickness of 1px and color will be black.
Below is the Python implementation –
# importing the required libraries from PyQt5.QtWidgets import * from PyQt5.QtGui import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # set the title self.setWindowTitle("Label") # setting the geometry of window self.setGeometry(0, 0, 400, 300) # creating a label widget # by default label will display at top left corner self.label_1 = QLabel('It is Label 1', self) # moving position self.label_1.move(100, 100) # setting up border self.label_1.setStyleSheet("border: 1px solid black;") # creating a label widget # by default label will display at top left corner self.label_2 = QLabel('It is Label 2', self) # moving position self.label_2.move(100, 200) # setting up border self.label_2.setStyleSheet("border: 3px solid blue;") # show all the widgets self.show() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window()# start the appsys.exit(App.exec())
Output :
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Enumerate() in Python
Different ways to create Pandas Dataframe
Read a file line by line in Python
How to Install PIP on Windows ?
Python String | replace()
Python OOPs Concepts
Python Classes and Objects
*args and **kwargs in Python
Introduction To PYTHON
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Mar, 2020"
},
{
"code": null,
"e": 190,
"s": 28,
"text": "When we create Label in PyQt5, we can see that there are no borders like there exist in Push Buttons, in this article we will see how to add border to the Label."
},
{
"code": null,
"e": 369,
"s": 190,
"text": "In order to add border to the Label we will use label.setStyleSheet() method, this will add the border to the label, also we can set the thickness as well as color of the border."
},
{
"code": null,
"e": 426,
"s": 369,
"text": "Syntax : label.setStyleSheet(“border: 1px solid black;”)"
},
{
"code": null,
"e": 468,
"s": 426,
"text": "Argument : It takes string as a argument."
},
{
"code": null,
"e": 569,
"s": 468,
"text": "Action performed : This will create a border on label with thickness of 1px and color will be black."
},
{
"code": null,
"e": 607,
"s": 569,
"text": " Below is the Python implementation –"
},
{
"code": "# importing the required libraries from PyQt5.QtWidgets import * from PyQt5.QtGui import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # set the title self.setWindowTitle(\"Label\") # setting the geometry of window self.setGeometry(0, 0, 400, 300) # creating a label widget # by default label will display at top left corner self.label_1 = QLabel('It is Label 1', self) # moving position self.label_1.move(100, 100) # setting up border self.label_1.setStyleSheet(\"border: 1px solid black;\") # creating a label widget # by default label will display at top left corner self.label_2 = QLabel('It is Label 2', self) # moving position self.label_2.move(100, 200) # setting up border self.label_2.setStyleSheet(\"border: 3px solid blue;\") # show all the widgets self.show() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window()# start the appsys.exit(App.exec())",
"e": 1718,
"s": 607,
"text": null
},
{
"code": null,
"e": 1727,
"s": 1718,
"text": "Output :"
},
{
"code": null,
"e": 1738,
"s": 1727,
"text": "Python-gui"
},
{
"code": null,
"e": 1750,
"s": 1738,
"text": "Python-PyQt"
},
{
"code": null,
"e": 1757,
"s": 1750,
"text": "Python"
},
{
"code": null,
"e": 1855,
"s": 1757,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1873,
"s": 1855,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1895,
"s": 1873,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1937,
"s": 1895,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1972,
"s": 1937,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2004,
"s": 1972,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2030,
"s": 2004,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2051,
"s": 2030,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2078,
"s": 2051,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2107,
"s": 2078,
"text": "*args and **kwargs in Python"
}
] |
How to Print Specific date-time in Golang?
|
17 May, 2020
Golang supports time formatting and parsing via pattern-based layouts. In Go, the current time can be determined by using time.Now(), provided by the time package. Package time provides functionality for measuring and displaying the time.
To print Current date-time you need to import the “time” package in your Go program to work with date and time.
Example:
// Golang program to show// the use of time.Now() Functionpackage main import "fmt"import "time" func main() { dt := time.Now() // printing the time in string format fmt.Println("Current date and time is: ", dt.String())}
Output :
Current date and time is: 2020-05-05 06:43:01.419199824 +0000 UTC m=+0.000076701
To print Specific date-time in Golang use format constants provided in the time package. The commonly used formats are:
const (
ANSIC = "Mon Jan _2 15:04:05 2006"
UnixDate = "Mon Jan _2 15:04:05 MST 2006"
RubyDate = "Mon Jan 02 15:04:05 -0700 2006"
RFC822 = "02 Jan 06 15:04 MST"
RFC822Z = "02 Jan 06 15:04 -0700" // RFC822 with numeric zone
RFC850 = "Monday, 02-Jan-06 15:04:05 MST"
RFC1123 = "Mon, 02 Jan 2006 15:04:05 MST"
RFC1123Z = "Mon, 02 Jan 2006 15:04:05 -0700" // RFC1123 with numeric zone
RFC3339 = "2006-01-02T15:04:05Z07:00"
RFC3339Nano = "2006-01-02T15:04:05.999999999Z07:00"
Kitchen = "3:04PM"
// Handy time stamps.
Stamp = "Jan _2 15:04:05"
StampMilli = "Jan _2 15:04:05.000"
StampMicro = "Jan _2 15:04:05.000000"
StampNano = "Jan _2 15:04:05.000000000"
)
Example:
// Golang program to print specific date and timepackage main import "fmt"import "time" func main() { dt := time.Now() // printing date and time in UnixDate format fmt.Println("Specific date and time is: ", dt.Format(time.UnixDate))}
Output:
Specific date and time is: Tue May 5 07:05:00 UTC 2020
Example:
// Golang program to print specific date and timepackage main import "fmt"import "time" func main() { dt := time.Now() // Format MM-DD-YYYY fmt.Println(dt.Format("01-02-2006")) // Format MM-DD-YYYY hh:mm:ss fmt.Println(dt.Format("01-02-2006 15:04:05")) // With short weekday (Mon) fmt.Println(dt.Format("01-02-2006 15:04:05 Mon")) // With weekday (Monday) fmt.Println(dt.Format("01-02-2006 15:04:05 Monday")) // Include micro seconds fmt.Println(dt.Format("01-02-2006 15:04:05.000000"))}
Output:
11-10-2009
11-10-2009 23:00:00
11-10-2009 23:00:00 Tue
11-10-2009 23:00:00 Tuesday
11-10-2009 23:00:00.000000
Golang-Program
GoLang-time
Picked
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 May, 2020"
},
{
"code": null,
"e": 267,
"s": 28,
"text": "Golang supports time formatting and parsing via pattern-based layouts. In Go, the current time can be determined by using time.Now(), provided by the time package. Package time provides functionality for measuring and displaying the time."
},
{
"code": null,
"e": 379,
"s": 267,
"text": "To print Current date-time you need to import the “time” package in your Go program to work with date and time."
},
{
"code": null,
"e": 388,
"s": 379,
"text": "Example:"
},
{
"code": "// Golang program to show// the use of time.Now() Functionpackage main import \"fmt\"import \"time\" func main() { dt := time.Now() // printing the time in string format fmt.Println(\"Current date and time is: \", dt.String())}",
"e": 627,
"s": 388,
"text": null
},
{
"code": null,
"e": 636,
"s": 627,
"text": "Output :"
},
{
"code": null,
"e": 718,
"s": 636,
"text": "Current date and time is: 2020-05-05 06:43:01.419199824 +0000 UTC m=+0.000076701"
},
{
"code": null,
"e": 838,
"s": 718,
"text": "To print Specific date-time in Golang use format constants provided in the time package. The commonly used formats are:"
},
{
"code": null,
"e": 1602,
"s": 838,
"text": "const (\n ANSIC = \"Mon Jan _2 15:04:05 2006\"\n UnixDate = \"Mon Jan _2 15:04:05 MST 2006\"\n RubyDate = \"Mon Jan 02 15:04:05 -0700 2006\"\n RFC822 = \"02 Jan 06 15:04 MST\"\n RFC822Z = \"02 Jan 06 15:04 -0700\" // RFC822 with numeric zone\n RFC850 = \"Monday, 02-Jan-06 15:04:05 MST\"\n RFC1123 = \"Mon, 02 Jan 2006 15:04:05 MST\"\n RFC1123Z = \"Mon, 02 Jan 2006 15:04:05 -0700\" // RFC1123 with numeric zone\n RFC3339 = \"2006-01-02T15:04:05Z07:00\"\n RFC3339Nano = \"2006-01-02T15:04:05.999999999Z07:00\"\n Kitchen = \"3:04PM\"\n // Handy time stamps.\n Stamp = \"Jan _2 15:04:05\"\n StampMilli = \"Jan _2 15:04:05.000\"\n StampMicro = \"Jan _2 15:04:05.000000\"\n StampNano = \"Jan _2 15:04:05.000000000\"\n)\n"
},
{
"code": null,
"e": 1611,
"s": 1602,
"text": "Example:"
},
{
"code": "// Golang program to print specific date and timepackage main import \"fmt\"import \"time\" func main() { dt := time.Now() // printing date and time in UnixDate format fmt.Println(\"Specific date and time is: \", dt.Format(time.UnixDate))}",
"e": 1864,
"s": 1611,
"text": null
},
{
"code": null,
"e": 1872,
"s": 1864,
"text": "Output:"
},
{
"code": null,
"e": 1930,
"s": 1872,
"text": "Specific date and time is: Tue May 5 07:05:00 UTC 2020\n"
},
{
"code": null,
"e": 1939,
"s": 1930,
"text": "Example:"
},
{
"code": "// Golang program to print specific date and timepackage main import \"fmt\"import \"time\" func main() { dt := time.Now() // Format MM-DD-YYYY fmt.Println(dt.Format(\"01-02-2006\")) // Format MM-DD-YYYY hh:mm:ss fmt.Println(dt.Format(\"01-02-2006 15:04:05\")) // With short weekday (Mon) fmt.Println(dt.Format(\"01-02-2006 15:04:05 Mon\")) // With weekday (Monday) fmt.Println(dt.Format(\"01-02-2006 15:04:05 Monday\")) // Include micro seconds fmt.Println(dt.Format(\"01-02-2006 15:04:05.000000\"))}",
"e": 2476,
"s": 1939,
"text": null
},
{
"code": null,
"e": 2484,
"s": 2476,
"text": "Output:"
},
{
"code": null,
"e": 2595,
"s": 2484,
"text": "11-10-2009\n11-10-2009 23:00:00\n11-10-2009 23:00:00 Tue\n11-10-2009 23:00:00 Tuesday\n11-10-2009 23:00:00.000000\n"
},
{
"code": null,
"e": 2610,
"s": 2595,
"text": "Golang-Program"
},
{
"code": null,
"e": 2622,
"s": 2610,
"text": "GoLang-time"
},
{
"code": null,
"e": 2629,
"s": 2622,
"text": "Picked"
},
{
"code": null,
"e": 2641,
"s": 2629,
"text": "Go Language"
}
] |
ASP Server.HTMLEncode() Method
|
05 Feb, 2021
The ASP Server.HTMLEncode() Method is used to convert an HTML code to a string. It is used to encode form data and other client request data before using it in the web application. When the string to be encoded is not a double-byte character set, this method will convert the characters as given below:
The less-than, greater-than, ampersand, and double-quote characters are converted to their respective entity names.
Any ASCII code character whose code is greater-than or equal to 0x80 is converted to &#<number>, where the <number> portion is the ASCII character’s value.
When the string to be encoded is a double-byte character set, this method converts characters as given below:
All the extended characters are converted.
Any ASCII code character whose code is greater-than or equal to 0x80 is converted to &#<number>, where <number> is the ASCII character value.
Syntax:
Server.HTMLEncode( string )
Parameter Values: It contains a string value that specifies the HTML to be encoded as a string.
Example: The following code illustrates this method.
<%response.write(Server.HTMLEncode("The Bold tag: <b>"))%>
Output: The script produces the following output in the encoded form
The Bold tag: <b>
The Web Browser displays the HTML as normal
The Bold tag: <b>
ASP-Methods
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Remove elements from a JavaScript Array
Differences between Functional Components and Class Components in React
Roadmap to Learn JavaScript For Beginners
REST API (Introduction)
How to float three div side by side using CSS?
Difference Between PUT and PATCH Request
ReactJS | Router
Axios in React: A Guide for Beginners
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Feb, 2021"
},
{
"code": null,
"e": 331,
"s": 28,
"text": "The ASP Server.HTMLEncode() Method is used to convert an HTML code to a string. It is used to encode form data and other client request data before using it in the web application. When the string to be encoded is not a double-byte character set, this method will convert the characters as given below:"
},
{
"code": null,
"e": 447,
"s": 331,
"text": "The less-than, greater-than, ampersand, and double-quote characters are converted to their respective entity names."
},
{
"code": null,
"e": 603,
"s": 447,
"text": "Any ASCII code character whose code is greater-than or equal to 0x80 is converted to &#<number>, where the <number> portion is the ASCII character’s value."
},
{
"code": null,
"e": 713,
"s": 603,
"text": "When the string to be encoded is a double-byte character set, this method converts characters as given below:"
},
{
"code": null,
"e": 756,
"s": 713,
"text": "All the extended characters are converted."
},
{
"code": null,
"e": 898,
"s": 756,
"text": "Any ASCII code character whose code is greater-than or equal to 0x80 is converted to &#<number>, where <number> is the ASCII character value."
},
{
"code": null,
"e": 907,
"s": 898,
"text": "Syntax: "
},
{
"code": null,
"e": 935,
"s": 907,
"text": "Server.HTMLEncode( string )"
},
{
"code": null,
"e": 1031,
"s": 935,
"text": "Parameter Values: It contains a string value that specifies the HTML to be encoded as a string."
},
{
"code": null,
"e": 1084,
"s": 1031,
"text": "Example: The following code illustrates this method."
},
{
"code": "<%response.write(Server.HTMLEncode(\"The Bold tag: <b>\"))%>",
"e": 1143,
"s": 1084,
"text": null
},
{
"code": null,
"e": 1212,
"s": 1143,
"text": "Output: The script produces the following output in the encoded form"
},
{
"code": null,
"e": 1236,
"s": 1212,
"text": "The Bold tag: <b>"
},
{
"code": null,
"e": 1280,
"s": 1236,
"text": "The Web Browser displays the HTML as normal"
},
{
"code": null,
"e": 1298,
"s": 1280,
"text": "The Bold tag: <b>"
},
{
"code": null,
"e": 1310,
"s": 1298,
"text": "ASP-Methods"
},
{
"code": null,
"e": 1327,
"s": 1310,
"text": "Web Technologies"
},
{
"code": null,
"e": 1425,
"s": 1327,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1486,
"s": 1425,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1529,
"s": 1486,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 1569,
"s": 1529,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 1641,
"s": 1569,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 1683,
"s": 1641,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 1707,
"s": 1683,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 1754,
"s": 1707,
"text": "How to float three div side by side using CSS?"
},
{
"code": null,
"e": 1795,
"s": 1754,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 1812,
"s": 1795,
"text": "ReactJS | Router"
}
] |
Storage of String in Java
|
30 Aug, 2020
Prerequisite: Strings in Java
As we know both Stack and Heap space are part of Java Virtual Machine (JVM). But these memory spaces are used for different purposes. Stack space contains specific values that are short-lived whereas Heap space used by Java Runtime to allocate memory to objects and JRE classes. In Java, strings are stored in the heap area.
Why Java strings stored in Heap, not in Stack?
Well, String is a class and strings in java treated as an object, hence the object of String class will be stored in Heap, not in the stack area. Let’s go deep into the topic. As we all know we can create string object in two ways i.e
1) By string literal
2) By using ‘new’ keyword
String Literal is created by using a double quote. For Example:
String s=”Welcome”;
Here the JVM checks the String Constant Pool. If the string does not exist then a new string instance is created and placed in the pool if the string exists then it will not create a new object rather it will return the reference to the same instance. The cache which stores these string instances is known as String Constant pool or String Pool. In earlier versions of Java up to JDK 6 String pool was located inside PermGen(Permanent Generation) space. But in JDK 7 it is moved to the main heap area.
Why did the String pool move from PermGen to normal heap area?
PermGen space is limited space, the default size is just 64 MB. And it was a problem of creating and storing too many string objects in PermGen space. That’s why the String pool is moved to a larger heap area. To make the java more memory efficient the concept of string literal is used.
By the use of ‘new’ keyword, the JVM will create a new string object in the normal heap area even if the same string object present in the string pool.
For example:
String a=new String(“Trident”);
Let’s have a look to the concept with a java program and visualize the actual JVM memory Structure:
Java
import java.io.*; class GFG { public static void main(String[] args) { // String created using String literal String s1 = "TAT"; String s2 = "TAT"; // String created using 'new' keyword String s3 = new String("TAT"); String s4 = new String("TAT"); System.out.println(s1); System.out.println(s2); System.out.println(s3); System.out.println(s4); }}
Output:
TAT
TAT
TAT
TAT
The below figure illustrates the storage of String :
Here in the above figure, the String is stored in String constant pool. String object reference variables are stored in the stack area under the method main( ). As main( ) is having some space in the stack area.
Note:
All objects in Java are stored in the heap. The reference variable to the object stored in the stack area or they can be contained in other objects which puts them in the heap area also.
The string is passed by reference by java.
A string reference variable is not a reference itself. It is a variable that stores a reference (memory address).
Java-Strings
Java
Java-Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n30 Aug, 2020"
},
{
"code": null,
"e": 85,
"s": 54,
"text": "Prerequisite: Strings in Java"
},
{
"code": null,
"e": 411,
"s": 85,
"text": "As we know both Stack and Heap space are part of Java Virtual Machine (JVM). But these memory spaces are used for different purposes. Stack space contains specific values that are short-lived whereas Heap space used by Java Runtime to allocate memory to objects and JRE classes. In Java, strings are stored in the heap area. "
},
{
"code": null,
"e": 459,
"s": 411,
"text": "Why Java strings stored in Heap, not in Stack? "
},
{
"code": null,
"e": 695,
"s": 459,
"text": "Well, String is a class and strings in java treated as an object, hence the object of String class will be stored in Heap, not in the stack area. Let’s go deep into the topic. As we all know we can create string object in two ways i.e "
},
{
"code": null,
"e": 717,
"s": 695,
"text": "1) By string literal "
},
{
"code": null,
"e": 744,
"s": 717,
"text": "2) By using ‘new’ keyword "
},
{
"code": null,
"e": 808,
"s": 744,
"text": "String Literal is created by using a double quote. For Example:"
},
{
"code": null,
"e": 829,
"s": 808,
"text": "String s=”Welcome”; "
},
{
"code": null,
"e": 1332,
"s": 829,
"text": "Here the JVM checks the String Constant Pool. If the string does not exist then a new string instance is created and placed in the pool if the string exists then it will not create a new object rather it will return the reference to the same instance. The cache which stores these string instances is known as String Constant pool or String Pool. In earlier versions of Java up to JDK 6 String pool was located inside PermGen(Permanent Generation) space. But in JDK 7 it is moved to the main heap area."
},
{
"code": null,
"e": 1395,
"s": 1332,
"text": "Why did the String pool move from PermGen to normal heap area?"
},
{
"code": null,
"e": 1683,
"s": 1395,
"text": "PermGen space is limited space, the default size is just 64 MB. And it was a problem of creating and storing too many string objects in PermGen space. That’s why the String pool is moved to a larger heap area. To make the java more memory efficient the concept of string literal is used."
},
{
"code": null,
"e": 1836,
"s": 1683,
"text": "By the use of ‘new’ keyword, the JVM will create a new string object in the normal heap area even if the same string object present in the string pool. "
},
{
"code": null,
"e": 1849,
"s": 1836,
"text": "For example:"
},
{
"code": null,
"e": 1881,
"s": 1849,
"text": "String a=new String(“Trident”);"
},
{
"code": null,
"e": 1981,
"s": 1881,
"text": "Let’s have a look to the concept with a java program and visualize the actual JVM memory Structure:"
},
{
"code": null,
"e": 1986,
"s": 1981,
"text": "Java"
},
{
"code": "import java.io.*; class GFG { public static void main(String[] args) { // String created using String literal String s1 = \"TAT\"; String s2 = \"TAT\"; // String created using 'new' keyword String s3 = new String(\"TAT\"); String s4 = new String(\"TAT\"); System.out.println(s1); System.out.println(s2); System.out.println(s3); System.out.println(s4); }}",
"e": 2443,
"s": 1986,
"text": null
},
{
"code": null,
"e": 2453,
"s": 2445,
"text": "Output:"
},
{
"code": null,
"e": 2469,
"s": 2453,
"text": "TAT\nTAT\nTAT\nTAT"
},
{
"code": null,
"e": 2522,
"s": 2469,
"text": "The below figure illustrates the storage of String :"
},
{
"code": null,
"e": 2734,
"s": 2522,
"text": "Here in the above figure, the String is stored in String constant pool. String object reference variables are stored in the stack area under the method main( ). As main( ) is having some space in the stack area."
},
{
"code": null,
"e": 2740,
"s": 2734,
"text": "Note:"
},
{
"code": null,
"e": 2927,
"s": 2740,
"text": "All objects in Java are stored in the heap. The reference variable to the object stored in the stack area or they can be contained in other objects which puts them in the heap area also."
},
{
"code": null,
"e": 2970,
"s": 2927,
"text": "The string is passed by reference by java."
},
{
"code": null,
"e": 3084,
"s": 2970,
"text": "A string reference variable is not a reference itself. It is a variable that stores a reference (memory address)."
},
{
"code": null,
"e": 3097,
"s": 3084,
"text": "Java-Strings"
},
{
"code": null,
"e": 3102,
"s": 3097,
"text": "Java"
},
{
"code": null,
"e": 3115,
"s": 3102,
"text": "Java-Strings"
},
{
"code": null,
"e": 3120,
"s": 3115,
"text": "Java"
}
] |
How to create three boxes in the same div using HTML and CSS ?
|
13 Jun, 2022
Three or more different div can be put side-by-side using CSS in the same div. This can be achieved with flexbox – but note that you will need to use wrapper divs and apply different flex-directions to each in order to make the grid layout work. Use CSS property to set the height and width of div.
Syntax:
flex: flex-grow flex-shrink flex-basis
| auto | initial | inherit;
flex-direction: row;
flex-direction: row-reverse;
flex-direction: column;
flex-direction: column-reverse;
flex-grow: number | initial | inherit;
Example: This example illustrates how to create 3 boxes in the same div with regular HTML and CSS.
HTML
<!DOCTYPE html><html lang='en'> <head> <meta charset="utf-8"> <title> How to create 3 boxes in the same div using HTML and CSS ? </title> <style> * { margin: 0; padding: 0; box-sizing: border-box; } body { margin: 2%; justify-content: center; overflow: hidden; } .box-wrapper { height: 95vh; width: 100%; display: flex; flex-direction: column; text-align: center; } #box1 { padding: 10px; border: solid 1px green } #box2 { padding: 8px; border: solid 1px blue } #box3 { padding: 10px; flex-grow: 1; display: flex; flex-direction: row; border: solid 1px green } #box4 { flex-grow: 2; border: solid 1px orange } .middle-column { flex-grow: 1; display: flex; flex-direction: column; } .middle-column div { flex-grow: 1; margin: 0 8px; border: solid 1px red; } .middle-column div+div { margin-top: 8px } #box8 { flex-grow: 1; border: solid 1px black } </style></head> <body> <div class="box-wrapper"> <div id="box1"> Box 1 </div> <div id="box2"> Box 2 </div> <div id="box3"> <div id="box4"> Box 4 </div> <div class="middle-column"> <div id="box5"> Box 5 </div> <div id="box6"> Box 6 </div> <div id="box7"> Box 7 </div> </div> <div id="box8"> Box 8 </div> </div> </div></body> </html>
Output:
Supported Browsers are listed below:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
HTML is the foundation of web pages and is used for webpage development by structuring websites and web apps. You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples.
CSS is the foundation of web pages and is used for webpage development by styling websites and web apps. You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples.
sanjyotpanure
CSS-Misc
HTML5
Picked
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Jun, 2022"
},
{
"code": null,
"e": 327,
"s": 28,
"text": "Three or more different div can be put side-by-side using CSS in the same div. This can be achieved with flexbox – but note that you will need to use wrapper divs and apply different flex-directions to each in order to make the grid layout work. Use CSS property to set the height and width of div."
},
{
"code": null,
"e": 335,
"s": 327,
"text": "Syntax:"
},
{
"code": null,
"e": 558,
"s": 335,
"text": "flex: flex-grow flex-shrink flex-basis \n | auto | initial | inherit;\nflex-direction: row;\nflex-direction: row-reverse;\nflex-direction: column;\nflex-direction: column-reverse;\nflex-grow: number | initial | inherit;"
},
{
"code": null,
"e": 657,
"s": 558,
"text": "Example: This example illustrates how to create 3 boxes in the same div with regular HTML and CSS."
},
{
"code": null,
"e": 662,
"s": 657,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang='en'> <head> <meta charset=\"utf-8\"> <title> How to create 3 boxes in the same div using HTML and CSS ? </title> <style> * { margin: 0; padding: 0; box-sizing: border-box; } body { margin: 2%; justify-content: center; overflow: hidden; } .box-wrapper { height: 95vh; width: 100%; display: flex; flex-direction: column; text-align: center; } #box1 { padding: 10px; border: solid 1px green } #box2 { padding: 8px; border: solid 1px blue } #box3 { padding: 10px; flex-grow: 1; display: flex; flex-direction: row; border: solid 1px green } #box4 { flex-grow: 2; border: solid 1px orange } .middle-column { flex-grow: 1; display: flex; flex-direction: column; } .middle-column div { flex-grow: 1; margin: 0 8px; border: solid 1px red; } .middle-column div+div { margin-top: 8px } #box8 { flex-grow: 1; border: solid 1px black } </style></head> <body> <div class=\"box-wrapper\"> <div id=\"box1\"> Box 1 </div> <div id=\"box2\"> Box 2 </div> <div id=\"box3\"> <div id=\"box4\"> Box 4 </div> <div class=\"middle-column\"> <div id=\"box5\"> Box 5 </div> <div id=\"box6\"> Box 6 </div> <div id=\"box7\"> Box 7 </div> </div> <div id=\"box8\"> Box 8 </div> </div> </div></body> </html>",
"e": 2700,
"s": 662,
"text": null
},
{
"code": null,
"e": 2708,
"s": 2700,
"text": "Output:"
},
{
"code": null,
"e": 2747,
"s": 2710,
"text": "Supported Browsers are listed below:"
},
{
"code": null,
"e": 2761,
"s": 2747,
"text": "Google Chrome"
},
{
"code": null,
"e": 2779,
"s": 2761,
"text": "Internet Explorer"
},
{
"code": null,
"e": 2787,
"s": 2779,
"text": "Firefox"
},
{
"code": null,
"e": 2793,
"s": 2787,
"text": "Opera"
},
{
"code": null,
"e": 2800,
"s": 2793,
"text": "Safari"
},
{
"code": null,
"e": 2999,
"s": 2800,
"text": "HTML is the foundation of web pages and is used for webpage development by structuring websites and web apps. You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples."
},
{
"code": null,
"e": 3190,
"s": 2999,
"text": "CSS is the foundation of web pages and is used for webpage development by styling websites and web apps. You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples."
},
{
"code": null,
"e": 3204,
"s": 3190,
"text": "sanjyotpanure"
},
{
"code": null,
"e": 3213,
"s": 3204,
"text": "CSS-Misc"
},
{
"code": null,
"e": 3219,
"s": 3213,
"text": "HTML5"
},
{
"code": null,
"e": 3226,
"s": 3219,
"text": "Picked"
},
{
"code": null,
"e": 3230,
"s": 3226,
"text": "CSS"
},
{
"code": null,
"e": 3235,
"s": 3230,
"text": "HTML"
},
{
"code": null,
"e": 3252,
"s": 3235,
"text": "Web Technologies"
},
{
"code": null,
"e": 3279,
"s": 3252,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 3284,
"s": 3279,
"text": "HTML"
}
] |
nCr | Practice | GeeksforGeeks
|
Given two integers n and r, find nCr. Since the answer may be very large, calculate the answer modulo 109+7.
Example 1:
Input: n = 3, r = 2
Output: 3
Explaination: 3C2 = 3.
Example 2:
Input: n = 2, r = 4
Output: 0
Explaination: r is greater than n.
Your Task:
You do not need to take input or print anything. Your task is to complete the function nCr() which takes n and r as input parameters and returns nCr modulo 109+7..
Expected Time Complexity: O(n*r)
Expected Auxiliary Space: O(r)
Constraints:
1 ≤ n ≤ 1000
1 ≤ r ≤ 800
0
aryabamboli200210 hours ago
Easy Pascal's Triangle based Solution
int size = min(r,n-r);
vector<int> dp(size+1,0);
dp[0]=1;
for(int i=1;i<=n;i++){
for(int j=size;j>=1;j--){
dp[j]=(dp[j]+dp[j-1])%mod;
}
}
return dp[size];
0
f2020155610 hours ago
int size = min(r,n-r);
vector<int> dp(size+1,0);
dp[0]=1;
for(int i=1;i<=n;i++){
for(int j=size;j>=1;j--){
dp[j]=(dp[j]+dp[j-1])%mod;
}
}
return dp[size];
+1
adarsh444 days ago
Method -1:
int nCr(int n, int r){
const int mod = 1e9 + 7;
int dp[n+1][r+1];
memset(dp, 0, sizeof(dp));
for(int i = 1; i <= n; i++){
for(int j = 0; j <= i and j <= r; j++){
if (j == 0 or i == j)
dp[i][j] = 1;
else
dp[i][j] = (dp[i-1][j-1] + dp[i-1][j]) % mod;
}
}
return dp[n][r];
}
Method -2:
// Space Optimised.
int nCr(int n , int r){
// Using pascal's traingle
const int mod = 1e9 + 7;
int dp[r+1];
memset(dp, 0, sizeof(dp));
dp[0] = 1 ;
for(int i = 1; i <= n; i++){
for(int j = min(i, r); j >= 1; j--)
dp[j] = (dp[j] + dp[j-1]) % mod;
}
return dp[r];
}
0
deepak202040584 days ago
int nCr(int n, int r){ int dp[n+1]; dp[0]=1; for(int i=1;i<n;i++){ dp[i]=dp[i-1]*i; } int m=(int) dp[n]/(dp[r]*dp[n-r]); return m%1000000007; }
isme kya probelem hai?
+3
vmsreeram021 week ago
Direct formula recursion
Use the formula
nCr = (n-1) C (r-1) + (n-1) C (r)
long long dp[1005][805];
long long ncr(int n, int r)
{
if(n<r)return 0;
if(n==r)return 1;
if(r==0)return 1;
if(r==1)return n;
if(dp[n][r]!=-1) return dp[n][r];
return dp[n][r]=(ncr(n-1,r-1)+ncr(n-1,r))%int(1e9+7);
}
int nCr(int n, int r){
// code here
for(int i=0;i<=n+1;i++)for(int j=0;j<=r+1;j++)dp[i][j]=-1;
return ncr(n,r);
}
0
codehackss1 week ago
No DP SOLution - Python 10 lines code
class Solution:
def nCr(self, n, r):
if r > n:
return 0
ans = 1
maxx = max(r,n-r)
for i in range(n,maxx,-1):
ans*=i
minn = min(r,n-r)
factt = 1
for j in range(2,minn+1):
factt*=j
return (ans//factt)%(pow(10,9) + 7)
+1
2019uee01191 week ago
//using the concept of pascal's traingle
//Simple code if you know pascal traingle
vector<int> nthRowOfPascalTriangle(int n) { vector<vector<int>>v(n); int mod =1000000007; for(int i=0;i<n;i++) { v[i].resize(i+1); v[i][0]=v[i][i]=1; for(int j=1;j<i;j++) { v[i][j]=((v[i-1][j]%mod+v[i-1][j-1]%mod)%mod)%mod; } } return v[n-1]; }
int nCr(int n, int r) { if(r>n) { return 0; } if(r==n) { return 1; } vector<int>ans; ans=nthRowOfPascalTriangle(n+1); return ans[r]; }
0
akkeshri140420012 weeks ago
const int mod=1e9+7;
int nCr(int n, int r){
// code here
if(n<r){
return 0;
}
vector<vector<int>>dp(n+1,vector<int>(r+1));
for(int i=0;i<n+1;i++){
dp[i][0]=1;
}
for(int j=0;j<r+1;j++){
dp[0][j]=0;
}
dp[0][0]=1;
for(int i=1;i<n+1;i++){
for(int j=1;j<r+1;j++){
if(j>i){
dp[i][j]=0;
}
else{
dp[i][j]=((dp[i-1][j])%mod + (dp[i-1][j-1])%mod)%mod;
}
}
}
return dp[n][r];
}
+1
somplz01092 weeks ago
SIMPLE C++ RECURSIVE CODE :
class Solution{
public:
int dp[1001][801];
int nccr(int n,int r){
if(r > n)return 0;
if(r == n || r==0)return 1;
if(dp[n][r]!=-1)return dp[n][r];
return dp[n][r] = (nccr(n-1,r) + nccr(n-1,r-1))%1000000007;
}
int nCr(int n, int r){
// code here
memset(dp,-1,sizeof(dp));
return nccr(n,r);
}
};
0
rk2207rajesh2 weeks ago
public: int nCr(int n, int R){ vector<vector<ll>>dp(n+1,vector<ll>(R+1,0)); for(int i=0;i<=n;i++) { for(int r=0;r<=R;r++) { if(r==0) dp[i][r]=1; else if(i==0) dp[i][r]=0; else { ll exclude=dp[i-1][r]%mod; ll include=0; if(r<=i) include=dp[i-1][r-1]%mod; dp[i][r]= (exclude+include)%mod; } } } return dp[n][R]; }
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.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems 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": 347,
"s": 238,
"text": "Given two integers n and r, find nCr. Since the answer may be very large, calculate the answer modulo 109+7."
},
{
"code": null,
"e": 358,
"s": 347,
"text": "Example 1:"
},
{
"code": null,
"e": 412,
"s": 358,
"text": "Input: n = 3, r = 2\nOutput: 3\nExplaination: 3C2 = 3. "
},
{
"code": null,
"e": 424,
"s": 412,
"text": "\nExample 2:"
},
{
"code": null,
"e": 489,
"s": 424,
"text": "Input: n = 2, r = 4\nOutput: 0\nExplaination: r is greater than n."
},
{
"code": null,
"e": 665,
"s": 489,
"text": "\nYour Task:\nYou do not need to take input or print anything. Your task is to complete the function nCr() which takes n and r as input parameters and returns nCr modulo 109+7.."
},
{
"code": null,
"e": 730,
"s": 665,
"text": "\nExpected Time Complexity: O(n*r)\nExpected Auxiliary Space: O(r)"
},
{
"code": null,
"e": 769,
"s": 730,
"text": "\nConstraints:\n1 ≤ n ≤ 1000\n1 ≤ r ≤ 800"
},
{
"code": null,
"e": 771,
"s": 769,
"text": "0"
},
{
"code": null,
"e": 799,
"s": 771,
"text": "aryabamboli200210 hours ago"
},
{
"code": null,
"e": 837,
"s": 799,
"text": "Easy Pascal's Triangle based Solution"
},
{
"code": null,
"e": 1072,
"s": 837,
"text": "int size = min(r,n-r);\n vector<int> dp(size+1,0);\n dp[0]=1;\n for(int i=1;i<=n;i++){\n for(int j=size;j>=1;j--){\n dp[j]=(dp[j]+dp[j-1])%mod;\n }\n }\n return dp[size];"
},
{
"code": null,
"e": 1074,
"s": 1072,
"text": "0"
},
{
"code": null,
"e": 1096,
"s": 1074,
"text": "f2020155610 hours ago"
},
{
"code": null,
"e": 1331,
"s": 1096,
"text": "int size = min(r,n-r);\n vector<int> dp(size+1,0);\n dp[0]=1;\n for(int i=1;i<=n;i++){\n for(int j=size;j>=1;j--){\n dp[j]=(dp[j]+dp[j-1])%mod;\n }\n }\n return dp[size];"
},
{
"code": null,
"e": 1334,
"s": 1331,
"text": "+1"
},
{
"code": null,
"e": 1353,
"s": 1334,
"text": "adarsh444 days ago"
},
{
"code": null,
"e": 1791,
"s": 1353,
"text": "Method -1:\nint nCr(int n, int r){\n const int mod = 1e9 + 7; \n int dp[n+1][r+1]; \n memset(dp, 0, sizeof(dp));\n for(int i = 1; i <= n; i++){\n for(int j = 0; j <= i and j <= r; j++){\n if (j == 0 or i == j)\n dp[i][j] = 1; \n else \n dp[i][j] = (dp[i-1][j-1] + dp[i-1][j]) % mod; \n }\n }\n return dp[n][r]; \n }"
},
{
"code": null,
"e": 2178,
"s": 1791,
"text": "Method -2:\n // Space Optimised. \n int nCr(int n , int r){\n // Using pascal's traingle \n const int mod = 1e9 + 7; \n int dp[r+1]; \n memset(dp, 0, sizeof(dp)); \n dp[0] = 1 ; \n for(int i = 1; i <= n; i++){\n for(int j = min(i, r); j >= 1; j--)\n dp[j] = (dp[j] + dp[j-1]) % mod; \n }\n return dp[r]; \n }"
},
{
"code": null,
"e": 2182,
"s": 2180,
"text": "0"
},
{
"code": null,
"e": 2207,
"s": 2182,
"text": "deepak202040584 days ago"
},
{
"code": null,
"e": 2374,
"s": 2207,
"text": " int nCr(int n, int r){ int dp[n+1]; dp[0]=1; for(int i=1;i<n;i++){ dp[i]=dp[i-1]*i; } int m=(int) dp[n]/(dp[r]*dp[n-r]); return m%1000000007; }"
},
{
"code": null,
"e": 2399,
"s": 2376,
"text": "isme kya probelem hai?"
},
{
"code": null,
"e": 2404,
"s": 2401,
"text": "+3"
},
{
"code": null,
"e": 2426,
"s": 2404,
"text": "vmsreeram021 week ago"
},
{
"code": null,
"e": 2451,
"s": 2426,
"text": "Direct formula recursion"
},
{
"code": null,
"e": 2467,
"s": 2451,
"text": "Use the formula"
},
{
"code": null,
"e": 2509,
"s": 2467,
"text": " nCr = (n-1) C (r-1) + (n-1) C (r)"
},
{
"code": null,
"e": 2875,
"s": 2509,
"text": "long long dp[1005][805];\nlong long ncr(int n, int r)\n{\n if(n<r)return 0;\n if(n==r)return 1;\n if(r==0)return 1;\n if(r==1)return n;\n if(dp[n][r]!=-1) return dp[n][r];\n return dp[n][r]=(ncr(n-1,r-1)+ncr(n-1,r))%int(1e9+7);\n}\nint nCr(int n, int r){\n // code here\n for(int i=0;i<=n+1;i++)for(int j=0;j<=r+1;j++)dp[i][j]=-1;\n return ncr(n,r);\n}"
},
{
"code": null,
"e": 2877,
"s": 2875,
"text": "0"
},
{
"code": null,
"e": 2898,
"s": 2877,
"text": "codehackss1 week ago"
},
{
"code": null,
"e": 2936,
"s": 2898,
"text": "No DP SOLution - Python 10 lines code"
},
{
"code": null,
"e": 3257,
"s": 2936,
"text": "class Solution:\n def nCr(self, n, r):\n if r > n:\n return 0\n ans = 1 \n maxx = max(r,n-r)\n for i in range(n,maxx,-1):\n ans*=i\n minn = min(r,n-r)\n factt = 1\n for j in range(2,minn+1):\n factt*=j\n return (ans//factt)%(pow(10,9) + 7)"
},
{
"code": null,
"e": 3260,
"s": 3257,
"text": "+1"
},
{
"code": null,
"e": 3282,
"s": 3260,
"text": "2019uee01191 week ago"
},
{
"code": null,
"e": 3324,
"s": 3282,
"text": "//using the concept of pascal's traingle "
},
{
"code": null,
"e": 3366,
"s": 3324,
"text": "//Simple code if you know pascal traingle"
},
{
"code": null,
"e": 3715,
"s": 3366,
"text": "vector<int> nthRowOfPascalTriangle(int n) { vector<vector<int>>v(n); int mod =1000000007; for(int i=0;i<n;i++) { v[i].resize(i+1); v[i][0]=v[i][i]=1; for(int j=1;j<i;j++) { v[i][j]=((v[i-1][j]%mod+v[i-1][j-1]%mod)%mod)%mod; } } return v[n-1]; }"
},
{
"code": null,
"e": 3931,
"s": 3715,
"text": " int nCr(int n, int r) { if(r>n) { return 0; } if(r==n) { return 1; } vector<int>ans; ans=nthRowOfPascalTriangle(n+1); return ans[r]; }"
},
{
"code": null,
"e": 3933,
"s": 3931,
"text": "0"
},
{
"code": null,
"e": 3961,
"s": 3933,
"text": "akkeshri140420012 weeks ago"
},
{
"code": null,
"e": 4595,
"s": 3961,
"text": "const int mod=1e9+7;\n int nCr(int n, int r){\n // code here\n if(n<r){\n return 0;\n }\n vector<vector<int>>dp(n+1,vector<int>(r+1));\n for(int i=0;i<n+1;i++){\n dp[i][0]=1;\n }\n for(int j=0;j<r+1;j++){\n dp[0][j]=0;\n }\n dp[0][0]=1;\n \n for(int i=1;i<n+1;i++){\n for(int j=1;j<r+1;j++){\n if(j>i){\n dp[i][j]=0;\n }\n else{\n dp[i][j]=((dp[i-1][j])%mod + (dp[i-1][j-1])%mod)%mod;\n }\n \n }\n }\n return dp[n][r];\n \n }"
},
{
"code": null,
"e": 4598,
"s": 4595,
"text": "+1"
},
{
"code": null,
"e": 4620,
"s": 4598,
"text": "somplz01092 weeks ago"
},
{
"code": null,
"e": 4649,
"s": 4620,
"text": "SIMPLE C++ RECURSIVE CODE : "
},
{
"code": null,
"e": 5029,
"s": 4649,
"text": "class Solution{\npublic:\n\n int dp[1001][801];\n \n int nccr(int n,int r){\n if(r > n)return 0;\n if(r == n || r==0)return 1;\n if(dp[n][r]!=-1)return dp[n][r];\n return dp[n][r] = (nccr(n-1,r) + nccr(n-1,r-1))%1000000007;\n }\n \n int nCr(int n, int r){\n // code here\n memset(dp,-1,sizeof(dp));\n return nccr(n,r);\n }\n};"
},
{
"code": null,
"e": 5031,
"s": 5029,
"text": "0"
},
{
"code": null,
"e": 5055,
"s": 5031,
"text": "rk2207rajesh2 weeks ago"
},
{
"code": null,
"e": 5607,
"s": 5055,
"text": "public: int nCr(int n, int R){ vector<vector<ll>>dp(n+1,vector<ll>(R+1,0)); for(int i=0;i<=n;i++) { for(int r=0;r<=R;r++) { if(r==0) dp[i][r]=1; else if(i==0) dp[i][r]=0; else { ll exclude=dp[i-1][r]%mod; ll include=0; if(r<=i) include=dp[i-1][r-1]%mod; dp[i][r]= (exclude+include)%mod; } } } return dp[n][R]; }"
},
{
"code": null,
"e": 5753,
"s": 5607,
"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": 5789,
"s": 5753,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 5799,
"s": 5789,
"text": "\nProblem\n"
},
{
"code": null,
"e": 5809,
"s": 5799,
"text": "\nContest\n"
},
{
"code": null,
"e": 5872,
"s": 5809,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 6057,
"s": 5872,
"text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 6341,
"s": 6057,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints."
},
{
"code": null,
"e": 6487,
"s": 6341,
"text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code."
},
{
"code": null,
"e": 6564,
"s": 6487,
"text": "You can view the solutions submitted by other users from the submission tab."
},
{
"code": null,
"e": 6605,
"s": 6564,
"text": "Make sure you are not using ad-blockers."
},
{
"code": null,
"e": 6633,
"s": 6605,
"text": "Disable browser extensions."
},
{
"code": null,
"e": 6704,
"s": 6633,
"text": "We recommend using latest version of your browser for best experience."
},
{
"code": null,
"e": 6891,
"s": 6704,
"text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values."
}
] |
How to Aggregate multiple columns in Data.table in R ?
|
17 Jun, 2021
In this article, we will discuss how to aggregate multiple columns in Data.table in R Programming Language.
A data.table contains elements that may be either duplicate or unique. As a result of this, the variables are divided into categories depending on the sets in which they can be segregated. The column values can be summed over such that the columns contains summation of frequency counts of variables.
The standard data table indexing methods can be used to segregate and aggregate data contained in a data frame. The “by” attribute is used to divide the data based on the specific column names, provided inside the list() method. A new variable can be added containing the sum of values obtained using the sum() method containing the columns to be summed over.
Syntax:
df[ , new-col-name:=sum(reqd-col-name), by = list(grouping columns)]
Example:
R
# importing required librarieslibrary(data.table) # creating a data framedata_frame <- data.table(col1 = sample(6:8, 12 , replace = TRUE), col2 = letters[1:2], col3 = 1) print ("Original DataFrame")print (data_frame) # compute the sum of col3 using grouping # of col1 and col2data_frame[ , count:=sum(col3), by = list(col1, col2)] print ("Modified DataFrame")print (data_frame)
Output
[1] "Original DataFrame"
col1 col2 col3
1: 7 a 1
2: 6 b 1
3: 8 a 1
4: 7 b 1
5: 6 a 1
6: 8 b 1
7: 7 a 1
8: 8 b 1
9: 8 a 1
10: 7 b 1
11: 6 a 1
12: 7 b 1
[1] "Modified DataFrame"
col1 col2 col3 count
1: 7 a 1 2
2: 6 b 1 1
3: 8 a 1 2
4: 7 b 1 3
5: 6 a 1 2
6: 8 b 1 2
7: 7 a 1 2
8: 8 b 1 2
9: 8 a 1 2
10: 7 b 1 3
11: 6 a 1 2
12: 7 b 1 3
The data.table library can be installed and loaded into the working space. The lapply() method can then be applied over this data.table object, to aggregate multiple columns using a group. The lapply() method is used to return an object of the same length as that of the input list. Each element returned is the result of the application of function, FUN.
Syntax:
lapply(obj, FUN, ...)
Parameters :
obj – a vector (atomic or list) or an expression object.
FUN – the function to be applied over elements.
The .SD attribute is used to calculate summary statistics for a larger list of variables. The sum function is applied as the function to compute the sum of the elements categorically falling within each group variable. The ‘by’ attribute is equivalent to the ‘group by’ in SQL while performing aggregation.
Syntax:
lapply (.SD , sum )
Example:
R
# importing required librarieslibrary(data.table) # creating a data framedata_frame <- data.table(col1 = sample(6:8, 12 , replace = TRUE), col2 = 1:2, col3 = 1) print ("Original DataFrame")print (data_frame) print ("Modified DataFrame")data_frame[, lapply(.SD, sum), by= col1]
Output
[1] "Original DataFrame"
col1 col2 col3
1: 7 1 1
2: 7 2 1
3: 8 1 1
4: 8 2 1
5: 8 1 1
6: 6 2 1
7: 7 1 1
8: 7 2 1
9: 8 1 1
10: 6 2 1
11: 7 1 1
12: 7 2 1
[1] "Modified DataFrame"
col1 col2 col3
1: 7 9 6
2: 8 5 4
3: 6 4 2
The aggregate() function in R is used to produce summary statistics for one or more variables in a data frame or a data.table respectively.
Syntax:
aggregate(sum_var ~ group_var, data = df, FUN = sum)
Parameters :
sum_var – The columns to compute sums for
group_var – The columns to group data by
data – The data frame to take
FUN – The function to apply
In case, the grouped variable are a combination of columns, the cbind() method is used to combine columns to be retrieved. The FUN to be applied is equivalent to sum, where each column’s summation over particular categorical group is returned.
Example:
R
# importing required librarieslibrary(data.table) # creating a data framedata_frame <- data.table(col1 = sample(6:8, 12 , replace = TRUE), col2 = 1:2, col3 = 1) print ("Original DataFrame")print (data_frame) print ("Modified DataFrame")aggregate(cbind(col2,col3) ~ col1, data = data_frame, FUN = sum)
Output
[1] "Original DataFrame"
col1 col2 col3
1: 6 1 1
2: 6 2 1
3: 7 1 1
4: 6 2 1
5: 6 1 1
6: 7 2 1
7: 8 1 1
8: 6 2 1
9: 8 1 1
10: 6 2 1
11: 7 1 1
12: 7 2
[1] "Modified DataFrame"
col1 col2 col3
1 6 10 6
2 7 6 4
3 8 2 2
Picked
R DataTable
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Jun, 2021"
},
{
"code": null,
"e": 136,
"s": 28,
"text": "In this article, we will discuss how to aggregate multiple columns in Data.table in R Programming Language."
},
{
"code": null,
"e": 437,
"s": 136,
"text": "A data.table contains elements that may be either duplicate or unique. As a result of this, the variables are divided into categories depending on the sets in which they can be segregated. The column values can be summed over such that the columns contains summation of frequency counts of variables."
},
{
"code": null,
"e": 797,
"s": 437,
"text": "The standard data table indexing methods can be used to segregate and aggregate data contained in a data frame. The “by” attribute is used to divide the data based on the specific column names, provided inside the list() method. A new variable can be added containing the sum of values obtained using the sum() method containing the columns to be summed over."
},
{
"code": null,
"e": 806,
"s": 797,
"text": "Syntax: "
},
{
"code": null,
"e": 876,
"s": 806,
"text": "df[ , new-col-name:=sum(reqd-col-name), by = list(grouping columns)] "
},
{
"code": null,
"e": 885,
"s": 876,
"text": "Example:"
},
{
"code": null,
"e": 887,
"s": 885,
"text": "R"
},
{
"code": "# importing required librarieslibrary(data.table) # creating a data framedata_frame <- data.table(col1 = sample(6:8, 12 , replace = TRUE), col2 = letters[1:2], col3 = 1) print (\"Original DataFrame\")print (data_frame) # compute the sum of col3 using grouping # of col1 and col2data_frame[ , count:=sum(col3), by = list(col1, col2)] print (\"Modified DataFrame\")print (data_frame)",
"e": 1318,
"s": 887,
"text": null
},
{
"code": null,
"e": 1325,
"s": 1318,
"text": "Output"
},
{
"code": null,
"e": 1941,
"s": 1325,
"text": "[1] \"Original DataFrame\" \n col1 col2 col3 \n1: 7 a 1 \n2: 6 b 1 \n3: 8 a 1 \n4: 7 b 1 \n5: 6 a 1 \n6: 8 b 1 \n7: 7 a 1 \n8: 8 b 1 \n9: 8 a 1 \n10: 7 b 1 \n11: 6 a 1 \n12: 7 b 1 \n[1] \"Modified DataFrame\" \n col1 col2 col3 count \n1: 7 a 1 2 \n2: 6 b 1 1 \n3: 8 a 1 2 \n4: 7 b 1 3 \n5: 6 a 1 2 \n6: 8 b 1 2 \n7: 7 a 1 2 \n8: 8 b 1 2 \n9: 8 a 1 2 \n10: 7 b 1 3 \n11: 6 a 1 2 \n12: 7 b 1 3"
},
{
"code": null,
"e": 2298,
"s": 1941,
"text": "The data.table library can be installed and loaded into the working space. The lapply() method can then be applied over this data.table object, to aggregate multiple columns using a group. The lapply() method is used to return an object of the same length as that of the input list. Each element returned is the result of the application of function, FUN. "
},
{
"code": null,
"e": 2306,
"s": 2298,
"text": "Syntax:"
},
{
"code": null,
"e": 2328,
"s": 2306,
"text": "lapply(obj, FUN, ...)"
},
{
"code": null,
"e": 2342,
"s": 2328,
"text": "Parameters : "
},
{
"code": null,
"e": 2399,
"s": 2342,
"text": "obj – a vector (atomic or list) or an expression object."
},
{
"code": null,
"e": 2448,
"s": 2399,
"text": "FUN – the function to be applied over elements. "
},
{
"code": null,
"e": 2756,
"s": 2448,
"text": "The .SD attribute is used to calculate summary statistics for a larger list of variables. The sum function is applied as the function to compute the sum of the elements categorically falling within each group variable. The ‘by’ attribute is equivalent to the ‘group by’ in SQL while performing aggregation. "
},
{
"code": null,
"e": 2764,
"s": 2756,
"text": "Syntax:"
},
{
"code": null,
"e": 2784,
"s": 2764,
"text": "lapply (.SD , sum )"
},
{
"code": null,
"e": 2793,
"s": 2784,
"text": "Example:"
},
{
"code": null,
"e": 2795,
"s": 2793,
"text": "R"
},
{
"code": "# importing required librarieslibrary(data.table) # creating a data framedata_frame <- data.table(col1 = sample(6:8, 12 , replace = TRUE), col2 = 1:2, col3 = 1) print (\"Original DataFrame\")print (data_frame) print (\"Modified DataFrame\")data_frame[, lapply(.SD, sum), by= col1]",
"e": 3123,
"s": 2795,
"text": null
},
{
"code": null,
"e": 3130,
"s": 3123,
"text": "Output"
},
{
"code": null,
"e": 3512,
"s": 3130,
"text": "[1] \"Original DataFrame\"\ncol1 col2 col3 \n1: 7 1 1 \n2: 7 2 1 \n3: 8 1 1 \n4: 8 2 1 \n5: 8 1 1 \n6: 6 2 1 \n7: 7 1 1 \n8: 7 2 1 \n9: 8 1 1 \n10: 6 2 1 \n11: 7 1 1 \n12: 7 2 1 \n[1] \"Modified DataFrame\" \n col1 col2 col3 \n1: 7 9 6 \n2: 8 5 4 \n3: 6 4 2"
},
{
"code": null,
"e": 3652,
"s": 3512,
"text": "The aggregate() function in R is used to produce summary statistics for one or more variables in a data frame or a data.table respectively."
},
{
"code": null,
"e": 3660,
"s": 3652,
"text": "Syntax:"
},
{
"code": null,
"e": 3713,
"s": 3660,
"text": "aggregate(sum_var ~ group_var, data = df, FUN = sum)"
},
{
"code": null,
"e": 3727,
"s": 3713,
"text": "Parameters : "
},
{
"code": null,
"e": 3769,
"s": 3727,
"text": "sum_var – The columns to compute sums for"
},
{
"code": null,
"e": 3810,
"s": 3769,
"text": "group_var – The columns to group data by"
},
{
"code": null,
"e": 3840,
"s": 3810,
"text": "data – The data frame to take"
},
{
"code": null,
"e": 3868,
"s": 3840,
"text": "FUN – The function to apply"
},
{
"code": null,
"e": 4113,
"s": 3868,
"text": "In case, the grouped variable are a combination of columns, the cbind() method is used to combine columns to be retrieved. The FUN to be applied is equivalent to sum, where each column’s summation over particular categorical group is returned. "
},
{
"code": null,
"e": 4122,
"s": 4113,
"text": "Example:"
},
{
"code": null,
"e": 4124,
"s": 4122,
"text": "R"
},
{
"code": "# importing required librarieslibrary(data.table) # creating a data framedata_frame <- data.table(col1 = sample(6:8, 12 , replace = TRUE), col2 = 1:2, col3 = 1) print (\"Original DataFrame\")print (data_frame) print (\"Modified DataFrame\")aggregate(cbind(col2,col3) ~ col1, data = data_frame, FUN = sum)",
"e": 4476,
"s": 4124,
"text": null
},
{
"code": null,
"e": 4483,
"s": 4476,
"text": "Output"
},
{
"code": null,
"e": 4855,
"s": 4483,
"text": "[1] \"Original DataFrame\"\ncol1 col2 col3 \n1: 6 1 1 \n2: 6 2 1 \n3: 7 1 1 \n4: 6 2 1 \n5: 6 1 1 \n6: 7 2 1 \n7: 8 1 1 \n8: 6 2 1 \n9: 8 1 1 \n10: 6 2 1 \n11: 7 1 1 \n12: 7 2 \n[1] \"Modified DataFrame\" \ncol1 col2 col3 \n1 6 10 6 \n2 7 6 4 \n3 8 2 2"
},
{
"code": null,
"e": 4862,
"s": 4855,
"text": "Picked"
},
{
"code": null,
"e": 4874,
"s": 4862,
"text": "R DataTable"
},
{
"code": null,
"e": 4885,
"s": 4874,
"text": "R Language"
}
] |
Convert dataframe to data.table in R
|
17 May, 2021
In this article, we will discuss how to convert dataframe to data.table in R Programming Language. data.table is an R package that provides an enhanced version of dataframe. Characteristics of data.table :
data.table doesn’t set or use row names
row numbers are printed with a : for better readability
Unlike dataframes, columns of character type are never converted to factors by default in data.table.
Method 1 : Using setDT() method
While dataframes are available using the base R packages, data.table object is a part of the data.table package, which needs to be installed in the working space. The setDT() method can be used to coerce the dataframe or the lists into data.table, where the conversion is made to the original dataframe. The modification is made by reference to the original data structure.
Syntax: setDT(x)
Arguments :
x : A named or unnamed list, data.frame or data.table.
Example 1:
R
# using the required librarylibrary(data.table) # declare a dataframedata_frame <- data.frame(col1 = c(1:7), col2 = LETTERS[1:7], col3 = letters[1:7]) print ("Original DataFrame")print (data_frame) # converting into data.tablesetDT(data_frame)print ("Resultant DataFrame")print (data_frame)
Output
[1] "Original DataFrame"
> print (data_frame)
col1 col2 col3
1 1 A a
2 2 B b
3 3 C c
4 4 D d
5 5 E e
6 6 F f
7 7 G g
[1] "Resultant DataFrame"
> print (data_frame)
col1 col2 col3
1: 1 A a
2: 2 B b
3: 3 C c
4: 4 D d
5: 5 E e
6: 6 F f
7: 7 G g
All the missing and NA values stored in a dataframe are preserved in data.table as well. The row names are reassigned to identifiers beginning with integer values starting from 1 till the number of rows in the dataframe. The library data.table also provides other functions to verify if the R object is a data.table using is.data.table(data_frame). It returns true if the specified argument is data.table else false.
Example 2:
R
# using the required librarylibrary(data.table) # declare a dataframedata_frame <- data.frame(col1 = c(1, NA, 4, NA, 3, NA), col2 = c("a", NA, "b", "e", "f", "G"), row.names = c("row1","row2","row3", "row4","row5","row6")) print ("Original DataFrame")print (data_frame) # converting into data.tablesetDT(data_frame)print ("Resultant DataFrame")print (data_frame) # checking if the dataframe is data tableprint ("Check if data table")print (is.data.table(data_frame))
Output
[1] "Original DataFrame"
col1 col2
row1 1 a
row2 NA <NA>
row3 4 b
row4 NA e
row5 3 f
row6 NA G
[1] "Resultant DataFrame"
col1 col2
1: 1 a
2: NA <NA>
3: 4 b
4: NA e
5: 3 f
6: NA G
[1] "Check if data table"
[1] TRUE
Explanation: The original dataframe is stored as a data.frame object and then using the setDT method the same dataframe is returned with row numbers appended at the beginning, with the row number identifier followed by a colon. The missing values, that is NA are returned as it is. Since the changes are made to the dataframe, when we check whether it is a data table or not using is.data.table(), it returns logical TRUE value.
Method 2 : Using as.data.table() method
The as.data.table() method can be used to coerce the dataframe or the lists into data.table if the specified object is not originally a data.table, and the conversion is possible. The changes are not made to the original dataframe, therefore, it creates a copy of the base object.
Syntax: as.data.table(x,keep.rownames=FALSE)
Arguments :
x : A named or unnamed list, data.frame or data.table.
keep.rownames : By default: False. For data.frames, TRUE retains the data.frame’s row names under a new column rn. keep.rownames = “id” names the column “id” instead.
Example:
R
# using the required librarylibrary(data.table) # declare a dataframedata_frame <- data.frame(col1 = c(1, NA, 4, NA, 3, NA), col2 = c("a", NA, "b", "e", "f", "G"), row.names = c("row1","row2","row3", "row4","row5","row6")) print ("Original DataFrame")print (data_frame) # converting into data.tabledt <- as.data.table(data_frame, TRUE)print ("Resultant DataFrame")print (dt)print ("Check if data table")print (is.data.table(dt))
Output
[1] "Original DataFrame"
> print (data_frame)
col1 col2
row1 1 a
row2 NA <NA>
row3 4 b
row4 NA e
row5 3 f
row6 NA G
[1] "Resultant DataFrame"
rn col1 col2
1: row1 1 a
2: row2 NA <NA>
3: row3 4 b
4: row4 NA e
5: row5 3 f
6: row6 NA G
[1] "Check if data table"
[1] TRUE
Explanation: The original dataframe has a row name for each of the rows. When the dataframe is converted to data table, the row names form a separate column “rn” and also each row is lead by a row number identifier followed by colon. However, the changes are not made to the original dataframe. So, when we apply the is.data.table() method to the original dataframe, it returns FALSE. On the contrary, if we apply this method to the result of the as.data.table() method, we get TRUE value.
Picked
R DataTable
R-DataFrame
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 May, 2021"
},
{
"code": null,
"e": 235,
"s": 28,
"text": "In this article, we will discuss how to convert dataframe to data.table in R Programming Language. data.table is an R package that provides an enhanced version of dataframe. Characteristics of data.table : "
},
{
"code": null,
"e": 275,
"s": 235,
"text": "data.table doesn’t set or use row names"
},
{
"code": null,
"e": 331,
"s": 275,
"text": "row numbers are printed with a : for better readability"
},
{
"code": null,
"e": 433,
"s": 331,
"text": "Unlike dataframes, columns of character type are never converted to factors by default in data.table."
},
{
"code": null,
"e": 465,
"s": 433,
"text": "Method 1 : Using setDT() method"
},
{
"code": null,
"e": 840,
"s": 465,
"text": "While dataframes are available using the base R packages, data.table object is a part of the data.table package, which needs to be installed in the working space. The setDT() method can be used to coerce the dataframe or the lists into data.table, where the conversion is made to the original dataframe. The modification is made by reference to the original data structure. "
},
{
"code": null,
"e": 857,
"s": 840,
"text": "Syntax: setDT(x)"
},
{
"code": null,
"e": 870,
"s": 857,
"text": "Arguments : "
},
{
"code": null,
"e": 925,
"s": 870,
"text": "x : A named or unnamed list, data.frame or data.table."
},
{
"code": null,
"e": 936,
"s": 925,
"text": "Example 1:"
},
{
"code": null,
"e": 938,
"s": 936,
"text": "R"
},
{
"code": "# using the required librarylibrary(data.table) # declare a dataframedata_frame <- data.frame(col1 = c(1:7), col2 = LETTERS[1:7], col3 = letters[1:7]) print (\"Original DataFrame\")print (data_frame) # converting into data.tablesetDT(data_frame)print (\"Resultant DataFrame\")print (data_frame)",
"e": 1280,
"s": 938,
"text": null
},
{
"code": null,
"e": 1287,
"s": 1280,
"text": "Output"
},
{
"code": null,
"e": 1664,
"s": 1287,
"text": "[1] \"Original DataFrame\"\n> print (data_frame)\n col1 col2 col3\n1 1 A a\n2 2 B b\n3 3 C c\n4 4 D d\n5 5 E e\n6 6 F f\n7 7 G g\n[1] \"Resultant DataFrame\"\n> print (data_frame)\n col1 col2 col3\n1: 1 A a\n2: 2 B b\n3: 3 C c\n4: 4 D d\n5: 5 E e\n6: 6 F f\n7: 7 G g"
},
{
"code": null,
"e": 2082,
"s": 1664,
"text": "All the missing and NA values stored in a dataframe are preserved in data.table as well. The row names are reassigned to identifiers beginning with integer values starting from 1 till the number of rows in the dataframe. The library data.table also provides other functions to verify if the R object is a data.table using is.data.table(data_frame). It returns true if the specified argument is data.table else false. "
},
{
"code": null,
"e": 2093,
"s": 2082,
"text": "Example 2:"
},
{
"code": null,
"e": 2095,
"s": 2093,
"text": "R"
},
{
"code": "# using the required librarylibrary(data.table) # declare a dataframedata_frame <- data.frame(col1 = c(1, NA, 4, NA, 3, NA), col2 = c(\"a\", NA, \"b\", \"e\", \"f\", \"G\"), row.names = c(\"row1\",\"row2\",\"row3\", \"row4\",\"row5\",\"row6\")) print (\"Original DataFrame\")print (data_frame) # converting into data.tablesetDT(data_frame)print (\"Resultant DataFrame\")print (data_frame) # checking if the dataframe is data tableprint (\"Check if data table\")print (is.data.table(data_frame))",
"e": 2659,
"s": 2095,
"text": null
},
{
"code": null,
"e": 2666,
"s": 2659,
"text": "Output"
},
{
"code": null,
"e": 2948,
"s": 2666,
"text": "[1] \"Original DataFrame\"\n col1 col2\nrow1 1 a\nrow2 NA <NA>\nrow3 4 b\nrow4 NA e\nrow5 3 f\nrow6 NA G\n[1] \"Resultant DataFrame\"\n col1 col2\n1: 1 a\n2: NA <NA>\n3: 4 b\n4: NA e\n5: 3 f\n6: NA G\n[1] \"Check if data table\"\n[1] TRUE"
},
{
"code": null,
"e": 3377,
"s": 2948,
"text": "Explanation: The original dataframe is stored as a data.frame object and then using the setDT method the same dataframe is returned with row numbers appended at the beginning, with the row number identifier followed by a colon. The missing values, that is NA are returned as it is. Since the changes are made to the dataframe, when we check whether it is a data table or not using is.data.table(), it returns logical TRUE value."
},
{
"code": null,
"e": 3417,
"s": 3377,
"text": "Method 2 : Using as.data.table() method"
},
{
"code": null,
"e": 3699,
"s": 3417,
"text": "The as.data.table() method can be used to coerce the dataframe or the lists into data.table if the specified object is not originally a data.table, and the conversion is possible. The changes are not made to the original dataframe, therefore, it creates a copy of the base object. "
},
{
"code": null,
"e": 3744,
"s": 3699,
"text": "Syntax: as.data.table(x,keep.rownames=FALSE)"
},
{
"code": null,
"e": 3756,
"s": 3744,
"text": "Arguments :"
},
{
"code": null,
"e": 3811,
"s": 3756,
"text": "x : A named or unnamed list, data.frame or data.table."
},
{
"code": null,
"e": 3979,
"s": 3811,
"text": "keep.rownames : By default: False. For data.frames, TRUE retains the data.frame’s row names under a new column rn. keep.rownames = “id” names the column “id” instead."
},
{
"code": null,
"e": 3988,
"s": 3979,
"text": "Example:"
},
{
"code": null,
"e": 3990,
"s": 3988,
"text": "R"
},
{
"code": "# using the required librarylibrary(data.table) # declare a dataframedata_frame <- data.frame(col1 = c(1, NA, 4, NA, 3, NA), col2 = c(\"a\", NA, \"b\", \"e\", \"f\", \"G\"), row.names = c(\"row1\",\"row2\",\"row3\", \"row4\",\"row5\",\"row6\")) print (\"Original DataFrame\")print (data_frame) # converting into data.tabledt <- as.data.table(data_frame, TRUE)print (\"Resultant DataFrame\")print (dt)print (\"Check if data table\")print (is.data.table(dt))",
"e": 4515,
"s": 3990,
"text": null
},
{
"code": null,
"e": 4522,
"s": 4515,
"text": "Output"
},
{
"code": null,
"e": 4908,
"s": 4522,
"text": "[1] \"Original DataFrame\" \n> print (data_frame) \n col1 col2 \n row1 1 a \n row2 NA <NA> \n row3 4 b \n row4 NA e \n row5 3 f \n row6 NA G \n[1] \"Resultant DataFrame\"\n rn col1 col2 \n1: row1 1 a \n2: row2 NA <NA> \n3: row3 4 b \n4: row4 NA e \n5: row5 3 f \n6: row6 NA G \n[1] \"Check if data table\" \n[1] TRUE"
},
{
"code": null,
"e": 5398,
"s": 4908,
"text": "Explanation: The original dataframe has a row name for each of the rows. When the dataframe is converted to data table, the row names form a separate column “rn” and also each row is lead by a row number identifier followed by colon. However, the changes are not made to the original dataframe. So, when we apply the is.data.table() method to the original dataframe, it returns FALSE. On the contrary, if we apply this method to the result of the as.data.table() method, we get TRUE value."
},
{
"code": null,
"e": 5405,
"s": 5398,
"text": "Picked"
},
{
"code": null,
"e": 5417,
"s": 5405,
"text": "R DataTable"
},
{
"code": null,
"e": 5429,
"s": 5417,
"text": "R-DataFrame"
},
{
"code": null,
"e": 5440,
"s": 5429,
"text": "R Language"
}
] |
Python | Image blurring using OpenCV
|
17 Apr, 2019
Image Blurring refers to making the image less clear or distinct. It is done with the help of various low pass filter kernels.
Advantages of blurring:
It helps in Noise removal. As noise is considered as high pass signal so by the application of low pass filter kernel we restrict noise.
It helps in smoothing the image.
Low intensity edges are removed.
It helps in hiding the details when necessary. For e.g. in many cases police deliberately want to hide the face of the victim, in such cases blurring is required.
Important types of blurring:
Gaussian Blurring:Gaussian blur is the result of blurring an image by a Gaussian function. It is a widely used effect in graphics software, typically to reduce image noise and reduce detail. It is also used as a preprocessing stage before applying our machine learning or deep learning models.E.g. of a Gaussian kernel(3×3)
Median Blur: The Median Filter is a non-linear digital filtering technique, often used to remove noise from an image or signal. Median filtering is very widely used in digital image processing because, under certain conditions, it preserves edges while removing noise. It is one of the best algorithms to remove Salt and pepper noise.
Bilateral Blur: A bilateral filter is a non-linear, edge-preserving, and noise-reducing smoothing filter for images. It replaces the intensity of each pixel with a weighted average of intensity values from nearby pixels. This weight can be based on a Gaussian distribution. Thus, sharp edges are preserved while discarding the weak ones.
Below is the Python code:
# importing librariesimport cv2import numpy as np image = cv2.imread('C://Geeksforgeeks//image_processing//fruits.jpg') cv2.imshow('Original Image', image)cv2.waitKey(0) # Gaussian BlurGaussian = cv2.GaussianBlur(image, (7, 7), 0)cv2.imshow('Gaussian Blurring', Gaussian)cv2.waitKey(0) # Median Blurmedian = cv2.medianBlur(image, 5)cv2.imshow('Median Blurring', median)cv2.waitKey(0) # Bilateral Blurbilateral = cv2.bilateralFilter(image, 9, 75, 75)cv2.imshow('Bilateral Blurring', bilateral)cv2.waitKey(0)cv2.destroyAllWindows()
Output:
Image-Processing
OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n17 Apr, 2019"
},
{
"code": null,
"e": 181,
"s": 54,
"text": "Image Blurring refers to making the image less clear or distinct. It is done with the help of various low pass filter kernels."
},
{
"code": null,
"e": 205,
"s": 181,
"text": "Advantages of blurring:"
},
{
"code": null,
"e": 342,
"s": 205,
"text": "It helps in Noise removal. As noise is considered as high pass signal so by the application of low pass filter kernel we restrict noise."
},
{
"code": null,
"e": 375,
"s": 342,
"text": "It helps in smoothing the image."
},
{
"code": null,
"e": 408,
"s": 375,
"text": "Low intensity edges are removed."
},
{
"code": null,
"e": 571,
"s": 408,
"text": "It helps in hiding the details when necessary. For e.g. in many cases police deliberately want to hide the face of the victim, in such cases blurring is required."
},
{
"code": null,
"e": 600,
"s": 571,
"text": "Important types of blurring:"
},
{
"code": null,
"e": 924,
"s": 600,
"text": "Gaussian Blurring:Gaussian blur is the result of blurring an image by a Gaussian function. It is a widely used effect in graphics software, typically to reduce image noise and reduce detail. It is also used as a preprocessing stage before applying our machine learning or deep learning models.E.g. of a Gaussian kernel(3×3)"
},
{
"code": null,
"e": 1259,
"s": 924,
"text": "Median Blur: The Median Filter is a non-linear digital filtering technique, often used to remove noise from an image or signal. Median filtering is very widely used in digital image processing because, under certain conditions, it preserves edges while removing noise. It is one of the best algorithms to remove Salt and pepper noise."
},
{
"code": null,
"e": 1597,
"s": 1259,
"text": "Bilateral Blur: A bilateral filter is a non-linear, edge-preserving, and noise-reducing smoothing filter for images. It replaces the intensity of each pixel with a weighted average of intensity values from nearby pixels. This weight can be based on a Gaussian distribution. Thus, sharp edges are preserved while discarding the weak ones."
},
{
"code": null,
"e": 1623,
"s": 1597,
"text": "Below is the Python code:"
},
{
"code": "# importing librariesimport cv2import numpy as np image = cv2.imread('C://Geeksforgeeks//image_processing//fruits.jpg') cv2.imshow('Original Image', image)cv2.waitKey(0) # Gaussian BlurGaussian = cv2.GaussianBlur(image, (7, 7), 0)cv2.imshow('Gaussian Blurring', Gaussian)cv2.waitKey(0) # Median Blurmedian = cv2.medianBlur(image, 5)cv2.imshow('Median Blurring', median)cv2.waitKey(0) # Bilateral Blurbilateral = cv2.bilateralFilter(image, 9, 75, 75)cv2.imshow('Bilateral Blurring', bilateral)cv2.waitKey(0)cv2.destroyAllWindows()",
"e": 2160,
"s": 1623,
"text": null
},
{
"code": null,
"e": 2168,
"s": 2160,
"text": "Output:"
},
{
"code": null,
"e": 2185,
"s": 2168,
"text": "Image-Processing"
},
{
"code": null,
"e": 2192,
"s": 2185,
"text": "OpenCV"
},
{
"code": null,
"e": 2199,
"s": 2192,
"text": "Python"
}
] |
Ruby | Hashes Basics
|
31 Jul, 2018
Hash is a data structure that maintains a set of objects which are termed as the keys and each key associates a value with it. In simple words, a hash is a collection of unique keys and their values. Hashes are sometimes called as associative arrays because it associates values with each of the keys but there is a difference between hashes and arrays. Arrays always use an integer value for indexing whereas hashes use the object. Hashes are also known as the maps because they map keys to values.
Hash Literals or Creating Hashes: A hash is created using the hash literal which is a comma-separated list of key/value pairs and it always enclosed within curly braces {}. There are different ways to create a hash :
Using new class method: new class method will create an empty hash means there will be no default value for the created hash.Syntax:hash_variable = Hash.newExample:geeks = Hash.newThis will create an empty hash geeks. You can also provide the default value to geeks in two ways as follows:geeks = Hash.new("GFG")
or
geeks = Hash.new "GFG"
Here GFG is the default value. Whenever the key or value doesn’t exist in above hash then accessing the hash will return the default value “GFG”. To provide key/value pairs you have to modify the hash values which is discussed below in this article.
Syntax:
hash_variable = Hash.new
Example:
geeks = Hash.new
This will create an empty hash geeks. You can also provide the default value to geeks in two ways as follows:
geeks = Hash.new("GFG")
or
geeks = Hash.new "GFG"
Here GFG is the default value. Whenever the key or value doesn’t exist in above hash then accessing the hash will return the default value “GFG”. To provide key/value pairs you have to modify the hash values which is discussed below in this article.
Using {} braces: In this hash variable is followed by = and curly braces {}. Between curly braces {}, the key/value pairs are created.Syntax:hash_variable = {"key1" => value1, "key2" => value2}
Syntax:
hash_variable = {"key1" => value1, "key2" => value2}
Fetching hash values: To fetch a hash value always put the required key within the square bracket [].
Example:
# Ruby program to demonstrate the creation# of hashes and fetching the hash values #!/usr/bin/ruby # Creating a hash using new class method# without the default valuegeeks = Hash.new # empty hash will return nothing on displayputs "#{geeks[4]}" # creating hash using new class method# providing default value# this could be written as # geeks = Hash.new "GFG"geeks_default = Hash.new("GFG") # it will return GFG for every index of hashputs "#{geeks_default[0]}"puts "#{geeks_default[7]}" # creating hash using {} bracesgeeks_hash1 = {"DS" => 1, "Java" => 2} # fetching values of hash using []puts geeks_hash1['DS'] puts geeks_hash1['Java']
Output:
GFG
GFG
1
2
Modifying hashes in Ruby: Hash can be modified by adding or deleting a key value/pair in an already existing hash. Also, you can change the existing value of key in the hash.
Example:
# Ruby program to demonstrate the modifying of hash #!/usr/bin/ruby # creating hash using {} bracesgeeks_hash1 = {"DS" => 1, "Java" => 2} puts "Before Modifying" # fetching values of hash using []puts geeks_hash1['DS'] puts geeks_hash1['Java'] puts "\n" puts "After Modifying" # modifying hash valuesgeeks_hash1["DS"] = 4geeks_hash1["Java"] = 5 # fetching values of hash using []puts geeks_hash1['DS'] puts geeks_hash1['Java']
Output:
Before Modifying
1
2
After Modifying
4
5
Note: Whenever user provides two different values to the same key in a hash then the previous value of the key is overwritten by the latest value of the key. Also, the program will run successfully but will give a warning as shown in below example:
# Ruby program to demonstrate the modifying hash #!/usr/bin/ruby # creating hash using {} braces# providing two different values to key "DS"geeks_hash1 = {"DS" => 1, "DS" => 4,"Java" => 2} puts "Before Modifying" # fetching values of hash using []puts geeks_hash1['DS'] puts geeks_hash1['Java'] puts "\n" puts "After Modifying" # modifying hash valuesgeeks_hash1["DS"] = 4geeks_hash1["Java"] = 5 # fetching values of hash using []puts geeks_hash1['DS'] puts geeks_hash1['Java']
Output:
Before Modifying
4
2
After Modifying
4
5
main.rb:7: warning: key "DS" is duplicated and overwritten on line 7
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n31 Jul, 2018"
},
{
"code": null,
"e": 553,
"s": 53,
"text": "Hash is a data structure that maintains a set of objects which are termed as the keys and each key associates a value with it. In simple words, a hash is a collection of unique keys and their values. Hashes are sometimes called as associative arrays because it associates values with each of the keys but there is a difference between hashes and arrays. Arrays always use an integer value for indexing whereas hashes use the object. Hashes are also known as the maps because they map keys to values."
},
{
"code": null,
"e": 770,
"s": 553,
"text": "Hash Literals or Creating Hashes: A hash is created using the hash literal which is a comma-separated list of key/value pairs and it always enclosed within curly braces {}. There are different ways to create a hash :"
},
{
"code": null,
"e": 1361,
"s": 770,
"text": "Using new class method: new class method will create an empty hash means there will be no default value for the created hash.Syntax:hash_variable = Hash.newExample:geeks = Hash.newThis will create an empty hash geeks. You can also provide the default value to geeks in two ways as follows:geeks = Hash.new(\"GFG\")\n\nor\n\ngeeks = Hash.new \"GFG\"\nHere GFG is the default value. Whenever the key or value doesn’t exist in above hash then accessing the hash will return the default value “GFG”. To provide key/value pairs you have to modify the hash values which is discussed below in this article."
},
{
"code": null,
"e": 1369,
"s": 1361,
"text": "Syntax:"
},
{
"code": null,
"e": 1394,
"s": 1369,
"text": "hash_variable = Hash.new"
},
{
"code": null,
"e": 1403,
"s": 1394,
"text": "Example:"
},
{
"code": null,
"e": 1420,
"s": 1403,
"text": "geeks = Hash.new"
},
{
"code": null,
"e": 1530,
"s": 1420,
"text": "This will create an empty hash geeks. You can also provide the default value to geeks in two ways as follows:"
},
{
"code": null,
"e": 1583,
"s": 1530,
"text": "geeks = Hash.new(\"GFG\")\n\nor\n\ngeeks = Hash.new \"GFG\"\n"
},
{
"code": null,
"e": 1833,
"s": 1583,
"text": "Here GFG is the default value. Whenever the key or value doesn’t exist in above hash then accessing the hash will return the default value “GFG”. To provide key/value pairs you have to modify the hash values which is discussed below in this article."
},
{
"code": null,
"e": 2028,
"s": 1833,
"text": "Using {} braces: In this hash variable is followed by = and curly braces {}. Between curly braces {}, the key/value pairs are created.Syntax:hash_variable = {\"key1\" => value1, \"key2\" => value2}\n"
},
{
"code": null,
"e": 2036,
"s": 2028,
"text": "Syntax:"
},
{
"code": null,
"e": 2090,
"s": 2036,
"text": "hash_variable = {\"key1\" => value1, \"key2\" => value2}\n"
},
{
"code": null,
"e": 2192,
"s": 2090,
"text": "Fetching hash values: To fetch a hash value always put the required key within the square bracket []."
},
{
"code": null,
"e": 2201,
"s": 2192,
"text": "Example:"
},
{
"code": "# Ruby program to demonstrate the creation# of hashes and fetching the hash values #!/usr/bin/ruby # Creating a hash using new class method# without the default valuegeeks = Hash.new # empty hash will return nothing on displayputs \"#{geeks[4]}\" # creating hash using new class method# providing default value# this could be written as # geeks = Hash.new \"GFG\"geeks_default = Hash.new(\"GFG\") # it will return GFG for every index of hashputs \"#{geeks_default[0]}\"puts \"#{geeks_default[7]}\" # creating hash using {} bracesgeeks_hash1 = {\"DS\" => 1, \"Java\" => 2} # fetching values of hash using []puts geeks_hash1['DS'] puts geeks_hash1['Java'] ",
"e": 2854,
"s": 2201,
"text": null
},
{
"code": null,
"e": 2862,
"s": 2854,
"text": "Output:"
},
{
"code": null,
"e": 2876,
"s": 2862,
"text": "\nGFG\nGFG\n1\n2\n"
},
{
"code": null,
"e": 3051,
"s": 2876,
"text": "Modifying hashes in Ruby: Hash can be modified by adding or deleting a key value/pair in an already existing hash. Also, you can change the existing value of key in the hash."
},
{
"code": null,
"e": 3060,
"s": 3051,
"text": "Example:"
},
{
"code": "# Ruby program to demonstrate the modifying of hash #!/usr/bin/ruby # creating hash using {} bracesgeeks_hash1 = {\"DS\" => 1, \"Java\" => 2} puts \"Before Modifying\" # fetching values of hash using []puts geeks_hash1['DS'] puts geeks_hash1['Java'] puts \"\\n\" puts \"After Modifying\" # modifying hash valuesgeeks_hash1[\"DS\"] = 4geeks_hash1[\"Java\"] = 5 # fetching values of hash using []puts geeks_hash1['DS'] puts geeks_hash1['Java'] ",
"e": 3500,
"s": 3060,
"text": null
},
{
"code": null,
"e": 3508,
"s": 3500,
"text": "Output:"
},
{
"code": null,
"e": 3551,
"s": 3508,
"text": "Before Modifying\n1\n2\n\nAfter Modifying\n4\n5\n"
},
{
"code": null,
"e": 3800,
"s": 3551,
"text": "Note: Whenever user provides two different values to the same key in a hash then the previous value of the key is overwritten by the latest value of the key. Also, the program will run successfully but will give a warning as shown in below example:"
},
{
"code": "# Ruby program to demonstrate the modifying hash #!/usr/bin/ruby # creating hash using {} braces# providing two different values to key \"DS\"geeks_hash1 = {\"DS\" => 1, \"DS\" => 4,\"Java\" => 2} puts \"Before Modifying\" # fetching values of hash using []puts geeks_hash1['DS'] puts geeks_hash1['Java'] puts \"\\n\" puts \"After Modifying\" # modifying hash valuesgeeks_hash1[\"DS\"] = 4geeks_hash1[\"Java\"] = 5 # fetching values of hash using []puts geeks_hash1['DS'] puts geeks_hash1['Java'] ",
"e": 4291,
"s": 3800,
"text": null
},
{
"code": null,
"e": 4299,
"s": 4291,
"text": "Output:"
},
{
"code": null,
"e": 4411,
"s": 4299,
"text": "Before Modifying\n4\n2\n\nAfter Modifying\n4\n5\nmain.rb:7: warning: key \"DS\" is duplicated and overwritten on line 7\n"
},
{
"code": null,
"e": 4416,
"s": 4411,
"text": "Ruby"
}
] |
What is Photoshop?
|
21 Jul, 2021
Photoshop is photo editing software that edits photos, and images should be in a raster image format. It is available in many different languages, such as English, Chinese, Japanese, Dutch, Polish, and so on. Nowadays, Photoshop is also known as Adobe Photoshop.
Adobe Photoshop is a user-friendly, most powerful, and widely used image/graphics editing software developed by Adobe. Adobe Photoshop is basically a raster-based image editing software. With multiple layers and features such as masking, image wrapping tools, alpha compositing, fluid camera rotation, and file display tools, and much more advanced tools, Photoshop can edit and compose raster images.
In 1988, Thomas and John Knoll developed the first basic version of Photoshop. Later, it was taken over by Adobe systems. Then the software has been upgraded and updated with more advanced features, a set of tools, and commands. The Photoshop CC version is the latest version of the series and it is a part of the Adobe Creative Cloud branding. The Photoshop family has some other software, consisting of Photoshop lightroom, Photoshop elements, Photoshop fix, Photoshop express, and other software.
Following are the list of Photoshop versions:
With every new version, Photoshop is developed, from a simple small photo editing tool to an industry-leading software that changed the global graphic designing and multimedia industries standards. Every new version has some new features introduced, but there are a few tools that are being tested with time and remain sturdy and highly important to the designers. Here are some tools and features that are proved as the best of Adobe Photoshop:
Layers: With the layers palette, we can draw/design different elements of your design independently in layers and then merge them up as per the order of display. It helps and enhances the power of the designer to control the flow of the design.Colour channels: In the color channels palette we can look at particular shades that are included in the picture. In the RGB mode, we get red, green, and blue. However, when we move to a different color space, these color channels will be different, such as LAB or CMYK.Shapes: By holding the original quality a shape layer can be easily edited with the help of a pen tool or a direct selection tool. The colors, gradients, and many other effects within the shape path can be changed anytime.Pen tool: One of the important features of Photoshop is a Pen tool. It is used for drawing paths along with the anchor points, the creative scope it provides is limitless. The pen tool is so flexible that the designer can draw any shape or edit the existing shapes as well as he is using his bare hand. We have a good amount of control through placing the anchor points in the right places.Hue and saturation: The Hue and Saturation feature is one of the most important in Photoshop. It enables the designer/editor to adjust the hue and saturation colors, change the richness of colors and their intensity in the photos. This will make the image look more natural and realistic.Selection Tools: The set of selection tools Photoshop offers is the most common and widely used feature by designers. Selection tools made life easy for photographers, graphic designers and every professional that is associated with multimedia the detail we obtain is fabulous.Vector Mask: A layer mask looks like a dry and non-responsive subject. Once the subject is grasped it starts to use the black and white colors within the masking layer thumbnail. The layer masks create a masking portion of an object by using the shades of gray, i.e, grayscale color combination. When the masking is done, the area of the object under the layer mask will disappear.Slice Tool: A slice tool provides the feature to snip the images into slices. These images basically used in the development of web technology so the loading time of a website can be optimized.Retouching Tools: Retouching tools are a combination of various tools such as Stamp tool, Pattern Stamp tool, Healing tool, Spot Healing tool, Patch tool, Redeye tool, and much more. These tools are used to correct images at the initial stages.3D: The feature Photoshop 3D, we can directly import the 3 Dimensional objects into Photoshop and draw the textures directly on the Photoshop canvas. We can make a series of images related to the 3D object and choose the pose and facial expressions from the animation within Photoshop.
Layers: With the layers palette, we can draw/design different elements of your design independently in layers and then merge them up as per the order of display. It helps and enhances the power of the designer to control the flow of the design.
Colour channels: In the color channels palette we can look at particular shades that are included in the picture. In the RGB mode, we get red, green, and blue. However, when we move to a different color space, these color channels will be different, such as LAB or CMYK.
Shapes: By holding the original quality a shape layer can be easily edited with the help of a pen tool or a direct selection tool. The colors, gradients, and many other effects within the shape path can be changed anytime.
Pen tool: One of the important features of Photoshop is a Pen tool. It is used for drawing paths along with the anchor points, the creative scope it provides is limitless. The pen tool is so flexible that the designer can draw any shape or edit the existing shapes as well as he is using his bare hand. We have a good amount of control through placing the anchor points in the right places.
Hue and saturation: The Hue and Saturation feature is one of the most important in Photoshop. It enables the designer/editor to adjust the hue and saturation colors, change the richness of colors and their intensity in the photos. This will make the image look more natural and realistic.
Selection Tools: The set of selection tools Photoshop offers is the most common and widely used feature by designers. Selection tools made life easy for photographers, graphic designers and every professional that is associated with multimedia the detail we obtain is fabulous.
Vector Mask: A layer mask looks like a dry and non-responsive subject. Once the subject is grasped it starts to use the black and white colors within the masking layer thumbnail. The layer masks create a masking portion of an object by using the shades of gray, i.e, grayscale color combination. When the masking is done, the area of the object under the layer mask will disappear.
Slice Tool: A slice tool provides the feature to snip the images into slices. These images basically used in the development of web technology so the loading time of a website can be optimized.
Retouching Tools: Retouching tools are a combination of various tools such as Stamp tool, Pattern Stamp tool, Healing tool, Spot Healing tool, Patch tool, Redeye tool, and much more. These tools are used to correct images at the initial stages.
3D: The feature Photoshop 3D, we can directly import the 3 Dimensional objects into Photoshop and draw the textures directly on the Photoshop canvas. We can make a series of images related to the 3D object and choose the pose and facial expressions from the animation within Photoshop.
File: The first menu given in the menu bar of Adobe Photoshop is File Menu. There are many options in this menu such as New, Open, Save, Revert, Place, Import, Export, Automate and also File Info, etc.
Edit: The 2nd tab that is given up in the menu bar of Adobe Photoshop stands for Edit Menu. Edit Menu is divided into 4 main sections. History, Clipboard, Transform, and Setting.
Image: The 3rd tab Image menu has features for dealing with images and canvas. Using the options of resizing files, adjust curves and levels, duplicating pictures, as well as rotating photos.
Layer: 4th tab menu has controls for working with your document/image layers. We can play with the layers with options like add, delete layers, create layer masks, and merge layers, among other things.
Type: 5th tab menu has added in Variation CS6 of Photoshop that is Type. A lot of the commands on the Type menu could be discovered on the Options bar, as well as the Paragraph and also Personality panels.
Select: 6th menu items let you grab layers, pick colors, use Quick Mask mode, Deselect, Reselect, Inverse, Deselect Layers, Color Range, Refine Mask, Transform Selection, and more.
Filter: The 7th menu filter is packed with all kinds of effects you can apply to your documents/images. It groups filter by type: Artistic, Blur, Sharpen, and many more.
3D: This 8th menu includes tools for working with 3-D images, like rendering and painting on 3-D objects.
View: The 9th menu gives us all sorts of different ways of looking at designs/images, from zooming in or out to adding guides and rulers.
Window: The 10th menu is used to change what we want to see in the Photoshop window. It lets you arrange your open documents, view or hide panels, and much more.
There are several file types found in Photoshop, some of them that most commonly used are:
JPEG – Joint Photographic Expert Group: It is the most popular and widely used file format for digital photos.
PNG – Portable Network Graphics: PNG is a great choice for saving digital photos as high-quality originals.
GIF – Graphics Interchange Format: GIF allows you to create simple animations. All web browsers support GIF files and their small file sizes load quickly on the screen.
PDF – Portable Document Format: PDF files used for viewing, sharing, and printing the documents.
TIFF – Tagged Image File Format: TIFF files can be very large, as compared with JPEG files. TIFF is the widely accepted standard for images destined for commercial printing.
PSD – Photoshop Document: PSD is Photoshop’s native file format. It is a file format of our working file in Photoshop.
The most basic use of Photoshop is photo editing, graphic editing, website theme designing, poster designing.
1. Photo Editing: Almost every photographer needs software for editing photos. Editing the photo involves actions,
To adjust the color levels of the photo.
Resize and Crop the photos.
Touch-up photos, by erasing, changing the objects in the photo.
Applying filters.
Change the format of the photo.
A designer can use their skills and transform the image.
2. UI content designing: Designing the User Interface content, for example, Logo’s, Buttons, Task Bar Design, GIF’s, etc.,
3. Graphics Design: Using paintbrushes, effects like drop shadows, water, fire, and many more effects. The graphic designer can produce high-quality graphics.
4. Social Media Content: Social media handler designs high-quality attractive posts, stories for their public engagement using various tools available in Photoshop.
5. Animation: Using Photoshop, we can make simple graphics animation. We have to create a set of layers and then activate the animation panel from the timeline. We can export our animation in the form of a GIF.
Photoshop is available on multiple platforms.
Features of editing different types of image format.
Professional Color Grading support.
Advanced layer management.
Professional Plug-Ins, Filters, Textures, and Overlays.
Merging images and graphics.
Supports Video Clips and Animation Layers.
Has Cloud Storage.
OpenType SVG Fonts and Emoji Support.
Beginners may find the interface complicated to learn.
It is a bit expensive.
Untested beta versions are sometimes released and may cause the software to crash.
A progress monitoring facility is not available in few tools.
Less support for vector graphics design.
The software consumes more disk space while running.
Picked
class 7
School Learning
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Jul, 2021"
},
{
"code": null,
"e": 291,
"s": 28,
"text": "Photoshop is photo editing software that edits photos, and images should be in a raster image format. It is available in many different languages, such as English, Chinese, Japanese, Dutch, Polish, and so on. Nowadays, Photoshop is also known as Adobe Photoshop."
},
{
"code": null,
"e": 693,
"s": 291,
"text": "Adobe Photoshop is a user-friendly, most powerful, and widely used image/graphics editing software developed by Adobe. Adobe Photoshop is basically a raster-based image editing software. With multiple layers and features such as masking, image wrapping tools, alpha compositing, fluid camera rotation, and file display tools, and much more advanced tools, Photoshop can edit and compose raster images."
},
{
"code": null,
"e": 1193,
"s": 693,
"text": "In 1988, Thomas and John Knoll developed the first basic version of Photoshop. Later, it was taken over by Adobe systems. Then the software has been upgraded and updated with more advanced features, a set of tools, and commands. The Photoshop CC version is the latest version of the series and it is a part of the Adobe Creative Cloud branding. The Photoshop family has some other software, consisting of Photoshop lightroom, Photoshop elements, Photoshop fix, Photoshop express, and other software."
},
{
"code": null,
"e": 1239,
"s": 1193,
"text": "Following are the list of Photoshop versions:"
},
{
"code": null,
"e": 1685,
"s": 1239,
"text": "With every new version, Photoshop is developed, from a simple small photo editing tool to an industry-leading software that changed the global graphic designing and multimedia industries standards. Every new version has some new features introduced, but there are a few tools that are being tested with time and remain sturdy and highly important to the designers. Here are some tools and features that are proved as the best of Adobe Photoshop:"
},
{
"code": null,
"e": 4480,
"s": 1685,
"text": "Layers: With the layers palette, we can draw/design different elements of your design independently in layers and then merge them up as per the order of display. It helps and enhances the power of the designer to control the flow of the design.Colour channels: In the color channels palette we can look at particular shades that are included in the picture. In the RGB mode, we get red, green, and blue. However, when we move to a different color space, these color channels will be different, such as LAB or CMYK.Shapes: By holding the original quality a shape layer can be easily edited with the help of a pen tool or a direct selection tool. The colors, gradients, and many other effects within the shape path can be changed anytime.Pen tool: One of the important features of Photoshop is a Pen tool. It is used for drawing paths along with the anchor points, the creative scope it provides is limitless. The pen tool is so flexible that the designer can draw any shape or edit the existing shapes as well as he is using his bare hand. We have a good amount of control through placing the anchor points in the right places.Hue and saturation: The Hue and Saturation feature is one of the most important in Photoshop. It enables the designer/editor to adjust the hue and saturation colors, change the richness of colors and their intensity in the photos. This will make the image look more natural and realistic.Selection Tools: The set of selection tools Photoshop offers is the most common and widely used feature by designers. Selection tools made life easy for photographers, graphic designers and every professional that is associated with multimedia the detail we obtain is fabulous.Vector Mask: A layer mask looks like a dry and non-responsive subject. Once the subject is grasped it starts to use the black and white colors within the masking layer thumbnail. The layer masks create a masking portion of an object by using the shades of gray, i.e, grayscale color combination. When the masking is done, the area of the object under the layer mask will disappear.Slice Tool: A slice tool provides the feature to snip the images into slices. These images basically used in the development of web technology so the loading time of a website can be optimized.Retouching Tools: Retouching tools are a combination of various tools such as Stamp tool, Pattern Stamp tool, Healing tool, Spot Healing tool, Patch tool, Redeye tool, and much more. These tools are used to correct images at the initial stages.3D: The feature Photoshop 3D, we can directly import the 3 Dimensional objects into Photoshop and draw the textures directly on the Photoshop canvas. We can make a series of images related to the 3D object and choose the pose and facial expressions from the animation within Photoshop."
},
{
"code": null,
"e": 4725,
"s": 4480,
"text": "Layers: With the layers palette, we can draw/design different elements of your design independently in layers and then merge them up as per the order of display. It helps and enhances the power of the designer to control the flow of the design."
},
{
"code": null,
"e": 4996,
"s": 4725,
"text": "Colour channels: In the color channels palette we can look at particular shades that are included in the picture. In the RGB mode, we get red, green, and blue. However, when we move to a different color space, these color channels will be different, such as LAB or CMYK."
},
{
"code": null,
"e": 5219,
"s": 4996,
"text": "Shapes: By holding the original quality a shape layer can be easily edited with the help of a pen tool or a direct selection tool. The colors, gradients, and many other effects within the shape path can be changed anytime."
},
{
"code": null,
"e": 5610,
"s": 5219,
"text": "Pen tool: One of the important features of Photoshop is a Pen tool. It is used for drawing paths along with the anchor points, the creative scope it provides is limitless. The pen tool is so flexible that the designer can draw any shape or edit the existing shapes as well as he is using his bare hand. We have a good amount of control through placing the anchor points in the right places."
},
{
"code": null,
"e": 5899,
"s": 5610,
"text": "Hue and saturation: The Hue and Saturation feature is one of the most important in Photoshop. It enables the designer/editor to adjust the hue and saturation colors, change the richness of colors and their intensity in the photos. This will make the image look more natural and realistic."
},
{
"code": null,
"e": 6177,
"s": 5899,
"text": "Selection Tools: The set of selection tools Photoshop offers is the most common and widely used feature by designers. Selection tools made life easy for photographers, graphic designers and every professional that is associated with multimedia the detail we obtain is fabulous."
},
{
"code": null,
"e": 6559,
"s": 6177,
"text": "Vector Mask: A layer mask looks like a dry and non-responsive subject. Once the subject is grasped it starts to use the black and white colors within the masking layer thumbnail. The layer masks create a masking portion of an object by using the shades of gray, i.e, grayscale color combination. When the masking is done, the area of the object under the layer mask will disappear."
},
{
"code": null,
"e": 6753,
"s": 6559,
"text": "Slice Tool: A slice tool provides the feature to snip the images into slices. These images basically used in the development of web technology so the loading time of a website can be optimized."
},
{
"code": null,
"e": 6998,
"s": 6753,
"text": "Retouching Tools: Retouching tools are a combination of various tools such as Stamp tool, Pattern Stamp tool, Healing tool, Spot Healing tool, Patch tool, Redeye tool, and much more. These tools are used to correct images at the initial stages."
},
{
"code": null,
"e": 7284,
"s": 6998,
"text": "3D: The feature Photoshop 3D, we can directly import the 3 Dimensional objects into Photoshop and draw the textures directly on the Photoshop canvas. We can make a series of images related to the 3D object and choose the pose and facial expressions from the animation within Photoshop."
},
{
"code": null,
"e": 7486,
"s": 7284,
"text": "File: The first menu given in the menu bar of Adobe Photoshop is File Menu. There are many options in this menu such as New, Open, Save, Revert, Place, Import, Export, Automate and also File Info, etc."
},
{
"code": null,
"e": 7665,
"s": 7486,
"text": "Edit: The 2nd tab that is given up in the menu bar of Adobe Photoshop stands for Edit Menu. Edit Menu is divided into 4 main sections. History, Clipboard, Transform, and Setting."
},
{
"code": null,
"e": 7857,
"s": 7665,
"text": "Image: The 3rd tab Image menu has features for dealing with images and canvas. Using the options of resizing files, adjust curves and levels, duplicating pictures, as well as rotating photos."
},
{
"code": null,
"e": 8060,
"s": 7857,
"text": "Layer: 4th tab menu has controls for working with your document/image layers. We can play with the layers with options like add, delete layers, create layer masks, and merge layers, among other things."
},
{
"code": null,
"e": 8266,
"s": 8060,
"text": "Type: 5th tab menu has added in Variation CS6 of Photoshop that is Type. A lot of the commands on the Type menu could be discovered on the Options bar, as well as the Paragraph and also Personality panels."
},
{
"code": null,
"e": 8447,
"s": 8266,
"text": "Select: 6th menu items let you grab layers, pick colors, use Quick Mask mode, Deselect, Reselect, Inverse, Deselect Layers, Color Range, Refine Mask, Transform Selection, and more."
},
{
"code": null,
"e": 8617,
"s": 8447,
"text": "Filter: The 7th menu filter is packed with all kinds of effects you can apply to your documents/images. It groups filter by type: Artistic, Blur, Sharpen, and many more."
},
{
"code": null,
"e": 8723,
"s": 8617,
"text": "3D: This 8th menu includes tools for working with 3-D images, like rendering and painting on 3-D objects."
},
{
"code": null,
"e": 8861,
"s": 8723,
"text": "View: The 9th menu gives us all sorts of different ways of looking at designs/images, from zooming in or out to adding guides and rulers."
},
{
"code": null,
"e": 9023,
"s": 8861,
"text": "Window: The 10th menu is used to change what we want to see in the Photoshop window. It lets you arrange your open documents, view or hide panels, and much more."
},
{
"code": null,
"e": 9114,
"s": 9023,
"text": "There are several file types found in Photoshop, some of them that most commonly used are:"
},
{
"code": null,
"e": 9225,
"s": 9114,
"text": "JPEG – Joint Photographic Expert Group: It is the most popular and widely used file format for digital photos."
},
{
"code": null,
"e": 9333,
"s": 9225,
"text": "PNG – Portable Network Graphics: PNG is a great choice for saving digital photos as high-quality originals."
},
{
"code": null,
"e": 9502,
"s": 9333,
"text": "GIF – Graphics Interchange Format: GIF allows you to create simple animations. All web browsers support GIF files and their small file sizes load quickly on the screen."
},
{
"code": null,
"e": 9599,
"s": 9502,
"text": "PDF – Portable Document Format: PDF files used for viewing, sharing, and printing the documents."
},
{
"code": null,
"e": 9773,
"s": 9599,
"text": "TIFF – Tagged Image File Format: TIFF files can be very large, as compared with JPEG files. TIFF is the widely accepted standard for images destined for commercial printing."
},
{
"code": null,
"e": 9892,
"s": 9773,
"text": "PSD – Photoshop Document: PSD is Photoshop’s native file format. It is a file format of our working file in Photoshop."
},
{
"code": null,
"e": 10002,
"s": 9892,
"text": "The most basic use of Photoshop is photo editing, graphic editing, website theme designing, poster designing."
},
{
"code": null,
"e": 10117,
"s": 10002,
"text": "1. Photo Editing: Almost every photographer needs software for editing photos. Editing the photo involves actions,"
},
{
"code": null,
"e": 10158,
"s": 10117,
"text": "To adjust the color levels of the photo."
},
{
"code": null,
"e": 10186,
"s": 10158,
"text": "Resize and Crop the photos."
},
{
"code": null,
"e": 10250,
"s": 10186,
"text": "Touch-up photos, by erasing, changing the objects in the photo."
},
{
"code": null,
"e": 10268,
"s": 10250,
"text": "Applying filters."
},
{
"code": null,
"e": 10300,
"s": 10268,
"text": "Change the format of the photo."
},
{
"code": null,
"e": 10357,
"s": 10300,
"text": "A designer can use their skills and transform the image."
},
{
"code": null,
"e": 10480,
"s": 10357,
"text": "2. UI content designing: Designing the User Interface content, for example, Logo’s, Buttons, Task Bar Design, GIF’s, etc.,"
},
{
"code": null,
"e": 10639,
"s": 10480,
"text": "3. Graphics Design: Using paintbrushes, effects like drop shadows, water, fire, and many more effects. The graphic designer can produce high-quality graphics."
},
{
"code": null,
"e": 10804,
"s": 10639,
"text": "4. Social Media Content: Social media handler designs high-quality attractive posts, stories for their public engagement using various tools available in Photoshop."
},
{
"code": null,
"e": 11016,
"s": 10804,
"text": "5. Animation: Using Photoshop, we can make simple graphics animation. We have to create a set of layers and then activate the animation panel from the timeline. We can export our animation in the form of a GIF. "
},
{
"code": null,
"e": 11062,
"s": 11016,
"text": "Photoshop is available on multiple platforms."
},
{
"code": null,
"e": 11115,
"s": 11062,
"text": "Features of editing different types of image format."
},
{
"code": null,
"e": 11151,
"s": 11115,
"text": "Professional Color Grading support."
},
{
"code": null,
"e": 11178,
"s": 11151,
"text": "Advanced layer management."
},
{
"code": null,
"e": 11234,
"s": 11178,
"text": "Professional Plug-Ins, Filters, Textures, and Overlays."
},
{
"code": null,
"e": 11263,
"s": 11234,
"text": "Merging images and graphics."
},
{
"code": null,
"e": 11306,
"s": 11263,
"text": "Supports Video Clips and Animation Layers."
},
{
"code": null,
"e": 11325,
"s": 11306,
"text": "Has Cloud Storage."
},
{
"code": null,
"e": 11363,
"s": 11325,
"text": "OpenType SVG Fonts and Emoji Support."
},
{
"code": null,
"e": 11418,
"s": 11363,
"text": "Beginners may find the interface complicated to learn."
},
{
"code": null,
"e": 11441,
"s": 11418,
"text": "It is a bit expensive."
},
{
"code": null,
"e": 11524,
"s": 11441,
"text": "Untested beta versions are sometimes released and may cause the software to crash."
},
{
"code": null,
"e": 11586,
"s": 11524,
"text": "A progress monitoring facility is not available in few tools."
},
{
"code": null,
"e": 11627,
"s": 11586,
"text": "Less support for vector graphics design."
},
{
"code": null,
"e": 11680,
"s": 11627,
"text": "The software consumes more disk space while running."
},
{
"code": null,
"e": 11687,
"s": 11680,
"text": "Picked"
},
{
"code": null,
"e": 11695,
"s": 11687,
"text": "class 7"
},
{
"code": null,
"e": 11711,
"s": 11695,
"text": "School Learning"
},
{
"code": null,
"e": 11730,
"s": 11711,
"text": "School Programming"
}
] |
How to create full width container using bootstrap?
|
05 May, 2022
We can create full width container using “container-fluid” class of bootstrap
Containers are the most basic layout element in Bootstrap and are required when using our default grid system. Choose from a responsive, fixed-width container (meaning its max-width changes at each breakpoint) or fluid-width (meaning it’s 100% wide all the time). container-fluid class can be used to get full width container.
container-fluid class provides a full-width container which spans the entire width of the viewport. In the below example, the div with class “container-fluid” will take-up the complete width of the viewport and will expand or shrink when ever the viewport is resized.
Method:
Basically we have to create a <div></div> (not necessary to be a div but it’s better if we use div) to which we have to give a class container-fluid(or container depends, upon the width) and put all the text inside that div which we want collectively to be in a container
Syntax:
.container- max-width changes at each breakpoint
<div class=”container”> <!– Content here –> </div>
.container-fluid- 100% width
<div class="container-fluid">
<!-- Content here -->
</div>
Example:
HTML
<!DOCTYPE html><html lang="en"><head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> <script src="https://kit.fontawesome.com/577845f6a5.js" crossorigin="anonymous"> </script> <title>Use of class container</title> <style type="text/css"> .bottom-left { left: 0; } </style></head><body> <!--class container: max-width changes at each breakpoint All the text is pushed inside a container--> <div class="container"> <!--class jumbotron: to highlight how the class container works--> <div class="jumbotron"> <h1 style="color: #006400;"> GeeksforGeeks </h1> <div> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200712114621/testimg.JPG" height="150"> </div> <div class="position-relative" style="color: green;"> <h1>Hey There..!!</h1> <p><b>This is an Example..</b></p> <p> Here I have used class container of bootstrap to put everything inside a container. </p> <br/> </div> <div class="position-relative"> <div class="position-absolute bottom-left"> <button type="button" class="btn btn-success"> Click me! </button> </div> </div> </div> </div></body></html>
image showing class container
Here, class container is used inside the top div tag to confine all the text inside a container whose width is fixed
Example:
HTML
<!DOCTYPE html><html lang="en"><head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> <script src="https://kit.fontawesome.com/577845f6a5.js" crossorigin="anonymous"> </script> <title>Use of class container-fluid</title> <style type="text/css"> .bottom-left { left: 0; } </style></head><body> <!--class container-fluid: 100% width--> <div class="container-fluid"> <!--class jumbotron: to highlight how the class container works--> <div class="jumbotron"> <h1 style="color: #006400;"> GeeksforGeeks </h1> <div> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200712114621/testimg.JPG" height="150"> </div> <div class="position-relative" style="color: green;"> <h1>Hey There..!!</h1> <p><b>This is an Example..</b></p> <p> Here I have used class container-fluid of bootstrap to put everything inside a container. </p> <br/> </div> <div class="position-relative"> <div class="position-absolute bottom-left"> <button type="button" class="btn btn-success"> Click me! </button> </div> </div> </div> </div></body></html>
Output:
image showing class container-fluid
Here class container-fluid is used to confine all the text in a container whose width is 10% of the screen
sumitgumber28
sahilintern
Bootstrap-Misc
Bootstrap
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to change navigation bar color in Bootstrap ?
Form validation using jQuery
How to pass data into a bootstrap modal?
How to align navbar items to the right in Bootstrap 4 ?
How to Show Images on Click using HTML ?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n05 May, 2022"
},
{
"code": null,
"e": 130,
"s": 52,
"text": "We can create full width container using “container-fluid” class of bootstrap"
},
{
"code": null,
"e": 457,
"s": 130,
"text": "Containers are the most basic layout element in Bootstrap and are required when using our default grid system. Choose from a responsive, fixed-width container (meaning its max-width changes at each breakpoint) or fluid-width (meaning it’s 100% wide all the time). container-fluid class can be used to get full width container."
},
{
"code": null,
"e": 725,
"s": 457,
"text": "container-fluid class provides a full-width container which spans the entire width of the viewport. In the below example, the div with class “container-fluid” will take-up the complete width of the viewport and will expand or shrink when ever the viewport is resized."
},
{
"code": null,
"e": 733,
"s": 725,
"text": "Method:"
},
{
"code": null,
"e": 1005,
"s": 733,
"text": "Basically we have to create a <div></div> (not necessary to be a div but it’s better if we use div) to which we have to give a class container-fluid(or container depends, upon the width) and put all the text inside that div which we want collectively to be in a container"
},
{
"code": null,
"e": 1013,
"s": 1005,
"text": "Syntax:"
},
{
"code": null,
"e": 1062,
"s": 1013,
"text": ".container- max-width changes at each breakpoint"
},
{
"code": null,
"e": 1113,
"s": 1062,
"text": "<div class=”container”> <!– Content here –> </div>"
},
{
"code": null,
"e": 1142,
"s": 1113,
"text": ".container-fluid- 100% width"
},
{
"code": null,
"e": 1213,
"s": 1142,
"text": "<div class=\"container-fluid\">\n\n <!-- Content here -->\n\n </div>"
},
{
"code": null,
"e": 1223,
"s": 1213,
"text": "Example: "
},
{
"code": null,
"e": 1228,
"s": 1223,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <!-- Required meta tags --> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\"> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css\" integrity=\"sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk\" crossorigin=\"anonymous\"> <script src=\"https://kit.fontawesome.com/577845f6a5.js\" crossorigin=\"anonymous\"> </script> <title>Use of class container</title> <style type=\"text/css\"> .bottom-left { left: 0; } </style></head><body> <!--class container: max-width changes at each breakpoint All the text is pushed inside a container--> <div class=\"container\"> <!--class jumbotron: to highlight how the class container works--> <div class=\"jumbotron\"> <h1 style=\"color: #006400;\"> GeeksforGeeks </h1> <div> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200712114621/testimg.JPG\" height=\"150\"> </div> <div class=\"position-relative\" style=\"color: green;\"> <h1>Hey There..!!</h1> <p><b>This is an Example..</b></p> <p> Here I have used class container of bootstrap to put everything inside a container. </p> <br/> </div> <div class=\"position-relative\"> <div class=\"position-absolute bottom-left\"> <button type=\"button\" class=\"btn btn-success\"> Click me! </button> </div> </div> </div> </div></body></html>",
"e": 3177,
"s": 1228,
"text": null
},
{
"code": null,
"e": 3207,
"s": 3177,
"text": "image showing class container"
},
{
"code": null,
"e": 3325,
"s": 3207,
"text": "Here, class container is used inside the top div tag to confine all the text inside a container whose width is fixed"
},
{
"code": null,
"e": 3335,
"s": 3325,
"text": "Example: "
},
{
"code": null,
"e": 3340,
"s": 3335,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <!-- Required meta tags --> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\"> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css\" integrity=\"sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk\" crossorigin=\"anonymous\"> <script src=\"https://kit.fontawesome.com/577845f6a5.js\" crossorigin=\"anonymous\"> </script> <title>Use of class container-fluid</title> <style type=\"text/css\"> .bottom-left { left: 0; } </style></head><body> <!--class container-fluid: 100% width--> <div class=\"container-fluid\"> <!--class jumbotron: to highlight how the class container works--> <div class=\"jumbotron\"> <h1 style=\"color: #006400;\"> GeeksforGeeks </h1> <div> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200712114621/testimg.JPG\" height=\"150\"> </div> <div class=\"position-relative\" style=\"color: green;\"> <h1>Hey There..!!</h1> <p><b>This is an Example..</b></p> <p> Here I have used class container-fluid of bootstrap to put everything inside a container. </p> <br/> </div> <div class=\"position-relative\"> <div class=\"position-absolute bottom-left\"> <button type=\"button\" class=\"btn btn-success\"> Click me! </button> </div> </div> </div> </div></body></html>",
"e": 5245,
"s": 3340,
"text": null
},
{
"code": null,
"e": 5253,
"s": 5245,
"text": "Output:"
},
{
"code": null,
"e": 5289,
"s": 5253,
"text": "image showing class container-fluid"
},
{
"code": null,
"e": 5396,
"s": 5289,
"text": "Here class container-fluid is used to confine all the text in a container whose width is 10% of the screen"
},
{
"code": null,
"e": 5410,
"s": 5396,
"text": "sumitgumber28"
},
{
"code": null,
"e": 5422,
"s": 5410,
"text": "sahilintern"
},
{
"code": null,
"e": 5437,
"s": 5422,
"text": "Bootstrap-Misc"
},
{
"code": null,
"e": 5447,
"s": 5437,
"text": "Bootstrap"
},
{
"code": null,
"e": 5464,
"s": 5447,
"text": "Web Technologies"
},
{
"code": null,
"e": 5562,
"s": 5464,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5612,
"s": 5562,
"text": "How to change navigation bar color in Bootstrap ?"
},
{
"code": null,
"e": 5641,
"s": 5612,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 5682,
"s": 5641,
"text": "How to pass data into a bootstrap modal?"
},
{
"code": null,
"e": 5738,
"s": 5682,
"text": "How to align navbar items to the right in Bootstrap 4 ?"
},
{
"code": null,
"e": 5779,
"s": 5738,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 5812,
"s": 5779,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 5874,
"s": 5812,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 5935,
"s": 5874,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 5985,
"s": 5935,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Distinct powers of a number N such that the sum is equal to K
|
24 Nov, 2021
Given two numbers N and K, the task is to print the distinct powers of N which are used to get the sum K. If it’s not possible, print -1.
Examples:
Input: N = 3, K = 40 Output: 0, 1, 2, 3 Explanation: The value of N is 3. 30 + 31 + 32 + 33 = 40
Input: N = 4, K = 65 Output: 0, 3 The value of N is 4. 40 + 43 = 65
Input: N = 4, K = 18 Output: -1 Explanation: It’s impossible to get 18 by adding the power of 4.
Observation: One observation that needs to be made for any arbitrary number a is that there can’t exist a number greater than aK if all the powers of a from 0 to k-1 are added by using each power at most once.
Example: Let a = 3 and K = 4. Then:
34 = 81. 30 + 31 + 32 + 33 = 40 which is less than 81(34).
Naive Approach: By using the above observation, the naive approach can be formed. The idea is to continuously subtract the highest power of N not exceeding K from K until K reaches 0. If at any instance, K becomes equal to some power that was already subtracted from it previously, then it’s not possible to get the sum equal to K. Therefore, an array is used to keep track of powers that have been subtracted from K.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation to find distinct// powers of N that add upto K #include <bits/stdc++.h>using namespace std; // Function to return the highest power// of N not exceeding Kint highestPower(int n, int k){ int i = 0; int a = pow(n, i); // Loop to find the highest power // less than K while (a <= k) { i += 1; a = pow(n, i); } return i - 1;} // Initializing the PowerArray// with all 0's.int b[50] = { 0 }; // Function to print// the distinct powers of N// that add upto Kint PowerArray(int n, int k){ while (k) { // Getting the highest // power of n before k int t = highestPower(n, k); // To check if the power // is being used twice or not if (b[t]) { // Print -1 if power // is being used twice cout << -1; return 0; } else // If the power is not visited, // then mark the power as visited b[t] = 1; // Decrementing the value of K k -= pow(n, t); } // Printing the powers of N // that sum up to K for (int i = 0; i < 50; i++) { if (b[i]) { cout << i << ", "; } }} // Driver codeint main(){ int N = 3; int K = 40; PowerArray(N, K); return 0;}
// Java implementation to find distinct// powers of N that add upto K class GFG{ // Function to return the highest power// of N not exceeding Kstatic int highestPower(int n, int k){ int i = 0; int a = (int) Math.pow(n, i); // Loop to find the highest power // less than K while (a <= k) { i += 1; a = (int) Math.pow(n, i); } return i - 1;} // Initializing the PowerArray// with all 0's.static int b[] = new int[50]; // Function to print// the distinct powers of N// that add upto Kstatic int PowerArray(int n, int k){ while (k>0) { // Getting the highest // power of n before k int t = highestPower(n, k); // To check if the power // is being used twice or not if (b[t]>0) { // Print -1 if power // is being used twice System.out.print(-1); return 0; } else // If the power is not visited, // then mark the power as visited b[t] = 1; // Decrementing the value of K k -= Math.pow(n, t); } // Printing the powers of N // that sum up to K for (int i = 0; i < 50; i++) { if (b[i] > 0) { System.out.print(i+ ", "); } } return 0;} // Driver codepublic static void main(String[] args){ int N = 3; int K = 40; PowerArray(N, K);}} // This code contributed by Rajput-Ji
# Python 3 implementation to find distinct# powers of N that add up to K from math import pow # Function to return the highest power# of N not exceeding Kdef highestPower(n,k): i = 0 a = pow(n, i) # Loop to find the highest power # less than K while (a <= k): i += 1 a = pow(n, i) return i - 1 # Initializing the PowerArray# with all 0's.b = [0 for i in range(50)] # Function to print# the distinct powers of N# that add upto Kdef PowerArray(n, k): while (k): # Getting the highest # power of n before k t = highestPower(n, k) # To check if the power # is being used twice or not if (b[t]): # Print -1 if power # is being used twice print(-1) return 0 else: # If the power is not visited, # then mark the power as visited b[t] = 1 # Decrementing the value of K k -= pow(n, t) # Printing the powers of N # that sum up to K for i in range(50): if (b[i]): print(i,end = ', ') # Driver codeif __name__ == '__main__': N = 3 K = 40 PowerArray(N, K) # This code is contributed by Surendra_Gangwar
// C# implementation to find distinct// powers of N that add up to K using System; public class GFG{ // Function to return the highest power// of N not exceeding Kstatic int highestPower(int n, int k){ int i = 0; int a = (int) Math.Pow(n, i); // Loop to find the highest power // less than K while (a <= k) { i += 1; a = (int) Math.Pow(n, i); } return i - 1;} // Initializing the PowerArray// with all 0's.static int []b = new int[50]; // Function to print// the distinct powers of N// that add upto Kstatic int PowerArray(int n, int k){ while (k > 0) { // Getting the highest // power of n before k int t = highestPower(n, k); // To check if the power // is being used twice or not if (b[t] > 0) { // Print -1 if power // is being used twice Console.Write(-1); return 0; } else // If the power is not visited, // then mark the power as visited b[t] = 1; // Decrementing the value of K k -= (int)Math.Pow(n, t); } // Printing the powers of N // that sum up to K for (int i = 0; i < 50; i++) { if (b[i] > 0) { Console.Write(i+ ", "); } } return 0;} // Driver codepublic static void Main(String[] args){ int N = 3; int K = 40; PowerArray(N, K);}} // This code is contributed by 29AjayKumar
<script>// Javascript implementation to find distinct// powers of N that add upto K // Function to return the highest power// of N not exceeding Kfunction highestPower(n, k){ let i = 0; let a = Math.pow(n, i); // Loop to find the highest power // less than K while (a <= k) { i += 1; a = Math.pow(n, i); } return i - 1;} // Initializing the PowerArray// with all 0's.let b = Array.from({length: 50}, (_, i) => 0); // Function to print// the distinct powers of N// that add upto Kfunction PowerArray(n, k){ while (k>0) { // Getting the highest // power of n before k let t = highestPower(n, k); // To check if the power // is being used twice or not if (b[t]>0) { // Print -1 if power // is being used twice document.write(-1); return 0; } else // If the power is not visited, // then mark the power as visited b[t] = 1; // Decrementing the value of K k -= Math.pow(n, t); } // Printing the powers of N // that sum up to K for (let i = 0; i < 50; i++) { if (b[i] > 0) { document.write(i+ ", "); } } return 0;} // Driver Code let N = 3; let K = 40; PowerArray(N, K); </script>
0, 1, 2, 3,
Time Complexity: O((log N)2)
Time taken to find out the power is Log(N).
On top of that, another Log(N) loop is being used for K.
So, the overall time complexity is Log(N)2
Auxiliary Space: O(50)
Efficient Approach: Another observation that can be made is that for K to be the sum of N’s powers which can be used only once, K % N either has to be 1 or 0 (1 because of N0). Therefore, if (K % N) comes out anything other than 0 or 1, it can be concluded that it is impossible to get the sum K.Therefore, by using the above observations, the following steps can be followed to compute the answer:
First, a counter is initialized with 0.If (K % N) = 0, then the counter is incremented by 1, and K is updated to K/N.If K % N = 1, then the frequency array f[count] is incremented by 1, and K is updated to K – 1.If, at any point, this f[count] becomes more than 1, then return -1(because the same power can’t be used twice).
First, a counter is initialized with 0.
If (K % N) = 0, then the counter is incremented by 1, and K is updated to K/N.
If K % N = 1, then the frequency array f[count] is incremented by 1, and K is updated to K – 1.
If, at any point, this f[count] becomes more than 1, then return -1(because the same power can’t be used twice).
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation to find out// the powers of N that add upto K #include <bits/stdc++.h>using namespace std; // Initializing the PowerArray// with all 0'sint b[50] = { 0 }; // Function to find the powers of N// that add up to Kint PowerArray(int n, int k){ // Initializing the counter int count = 0; // Executing the while // loop until K is // greater than 0 while (k) { if (k % n == 0) { k /= n; count++; } // If K % N == 1, // then the power array // is incremented by 1 else if (k % n == 1) { k -= 1; b[count]++; // Checking if any power is // occurred more than once if (b[count] > 1) { cout << -1; return 0; } } // For any other value, the sum of // powers cannot be added up to K else { cout << -1; return 0; } } // Printing the powers of N // that sum up to K for (int i = 0; i < 50; i++) { if (b[i]) { cout << i << ", "; } }} // Driver codeint main(){ int N = 3; int K = 40; PowerArray(N, K); return 0;}
// Java implementation to find out// the powers of N that add upto Kclass GFG{ // Initializing the PowerArray// with all 0'sstatic int b[] = new int[50]; // Function to find the powers of N// that add up to Kstatic int PowerArray(int n, int k){ // Initializing the counter int count = 0; // Executing the while // loop until K is // greater than 0 while (k > 0) { if (k % n == 0) { k /= n; count++; } // If K % N == 1, // then the power array // is incremented by 1 else if (k % n == 1) { k -= 1; b[count]++; // Checking if any power is // occurred more than once if (b[count] > 1) { System.out.print(-1); return 0; } } // For any other value, the sum of // powers cannot be added up to K else { System.out.print(-1); return 0; } } // Printing the powers of N // that sum up to K for(int i = 0; i < 50; i++) { if (b[i] != 0) { System.out.print(i + ", "); } } return Integer.MIN_VALUE;} // Driver codepublic static void main(String[] args){ int N = 3; int K = 40; PowerArray(N, K);}} // This code is contributed by Rajput-Ji
# Python3 implementation to find out# the powers of N that add upto K # Initializing the PowerArray# with all 0'sb = [0 for i in range(50)] # Function to find the powers of N# that add up to Kdef PowerArray(n, k): # Initializing the counter count = 0 # Executing the while # loop until K is # greater than 0 while (k): if (k % n == 0): k //= n count += 1 # If K % N == 1, # then the power array # is incremented by 1 elif (k % n == 1): k -= 1 b[count] += 1 # Checking if any power is # occurred more than once if (b[count] > 1): print(-1) return 0 # For any other value, the sum of # powers cannot be added up to K else: print(-1) return 0 # Printing the powers of N # that sum up to K for i in range(50): if (b[i]): print(i,end = ",") # Driver codeif __name__ == '__main__': N = 3 K = 40 PowerArray(N, K) # This code is contributed by ipg2016107
// C# implementation to find out// the powers of N that add upto Kusing System; class GFG{ // Initializing the PowerArray// with all 0'sstatic int []b = new int[50]; // Function to find the powers of N// that add up to Kstatic int PowerArray(int n, int k){ // Initializing the counter int count = 0; // Executing the while loop // until K is greater than 0 while (k > 0) { if (k % n == 0) { k /= n; count++; } // If K % N == 1, then // the power array is // incremented by 1 else if (k % n == 1) { k -= 1; b[count]++; // Checking if any power is // occurred more than once if (b[count] > 1) { Console.Write(-1); return 0; } } // For any other value, the sum of // powers cannot be added up to K else { Console.Write(-1); return 0; } } // Printing the powers of N // that sum up to K for(int i = 0; i < 50; i++) { if (b[i] != 0) { Console.Write(i + ", "); } } return int.MinValue;} // Driver codepublic static void Main(String[] args){ int N = 3; int K = 40; PowerArray(N, K);}} // This code is contributed by Rohit_ranjan
<script> // Javascript implementation to find out // the powers of N that add upto K // Initializing the PowerArray // with all 0's let b = new Array(50); b.fill(0); // Function to find the powers of N // that add up to K function PowerArray(n, k) { // Initializing the counter let count = 0; // Executing the while loop // until K is greater than 0 while (k > 0) { if (k % n == 0) { k = parseInt(k / n, 10); count++; } // If K % N == 1, then // the power array is // incremented by 1 else if (k % n == 1) { k -= 1; b[count]++; // Checking if any power is // occurred more than once if (b[count] > 1) { document.write(-1); return 0; } } // For any other value, the sum of // powers cannot be added up to K else { document.write(-1); return 0; } } // Printing the powers of N // that sum up to K for(let i = 0; i < 50; i++) { if (b[i] != 0) { document.write(i + ", "); } } return Number.MIN_VALUE; } let N = 3; let K = 40; PowerArray(N, K); </script>
0, 1, 2, 3,
Time Complexity: Since the highest power is not checked every time, the running time of this algorithm is log(N).
Auxiliary Space: O(50)
SURENDRA_GANGWAR
Rajput-Ji
29AjayKumar
Rohit_ranjan
code_hunt
divyesh072019
ipg2016107
Kirti_Mangal
subham348
maths-power
Competitive Programming
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count of strings whose prefix match with the given string to a given length k
Most important type of Algorithms
The Ultimate Beginner's Guide For DSA
Find two numbers from their sum and XOR
C++: Methods of code shortening in competitive programming
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
C++ Data Types
Merge two sorted arrays
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n24 Nov, 2021"
},
{
"code": null,
"e": 192,
"s": 54,
"text": "Given two numbers N and K, the task is to print the distinct powers of N which are used to get the sum K. If it’s not possible, print -1."
},
{
"code": null,
"e": 204,
"s": 192,
"text": "Examples: "
},
{
"code": null,
"e": 301,
"s": 204,
"text": "Input: N = 3, K = 40 Output: 0, 1, 2, 3 Explanation: The value of N is 3. 30 + 31 + 32 + 33 = 40"
},
{
"code": null,
"e": 369,
"s": 301,
"text": "Input: N = 4, K = 65 Output: 0, 3 The value of N is 4. 40 + 43 = 65"
},
{
"code": null,
"e": 468,
"s": 369,
"text": "Input: N = 4, K = 18 Output: -1 Explanation: It’s impossible to get 18 by adding the power of 4. "
},
{
"code": null,
"e": 680,
"s": 468,
"text": "Observation: One observation that needs to be made for any arbitrary number a is that there can’t exist a number greater than aK if all the powers of a from 0 to k-1 are added by using each power at most once. "
},
{
"code": null,
"e": 718,
"s": 680,
"text": "Example: Let a = 3 and K = 4. Then: "
},
{
"code": null,
"e": 779,
"s": 718,
"text": "34 = 81. 30 + 31 + 32 + 33 = 40 which is less than 81(34). "
},
{
"code": null,
"e": 1198,
"s": 779,
"text": "Naive Approach: By using the above observation, the naive approach can be formed. The idea is to continuously subtract the highest power of N not exceeding K from K until K reaches 0. If at any instance, K becomes equal to some power that was already subtracted from it previously, then it’s not possible to get the sum equal to K. Therefore, an array is used to keep track of powers that have been subtracted from K. "
},
{
"code": null,
"e": 1250,
"s": 1198,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1254,
"s": 1250,
"text": "C++"
},
{
"code": null,
"e": 1259,
"s": 1254,
"text": "Java"
},
{
"code": null,
"e": 1267,
"s": 1259,
"text": "Python3"
},
{
"code": null,
"e": 1270,
"s": 1267,
"text": "C#"
},
{
"code": null,
"e": 1281,
"s": 1270,
"text": "Javascript"
},
{
"code": "// C++ implementation to find distinct// powers of N that add upto K #include <bits/stdc++.h>using namespace std; // Function to return the highest power// of N not exceeding Kint highestPower(int n, int k){ int i = 0; int a = pow(n, i); // Loop to find the highest power // less than K while (a <= k) { i += 1; a = pow(n, i); } return i - 1;} // Initializing the PowerArray// with all 0's.int b[50] = { 0 }; // Function to print// the distinct powers of N// that add upto Kint PowerArray(int n, int k){ while (k) { // Getting the highest // power of n before k int t = highestPower(n, k); // To check if the power // is being used twice or not if (b[t]) { // Print -1 if power // is being used twice cout << -1; return 0; } else // If the power is not visited, // then mark the power as visited b[t] = 1; // Decrementing the value of K k -= pow(n, t); } // Printing the powers of N // that sum up to K for (int i = 0; i < 50; i++) { if (b[i]) { cout << i << \", \"; } }} // Driver codeint main(){ int N = 3; int K = 40; PowerArray(N, K); return 0;}",
"e": 2573,
"s": 1281,
"text": null
},
{
"code": "// Java implementation to find distinct// powers of N that add upto K class GFG{ // Function to return the highest power// of N not exceeding Kstatic int highestPower(int n, int k){ int i = 0; int a = (int) Math.pow(n, i); // Loop to find the highest power // less than K while (a <= k) { i += 1; a = (int) Math.pow(n, i); } return i - 1;} // Initializing the PowerArray// with all 0's.static int b[] = new int[50]; // Function to print// the distinct powers of N// that add upto Kstatic int PowerArray(int n, int k){ while (k>0) { // Getting the highest // power of n before k int t = highestPower(n, k); // To check if the power // is being used twice or not if (b[t]>0) { // Print -1 if power // is being used twice System.out.print(-1); return 0; } else // If the power is not visited, // then mark the power as visited b[t] = 1; // Decrementing the value of K k -= Math.pow(n, t); } // Printing the powers of N // that sum up to K for (int i = 0; i < 50; i++) { if (b[i] > 0) { System.out.print(i+ \", \"); } } return 0;} // Driver codepublic static void main(String[] args){ int N = 3; int K = 40; PowerArray(N, K);}} // This code contributed by Rajput-Ji",
"e": 3988,
"s": 2573,
"text": null
},
{
"code": "# Python 3 implementation to find distinct# powers of N that add up to K from math import pow # Function to return the highest power# of N not exceeding Kdef highestPower(n,k): i = 0 a = pow(n, i) # Loop to find the highest power # less than K while (a <= k): i += 1 a = pow(n, i) return i - 1 # Initializing the PowerArray# with all 0's.b = [0 for i in range(50)] # Function to print# the distinct powers of N# that add upto Kdef PowerArray(n, k): while (k): # Getting the highest # power of n before k t = highestPower(n, k) # To check if the power # is being used twice or not if (b[t]): # Print -1 if power # is being used twice print(-1) return 0 else: # If the power is not visited, # then mark the power as visited b[t] = 1 # Decrementing the value of K k -= pow(n, t) # Printing the powers of N # that sum up to K for i in range(50): if (b[i]): print(i,end = ', ') # Driver codeif __name__ == '__main__': N = 3 K = 40 PowerArray(N, K) # This code is contributed by Surendra_Gangwar",
"e": 5198,
"s": 3988,
"text": null
},
{
"code": " // C# implementation to find distinct// powers of N that add up to K using System; public class GFG{ // Function to return the highest power// of N not exceeding Kstatic int highestPower(int n, int k){ int i = 0; int a = (int) Math.Pow(n, i); // Loop to find the highest power // less than K while (a <= k) { i += 1; a = (int) Math.Pow(n, i); } return i - 1;} // Initializing the PowerArray// with all 0's.static int []b = new int[50]; // Function to print// the distinct powers of N// that add upto Kstatic int PowerArray(int n, int k){ while (k > 0) { // Getting the highest // power of n before k int t = highestPower(n, k); // To check if the power // is being used twice or not if (b[t] > 0) { // Print -1 if power // is being used twice Console.Write(-1); return 0; } else // If the power is not visited, // then mark the power as visited b[t] = 1; // Decrementing the value of K k -= (int)Math.Pow(n, t); } // Printing the powers of N // that sum up to K for (int i = 0; i < 50; i++) { if (b[i] > 0) { Console.Write(i+ \", \"); } } return 0;} // Driver codepublic static void Main(String[] args){ int N = 3; int K = 40; PowerArray(N, K);}} // This code is contributed by 29AjayKumar",
"e": 6635,
"s": 5198,
"text": null
},
{
"code": "<script>// Javascript implementation to find distinct// powers of N that add upto K // Function to return the highest power// of N not exceeding Kfunction highestPower(n, k){ let i = 0; let a = Math.pow(n, i); // Loop to find the highest power // less than K while (a <= k) { i += 1; a = Math.pow(n, i); } return i - 1;} // Initializing the PowerArray// with all 0's.let b = Array.from({length: 50}, (_, i) => 0); // Function to print// the distinct powers of N// that add upto Kfunction PowerArray(n, k){ while (k>0) { // Getting the highest // power of n before k let t = highestPower(n, k); // To check if the power // is being used twice or not if (b[t]>0) { // Print -1 if power // is being used twice document.write(-1); return 0; } else // If the power is not visited, // then mark the power as visited b[t] = 1; // Decrementing the value of K k -= Math.pow(n, t); } // Printing the powers of N // that sum up to K for (let i = 0; i < 50; i++) { if (b[i] > 0) { document.write(i+ \", \"); } } return 0;} // Driver Code let N = 3; let K = 40; PowerArray(N, K); </script>",
"e": 7976,
"s": 6635,
"text": null
},
{
"code": null,
"e": 7988,
"s": 7976,
"text": "0, 1, 2, 3,"
},
{
"code": null,
"e": 8021,
"s": 7990,
"text": "Time Complexity: O((log N)2) "
},
{
"code": null,
"e": 8065,
"s": 8021,
"text": "Time taken to find out the power is Log(N)."
},
{
"code": null,
"e": 8122,
"s": 8065,
"text": "On top of that, another Log(N) loop is being used for K."
},
{
"code": null,
"e": 8165,
"s": 8122,
"text": "So, the overall time complexity is Log(N)2"
},
{
"code": null,
"e": 8188,
"s": 8165,
"text": "Auxiliary Space: O(50)"
},
{
"code": null,
"e": 8589,
"s": 8188,
"text": "Efficient Approach: Another observation that can be made is that for K to be the sum of N’s powers which can be used only once, K % N either has to be 1 or 0 (1 because of N0). Therefore, if (K % N) comes out anything other than 0 or 1, it can be concluded that it is impossible to get the sum K.Therefore, by using the above observations, the following steps can be followed to compute the answer: "
},
{
"code": null,
"e": 8914,
"s": 8589,
"text": "First, a counter is initialized with 0.If (K % N) = 0, then the counter is incremented by 1, and K is updated to K/N.If K % N = 1, then the frequency array f[count] is incremented by 1, and K is updated to K – 1.If, at any point, this f[count] becomes more than 1, then return -1(because the same power can’t be used twice)."
},
{
"code": null,
"e": 8954,
"s": 8914,
"text": "First, a counter is initialized with 0."
},
{
"code": null,
"e": 9033,
"s": 8954,
"text": "If (K % N) = 0, then the counter is incremented by 1, and K is updated to K/N."
},
{
"code": null,
"e": 9129,
"s": 9033,
"text": "If K % N = 1, then the frequency array f[count] is incremented by 1, and K is updated to K – 1."
},
{
"code": null,
"e": 9242,
"s": 9129,
"text": "If, at any point, this f[count] becomes more than 1, then return -1(because the same power can’t be used twice)."
},
{
"code": null,
"e": 9294,
"s": 9242,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 9298,
"s": 9294,
"text": "C++"
},
{
"code": null,
"e": 9303,
"s": 9298,
"text": "Java"
},
{
"code": null,
"e": 9311,
"s": 9303,
"text": "Python3"
},
{
"code": null,
"e": 9314,
"s": 9311,
"text": "C#"
},
{
"code": null,
"e": 9325,
"s": 9314,
"text": "Javascript"
},
{
"code": "// C++ implementation to find out// the powers of N that add upto K #include <bits/stdc++.h>using namespace std; // Initializing the PowerArray// with all 0'sint b[50] = { 0 }; // Function to find the powers of N// that add up to Kint PowerArray(int n, int k){ // Initializing the counter int count = 0; // Executing the while // loop until K is // greater than 0 while (k) { if (k % n == 0) { k /= n; count++; } // If K % N == 1, // then the power array // is incremented by 1 else if (k % n == 1) { k -= 1; b[count]++; // Checking if any power is // occurred more than once if (b[count] > 1) { cout << -1; return 0; } } // For any other value, the sum of // powers cannot be added up to K else { cout << -1; return 0; } } // Printing the powers of N // that sum up to K for (int i = 0; i < 50; i++) { if (b[i]) { cout << i << \", \"; } }} // Driver codeint main(){ int N = 3; int K = 40; PowerArray(N, K); return 0;}",
"e": 10535,
"s": 9325,
"text": null
},
{
"code": "// Java implementation to find out// the powers of N that add upto Kclass GFG{ // Initializing the PowerArray// with all 0'sstatic int b[] = new int[50]; // Function to find the powers of N// that add up to Kstatic int PowerArray(int n, int k){ // Initializing the counter int count = 0; // Executing the while // loop until K is // greater than 0 while (k > 0) { if (k % n == 0) { k /= n; count++; } // If K % N == 1, // then the power array // is incremented by 1 else if (k % n == 1) { k -= 1; b[count]++; // Checking if any power is // occurred more than once if (b[count] > 1) { System.out.print(-1); return 0; } } // For any other value, the sum of // powers cannot be added up to K else { System.out.print(-1); return 0; } } // Printing the powers of N // that sum up to K for(int i = 0; i < 50; i++) { if (b[i] != 0) { System.out.print(i + \", \"); } } return Integer.MIN_VALUE;} // Driver codepublic static void main(String[] args){ int N = 3; int K = 40; PowerArray(N, K);}} // This code is contributed by Rajput-Ji",
"e": 11893,
"s": 10535,
"text": null
},
{
"code": "# Python3 implementation to find out# the powers of N that add upto K # Initializing the PowerArray# with all 0'sb = [0 for i in range(50)] # Function to find the powers of N# that add up to Kdef PowerArray(n, k): # Initializing the counter count = 0 # Executing the while # loop until K is # greater than 0 while (k): if (k % n == 0): k //= n count += 1 # If K % N == 1, # then the power array # is incremented by 1 elif (k % n == 1): k -= 1 b[count] += 1 # Checking if any power is # occurred more than once if (b[count] > 1): print(-1) return 0 # For any other value, the sum of # powers cannot be added up to K else: print(-1) return 0 # Printing the powers of N # that sum up to K for i in range(50): if (b[i]): print(i,end = \",\") # Driver codeif __name__ == '__main__': N = 3 K = 40 PowerArray(N, K) # This code is contributed by ipg2016107",
"e": 13003,
"s": 11893,
"text": null
},
{
"code": "// C# implementation to find out// the powers of N that add upto Kusing System; class GFG{ // Initializing the PowerArray// with all 0'sstatic int []b = new int[50]; // Function to find the powers of N// that add up to Kstatic int PowerArray(int n, int k){ // Initializing the counter int count = 0; // Executing the while loop // until K is greater than 0 while (k > 0) { if (k % n == 0) { k /= n; count++; } // If K % N == 1, then // the power array is // incremented by 1 else if (k % n == 1) { k -= 1; b[count]++; // Checking if any power is // occurred more than once if (b[count] > 1) { Console.Write(-1); return 0; } } // For any other value, the sum of // powers cannot be added up to K else { Console.Write(-1); return 0; } } // Printing the powers of N // that sum up to K for(int i = 0; i < 50; i++) { if (b[i] != 0) { Console.Write(i + \", \"); } } return int.MinValue;} // Driver codepublic static void Main(String[] args){ int N = 3; int K = 40; PowerArray(N, K);}} // This code is contributed by Rohit_ranjan",
"e": 14361,
"s": 13003,
"text": null
},
{
"code": "<script> // Javascript implementation to find out // the powers of N that add upto K // Initializing the PowerArray // with all 0's let b = new Array(50); b.fill(0); // Function to find the powers of N // that add up to K function PowerArray(n, k) { // Initializing the counter let count = 0; // Executing the while loop // until K is greater than 0 while (k > 0) { if (k % n == 0) { k = parseInt(k / n, 10); count++; } // If K % N == 1, then // the power array is // incremented by 1 else if (k % n == 1) { k -= 1; b[count]++; // Checking if any power is // occurred more than once if (b[count] > 1) { document.write(-1); return 0; } } // For any other value, the sum of // powers cannot be added up to K else { document.write(-1); return 0; } } // Printing the powers of N // that sum up to K for(let i = 0; i < 50; i++) { if (b[i] != 0) { document.write(i + \", \"); } } return Number.MIN_VALUE; } let N = 3; let K = 40; PowerArray(N, K); </script>",
"e": 15868,
"s": 14361,
"text": null
},
{
"code": null,
"e": 15880,
"s": 15868,
"text": "0, 1, 2, 3,"
},
{
"code": null,
"e": 15996,
"s": 15882,
"text": "Time Complexity: Since the highest power is not checked every time, the running time of this algorithm is log(N)."
},
{
"code": null,
"e": 16020,
"s": 15996,
"text": "Auxiliary Space: O(50) "
},
{
"code": null,
"e": 16037,
"s": 16020,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 16047,
"s": 16037,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 16059,
"s": 16047,
"text": "29AjayKumar"
},
{
"code": null,
"e": 16072,
"s": 16059,
"text": "Rohit_ranjan"
},
{
"code": null,
"e": 16082,
"s": 16072,
"text": "code_hunt"
},
{
"code": null,
"e": 16096,
"s": 16082,
"text": "divyesh072019"
},
{
"code": null,
"e": 16107,
"s": 16096,
"text": "ipg2016107"
},
{
"code": null,
"e": 16120,
"s": 16107,
"text": "Kirti_Mangal"
},
{
"code": null,
"e": 16130,
"s": 16120,
"text": "subham348"
},
{
"code": null,
"e": 16142,
"s": 16130,
"text": "maths-power"
},
{
"code": null,
"e": 16166,
"s": 16142,
"text": "Competitive Programming"
},
{
"code": null,
"e": 16179,
"s": 16166,
"text": "Mathematical"
},
{
"code": null,
"e": 16192,
"s": 16179,
"text": "Mathematical"
},
{
"code": null,
"e": 16290,
"s": 16192,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 16368,
"s": 16290,
"text": "Count of strings whose prefix match with the given string to a given length k"
},
{
"code": null,
"e": 16402,
"s": 16368,
"text": "Most important type of Algorithms"
},
{
"code": null,
"e": 16440,
"s": 16402,
"text": "The Ultimate Beginner's Guide For DSA"
},
{
"code": null,
"e": 16480,
"s": 16440,
"text": "Find two numbers from their sum and XOR"
},
{
"code": null,
"e": 16539,
"s": 16480,
"text": "C++: Methods of code shortening in competitive programming"
},
{
"code": null,
"e": 16569,
"s": 16539,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 16612,
"s": 16569,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 16672,
"s": 16612,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 16687,
"s": 16672,
"text": "C++ Data Types"
}
] |
How does concatenation operator work on list in Python?
|
The concatenation operator creates a new list in Python using the initial lists in the order they were added in. This is not an inplace operation.
list1 = [1, 2, 3]
list2 = ['a', 'b']
list3 = list1 + list2
print(list3)
This will give the output −
[1, 2, 3, 'a', 'b']
There are other ways to concatenate 2 lists. Easiest is to use the extend function, if you want to extend the list in place.
list1 = [1, 2, 3]
list2 = ['a', 'b']
list1.extend(list2)
print(list1)
This will give the output −
[1, 2, 3, 'a', 'b']
You can also use unpacking operator * to create list from 2 lists. This can be used only in Python 3.5+.
list1 = [1, 2, 3]
list2 = ['a', 'b']
list3 = [*list1, *list2]
print(list3)
This will give the output −
[1, 2, 3, 'a', 'b']
|
[
{
"code": null,
"e": 1335,
"s": 1187,
"text": "The concatenation operator creates a new list in Python using the initial lists in the order they were added in. This is not an inplace operation. "
},
{
"code": null,
"e": 1407,
"s": 1335,
"text": "list1 = [1, 2, 3]\nlist2 = ['a', 'b']\nlist3 = list1 + list2\nprint(list3)"
},
{
"code": null,
"e": 1435,
"s": 1407,
"text": "This will give the output −"
},
{
"code": null,
"e": 1455,
"s": 1435,
"text": "[1, 2, 3, 'a', 'b']"
},
{
"code": null,
"e": 1581,
"s": 1455,
"text": "There are other ways to concatenate 2 lists. Easiest is to use the extend function, if you want to extend the list in place. "
},
{
"code": null,
"e": 1651,
"s": 1581,
"text": "list1 = [1, 2, 3]\nlist2 = ['a', 'b']\nlist1.extend(list2)\nprint(list1)"
},
{
"code": null,
"e": 1679,
"s": 1651,
"text": "This will give the output −"
},
{
"code": null,
"e": 1699,
"s": 1679,
"text": "[1, 2, 3, 'a', 'b']"
},
{
"code": null,
"e": 1804,
"s": 1699,
"text": "You can also use unpacking operator * to create list from 2 lists. This can be used only in Python 3.5+."
},
{
"code": null,
"e": 1879,
"s": 1804,
"text": "list1 = [1, 2, 3]\nlist2 = ['a', 'b']\nlist3 = [*list1, *list2]\nprint(list3)"
},
{
"code": null,
"e": 1907,
"s": 1879,
"text": "This will give the output −"
},
{
"code": null,
"e": 1927,
"s": 1907,
"text": "[1, 2, 3, 'a', 'b']"
}
] |
Version and Release Management in Software Engineering
|
18 Jan, 2021
The process involved in version and release management are concerned with identifying and keeping track of the versions of a system. Versions managers devise procedures to ensure that versions of a system may be retrieved when required and are not accidentally changed by the development team. For products, version managers work with marketing staff and for custom systems with customers, to plan when new releases of a system should be created not distributed for deployment.
A system instance is an instance of a system which can be different from other instances in some way. There is a chance in which versions of the system may have different functionality, enhanced performance or repaired software faults. Some versions may be functionally equivalent but designed for different hardware or software configuration. Versions with only small differences are sometimes called variants.
A system release may be a version that’s distributed to customers. Each system release should either include new functionality or should be intended for a special hardware platform. There are normally many more versions of a system than release. Versions are created with an organization for internal development or testing and are not intended for release to customers.
Version Identification :To create a specific version of a system, you’ve got to specify the versions of the system components that ought to be included in it. In a large software system, there are hundreds to software components, each of which may exist in several different versions.
There must therefore be an unambiguous way to identify each component version to ensure that the right components are included in the system. Three basic techniques are used for components version identification :
Version Numbering :In version numbering scheme, a version number is added to the components or system name. If the first version is called 1.0, subsequent versions are 1.1, 1.2 and so on. At some stage, a new release is created (release 2.0) and process start again at version 2.1.The scheme is linear, based on the assumption that system versions are created in sequence. Most version management tools such as RCS and CVS support this approach to version identification.
Attribute Based Identification :If each version is identified by a unique set of attributes, it is easy to add new versions, that are derived from any of existing versions. These are identified using unique set of attribute values. They share most of those values with their parent version so relationships between versions are maintained. You can retrieve specific versions by specifying attribute values required. Functions on attributes support queries like ‘the last created version’ or ‘the version created between given dates’. Attribute-based identification may be implemented directly by version management system, with component attributes maintained in a system database. Alternatively, attribute identification system may be built as a layer on top of a hidden version-numbering scheme.
Change Oriented Identification :Each component is known as as in attribute-based identification but is additionally related to one or more change requests. That is, it is assumed that each version of component has been created in response to one or more change requests. Component version is identified by set of change requests that apply to components.
Software Engineering
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Jan, 2021"
},
{
"code": null,
"e": 506,
"s": 28,
"text": "The process involved in version and release management are concerned with identifying and keeping track of the versions of a system. Versions managers devise procedures to ensure that versions of a system may be retrieved when required and are not accidentally changed by the development team. For products, version managers work with marketing staff and for custom systems with customers, to plan when new releases of a system should be created not distributed for deployment."
},
{
"code": null,
"e": 918,
"s": 506,
"text": "A system instance is an instance of a system which can be different from other instances in some way. There is a chance in which versions of the system may have different functionality, enhanced performance or repaired software faults. Some versions may be functionally equivalent but designed for different hardware or software configuration. Versions with only small differences are sometimes called variants."
},
{
"code": null,
"e": 1289,
"s": 918,
"text": "A system release may be a version that’s distributed to customers. Each system release should either include new functionality or should be intended for a special hardware platform. There are normally many more versions of a system than release. Versions are created with an organization for internal development or testing and are not intended for release to customers."
},
{
"code": null,
"e": 1574,
"s": 1289,
"text": "Version Identification :To create a specific version of a system, you’ve got to specify the versions of the system components that ought to be included in it. In a large software system, there are hundreds to software components, each of which may exist in several different versions."
},
{
"code": null,
"e": 1788,
"s": 1574,
"text": "There must therefore be an unambiguous way to identify each component version to ensure that the right components are included in the system. Three basic techniques are used for components version identification :"
},
{
"code": null,
"e": 2260,
"s": 1788,
"text": "Version Numbering :In version numbering scheme, a version number is added to the components or system name. If the first version is called 1.0, subsequent versions are 1.1, 1.2 and so on. At some stage, a new release is created (release 2.0) and process start again at version 2.1.The scheme is linear, based on the assumption that system versions are created in sequence. Most version management tools such as RCS and CVS support this approach to version identification."
},
{
"code": null,
"e": 3058,
"s": 2260,
"text": "Attribute Based Identification :If each version is identified by a unique set of attributes, it is easy to add new versions, that are derived from any of existing versions. These are identified using unique set of attribute values. They share most of those values with their parent version so relationships between versions are maintained. You can retrieve specific versions by specifying attribute values required. Functions on attributes support queries like ‘the last created version’ or ‘the version created between given dates’. Attribute-based identification may be implemented directly by version management system, with component attributes maintained in a system database. Alternatively, attribute identification system may be built as a layer on top of a hidden version-numbering scheme."
},
{
"code": null,
"e": 3413,
"s": 3058,
"text": "Change Oriented Identification :Each component is known as as in attribute-based identification but is additionally related to one or more change requests. That is, it is assumed that each version of component has been created in response to one or more change requests. Component version is identified by set of change requests that apply to components."
},
{
"code": null,
"e": 3434,
"s": 3413,
"text": "Software Engineering"
}
] |
How to convert byte array to string in C#?
|
In .Net, every string has a character set and encoding. A character encoding tells the computer how to interpret raw zeroes and ones into real characters. It usually does this by pairing numbers with characters. Actually, it is the process of transforming a set of Unicode characters into a sequence of bytes.
We can use Encoding.GetString Method (Byte[]) to decodes all the bytes in the specified byte array into a string. Several other decoding schemes are also available in Encoding class such as UTF8, Unicode, UTF32, ASCII etc. The Encoding class is available as part of System.Text namespace.
string result = Encoding.Default.GetString(byteArray);
Live Demo
using System;
using System.Text;
namespace DemoApplication {
public class Program {
static void Main(string[] args) {
byte[] byteArray = Encoding.Default.GetBytes("Hello World");
Console.WriteLine($"Byte Array is: {string.Join(" ", byteArray)}");
string str = Encoding.Default.GetString(byteArray);
Console.WriteLine($"String is: {str}");
Console.ReadLine();
}
}
}
The output of the above code is
Byte Array is: 72 101 108 108 111 32 87 111 114 108 100
String is: Hello World
It is important to note that we should use the same encoding for both directions. For example, if the byte array is encoded with ASCII and we are trying to get the string using UTF32, we won’t get the desired string.
Live Demo
using System;
using System.Text;
namespace DemoApplication {
public class Program {
static void Main(string[] args) {
byte[] byteArray = Encoding.ASCII.GetBytes("Hello World");
Console.WriteLine($"Byte Array is: {string.Join(" ", byteArray)}");
string str = Encoding.UTF32.GetString(byteArray);
Console.WriteLine($"String is: {str}");
Console.ReadLine();
}
}
}
The output of the above code is
Byte Array is: 72 101 108 108 111 32 87 111 114 108 100
String is: ???
|
[
{
"code": null,
"e": 1497,
"s": 1187,
"text": "In .Net, every string has a character set and encoding. A character encoding tells the computer how to interpret raw zeroes and ones into real characters. It usually does this by pairing numbers with characters. Actually, it is the process of transforming a set of Unicode characters into a sequence of bytes."
},
{
"code": null,
"e": 1786,
"s": 1497,
"text": "We can use Encoding.GetString Method (Byte[]) to decodes all the bytes in the specified byte array into a string. Several other decoding schemes are also available in Encoding class such as UTF8, Unicode, UTF32, ASCII etc. The Encoding class is available as part of System.Text namespace."
},
{
"code": null,
"e": 1841,
"s": 1786,
"text": "string result = Encoding.Default.GetString(byteArray);"
},
{
"code": null,
"e": 1852,
"s": 1841,
"text": " Live Demo"
},
{
"code": null,
"e": 2280,
"s": 1852,
"text": "using System;\nusing System.Text;\nnamespace DemoApplication {\n public class Program {\n static void Main(string[] args) {\n byte[] byteArray = Encoding.Default.GetBytes(\"Hello World\");\n Console.WriteLine($\"Byte Array is: {string.Join(\" \", byteArray)}\");\n string str = Encoding.Default.GetString(byteArray);\n Console.WriteLine($\"String is: {str}\");\n Console.ReadLine();\n }\n }\n}"
},
{
"code": null,
"e": 2312,
"s": 2280,
"text": "The output of the above code is"
},
{
"code": null,
"e": 2391,
"s": 2312,
"text": "Byte Array is: 72 101 108 108 111 32 87 111 114 108 100\nString is: Hello World"
},
{
"code": null,
"e": 2608,
"s": 2391,
"text": "It is important to note that we should use the same encoding for both directions. For example, if the byte array is encoded with ASCII and we are trying to get the string using UTF32, we won’t get the desired string."
},
{
"code": null,
"e": 2619,
"s": 2608,
"text": " Live Demo"
},
{
"code": null,
"e": 3043,
"s": 2619,
"text": "using System;\nusing System.Text;\nnamespace DemoApplication {\n public class Program {\n static void Main(string[] args) {\n byte[] byteArray = Encoding.ASCII.GetBytes(\"Hello World\");\n Console.WriteLine($\"Byte Array is: {string.Join(\" \", byteArray)}\");\n string str = Encoding.UTF32.GetString(byteArray);\n Console.WriteLine($\"String is: {str}\");\n Console.ReadLine();\n }\n }\n}"
},
{
"code": null,
"e": 3075,
"s": 3043,
"text": "The output of the above code is"
},
{
"code": null,
"e": 3146,
"s": 3075,
"text": "Byte Array is: 72 101 108 108 111 32 87 111 114 108 100\nString is: ???"
}
] |
Map remove() Method in Java with Examples
|
27 Aug, 2021
This method is used to remove the mapping for a key from this map if it is present in the map.
Syntax:
V remove(Object key)
Parameters: This method has the only argument key, whose mapping is to be removed from the map.Returns: This method returns the value to which this map previously associated the key, or null if the map contained no mapping for the key.Below programs show the implementation of int remove() method.Program 1:
Java
// Java code to show the implementation of// remove method in Map interfaceimport java.util.*;public class GfG { // Driver code public static void main(String[] args) { // Initializing a Map of type HashMap Map<Integer, String> map = new HashMap<>(); map.put(1, "One"); map.put(3, "Three"); map.put(5, "Five"); map.put(7, "Seven"); map.put(9, "Nine"); System.out.println(map); map.remove(3); System.out.println(map); // If it doesn't exists, returns // null and does not affects the map map.remove(2); System.out.println(map); }}
{1=One, 3=Three, 5=Five, 7=Seven, 9=Nine}
{1=One, 5=Five, 7=Seven, 9=Nine}
{1=One, 5=Five, 7=Seven, 9=Nine}
Program 2: Below is the code to show implementation of put().
Java
// Java code to show the implementation of// remove method in Map interfaceimport java.util.*;public class GfG { // Driver code public static void main(String[] args) { // Initializing a Map of type HashMap Map<String, String> map = new HashMap<>(); map.put("1", "One"); map.put("3", "Three"); map.put("5", "Five"); map.put("7", "Seven"); map.put("9", "Nine"); System.out.println(map); map.remove("3"); System.out.println(map); }}
{1=One, 3=Three, 5=Five, 7=Seven, 9=Nine}
{1=One, 5=Five, 7=Seven, 9=Nine}
Reference: Oracle Docs
sagar0719kumar
Java - util package
Java-Collections
Java-Functions
java-map
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Aug, 2021"
},
{
"code": null,
"e": 125,
"s": 28,
"text": "This method is used to remove the mapping for a key from this map if it is present in the map. "
},
{
"code": null,
"e": 135,
"s": 125,
"text": "Syntax: "
},
{
"code": null,
"e": 156,
"s": 135,
"text": "V remove(Object key)"
},
{
"code": null,
"e": 465,
"s": 156,
"text": "Parameters: This method has the only argument key, whose mapping is to be removed from the map.Returns: This method returns the value to which this map previously associated the key, or null if the map contained no mapping for the key.Below programs show the implementation of int remove() method.Program 1: "
},
{
"code": null,
"e": 470,
"s": 465,
"text": "Java"
},
{
"code": "// Java code to show the implementation of// remove method in Map interfaceimport java.util.*;public class GfG { // Driver code public static void main(String[] args) { // Initializing a Map of type HashMap Map<Integer, String> map = new HashMap<>(); map.put(1, \"One\"); map.put(3, \"Three\"); map.put(5, \"Five\"); map.put(7, \"Seven\"); map.put(9, \"Nine\"); System.out.println(map); map.remove(3); System.out.println(map); // If it doesn't exists, returns // null and does not affects the map map.remove(2); System.out.println(map); }}",
"e": 1116,
"s": 470,
"text": null
},
{
"code": null,
"e": 1224,
"s": 1116,
"text": "{1=One, 3=Three, 5=Five, 7=Seven, 9=Nine}\n{1=One, 5=Five, 7=Seven, 9=Nine}\n{1=One, 5=Five, 7=Seven, 9=Nine}"
},
{
"code": null,
"e": 1289,
"s": 1226,
"text": "Program 2: Below is the code to show implementation of put(). "
},
{
"code": null,
"e": 1294,
"s": 1289,
"text": "Java"
},
{
"code": "// Java code to show the implementation of// remove method in Map interfaceimport java.util.*;public class GfG { // Driver code public static void main(String[] args) { // Initializing a Map of type HashMap Map<String, String> map = new HashMap<>(); map.put(\"1\", \"One\"); map.put(\"3\", \"Three\"); map.put(\"5\", \"Five\"); map.put(\"7\", \"Seven\"); map.put(\"9\", \"Nine\"); System.out.println(map); map.remove(\"3\"); System.out.println(map); }}",
"e": 1811,
"s": 1294,
"text": null
},
{
"code": null,
"e": 1886,
"s": 1811,
"text": "{1=One, 3=Three, 5=Five, 7=Seven, 9=Nine}\n{1=One, 5=Five, 7=Seven, 9=Nine}"
},
{
"code": null,
"e": 1911,
"s": 1888,
"text": "Reference: Oracle Docs"
},
{
"code": null,
"e": 1926,
"s": 1911,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 1946,
"s": 1926,
"text": "Java - util package"
},
{
"code": null,
"e": 1963,
"s": 1946,
"text": "Java-Collections"
},
{
"code": null,
"e": 1978,
"s": 1963,
"text": "Java-Functions"
},
{
"code": null,
"e": 1987,
"s": 1978,
"text": "java-map"
},
{
"code": null,
"e": 1992,
"s": 1987,
"text": "Java"
},
{
"code": null,
"e": 1997,
"s": 1992,
"text": "Java"
},
{
"code": null,
"e": 2014,
"s": 1997,
"text": "Java-Collections"
},
{
"code": null,
"e": 2112,
"s": 2014,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2127,
"s": 2112,
"text": "Stream In Java"
},
{
"code": null,
"e": 2148,
"s": 2127,
"text": "Introduction to Java"
},
{
"code": null,
"e": 2169,
"s": 2148,
"text": "Constructors in Java"
},
{
"code": null,
"e": 2188,
"s": 2169,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 2205,
"s": 2188,
"text": "Generics in Java"
},
{
"code": null,
"e": 2235,
"s": 2205,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 2261,
"s": 2235,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 2277,
"s": 2261,
"text": "Strings in Java"
},
{
"code": null,
"e": 2314,
"s": 2277,
"text": "Differences between JDK, JRE and JVM"
}
] |
Python | Minimum value keys in Dictionary
|
11 Jul, 2019
Many times, we may have problem in which we require to find not just the value, but the corresponding keys to the minimum value in the entire dictionary. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using min() + list comprehension + values()The combination of above functions can be used to perform this particular task. In this, minimum value is extracted using the min function, while values of dictionary is extracted using values(). The list comprehension is used to iterate through the dictionary for matching keys with min value.
# Python3 code to demonstrate working of# Finding min value keys in dictionary# Using min() + list comprehension + values() # initializing dictionarytest_dict = {'Gfg' : 11, 'for' : 2, 'CS' : 11, 'geeks':8, 'nerd':2} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # Using min() + list comprehension + values()# Finding min value keys in dictionarytemp = min(test_dict.values())res = [key for key in test_dict if test_dict[key] == temp] # printing result print("Keys with minimum values are : " + str(res))
The original dictionary is : {‘nerd’: 2, ‘Gfg’: 11, ‘geeks’: 8, ‘CS’: 11, ‘for’: 2}Keys with minimum values are : [‘nerd’, ‘for’]
Method #2 : Using all() + list comprehensionThis task can also be performed using list comprehension and all function. In this, we take all the elements values, using all function that are greater than values with keys and return the keys with smallest values using list comprehension.
# Python3 code to demonstrate working of# Finding min value keys in dictionary# Using all() + list comprehension # initializing dictionarytest_dict = {'Gfg' : 1, 'for' : 2, 'CS' : 1} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # Using all() + list comprehension# Finding min value keys in dictionaryres = [key for key in test_dict if all(test_dict[temp] >= test_dict[key] for temp in test_dict)] # printing result print("Keys with minimum values are : " + str(res))
The original dictionary is : {‘Gfg’: 1, ‘CS’: 1, ‘for’: 2}Keys with minimum values are : [‘Gfg’, ‘CS’]
Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n11 Jul, 2019"
},
{
"code": null,
"e": 271,
"s": 53,
"text": "Many times, we may have problem in which we require to find not just the value, but the corresponding keys to the minimum value in the entire dictionary. Let’s discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 621,
"s": 271,
"text": "Method #1 : Using min() + list comprehension + values()The combination of above functions can be used to perform this particular task. In this, minimum value is extracted using the min function, while values of dictionary is extracted using values(). The list comprehension is used to iterate through the dictionary for matching keys with min value."
},
{
"code": "# Python3 code to demonstrate working of# Finding min value keys in dictionary# Using min() + list comprehension + values() # initializing dictionarytest_dict = {'Gfg' : 11, 'for' : 2, 'CS' : 11, 'geeks':8, 'nerd':2} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # Using min() + list comprehension + values()# Finding min value keys in dictionarytemp = min(test_dict.values())res = [key for key in test_dict if test_dict[key] == temp] # printing result print(\"Keys with minimum values are : \" + str(res))",
"e": 1170,
"s": 621,
"text": null
},
{
"code": null,
"e": 1300,
"s": 1170,
"text": "The original dictionary is : {‘nerd’: 2, ‘Gfg’: 11, ‘geeks’: 8, ‘CS’: 11, ‘for’: 2}Keys with minimum values are : [‘nerd’, ‘for’]"
},
{
"code": null,
"e": 1588,
"s": 1302,
"text": "Method #2 : Using all() + list comprehensionThis task can also be performed using list comprehension and all function. In this, we take all the elements values, using all function that are greater than values with keys and return the keys with smallest values using list comprehension."
},
{
"code": "# Python3 code to demonstrate working of# Finding min value keys in dictionary# Using all() + list comprehension # initializing dictionarytest_dict = {'Gfg' : 1, 'for' : 2, 'CS' : 1} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # Using all() + list comprehension# Finding min value keys in dictionaryres = [key for key in test_dict if all(test_dict[temp] >= test_dict[key] for temp in test_dict)] # printing result print(\"Keys with minimum values are : \" + str(res))",
"e": 2116,
"s": 1588,
"text": null
},
{
"code": null,
"e": 2219,
"s": 2116,
"text": "The original dictionary is : {‘Gfg’: 1, ‘CS’: 1, ‘for’: 2}Keys with minimum values are : [‘Gfg’, ‘CS’]"
},
{
"code": null,
"e": 2246,
"s": 2219,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 2253,
"s": 2246,
"text": "Python"
},
{
"code": null,
"e": 2269,
"s": 2253,
"text": "Python Programs"
}
] |
Equivalence Partitioning Method
|
24 Nov, 2021
Equivalence Partitioning Method is also known as Equivalence class partitioning (ECP). It is a software testing technique or black-box testing that divides input domain into classes of data, and with the help of these classes of data, test cases can be derived. An ideal test case identifies class of error that might require many arbitrary test cases to be executed before general error is observed.
In equivalence partitioning, equivalence classes are evaluated for given input conditions. Whenever any input is given, then type of input condition is checked, then for this input conditions, Equivalence class represents or describes set of valid or invalid states.
Guidelines for Equivalence Partitioning :
If the range condition is given as an input, then one valid and two invalid equivalence classes are defined.
If a specific value is given as input, then one valid and two invalid equivalence classes are defined.
If a member of set is given as an input, then one valid and one invalid equivalence class is defined.
If Boolean no. is given as an input condition, then one valid and one invalid equivalence class is defined.
Example-1: Let us consider an example of any college admission process. There is a college that gives admissions to students based upon their percentage.
Consider percentage field that will accept percentage only between 50 to 90 %, more and even less than not be accepted, and application will redirect user to an error page. If percentage entered by user is less than 50 %or more than 90 %, that equivalence partitioning method will show an invalid percentage. If percentage entered is between 50 to 90 %, then equivalence partitioning method will show valid percentage.
Example 2: Let us consider an example of an online shopping site. In this site, each of products has a specific product ID and product name. We can search for product either by using name of product or by product ID. Here, we consider search field that accepts only valid product ID or product name.
Let us consider a set of products with product IDs and users wants to search for Mobiles. Below is a table of some products with their product Id.
If the product ID entered by user is invalid then application will redirect customer or user to error page. If product ID entered by user is valid i.e. 45 for mobile, then equivalence partitioning method will show a valid product ID.
Example-3 : Let us consider an example of software application. There is function of software application that accepts only particular number of digits, not even greater or less than that particular number.
Consider an OTP number that contains only 6 digit number, greater and even less than six digits will not be accepted, and the application will redirect customer or user to error page. If password entered by user is less or more than six characters, that equivalence partitioning method will show an invalid OTP. If password entered is exactly six characters, then equivalence partitioning method will show valid OTP.
yaaseenn
rishitchaudhary
Software Testing
Software Engineering
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Unit Testing | Software Testing
Software Requirement Specification (SRS) Format
Difference between Spring and Spring Boot
Software Engineering | Requirements Engineering Process
Software Testing Life Cycle (STLC)
Difference between IAAS, PAAS and SAAS
Software Engineering | SDLC V-Model
Software Engineering | Iterative Waterfall Model
What is DFD(Data Flow Diagram)?
Software Engineering | Quality Characteristics of a good SRS
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n24 Nov, 2021"
},
{
"code": null,
"e": 454,
"s": 52,
"text": "Equivalence Partitioning Method is also known as Equivalence class partitioning (ECP). It is a software testing technique or black-box testing that divides input domain into classes of data, and with the help of these classes of data, test cases can be derived. An ideal test case identifies class of error that might require many arbitrary test cases to be executed before general error is observed. "
},
{
"code": null,
"e": 722,
"s": 454,
"text": "In equivalence partitioning, equivalence classes are evaluated for given input conditions. Whenever any input is given, then type of input condition is checked, then for this input conditions, Equivalence class represents or describes set of valid or invalid states. "
},
{
"code": null,
"e": 765,
"s": 722,
"text": "Guidelines for Equivalence Partitioning : "
},
{
"code": null,
"e": 875,
"s": 765,
"text": "If the range condition is given as an input, then one valid and two invalid equivalence classes are defined. "
},
{
"code": null,
"e": 979,
"s": 875,
"text": "If a specific value is given as input, then one valid and two invalid equivalence classes are defined. "
},
{
"code": null,
"e": 1082,
"s": 979,
"text": "If a member of set is given as an input, then one valid and one invalid equivalence class is defined. "
},
{
"code": null,
"e": 1191,
"s": 1082,
"text": "If Boolean no. is given as an input condition, then one valid and one invalid equivalence class is defined. "
},
{
"code": null,
"e": 1346,
"s": 1191,
"text": "Example-1: Let us consider an example of any college admission process. There is a college that gives admissions to students based upon their percentage. "
},
{
"code": null,
"e": 1767,
"s": 1346,
"text": "Consider percentage field that will accept percentage only between 50 to 90 %, more and even less than not be accepted, and application will redirect user to an error page. If percentage entered by user is less than 50 %or more than 90 %, that equivalence partitioning method will show an invalid percentage. If percentage entered is between 50 to 90 %, then equivalence partitioning method will show valid percentage. "
},
{
"code": null,
"e": 2068,
"s": 1767,
"text": "Example 2: Let us consider an example of an online shopping site. In this site, each of products has a specific product ID and product name. We can search for product either by using name of product or by product ID. Here, we consider search field that accepts only valid product ID or product name. "
},
{
"code": null,
"e": 2216,
"s": 2068,
"text": "Let us consider a set of products with product IDs and users wants to search for Mobiles. Below is a table of some products with their product Id. "
},
{
"code": null,
"e": 2451,
"s": 2216,
"text": "If the product ID entered by user is invalid then application will redirect customer or user to error page. If product ID entered by user is valid i.e. 45 for mobile, then equivalence partitioning method will show a valid product ID. "
},
{
"code": null,
"e": 2659,
"s": 2451,
"text": "Example-3 : Let us consider an example of software application. There is function of software application that accepts only particular number of digits, not even greater or less than that particular number. "
},
{
"code": null,
"e": 3077,
"s": 2659,
"text": "Consider an OTP number that contains only 6 digit number, greater and even less than six digits will not be accepted, and the application will redirect customer or user to error page. If password entered by user is less or more than six characters, that equivalence partitioning method will show an invalid OTP. If password entered is exactly six characters, then equivalence partitioning method will show valid OTP. "
},
{
"code": null,
"e": 3088,
"s": 3079,
"text": "yaaseenn"
},
{
"code": null,
"e": 3104,
"s": 3088,
"text": "rishitchaudhary"
},
{
"code": null,
"e": 3121,
"s": 3104,
"text": "Software Testing"
},
{
"code": null,
"e": 3142,
"s": 3121,
"text": "Software Engineering"
},
{
"code": null,
"e": 3240,
"s": 3142,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3272,
"s": 3240,
"text": "Unit Testing | Software Testing"
},
{
"code": null,
"e": 3320,
"s": 3272,
"text": "Software Requirement Specification (SRS) Format"
},
{
"code": null,
"e": 3362,
"s": 3320,
"text": "Difference between Spring and Spring Boot"
},
{
"code": null,
"e": 3418,
"s": 3362,
"text": "Software Engineering | Requirements Engineering Process"
},
{
"code": null,
"e": 3453,
"s": 3418,
"text": "Software Testing Life Cycle (STLC)"
},
{
"code": null,
"e": 3492,
"s": 3453,
"text": "Difference between IAAS, PAAS and SAAS"
},
{
"code": null,
"e": 3528,
"s": 3492,
"text": "Software Engineering | SDLC V-Model"
},
{
"code": null,
"e": 3577,
"s": 3528,
"text": "Software Engineering | Iterative Waterfall Model"
},
{
"code": null,
"e": 3609,
"s": 3577,
"text": "What is DFD(Data Flow Diagram)?"
}
] |
Replace every character of a string by a different character
|
27 May, 2022
Given a string str of lowercase alphabets only. The task is to replace every character by some new character. The new character belongs to (small case only) Replacement of str[i] is determined by:
str[i] = Character obtained after traversing ascii(str[i]) no. of characters in ‘a-z’ repeatedly after str[i].
Examples:
Input: str = “geeksforgeeks” Output: fbbnddvbfbbndIn the above case str = “geeksforgeeks”, the ASCII value of ‘g’ is 103 therefore ‘g’ has been replaced by moving 103 times from ‘g’ in the desired range i.e., a-z. Hence, character ‘g’ is replaced by ‘f’. Similarly, the complete string “geeksforgeeks” becomes “fbbnddvbfbbnd”.Input: str = “science” Output: dxjbtxb
Approach:
Traverse the string.For every i, find the character that needs to be replaced with str[i].Replace str[i] with that character.
Traverse the string.
For every i, find the character that needs to be replaced with str[i].
Replace str[i] with that character.
Below is the implementation of above approach:
C++
Java
Python 3
C#
Javascript
// C++ program for Replace every character of a// string by a different character#include <bits/stdc++.h>using namespace std; // Function to manipulate the stringvoid manipulateString(string &str){ // looping through each character of string for (int i = 0; i < str.length(); i++) { // storing integer ASCII value of // the character in 'asc' int asc = str[i]; // 'rem' contains coded value which // needs to be rounded to 26 int rem = asc - (26 - (str[i] - 'a')); // converting 'rem' character in range // 0-25 and storing in 'm' int m = rem % 26; // printing character by adding ascii value of 'a' // so that it becomes in the desired range i.e. a-z str[i] = (char)(m + 'a'); }} // Driver codeint main(){ // Declaring str as 'geeksforgeeks' string str = "geeksforgeeks"; manipulateString(str); cout << str; return 0;}
// Java program for Replace every character of a// string by a different characterpublic class GFG { //Function to manipulate the string static void manipulateString(String str) { char[] str1 = str.toCharArray(); // looping through each character of string for (int i = 0; i < str.length(); i++) { // storing integer ASCII value of // the character in 'asc' int asc = str1[i]; // 'rem' contains coded value which // needs to be rounded to 26 int rem = asc - (26 - (str1[i] - 97)); // converting 'rem' character in range // 0-25 and storing in 'm' int m = rem % 26; // printing character by adding ascii value of 'a' // so that it becomes in the desired range i.e. a-z str1[i] = (char)(m + 'a'); } String str2 = String.valueOf(str1); System.out.println(str2); } //Driver code public static void main(String[] args) { // Declaring str as 'geeksforgeeks' String str = "geeksforgeeks"; manipulateString(str); }}
# Python 3 program for Replace every character of a# string by a different character # Function to manipulate the stringdef manipulateString(str) : # looping through each character of string for i in range(len(str)) : # storing integer ASCII value of # the character in 'asc' asc = ord(str[i]) # 'rem' contains coded value which # needs to be rounded to 26 rem = asc - (26 - (ord(str[i]) - ord('a'))) # converting 'rem' character in range # 0-25 and storing in 'm' m = rem % 26 #printing character by adding ascii value of 'a' # so that it becomes in the desired range i str[i] = chr(m + ord('a')) # join method join all individual # characters to form a string print(''.join(str)) # Driver code if __name__ == "__main__" : str = "geeksforgeeks" # convert string into list of characters str = list(str) # Function calling manipulateString(str) # This code is contributed by ANKITRAI1
// C# program for Replace every character of a// string by a different characterusing System;public class GFG { //Function to manipulate the string static void manipulateString(String str) { char[] str1 = str.ToCharArray(); // looping through each character of string for (int i = 0; i < str.Length; i++) { // storing integer ASCII value of // the character in 'asc' int asc = str1[i]; // 'rem' contains coded value which // needs to be rounded to 26 int rem = asc - (26 - (str1[i] - 97)); // converting 'rem' character in range // 0-25 and storing in 'm' int m = rem % 26; // printing character by adding ascii value of 'a' // so that it becomes in the desired range i.e. a-z str1[i] = (char)(m + 'a'); } String str2 = String.Join("",str1); Console.WriteLine(str2); } //Driver code public static void Main() { // Declaring str as 'geeksforgeeks' String str = "geeksforgeeks"; manipulateString(str); }}// This code is contributed by PrinciRaj1992
<script> // Javascript program for Replace every character of a// string by a different character // Function to manipulate the stringfunction manipulateString(str){ // looping through each character of string for (var i = 0; i < str.length; i++) { // storing integer ASCII value of // the character in 'asc' var asc = str[i]; // 'rem' contains coded value which // needs to be rounded to 26 var rem = asc.charCodeAt(0) - (26 - (str[i].charCodeAt(0) - 'a'.charCodeAt(0))); // converting 'rem' character in range // 0-25 and storing in 'm' var m = (rem % 26); // printing character by adding ascii value of 'a' // so that it becomes in the desired range i.e. a-z str[i] = String.fromCharCode(m + 'a'.charCodeAt(0)); } return str;} // Driver code// Declaring str as 'geeksforgeeks'var str = "geeksforgeeks";document.write(manipulateString(str.split('')).join('')); </script>
fbbnddvbfbbnd
Time Complexity: O(N), as we are using a loop to traverse N times so it will cost us O(N) time.Auxiliary Space: O(1), as we are not using any extra space.
ankthon
ukasp
princiraj1992
noob2000
simmytarika5
saurabh1990aror
rohitsingh07052
ASCII
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python program to check if a string is palindrome or not
Longest Palindromic Substring | Set 1
Length of the longest substring without repeating characters
Convert string to char array in C++
Top 50 String Coding Problems for Interviews
Check whether two strings are anagram of each other
What is Data Structure: Types, Classifications and Applications
Reverse words in a given string
Print all the duplicates in the input string
Reverse string in Python (6 different ways)
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n27 May, 2022"
},
{
"code": null,
"e": 252,
"s": 54,
"text": "Given a string str of lowercase alphabets only. The task is to replace every character by some new character. The new character belongs to (small case only) Replacement of str[i] is determined by: "
},
{
"code": null,
"e": 363,
"s": 252,
"text": "str[i] = Character obtained after traversing ascii(str[i]) no. of characters in ‘a-z’ repeatedly after str[i]."
},
{
"code": null,
"e": 375,
"s": 363,
"text": "Examples: "
},
{
"code": null,
"e": 740,
"s": 375,
"text": "Input: str = “geeksforgeeks” Output: fbbnddvbfbbndIn the above case str = “geeksforgeeks”, the ASCII value of ‘g’ is 103 therefore ‘g’ has been replaced by moving 103 times from ‘g’ in the desired range i.e., a-z. Hence, character ‘g’ is replaced by ‘f’. Similarly, the complete string “geeksforgeeks” becomes “fbbnddvbfbbnd”.Input: str = “science” Output: dxjbtxb"
},
{
"code": null,
"e": 754,
"s": 742,
"text": "Approach: "
},
{
"code": null,
"e": 880,
"s": 754,
"text": "Traverse the string.For every i, find the character that needs to be replaced with str[i].Replace str[i] with that character."
},
{
"code": null,
"e": 901,
"s": 880,
"text": "Traverse the string."
},
{
"code": null,
"e": 972,
"s": 901,
"text": "For every i, find the character that needs to be replaced with str[i]."
},
{
"code": null,
"e": 1008,
"s": 972,
"text": "Replace str[i] with that character."
},
{
"code": null,
"e": 1057,
"s": 1008,
"text": "Below is the implementation of above approach: "
},
{
"code": null,
"e": 1061,
"s": 1057,
"text": "C++"
},
{
"code": null,
"e": 1066,
"s": 1061,
"text": "Java"
},
{
"code": null,
"e": 1075,
"s": 1066,
"text": "Python 3"
},
{
"code": null,
"e": 1078,
"s": 1075,
"text": "C#"
},
{
"code": null,
"e": 1089,
"s": 1078,
"text": "Javascript"
},
{
"code": "// C++ program for Replace every character of a// string by a different character#include <bits/stdc++.h>using namespace std; // Function to manipulate the stringvoid manipulateString(string &str){ // looping through each character of string for (int i = 0; i < str.length(); i++) { // storing integer ASCII value of // the character in 'asc' int asc = str[i]; // 'rem' contains coded value which // needs to be rounded to 26 int rem = asc - (26 - (str[i] - 'a')); // converting 'rem' character in range // 0-25 and storing in 'm' int m = rem % 26; // printing character by adding ascii value of 'a' // so that it becomes in the desired range i.e. a-z str[i] = (char)(m + 'a'); }} // Driver codeint main(){ // Declaring str as 'geeksforgeeks' string str = \"geeksforgeeks\"; manipulateString(str); cout << str; return 0;}",
"e": 2026,
"s": 1089,
"text": null
},
{
"code": "// Java program for Replace every character of a// string by a different characterpublic class GFG { //Function to manipulate the string static void manipulateString(String str) { char[] str1 = str.toCharArray(); // looping through each character of string for (int i = 0; i < str.length(); i++) { // storing integer ASCII value of // the character in 'asc' int asc = str1[i]; // 'rem' contains coded value which // needs to be rounded to 26 int rem = asc - (26 - (str1[i] - 97)); // converting 'rem' character in range // 0-25 and storing in 'm' int m = rem % 26; // printing character by adding ascii value of 'a' // so that it becomes in the desired range i.e. a-z str1[i] = (char)(m + 'a'); } String str2 = String.valueOf(str1); System.out.println(str2); } //Driver code public static void main(String[] args) { // Declaring str as 'geeksforgeeks' String str = \"geeksforgeeks\"; manipulateString(str); }}",
"e": 3195,
"s": 2026,
"text": null
},
{
"code": "# Python 3 program for Replace every character of a# string by a different character # Function to manipulate the stringdef manipulateString(str) : # looping through each character of string for i in range(len(str)) : # storing integer ASCII value of # the character in 'asc' asc = ord(str[i]) # 'rem' contains coded value which # needs to be rounded to 26 rem = asc - (26 - (ord(str[i]) - ord('a'))) # converting 'rem' character in range # 0-25 and storing in 'm' m = rem % 26 #printing character by adding ascii value of 'a' # so that it becomes in the desired range i str[i] = chr(m + ord('a')) # join method join all individual # characters to form a string print(''.join(str)) # Driver code if __name__ == \"__main__\" : str = \"geeksforgeeks\" # convert string into list of characters str = list(str) # Function calling manipulateString(str) # This code is contributed by ANKITRAI1",
"e": 4216,
"s": 3195,
"text": null
},
{
"code": " // C# program for Replace every character of a// string by a different characterusing System;public class GFG { //Function to manipulate the string static void manipulateString(String str) { char[] str1 = str.ToCharArray(); // looping through each character of string for (int i = 0; i < str.Length; i++) { // storing integer ASCII value of // the character in 'asc' int asc = str1[i]; // 'rem' contains coded value which // needs to be rounded to 26 int rem = asc - (26 - (str1[i] - 97)); // converting 'rem' character in range // 0-25 and storing in 'm' int m = rem % 26; // printing character by adding ascii value of 'a' // so that it becomes in the desired range i.e. a-z str1[i] = (char)(m + 'a'); } String str2 = String.Join(\"\",str1); Console.WriteLine(str2); } //Driver code public static void Main() { // Declaring str as 'geeksforgeeks' String str = \"geeksforgeeks\"; manipulateString(str); }}// This code is contributed by PrinciRaj1992",
"e": 5443,
"s": 4216,
"text": null
},
{
"code": "<script> // Javascript program for Replace every character of a// string by a different character // Function to manipulate the stringfunction manipulateString(str){ // looping through each character of string for (var i = 0; i < str.length; i++) { // storing integer ASCII value of // the character in 'asc' var asc = str[i]; // 'rem' contains coded value which // needs to be rounded to 26 var rem = asc.charCodeAt(0) - (26 - (str[i].charCodeAt(0) - 'a'.charCodeAt(0))); // converting 'rem' character in range // 0-25 and storing in 'm' var m = (rem % 26); // printing character by adding ascii value of 'a' // so that it becomes in the desired range i.e. a-z str[i] = String.fromCharCode(m + 'a'.charCodeAt(0)); } return str;} // Driver code// Declaring str as 'geeksforgeeks'var str = \"geeksforgeeks\";document.write(manipulateString(str.split('')).join('')); </script>",
"e": 6418,
"s": 5443,
"text": null
},
{
"code": null,
"e": 6432,
"s": 6418,
"text": "fbbnddvbfbbnd"
},
{
"code": null,
"e": 6589,
"s": 6434,
"text": "Time Complexity: O(N), as we are using a loop to traverse N times so it will cost us O(N) time.Auxiliary Space: O(1), as we are not using any extra space."
},
{
"code": null,
"e": 6597,
"s": 6589,
"text": "ankthon"
},
{
"code": null,
"e": 6603,
"s": 6597,
"text": "ukasp"
},
{
"code": null,
"e": 6617,
"s": 6603,
"text": "princiraj1992"
},
{
"code": null,
"e": 6626,
"s": 6617,
"text": "noob2000"
},
{
"code": null,
"e": 6639,
"s": 6626,
"text": "simmytarika5"
},
{
"code": null,
"e": 6655,
"s": 6639,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 6671,
"s": 6655,
"text": "rohitsingh07052"
},
{
"code": null,
"e": 6677,
"s": 6671,
"text": "ASCII"
},
{
"code": null,
"e": 6685,
"s": 6677,
"text": "Strings"
},
{
"code": null,
"e": 6693,
"s": 6685,
"text": "Strings"
},
{
"code": null,
"e": 6791,
"s": 6693,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6848,
"s": 6791,
"text": "Python program to check if a string is palindrome or not"
},
{
"code": null,
"e": 6886,
"s": 6848,
"text": "Longest Palindromic Substring | Set 1"
},
{
"code": null,
"e": 6947,
"s": 6886,
"text": "Length of the longest substring without repeating characters"
},
{
"code": null,
"e": 6983,
"s": 6947,
"text": "Convert string to char array in C++"
},
{
"code": null,
"e": 7028,
"s": 6983,
"text": "Top 50 String Coding Problems for Interviews"
},
{
"code": null,
"e": 7080,
"s": 7028,
"text": "Check whether two strings are anagram of each other"
},
{
"code": null,
"e": 7144,
"s": 7080,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 7176,
"s": 7144,
"text": "Reverse words in a given string"
},
{
"code": null,
"e": 7221,
"s": 7176,
"text": "Print all the duplicates in the input string"
}
] |
Covariant Return Types in Java
|
03 Dec, 2021
As the ear hit eardrums “overriding” we quickly get to know that it can be done either virtue of different datatypes or arguments passed to a function what a programmer learned initially while learning polymorphism in java. Before JDK 5.0, it was not possible to override a method by changing the return type. When we override a parent class method, the name, argument types, and return type of the overriding method in child class has to be exactly the same as that of the parent class method. The overriding method was said to be invariant with respect to return type.
Java version 5.0 onwards it is possible to have different return types for an overriding method in the child class, but the child’s return type should be a subtype of the parent’s return type. The overriding method becomes variant with respect to return type.
The co-variant return type is based on the Liskov substitution principle.
Now geeks you must be wondering about why to use for which we will be listing down the advantages as follows:
It helps to avoid confusing type casts present in the class hierarchy and thus making the code readable, usable and maintainable.
We get the liberty to have more specific return types when overriding methods.
Help in preventing run-time ClassCastExceptions on returns
Note: If we swap return types of Base and Derived, then above program would not work. Please see this program for example.
Example Two classes used for return types
Java
// Java Program to Demonstrate Different Return Types// if Return Type in Overridden method is Sub-type // Class 1class A {} // Class 2class B extends A {} // Class 3// Helper class (Base class)class Base { // Method of this class of class1 return type A fun() { // Display message only System.out.println("Base fun()"); return new A(); }} // Class 4// Helper class extending above classclass Derived extends Base { // Method of this class of class1 return type B fun() { // Display message only System.out.println("Derived fun()"); return new B(); }} // Class 5// Main classpublic class GFG { // Main driver method public static void main(String args[]) { // Creating object of class3 type Base base = new Base(); // Calling method fun() over this object // inside main() method base.fun(); // Creating object of class4 type Derived derived = new Derived(); // Again calling method fun() over this object // inside main() method derived.fun(); }}
Output:
Base fun()
Derived fun()
This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
solankimayank
java-inheritance
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n03 Dec, 2021"
},
{
"code": null,
"e": 625,
"s": 52,
"text": "As the ear hit eardrums “overriding” we quickly get to know that it can be done either virtue of different datatypes or arguments passed to a function what a programmer learned initially while learning polymorphism in java. Before JDK 5.0, it was not possible to override a method by changing the return type. When we override a parent class method, the name, argument types, and return type of the overriding method in child class has to be exactly the same as that of the parent class method. The overriding method was said to be invariant with respect to return type. "
},
{
"code": null,
"e": 885,
"s": 625,
"text": "Java version 5.0 onwards it is possible to have different return types for an overriding method in the child class, but the child’s return type should be a subtype of the parent’s return type. The overriding method becomes variant with respect to return type."
},
{
"code": null,
"e": 959,
"s": 885,
"text": "The co-variant return type is based on the Liskov substitution principle."
},
{
"code": null,
"e": 1069,
"s": 959,
"text": "Now geeks you must be wondering about why to use for which we will be listing down the advantages as follows:"
},
{
"code": null,
"e": 1199,
"s": 1069,
"text": "It helps to avoid confusing type casts present in the class hierarchy and thus making the code readable, usable and maintainable."
},
{
"code": null,
"e": 1278,
"s": 1199,
"text": "We get the liberty to have more specific return types when overriding methods."
},
{
"code": null,
"e": 1337,
"s": 1278,
"text": "Help in preventing run-time ClassCastExceptions on returns"
},
{
"code": null,
"e": 1460,
"s": 1337,
"text": "Note: If we swap return types of Base and Derived, then above program would not work. Please see this program for example."
},
{
"code": null,
"e": 1502,
"s": 1460,
"text": "Example Two classes used for return types"
},
{
"code": null,
"e": 1507,
"s": 1502,
"text": "Java"
},
{
"code": "// Java Program to Demonstrate Different Return Types// if Return Type in Overridden method is Sub-type // Class 1class A {} // Class 2class B extends A {} // Class 3// Helper class (Base class)class Base { // Method of this class of class1 return type A fun() { // Display message only System.out.println(\"Base fun()\"); return new A(); }} // Class 4// Helper class extending above classclass Derived extends Base { // Method of this class of class1 return type B fun() { // Display message only System.out.println(\"Derived fun()\"); return new B(); }} // Class 5// Main classpublic class GFG { // Main driver method public static void main(String args[]) { // Creating object of class3 type Base base = new Base(); // Calling method fun() over this object // inside main() method base.fun(); // Creating object of class4 type Derived derived = new Derived(); // Again calling method fun() over this object // inside main() method derived.fun(); }}",
"e": 2612,
"s": 1507,
"text": null
},
{
"code": null,
"e": 2621,
"s": 2612,
"text": "Output: "
},
{
"code": null,
"e": 2646,
"s": 2621,
"text": "Base fun()\nDerived fun()"
},
{
"code": null,
"e": 3069,
"s": 2646,
"text": "This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 3083,
"s": 3069,
"text": "solankimayank"
},
{
"code": null,
"e": 3100,
"s": 3083,
"text": "java-inheritance"
},
{
"code": null,
"e": 3105,
"s": 3100,
"text": "Java"
},
{
"code": null,
"e": 3110,
"s": 3105,
"text": "Java"
}
] |
How to save a NumPy array to a text file?
|
18 Jun, 2021
Let us see how to save a numpy array to a text file.
Method 1: Using File handling Creating a text file using the in-built open() function and then converting the array into string and writing it into the text file using the write() function. Finally closing the file using close() function. Below are some programs of the this approach:
Example 1:
Python3
# Program to save a NumPy array to a text file # Importing required librariesimport numpy # Creating an arrayList = [1, 2, 3, 4, 5]Array = numpy.array(List) # Displaying the arrayprint('Array:\n', Array)file = open("file1.txt", "w+") # Saving the array in a text filecontent = str(Array)file.write(content)file.close() # Displaying the contents of the text filefile = open("file1.txt", "r")content = file.read() print("\nContent in file1.txt:\n", content)file.close()
Output:
Array:
[1 2 3 4 5]
Content in file1.txt:
[1 2 3 4 5]
Example 2:
Python3
# Program to save a NumPy array to a text file # Importing required librariesimport numpy # Creating 2D arrayList = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]Array = numpy.array(List) # Displaying the arrayprint('Array:\n', Array)file = open("file2.txt", "w+") # Saving the 2D array in a text filecontent = str(Array)file.write(content)file.close() # Displaying the contents of the text filefile = open("file2.txt", "r")content = file.read() print("\nContent in file2.txt:\n", content)file.close()
Output:
Array:
[[1 2 3]
[4 5 6]
[7 8 9]]
Content in file2.txt:
[[1 2 3]
[4 5 6]
[7 8 9]]
Method 2:
Using NumPy functions
After creating the array, the
numpy.savetxt()
function can be used to save the array into a text file. Below are some programs of this approach.
Example 1:
Python3
# Program to save a NumPy array to a text file # Importing required librariesimport numpy # Creating an arrayList = [1, 2, 3, 4, 5]Array = numpy.array(List) # Displaying the arrayprint('Array:\n', Array) # Saving the array in a text filenumpy.savetxt("file1.txt", Array) # Displaying the contents of the text filecontent = numpy.loadtxt('file1.txt')print("\nContent in file1.txt:\n", content)
Output:
Array:
[1 2 3 4 5]
Content in file1.txt:
[1. 2. 3. 4. 5.]
Example 2:
Python3
# Program to save a NumPy array to a text file # Importing required librariesimport numpy # Creating 2D arrayList = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]Array = numpy.array(List) # Displaying the arrayprint('Array:\n', Array) # Saving the 2D array in a text filenumpy.savetxt("file2.txt", Array) # Displaying the contents of the text filecontent = numpy.loadtxt('file2.txt')print("\nContent in file2.txt:\n", content)
Output:
Array:
[[1 2 3]
[4 5 6]
[7 8 9]]
Content in file2.txt:
[[1. 2. 3.]
[4. 5. 6.]
[7. 8. 9.]]
anikakapoor
Python numpy-io
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Create a directory in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Jun, 2021"
},
{
"code": null,
"e": 81,
"s": 28,
"text": "Let us see how to save a numpy array to a text file."
},
{
"code": null,
"e": 367,
"s": 81,
"text": "Method 1: Using File handling Creating a text file using the in-built open() function and then converting the array into string and writing it into the text file using the write() function. Finally closing the file using close() function. Below are some programs of the this approach: "
},
{
"code": null,
"e": 379,
"s": 367,
"text": "Example 1: "
},
{
"code": null,
"e": 387,
"s": 379,
"text": "Python3"
},
{
"code": "# Program to save a NumPy array to a text file # Importing required librariesimport numpy # Creating an arrayList = [1, 2, 3, 4, 5]Array = numpy.array(List) # Displaying the arrayprint('Array:\\n', Array)file = open(\"file1.txt\", \"w+\") # Saving the array in a text filecontent = str(Array)file.write(content)file.close() # Displaying the contents of the text filefile = open(\"file1.txt\", \"r\")content = file.read() print(\"\\nContent in file1.txt:\\n\", content)file.close()",
"e": 855,
"s": 387,
"text": null
},
{
"code": null,
"e": 864,
"s": 855,
"text": "Output: "
},
{
"code": null,
"e": 920,
"s": 864,
"text": "Array:\n [1 2 3 4 5]\n\nContent in file1.txt:\n [1 2 3 4 5]"
},
{
"code": null,
"e": 932,
"s": 920,
"text": "Example 2: "
},
{
"code": null,
"e": 940,
"s": 932,
"text": "Python3"
},
{
"code": "# Program to save a NumPy array to a text file # Importing required librariesimport numpy # Creating 2D arrayList = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]Array = numpy.array(List) # Displaying the arrayprint('Array:\\n', Array)file = open(\"file2.txt\", \"w+\") # Saving the 2D array in a text filecontent = str(Array)file.write(content)file.close() # Displaying the contents of the text filefile = open(\"file2.txt\", \"r\")content = file.read() print(\"\\nContent in file2.txt:\\n\", content)file.close()",
"e": 1429,
"s": 940,
"text": null
},
{
"code": null,
"e": 1438,
"s": 1429,
"text": "Output: "
},
{
"code": null,
"e": 1526,
"s": 1438,
"text": "Array:\n [[1 2 3]\n [4 5 6]\n [7 8 9]]\n\nContent in file2.txt:\n [[1 2 3]\n [4 5 6]\n [7 8 9]]"
},
{
"code": null,
"e": 1536,
"s": 1526,
"text": "Method 2:"
},
{
"code": null,
"e": 1558,
"s": 1536,
"text": "Using NumPy functions"
},
{
"code": null,
"e": 1589,
"s": 1558,
"text": "After creating the array, the "
},
{
"code": null,
"e": 1605,
"s": 1589,
"text": "numpy.savetxt()"
},
{
"code": null,
"e": 1704,
"s": 1605,
"text": "function can be used to save the array into a text file. Below are some programs of this approach."
},
{
"code": null,
"e": 1716,
"s": 1704,
"text": "Example 1: "
},
{
"code": null,
"e": 1724,
"s": 1716,
"text": "Python3"
},
{
"code": "# Program to save a NumPy array to a text file # Importing required librariesimport numpy # Creating an arrayList = [1, 2, 3, 4, 5]Array = numpy.array(List) # Displaying the arrayprint('Array:\\n', Array) # Saving the array in a text filenumpy.savetxt(\"file1.txt\", Array) # Displaying the contents of the text filecontent = numpy.loadtxt('file1.txt')print(\"\\nContent in file1.txt:\\n\", content)",
"e": 2117,
"s": 1724,
"text": null
},
{
"code": null,
"e": 2126,
"s": 2117,
"text": "Output: "
},
{
"code": null,
"e": 2187,
"s": 2126,
"text": "Array:\n [1 2 3 4 5]\n\nContent in file1.txt:\n [1. 2. 3. 4. 5.]"
},
{
"code": null,
"e": 2199,
"s": 2187,
"text": "Example 2: "
},
{
"code": null,
"e": 2207,
"s": 2199,
"text": "Python3"
},
{
"code": "# Program to save a NumPy array to a text file # Importing required librariesimport numpy # Creating 2D arrayList = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]Array = numpy.array(List) # Displaying the arrayprint('Array:\\n', Array) # Saving the 2D array in a text filenumpy.savetxt(\"file2.txt\", Array) # Displaying the contents of the text filecontent = numpy.loadtxt('file2.txt')print(\"\\nContent in file2.txt:\\n\", content)",
"e": 2621,
"s": 2207,
"text": null
},
{
"code": null,
"e": 2630,
"s": 2621,
"text": "Output: "
},
{
"code": null,
"e": 2727,
"s": 2630,
"text": "Array:\n [[1 2 3]\n [4 5 6]\n [7 8 9]]\n\nContent in file2.txt:\n [[1. 2. 3.]\n [4. 5. 6.]\n [7. 8. 9.]]"
},
{
"code": null,
"e": 2741,
"s": 2729,
"text": "anikakapoor"
},
{
"code": null,
"e": 2757,
"s": 2741,
"text": "Python numpy-io"
},
{
"code": null,
"e": 2770,
"s": 2757,
"text": "Python-numpy"
},
{
"code": null,
"e": 2777,
"s": 2770,
"text": "Python"
},
{
"code": null,
"e": 2875,
"s": 2777,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2907,
"s": 2875,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2934,
"s": 2907,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2965,
"s": 2934,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2988,
"s": 2965,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 3009,
"s": 2988,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3065,
"s": 3009,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 3107,
"s": 3065,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 3149,
"s": 3107,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 3188,
"s": 3149,
"text": "Python | Get unique values from a list"
}
] |
Python | Tokenize text using TextBlob
|
01 Jan, 2019
TextBlob module is a Python library and offers a simple API to access its methods and perform basic NLP tasks. It is built on the top of NLTK module.
Install TextBlob using the following commands in terminal:
pip install -U textblob
python -m textblob.download_corpora
This will install TextBlob and download the necessary NLTK corpora. The above installation will take quite some time due to the massive amount of tokenizers, chunkers, other algorithms, and all of the corpora to be downloaded.
Some terms that will be frequently used are :
Corpus – Body of text, singular. Corpora is the plural of this.
Lexicon – Words and their meanings.
Token – Each “entity” that is a part of whatever was split up based on rules. For examples, each word is a token when a sentence is “tokenized” into words. Each sentence can also be a token, if you tokenized the sentences out of a paragraph.
So basically tokenizing involves splitting sentences and words from the body of the text.
# from textblob lib. import TextBlob methodfrom textblob import TextBlob text = ("Natural language processing (NLP) is a field " + "of computer science, artificial intelligence " + "and computational linguistics concerned with " + "the interactions between computers and human " + "(natural) languages, and, in particular, " + "concerned with programming computers to " + "fruitfully process large natural language " + "corpora. Challenges in natural language " + "processing frequently involve natural " + "language understanding, natural language" + "generation frequently from formal, machine" + "-readable logical forms), connecting language " + "and machine perception, managing human-" + "computer dialog systems, or some combination " + "thereof.") # create a TextBlob objectblob_object = TextBlob(text) # tokenize paragraph into words.print(" Word Tokenize :\n", blob_object.words) # tokenize paragraph into sentences.print("\n Sentence Tokenize :\n", blob_object.sentences)
Output :
Word Tokenize :[‘Natural’, ‘language’, ‘processing’, ‘NLP’, ‘is’, ‘a’, ‘field’, ‘of’, ‘computer’, ‘science’, ‘artificial’, ‘intelligence’, ‘and’, ‘computational’, ‘linguistics’, ‘concerned’, ‘with’, ‘the’, ‘interactions’, ‘between’, ‘computers’, ‘and’, ‘human’, ‘natural’, ‘languages’, ‘and’, ‘in’, ‘particular’, ‘concerned’, ‘with’, ‘programming’, ‘computers’, ‘to’, ‘fruitfully’, ‘process’, ‘large’, ‘natural’, ‘language’, ‘corpora’, ‘Challenges’, ‘in’, ‘natural’, ‘language’, ‘processing’, ‘frequently’, ‘involve’, ‘natural’, ‘language’, ‘understanding’, ‘natural’, ‘languagegeneration’, ‘frequently’, ‘from’, ‘formal’, ‘machine-readable’, ‘logical’, ‘forms’, ‘connecting’, ‘language’, ‘and’, ‘machine’, ‘perception’, ‘managing’, ‘human-computer’, ‘dialog’, ‘systems’, ‘or’, ‘some’, ‘combination’, ‘thereof’]
Sentence Tokenize :[Sentence(“Natural language processing (NLP) is a field of computer science, artificial intelligence and computational linguistics concerned with the interactions between computers and human (natural) languages, and, in particular, concerned with programming computers to fruitfully process large natural language corpora.”), Sentence(“Challenges in natural language processing frequently involve natural language understanding, natural language generation frequently from formal, machine-readable logical forms), connecting language and machine perception, managing human-computer dialog systems, or some combination thereof.”)]
Advanced Computer Subject
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
System Design Tutorial
Docker - COPY Instruction
Getting started with Machine Learning
How to Run a Python Script using Docker?
ML | Monte Carlo Tree Search (MCTS)
Agents in Artificial Intelligence
Search Algorithms in AI
Getting started with Machine Learning
Introduction to Recurrent Neural Network
Support Vector Machine Algorithm
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n01 Jan, 2019"
},
{
"code": null,
"e": 204,
"s": 54,
"text": "TextBlob module is a Python library and offers a simple API to access its methods and perform basic NLP tasks. It is built on the top of NLTK module."
},
{
"code": null,
"e": 263,
"s": 204,
"text": "Install TextBlob using the following commands in terminal:"
},
{
"code": null,
"e": 324,
"s": 263,
"text": "pip install -U textblob\npython -m textblob.download_corpora\n"
},
{
"code": null,
"e": 551,
"s": 324,
"text": "This will install TextBlob and download the necessary NLTK corpora. The above installation will take quite some time due to the massive amount of tokenizers, chunkers, other algorithms, and all of the corpora to be downloaded."
},
{
"code": null,
"e": 597,
"s": 551,
"text": "Some terms that will be frequently used are :"
},
{
"code": null,
"e": 661,
"s": 597,
"text": "Corpus – Body of text, singular. Corpora is the plural of this."
},
{
"code": null,
"e": 697,
"s": 661,
"text": "Lexicon – Words and their meanings."
},
{
"code": null,
"e": 939,
"s": 697,
"text": "Token – Each “entity” that is a part of whatever was split up based on rules. For examples, each word is a token when a sentence is “tokenized” into words. Each sentence can also be a token, if you tokenized the sentences out of a paragraph."
},
{
"code": null,
"e": 1029,
"s": 939,
"text": "So basically tokenizing involves splitting sentences and words from the body of the text."
},
{
"code": "# from textblob lib. import TextBlob methodfrom textblob import TextBlob text = (\"Natural language processing (NLP) is a field \" + \"of computer science, artificial intelligence \" + \"and computational linguistics concerned with \" + \"the interactions between computers and human \" + \"(natural) languages, and, in particular, \" + \"concerned with programming computers to \" + \"fruitfully process large natural language \" + \"corpora. Challenges in natural language \" + \"processing frequently involve natural \" + \"language understanding, natural language\" + \"generation frequently from formal, machine\" + \"-readable logical forms), connecting language \" + \"and machine perception, managing human-\" + \"computer dialog systems, or some combination \" + \"thereof.\") # create a TextBlob objectblob_object = TextBlob(text) # tokenize paragraph into words.print(\" Word Tokenize :\\n\", blob_object.words) # tokenize paragraph into sentences.print(\"\\n Sentence Tokenize :\\n\", blob_object.sentences)",
"e": 2125,
"s": 1029,
"text": null
},
{
"code": null,
"e": 2134,
"s": 2125,
"text": "Output :"
},
{
"code": null,
"e": 2946,
"s": 2134,
"text": "Word Tokenize :[‘Natural’, ‘language’, ‘processing’, ‘NLP’, ‘is’, ‘a’, ‘field’, ‘of’, ‘computer’, ‘science’, ‘artificial’, ‘intelligence’, ‘and’, ‘computational’, ‘linguistics’, ‘concerned’, ‘with’, ‘the’, ‘interactions’, ‘between’, ‘computers’, ‘and’, ‘human’, ‘natural’, ‘languages’, ‘and’, ‘in’, ‘particular’, ‘concerned’, ‘with’, ‘programming’, ‘computers’, ‘to’, ‘fruitfully’, ‘process’, ‘large’, ‘natural’, ‘language’, ‘corpora’, ‘Challenges’, ‘in’, ‘natural’, ‘language’, ‘processing’, ‘frequently’, ‘involve’, ‘natural’, ‘language’, ‘understanding’, ‘natural’, ‘languagegeneration’, ‘frequently’, ‘from’, ‘formal’, ‘machine-readable’, ‘logical’, ‘forms’, ‘connecting’, ‘language’, ‘and’, ‘machine’, ‘perception’, ‘managing’, ‘human-computer’, ‘dialog’, ‘systems’, ‘or’, ‘some’, ‘combination’, ‘thereof’]"
},
{
"code": null,
"e": 3595,
"s": 2946,
"text": "Sentence Tokenize :[Sentence(“Natural language processing (NLP) is a field of computer science, artificial intelligence and computational linguistics concerned with the interactions between computers and human (natural) languages, and, in particular, concerned with programming computers to fruitfully process large natural language corpora.”), Sentence(“Challenges in natural language processing frequently involve natural language understanding, natural language generation frequently from formal, machine-readable logical forms), connecting language and machine perception, managing human-computer dialog systems, or some combination thereof.”)]"
},
{
"code": null,
"e": 3621,
"s": 3595,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 3638,
"s": 3621,
"text": "Machine Learning"
},
{
"code": null,
"e": 3645,
"s": 3638,
"text": "Python"
},
{
"code": null,
"e": 3662,
"s": 3645,
"text": "Machine Learning"
},
{
"code": null,
"e": 3760,
"s": 3662,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3783,
"s": 3760,
"text": "System Design Tutorial"
},
{
"code": null,
"e": 3809,
"s": 3783,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 3847,
"s": 3809,
"text": "Getting started with Machine Learning"
},
{
"code": null,
"e": 3888,
"s": 3847,
"text": "How to Run a Python Script using Docker?"
},
{
"code": null,
"e": 3924,
"s": 3888,
"text": "ML | Monte Carlo Tree Search (MCTS)"
},
{
"code": null,
"e": 3958,
"s": 3924,
"text": "Agents in Artificial Intelligence"
},
{
"code": null,
"e": 3982,
"s": 3958,
"text": "Search Algorithms in AI"
},
{
"code": null,
"e": 4020,
"s": 3982,
"text": "Getting started with Machine Learning"
},
{
"code": null,
"e": 4061,
"s": 4020,
"text": "Introduction to Recurrent Neural Network"
}
] |
Python – tensorflow.convert_to_tensor()
|
26 Jun, 2020
TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning neural networks.
convert_to_tensor() is used to convert the given value to a Tensor
Syntax: tensorflow.convert_to_tensor( value, dtype, dtype_hint, name )
Parameters:
value: It is the value that needed to be converted to Tensor.
dtype(optional): It defines the type of the output Tensor.
dtype_hint(optional): It is used when dtype is None. In some cases, a caller may not have a dtype in mind when converting to a tensor, so dtype_hint can be used as a soft preference. If the conversion to dtype_hint is not possible, this argument has no effect.
name(optiona): It defines the name for the operation.
Returns: It returns a Tensor.
Example 1: From Python list
Python3
# Importing the libraryimport tensorflow as tf # Initializing the inputl = [1, 2, 3, 4] # Printing the inputprint('l: ', l) # Calculating resultx = tf.convert_to_tensor(l) # Printing the resultprint('x: ', x)
Output:
l: [1, 2, 3, 4]
x: tf.Tensor([1 2 3 4], shape=(4, ), dtype=int32)
Example 2: From Python tuple
Python3
# Importing the libraryimport tensorflow as tf # Initializing the inputl = (1, 2, 3, 4) # Printing the inputprint('l: ', l) # Calculating resultx = tf.convert_to_tensor(l, dtype = tf.float64) # Printing the resultprint('x: ', x)
Output:
l: (1, 2, 3, 4)
x: tf.Tensor([1. 2. 3. 4.], shape=(4, ), dtype=float64)
Python-Tensorflow
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Jun, 2020"
},
{
"code": null,
"e": 159,
"s": 28,
"text": "TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning neural networks."
},
{
"code": null,
"e": 226,
"s": 159,
"text": "convert_to_tensor() is used to convert the given value to a Tensor"
},
{
"code": null,
"e": 297,
"s": 226,
"text": "Syntax: tensorflow.convert_to_tensor( value, dtype, dtype_hint, name )"
},
{
"code": null,
"e": 309,
"s": 297,
"text": "Parameters:"
},
{
"code": null,
"e": 371,
"s": 309,
"text": "value: It is the value that needed to be converted to Tensor."
},
{
"code": null,
"e": 430,
"s": 371,
"text": "dtype(optional): It defines the type of the output Tensor."
},
{
"code": null,
"e": 691,
"s": 430,
"text": "dtype_hint(optional): It is used when dtype is None. In some cases, a caller may not have a dtype in mind when converting to a tensor, so dtype_hint can be used as a soft preference. If the conversion to dtype_hint is not possible, this argument has no effect."
},
{
"code": null,
"e": 745,
"s": 691,
"text": "name(optiona): It defines the name for the operation."
},
{
"code": null,
"e": 775,
"s": 745,
"text": "Returns: It returns a Tensor."
},
{
"code": null,
"e": 803,
"s": 775,
"text": "Example 1: From Python list"
},
{
"code": null,
"e": 811,
"s": 803,
"text": "Python3"
},
{
"code": "# Importing the libraryimport tensorflow as tf # Initializing the inputl = [1, 2, 3, 4] # Printing the inputprint('l: ', l) # Calculating resultx = tf.convert_to_tensor(l) # Printing the resultprint('x: ', x)",
"e": 1026,
"s": 811,
"text": null
},
{
"code": null,
"e": 1034,
"s": 1026,
"text": "Output:"
},
{
"code": null,
"e": 1104,
"s": 1034,
"text": "l: [1, 2, 3, 4]\nx: tf.Tensor([1 2 3 4], shape=(4, ), dtype=int32)\n\n"
},
{
"code": null,
"e": 1133,
"s": 1104,
"text": "Example 2: From Python tuple"
},
{
"code": null,
"e": 1141,
"s": 1133,
"text": "Python3"
},
{
"code": "# Importing the libraryimport tensorflow as tf # Initializing the inputl = (1, 2, 3, 4) # Printing the inputprint('l: ', l) # Calculating resultx = tf.convert_to_tensor(l, dtype = tf.float64) # Printing the resultprint('x: ', x)",
"e": 1376,
"s": 1141,
"text": null
},
{
"code": null,
"e": 1384,
"s": 1376,
"text": "Output:"
},
{
"code": null,
"e": 1461,
"s": 1384,
"text": "l: (1, 2, 3, 4)\nx: tf.Tensor([1. 2. 3. 4.], shape=(4, ), dtype=float64)\n\n\n"
},
{
"code": null,
"e": 1479,
"s": 1461,
"text": "Python-Tensorflow"
},
{
"code": null,
"e": 1486,
"s": 1479,
"text": "Python"
}
] |
ML | Logistic Regression v/s Decision Tree Classification
|
25 Aug, 2021
Logistic Regression and Decision Tree classification are two of the most popular and basic classification algorithms being used today. None of the algorithms is better than the other and one’s superior performance is often credited to the nature of the data being worked upon.
We can compare the two algorithms on different categories –
As a simple experiment, we run the two models on the same dataset and compare their performances.
Step 1: Importing the required libraries
Python3
import numpy as npimport pandas as pdfrom sklearn.model_selection import train_test_splitfrom sklearn.linear_model import LogisticRegressionfrom sklearn.tree import DecisionTreeClassifier
Step 2: Reading and cleaning the Dataset
Python3
cd C:\Users\Dev\Desktop\Kaggle\Sinking Titanic# Changing the working location to the location of the filedf = pd.read_csv('_train.csv')y = df['Survived'] X = df.drop('Survived', axis = 1)X = X.drop(['Name', 'Ticket', 'Cabin', 'Embarked'], axis = 1) X = X.replace(['male', 'female'], [2, 3])# Hot-encoding the categorical variables X.fillna(method ='ffill', inplace = True)# Handling the missing values
Step 3: Training and evaluating the Logistic Regression model
Python3
X_train, X_test, y_train, y_test = train_test_split( X, y, test_size = 0.3, random_state = 0) lr = LogisticRegression()lr.fit(X_train, y_train)print(lr.score(X_test, y_test))
Step 4: Training and evaluating the Decision Tree Classifier model
Python3
criteria = ['gini', 'entropy']scores = {} for c in criteria: dt = DecisionTreeClassifier(criterion = c) dt.fit(X_train, y_train) test_score = dt.score(X_test, y_test) scores = test_score print(scores)
On comparing the scores, we can see that the logistic regression model performed better on the current dataset but this might not be the case always.
simmytarika5
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Support Vector Machine Algorithm
Introduction to Recurrent Neural Network
ML | Monte Carlo Tree Search (MCTS)
Markov Decision Process
DBSCAN Clustering in ML | Density based clustering
Read JSON file using Python
Python map() function
Adding new column to existing DataFrame in Pandas
Python Dictionary
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 Aug, 2021"
},
{
"code": null,
"e": 306,
"s": 28,
"text": "Logistic Regression and Decision Tree classification are two of the most popular and basic classification algorithms being used today. None of the algorithms is better than the other and one’s superior performance is often credited to the nature of the data being worked upon. "
},
{
"code": null,
"e": 367,
"s": 306,
"text": "We can compare the two algorithms on different categories – "
},
{
"code": null,
"e": 465,
"s": 367,
"text": "As a simple experiment, we run the two models on the same dataset and compare their performances."
},
{
"code": null,
"e": 507,
"s": 465,
"text": "Step 1: Importing the required libraries "
},
{
"code": null,
"e": 515,
"s": 507,
"text": "Python3"
},
{
"code": "import numpy as npimport pandas as pdfrom sklearn.model_selection import train_test_splitfrom sklearn.linear_model import LogisticRegressionfrom sklearn.tree import DecisionTreeClassifier",
"e": 703,
"s": 515,
"text": null
},
{
"code": null,
"e": 746,
"s": 703,
"text": " Step 2: Reading and cleaning the Dataset"
},
{
"code": null,
"e": 754,
"s": 746,
"text": "Python3"
},
{
"code": "cd C:\\Users\\Dev\\Desktop\\Kaggle\\Sinking Titanic# Changing the working location to the location of the filedf = pd.read_csv('_train.csv')y = df['Survived'] X = df.drop('Survived', axis = 1)X = X.drop(['Name', 'Ticket', 'Cabin', 'Embarked'], axis = 1) X = X.replace(['male', 'female'], [2, 3])# Hot-encoding the categorical variables X.fillna(method ='ffill', inplace = True)# Handling the missing values",
"e": 1156,
"s": 754,
"text": null
},
{
"code": null,
"e": 1220,
"s": 1156,
"text": " Step 3: Training and evaluating the Logistic Regression model"
},
{
"code": null,
"e": 1228,
"s": 1220,
"text": "Python3"
},
{
"code": "X_train, X_test, y_train, y_test = train_test_split( X, y, test_size = 0.3, random_state = 0) lr = LogisticRegression()lr.fit(X_train, y_train)print(lr.score(X_test, y_test))",
"e": 1414,
"s": 1228,
"text": null
},
{
"code": null,
"e": 1483,
"s": 1414,
"text": " Step 4: Training and evaluating the Decision Tree Classifier model"
},
{
"code": null,
"e": 1491,
"s": 1483,
"text": "Python3"
},
{
"code": "criteria = ['gini', 'entropy']scores = {} for c in criteria: dt = DecisionTreeClassifier(criterion = c) dt.fit(X_train, y_train) test_score = dt.score(X_test, y_test) scores = test_score print(scores)",
"e": 1704,
"s": 1491,
"text": null
},
{
"code": null,
"e": 1855,
"s": 1704,
"text": "On comparing the scores, we can see that the logistic regression model performed better on the current dataset but this might not be the case always. "
},
{
"code": null,
"e": 1868,
"s": 1855,
"text": "simmytarika5"
},
{
"code": null,
"e": 1885,
"s": 1868,
"text": "Machine Learning"
},
{
"code": null,
"e": 1892,
"s": 1885,
"text": "Python"
},
{
"code": null,
"e": 1909,
"s": 1892,
"text": "Machine Learning"
},
{
"code": null,
"e": 2007,
"s": 1909,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2040,
"s": 2007,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 2081,
"s": 2040,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 2117,
"s": 2081,
"text": "ML | Monte Carlo Tree Search (MCTS)"
},
{
"code": null,
"e": 2141,
"s": 2117,
"text": "Markov Decision Process"
},
{
"code": null,
"e": 2192,
"s": 2141,
"text": "DBSCAN Clustering in ML | Density based clustering"
},
{
"code": null,
"e": 2220,
"s": 2192,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 2242,
"s": 2220,
"text": "Python map() function"
},
{
"code": null,
"e": 2292,
"s": 2242,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 2310,
"s": 2292,
"text": "Python Dictionary"
}
] |
jQuery | Animation, Slide methods with Examples
|
12 Feb, 2019
jQuery is a very powerful JavaScript framework.Using jQuery, we can add special effects to our website or web-based application.We can add various effects using jQuery such as hide/show, fading effects, animation, call back and many more.For hide/show, Toggle, Fade effect.The jQuery contains the library of several functions that provide techniques for adding animation to a web page. These include simple animation, standard animations.In this article, we are going to learn how to add above effects to our web page.
jQuery Animation:
In jQuery, we can produce various types of animation using the animate() method. This method can produce simple to complex animation in the web page. Using animation, we can change the properties of HTML elements such as background colour, changing border styles, changing navigation properties, formatting the font properties, etc.We apply changes to the properties by providing the styles rules in the params parameter of the method.Syntax:
$("selector").animate({params}, speed, callback);
where
params parameter specifies the CSS property to be changed during execution of animate() method . It is the required parameter.
speed parameter specifies the speed at which the effect is applied .They can accept only these values : “slow”, “fast” or milliseconds.
call back parameter specifies the function to be executed after the execution of animate() method.
Let’s see it’s implementation with JavaScript code:In this code, we animate the rectangle and change its shape to circle.
<!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/ libs/jquery/3.3.1/jquery.min.js"></script> <style type="text/css"> div { width: 100px; height: 100px; background-color: green; } </style></head> <body> <div></div> <br/> <button id="animate">Animate Me</button> <script type="text/javascript"> $("#animate").click(function() { $("div").animate({ width: "200px", height: "200px", borderRadius: "50%", marginLeft: "210px", marginTop: "70px", }, 2000, ); }); </script></body> </html>
Output:Before the Animate Me is clickedAfter the Animate Me is clicked
slideDown() :This method makes the element to slide down.Syntax:$(selector).slideDown(speed,callback);Example :In this example, we show the slide down effect .If the Slide Down panel is clicked ,the corresponding change is made to the HTML element.Code:<!DOCTYPE html><html><head><script src="https://ajax.googleapis.com/ ajax/libs/jquery/3.3.1/jquery.min.js"></script><style type="text/css"> #p1, #f1 { padding: 5px; text-align: center; background-color: white; border: solid 2px green; }#p1 { padding: 50px; width:100px; display:none; color: green; font-style: italic; }#f1 { width:190px; } </style></head><body><h1 align="center">Silde Down Example</h1><center><div id="f1">Slide down Effect</div><div id="p1">Welcome to GeeksForGeeks.</div></center><script type="text/javascript"> $("#f1").click(function(){ $("#p1").slideDown("slow"); });</script></body></html>Output:Before the Down EffectAfter the Down Effect
$(selector).slideDown(speed,callback);
Example :In this example, we show the slide down effect .If the Slide Down panel is clicked ,the corresponding change is made to the HTML element.Code:
<!DOCTYPE html><html><head><script src="https://ajax.googleapis.com/ ajax/libs/jquery/3.3.1/jquery.min.js"></script><style type="text/css"> #p1, #f1 { padding: 5px; text-align: center; background-color: white; border: solid 2px green; }#p1 { padding: 50px; width:100px; display:none; color: green; font-style: italic; }#f1 { width:190px; } </style></head><body><h1 align="center">Silde Down Example</h1><center><div id="f1">Slide down Effect</div><div id="p1">Welcome to GeeksForGeeks.</div></center><script type="text/javascript"> $("#f1").click(function(){ $("#p1").slideDown("slow"); });</script></body></html>
Output:Before the Down EffectAfter the Down Effect
slideUp():This method makes the element to slide up.Syntax:$(selector).slideUp(speed,callback);Example :In this example, we show the slide up effect .If the Slide Up panel is clicked ,the corresponding change is made to the HTML element.Code:<!DOCTYPE html><html><head><script src="https://ajax.googleapis.com/ajax/ libs/jquery/3.3.1/jquery.min.js"></script><style type="text/css"> #p2, #f2 { padding: 5px; text-align: center; background-color: white; border: solid 2px black; }#p2 { padding: 50px; width:100px; color: green; font-style: italic; }#f2 { width:190px; } </style></head><body><h1 align="center">Slide Up Example</h1><center><div id="f2">Slide up Effect</div><div id="p2">Welcome to GeeksForGeeks.</div></center><script type="text/javascript"> $("#f2").click(function(){ $("#p2").slideUp("slow"); });</script></body></html>Output:Before the Up EffectAfter the Up Effect
$(selector).slideUp(speed,callback);
Example :In this example, we show the slide up effect .If the Slide Up panel is clicked ,the corresponding change is made to the HTML element.Code:
<!DOCTYPE html><html><head><script src="https://ajax.googleapis.com/ajax/ libs/jquery/3.3.1/jquery.min.js"></script><style type="text/css"> #p2, #f2 { padding: 5px; text-align: center; background-color: white; border: solid 2px black; }#p2 { padding: 50px; width:100px; color: green; font-style: italic; }#f2 { width:190px; } </style></head><body><h1 align="center">Slide Up Example</h1><center><div id="f2">Slide up Effect</div><div id="p2">Welcome to GeeksForGeeks.</div></center><script type="text/javascript"> $("#f2").click(function(){ $("#p2").slideUp("slow"); });</script></body></html>
Output:Before the Up EffectAfter the Up Effect
slideToggle() :This method makes the element to slide up/down.If the element is in the slide up position, it makes it slide down.If the element is in the slide down position, it makes it slide up.Syntax:$(selector).slideToggle(speed,callback);wherespeed parameter specifies the speed at which the effect is applied .They can accept only these values : “slow” , “fast” or milliseconds.call back parameter specifies the function to be executed after the execution of particular slide method.Example :In this example, we show the slide up effect .If the Slide Up panel is clicked ,the corresponding change is made to the HTML element.Code:<!DOCTYPE html><html><head><script src="https://ajax.googleapis.com/ ajax/libs/jquery/3.3.1/jquery.min.js"></script><style type="text/css"> #p3 ,#f3 { padding: 5px; text-align: center; background-color: white; border: solid 2px green; }#p3 { padding: 50px; width:100px; color: green; font-style: italic; }#f3 { width:190px; } </style></head><body><h1 align="center">Slide Up/Down Example</h1><center><div id="f3">Slide up/down Effect</div><div id="p3">Welcome to GeeksForGeeks.</div></center><script type="text/javascript"> $("#f3").click(function(){ $("#p3").slideToggle("slow"); });</script></body></html>Output:Before the EffectWhen the Up/Down Strip is clicked first timeWhen the Up/Down Strip is clicked second time
$(selector).slideToggle(speed,callback);
where
speed parameter specifies the speed at which the effect is applied .They can accept only these values : “slow” , “fast” or milliseconds.
call back parameter specifies the function to be executed after the execution of particular slide method.
Example :In this example, we show the slide up effect .If the Slide Up panel is clicked ,the corresponding change is made to the HTML element.Code:
<!DOCTYPE html><html><head><script src="https://ajax.googleapis.com/ ajax/libs/jquery/3.3.1/jquery.min.js"></script><style type="text/css"> #p3 ,#f3 { padding: 5px; text-align: center; background-color: white; border: solid 2px green; }#p3 { padding: 50px; width:100px; color: green; font-style: italic; }#f3 { width:190px; } </style></head><body><h1 align="center">Slide Up/Down Example</h1><center><div id="f3">Slide up/down Effect</div><div id="p3">Welcome to GeeksForGeeks.</div></center><script type="text/javascript"> $("#f3").click(function(){ $("#p3").slideToggle("slow"); });</script></body></html>
Output:Before the EffectWhen the Up/Down Strip is clicked first timeWhen the Up/Down Strip is clicked second time
jQuery-Basics
JavaScript
JQuery
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n12 Feb, 2019"
},
{
"code": null,
"e": 571,
"s": 52,
"text": "jQuery is a very powerful JavaScript framework.Using jQuery, we can add special effects to our website or web-based application.We can add various effects using jQuery such as hide/show, fading effects, animation, call back and many more.For hide/show, Toggle, Fade effect.The jQuery contains the library of several functions that provide techniques for adding animation to a web page. These include simple animation, standard animations.In this article, we are going to learn how to add above effects to our web page."
},
{
"code": null,
"e": 589,
"s": 571,
"text": "jQuery Animation:"
},
{
"code": null,
"e": 1032,
"s": 589,
"text": "In jQuery, we can produce various types of animation using the animate() method. This method can produce simple to complex animation in the web page. Using animation, we can change the properties of HTML elements such as background colour, changing border styles, changing navigation properties, formatting the font properties, etc.We apply changes to the properties by providing the styles rules in the params parameter of the method.Syntax:"
},
{
"code": null,
"e": 1082,
"s": 1032,
"text": "$(\"selector\").animate({params}, speed, callback);"
},
{
"code": null,
"e": 1088,
"s": 1082,
"text": "where"
},
{
"code": null,
"e": 1215,
"s": 1088,
"text": "params parameter specifies the CSS property to be changed during execution of animate() method . It is the required parameter."
},
{
"code": null,
"e": 1351,
"s": 1215,
"text": "speed parameter specifies the speed at which the effect is applied .They can accept only these values : “slow”, “fast” or milliseconds."
},
{
"code": null,
"e": 1450,
"s": 1351,
"text": "call back parameter specifies the function to be executed after the execution of animate() method."
},
{
"code": null,
"e": 1572,
"s": 1450,
"text": "Let’s see it’s implementation with JavaScript code:In this code, we animate the rectangle and change its shape to circle."
},
{
"code": "<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/ libs/jquery/3.3.1/jquery.min.js\"></script> <style type=\"text/css\"> div { width: 100px; height: 100px; background-color: green; } </style></head> <body> <div></div> <br/> <button id=\"animate\">Animate Me</button> <script type=\"text/javascript\"> $(\"#animate\").click(function() { $(\"div\").animate({ width: \"200px\", height: \"200px\", borderRadius: \"50%\", marginLeft: \"210px\", marginTop: \"70px\", }, 2000, ); }); </script></body> </html>",
"e": 2334,
"s": 1572,
"text": null
},
{
"code": null,
"e": 2405,
"s": 2334,
"text": "Output:Before the Animate Me is clickedAfter the Animate Me is clicked"
},
{
"code": null,
"e": 3390,
"s": 2405,
"text": "slideDown() :This method makes the element to slide down.Syntax:$(selector).slideDown(speed,callback);Example :In this example, we show the slide down effect .If the Slide Down panel is clicked ,the corresponding change is made to the HTML element.Code:<!DOCTYPE html><html><head><script src=\"https://ajax.googleapis.com/ ajax/libs/jquery/3.3.1/jquery.min.js\"></script><style type=\"text/css\"> #p1, #f1 { padding: 5px; text-align: center; background-color: white; border: solid 2px green; }#p1 { padding: 50px; width:100px; display:none; color: green; font-style: italic; }#f1 { width:190px; } </style></head><body><h1 align=\"center\">Silde Down Example</h1><center><div id=\"f1\">Slide down Effect</div><div id=\"p1\">Welcome to GeeksForGeeks.</div></center><script type=\"text/javascript\"> $(\"#f1\").click(function(){ $(\"#p1\").slideDown(\"slow\"); });</script></body></html>Output:Before the Down EffectAfter the Down Effect"
},
{
"code": null,
"e": 3429,
"s": 3390,
"text": "$(selector).slideDown(speed,callback);"
},
{
"code": null,
"e": 3581,
"s": 3429,
"text": "Example :In this example, we show the slide down effect .If the Slide Down panel is clicked ,the corresponding change is made to the HTML element.Code:"
},
{
"code": "<!DOCTYPE html><html><head><script src=\"https://ajax.googleapis.com/ ajax/libs/jquery/3.3.1/jquery.min.js\"></script><style type=\"text/css\"> #p1, #f1 { padding: 5px; text-align: center; background-color: white; border: solid 2px green; }#p1 { padding: 50px; width:100px; display:none; color: green; font-style: italic; }#f1 { width:190px; } </style></head><body><h1 align=\"center\">Silde Down Example</h1><center><div id=\"f1\">Slide down Effect</div><div id=\"p1\">Welcome to GeeksForGeeks.</div></center><script type=\"text/javascript\"> $(\"#f1\").click(function(){ $(\"#p1\").slideDown(\"slow\"); });</script></body></html>",
"e": 4263,
"s": 3581,
"text": null
},
{
"code": null,
"e": 4314,
"s": 4263,
"text": "Output:Before the Down EffectAfter the Down Effect"
},
{
"code": null,
"e": 5261,
"s": 4314,
"text": "slideUp():This method makes the element to slide up.Syntax:$(selector).slideUp(speed,callback);Example :In this example, we show the slide up effect .If the Slide Up panel is clicked ,the corresponding change is made to the HTML element.Code:<!DOCTYPE html><html><head><script src=\"https://ajax.googleapis.com/ajax/ libs/jquery/3.3.1/jquery.min.js\"></script><style type=\"text/css\"> #p2, #f2 { padding: 5px; text-align: center; background-color: white; border: solid 2px black; }#p2 { padding: 50px; width:100px; color: green; font-style: italic; }#f2 { width:190px; } </style></head><body><h1 align=\"center\">Slide Up Example</h1><center><div id=\"f2\">Slide up Effect</div><div id=\"p2\">Welcome to GeeksForGeeks.</div></center><script type=\"text/javascript\"> $(\"#f2\").click(function(){ $(\"#p2\").slideUp(\"slow\"); });</script></body></html>Output:Before the Up EffectAfter the Up Effect"
},
{
"code": null,
"e": 5298,
"s": 5261,
"text": "$(selector).slideUp(speed,callback);"
},
{
"code": null,
"e": 5446,
"s": 5298,
"text": "Example :In this example, we show the slide up effect .If the Slide Up panel is clicked ,the corresponding change is made to the HTML element.Code:"
},
{
"code": "<!DOCTYPE html><html><head><script src=\"https://ajax.googleapis.com/ajax/ libs/jquery/3.3.1/jquery.min.js\"></script><style type=\"text/css\"> #p2, #f2 { padding: 5px; text-align: center; background-color: white; border: solid 2px black; }#p2 { padding: 50px; width:100px; color: green; font-style: italic; }#f2 { width:190px; } </style></head><body><h1 align=\"center\">Slide Up Example</h1><center><div id=\"f2\">Slide up Effect</div><div id=\"p2\">Welcome to GeeksForGeeks.</div></center><script type=\"text/javascript\"> $(\"#f2\").click(function(){ $(\"#p2\").slideUp(\"slow\"); });</script></body></html>",
"e": 6105,
"s": 5446,
"text": null
},
{
"code": null,
"e": 6152,
"s": 6105,
"text": "Output:Before the Up EffectAfter the Up Effect"
},
{
"code": null,
"e": 7573,
"s": 6152,
"text": "slideToggle() :This method makes the element to slide up/down.If the element is in the slide up position, it makes it slide down.If the element is in the slide down position, it makes it slide up.Syntax:$(selector).slideToggle(speed,callback);wherespeed parameter specifies the speed at which the effect is applied .They can accept only these values : “slow” , “fast” or milliseconds.call back parameter specifies the function to be executed after the execution of particular slide method.Example :In this example, we show the slide up effect .If the Slide Up panel is clicked ,the corresponding change is made to the HTML element.Code:<!DOCTYPE html><html><head><script src=\"https://ajax.googleapis.com/ ajax/libs/jquery/3.3.1/jquery.min.js\"></script><style type=\"text/css\"> #p3 ,#f3 { padding: 5px; text-align: center; background-color: white; border: solid 2px green; }#p3 { padding: 50px; width:100px; color: green; font-style: italic; }#f3 { width:190px; } </style></head><body><h1 align=\"center\">Slide Up/Down Example</h1><center><div id=\"f3\">Slide up/down Effect</div><div id=\"p3\">Welcome to GeeksForGeeks.</div></center><script type=\"text/javascript\"> $(\"#f3\").click(function(){ $(\"#p3\").slideToggle(\"slow\"); });</script></body></html>Output:Before the EffectWhen the Up/Down Strip is clicked first timeWhen the Up/Down Strip is clicked second time"
},
{
"code": null,
"e": 7614,
"s": 7573,
"text": "$(selector).slideToggle(speed,callback);"
},
{
"code": null,
"e": 7620,
"s": 7614,
"text": "where"
},
{
"code": null,
"e": 7757,
"s": 7620,
"text": "speed parameter specifies the speed at which the effect is applied .They can accept only these values : “slow” , “fast” or milliseconds."
},
{
"code": null,
"e": 7863,
"s": 7757,
"text": "call back parameter specifies the function to be executed after the execution of particular slide method."
},
{
"code": null,
"e": 8011,
"s": 7863,
"text": "Example :In this example, we show the slide up effect .If the Slide Up panel is clicked ,the corresponding change is made to the HTML element.Code:"
},
{
"code": "<!DOCTYPE html><html><head><script src=\"https://ajax.googleapis.com/ ajax/libs/jquery/3.3.1/jquery.min.js\"></script><style type=\"text/css\"> #p3 ,#f3 { padding: 5px; text-align: center; background-color: white; border: solid 2px green; }#p3 { padding: 50px; width:100px; color: green; font-style: italic; }#f3 { width:190px; } </style></head><body><h1 align=\"center\">Slide Up/Down Example</h1><center><div id=\"f3\">Slide up/down Effect</div><div id=\"p3\">Welcome to GeeksForGeeks.</div></center><script type=\"text/javascript\"> $(\"#f3\").click(function(){ $(\"#p3\").slideToggle(\"slow\"); });</script></body></html>",
"e": 8683,
"s": 8011,
"text": null
},
{
"code": null,
"e": 8797,
"s": 8683,
"text": "Output:Before the EffectWhen the Up/Down Strip is clicked first timeWhen the Up/Down Strip is clicked second time"
},
{
"code": null,
"e": 8811,
"s": 8797,
"text": "jQuery-Basics"
},
{
"code": null,
"e": 8822,
"s": 8811,
"text": "JavaScript"
},
{
"code": null,
"e": 8829,
"s": 8822,
"text": "JQuery"
}
] |
Lodash _.transform() Method
|
27 Jul, 2021
Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, collection, strings, lang, function, objects, numbers etc. The _.transform() method is an alternative to _.reduce() method transforms object to a new accumulator object which is the result of running each of its own enumerable string keyed properties through iteratee with each invocation potentially mutating the accumulator object. A new object with the same prototype will be used if an accumulator is not provided. Syntax:
_.transform(object, iteratee, accumulator)
Parameters: This method accepts three parameters as mentioned above and described below:
object: It holds the object to iterate over.
iteratee: It is the function that the method invoked per iteration for every element.
accumulator: It holds the custom accumulator value.
Return Value: This method returns the accumulated value.Example 1: Here, const _ = require(‘lodash’) is used to import the lodash library in the file.
javascript
// Requiring the lodash libraryconst _ = require("lodash"); // Original arrayvar object = [12, 13, 14]; // Using the _.transform() methodlet st_elem = _.transform(object, function(result, n) { result.push(n *= n); return n % 2 == 0;}, []); // Printing the outputconsole.log(st_elem);
Output:
144, 169
Example 2:
javascript
// Requiring the lodash libraryconst _ = require("lodash"); // Original arrayvar object = { 'p': 3, 'q': 6, 'r': 3 }; // Using the _.transform() methodlet st_elem = _.transform(object, function(result, value, key) { (result[value] || (result[value] = [])).push(key);}, {}); // Printing the outputconsole.log(st_elem);
Output:
{ '3': ['p', 'r'], '6': ['q'] }
Note: This code will not work in normal JavaScript because it requires the library lodash to be installed.
kapoorsagar226
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
JavaScript | Promises
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Jul, 2021"
},
{
"code": null,
"e": 565,
"s": 28,
"text": "Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, collection, strings, lang, function, objects, numbers etc. The _.transform() method is an alternative to _.reduce() method transforms object to a new accumulator object which is the result of running each of its own enumerable string keyed properties through iteratee with each invocation potentially mutating the accumulator object. A new object with the same prototype will be used if an accumulator is not provided. Syntax: "
},
{
"code": null,
"e": 608,
"s": 565,
"text": "_.transform(object, iteratee, accumulator)"
},
{
"code": null,
"e": 698,
"s": 608,
"text": "Parameters: This method accepts three parameters as mentioned above and described below: "
},
{
"code": null,
"e": 743,
"s": 698,
"text": "object: It holds the object to iterate over."
},
{
"code": null,
"e": 829,
"s": 743,
"text": "iteratee: It is the function that the method invoked per iteration for every element."
},
{
"code": null,
"e": 881,
"s": 829,
"text": "accumulator: It holds the custom accumulator value."
},
{
"code": null,
"e": 1033,
"s": 881,
"text": "Return Value: This method returns the accumulated value.Example 1: Here, const _ = require(‘lodash’) is used to import the lodash library in the file. "
},
{
"code": null,
"e": 1044,
"s": 1033,
"text": "javascript"
},
{
"code": "// Requiring the lodash libraryconst _ = require(\"lodash\"); // Original arrayvar object = [12, 13, 14]; // Using the _.transform() methodlet st_elem = _.transform(object, function(result, n) { result.push(n *= n); return n % 2 == 0;}, []); // Printing the outputconsole.log(st_elem);",
"e": 1346,
"s": 1044,
"text": null
},
{
"code": null,
"e": 1356,
"s": 1346,
"text": "Output: "
},
{
"code": null,
"e": 1365,
"s": 1356,
"text": "144, 169"
},
{
"code": null,
"e": 1376,
"s": 1365,
"text": "Example 2:"
},
{
"code": null,
"e": 1387,
"s": 1376,
"text": "javascript"
},
{
"code": "// Requiring the lodash libraryconst _ = require(\"lodash\"); // Original arrayvar object = { 'p': 3, 'q': 6, 'r': 3 }; // Using the _.transform() methodlet st_elem = _.transform(object, function(result, value, key) { (result[value] || (result[value] = [])).push(key);}, {}); // Printing the outputconsole.log(st_elem);",
"e": 1714,
"s": 1387,
"text": null
},
{
"code": null,
"e": 1723,
"s": 1714,
"text": "Output: "
},
{
"code": null,
"e": 1755,
"s": 1723,
"text": "{ '3': ['p', 'r'], '6': ['q'] }"
},
{
"code": null,
"e": 1862,
"s": 1755,
"text": "Note: This code will not work in normal JavaScript because it requires the library lodash to be installed."
},
{
"code": null,
"e": 1877,
"s": 1862,
"text": "kapoorsagar226"
},
{
"code": null,
"e": 1895,
"s": 1877,
"text": "JavaScript-Lodash"
},
{
"code": null,
"e": 1906,
"s": 1895,
"text": "JavaScript"
},
{
"code": null,
"e": 1923,
"s": 1906,
"text": "Web Technologies"
},
{
"code": null,
"e": 2021,
"s": 1923,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2082,
"s": 2021,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2122,
"s": 2082,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 2163,
"s": 2122,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 2205,
"s": 2163,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 2227,
"s": 2205,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 2260,
"s": 2227,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2322,
"s": 2260,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2383,
"s": 2322,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2433,
"s": 2383,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Insert a node at a specific position in a linked list
|
24 Jun, 2022
Given a singly linked list, a position and an element, the task is to write a program to insert that element in a linked list at a given position.
Examples:
Input: 3->5->8->10, data = 2, position = 2
Output: 3->2->5->8->10
Input: 3->5->8->10, data = 11, position = 5
Output: 3->5->8->10->11
Approach: To insert a given data at a specified position, the below algorithm is to be followed:
Traverse the Linked list upto position-1 nodes.
Once all the position-1 nodes are traversed, allocate memory and the given data to the new node.
Point the next pointer of the new node to the next of current node.
Point the next pointer of current node to the new node.
Below is the implementation of the above algorithm.
C++
Java
Python3
C#
Javascript
// C++ program for insertion in a single linked// list at a specified position#include <bits/stdc++.h>using namespace std; // A linked list Nodestruct Node { int data; struct Node* next;}; // Size of linked listint size = 0; // function to create and return a NodeNode* getNode(int data){ // allocating space Node* newNode = new Node(); // inserting the required data newNode->data = data; newNode->next = NULL; return newNode;} // function to insert a Node at required positionvoid insertPos(Node** current, int pos, int data){ // This condition to check whether the // position given is valid or not. if (pos < 1 || pos > size + 1) cout << "Invalid position!" << endl; else { // Keep looping until the pos is zero while (pos--) { if (pos == 0) { // adding Node at required position Node* temp = getNode(data); // Making the new Node to point to // the old Node at the same position temp->next = *current; // Changing the pointer of the Node previous // to the old Node to point to the new Node *current = temp; } else // Assign double pointer variable to point to the // pointer pointing to the address of next Node current = &(*current)->next; } size++; }} // This function prints contents // of the linked list void printList(struct Node* head){ while (head != NULL) { cout << " " << head->data; head = head->next; } cout << endl;} // Driver Codeint main(){ // Creating the list 3->5->8->10 Node* head = NULL; head = getNode(3); head->next = getNode(5); head->next->next = getNode(8); head->next->next->next = getNode(10); size = 4; cout << "Linked list before insertion: "; printList(head); int data = 12, pos = 3; insertPos(&head, pos, data); cout << "Linked list after insertion of 12 at position 3: "; printList(head); // front of the linked list data = 1, pos = 1; insertPos(&head, pos, data); cout << "Linked list after insertion of 1 at position 1: "; printList(head); // insertion at end of the linked list data = 15, pos = 7; insertPos(&head, pos, data); cout << "Linked list after insertion of 15 at position 7: "; printList(head); return 0;}
// Java program for insertion in a single linked // list at a specified position class GFG { // A linked list Node static class Node { public int data; public Node nextNode; // inserting the required data public Node(int data) { this.data = data; } } // function to create and return a Node static Node GetNode(int data) { return new Node(data); } // function to insert a Node at required position static Node InsertPos(Node headNode, int position, int data) { Node head = headNode; if (position < 1) System.out.print("Invalid position"); // if position is 1 then new node is // set infornt of head node // head node is changing. if (position == 1) { Node newNode = new Node(data); newNode.nextNode = headNode; head = newNode; } else { while (position-- != 0) { if (position == 1) { // adding Node at required position Node newNode = GetNode(data); // Making the new Node to point to // the old Node at the same position newNode.nextNode = headNode.nextNode; // Replacing current with new Node // to the old Node to point to the new Node headNode.nextNode = newNode; break; } headNode = headNode.nextNode; } if (position != 1) System.out.print("Position out of range"); } return head; } static void PrintList(Node node) { while (node != null) { System.out.print(node.data); node = node.nextNode; if (node != null) System.out.print(","); } System.out.println(); } // Driver code public static void main(String[] args) { Node head = GetNode(3); head.nextNode = GetNode(5); head.nextNode.nextNode = GetNode(8); head.nextNode.nextNode.nextNode = GetNode(10); System.out.print("Linked list before insertion: "); PrintList(head); int data = 12, pos = 3; head = InsertPos(head, pos, data); System.out.print("Linked list after" + " insertion of 12 at position 3: "); PrintList(head); // front of the linked list data = 1; pos = 1; head = InsertPos(head, pos, data); System.out.print("Linked list after" + "insertion of 1 at position 1: "); PrintList(head); // insertion at end of the linked list data = 15; pos = 7; head = InsertPos(head, pos, data); System.out.print("Linked list after" + " insertion of 15 at position 7: "); PrintList(head); }} // This code is contributed by Rajput-Ji
# Python3 program for insertion in a single linked# list at a specified position # A linked list Nodeclass Node: def __init__(self, data): self.data = data self.nextNode = None # function to create and return a Nodedef getNode(data): # allocating space newNode = Node(data) return newNode; # function to insert a Node at required positiondef insertPos(headNode, position, data): head = headNode # This condition to check whether the # position given is valid or not. if (position < 1): print("Invalid position!") if position == 1: newNode = Node(data) newNode.nextNode = headNode head = newNode else: # Keep looping until the position is zero while (position != 0): position -= 1 if (position == 1): # adding Node at required position newNode = getNode(data) # Making the new Node to point to # the old Node at the same position newNode.nextNode = headNode.nextNode # Replacing headNode with new Node # to the old Node to point to the new Node headNode.nextNode = newNode break headNode = headNode.nextNode if headNode == None: break if position != 1: print("position out of range") return head # This function prints contents # of the linked list def printList(head): while (head != None): print(' ' + str(head.data), end = '') head = head.nextNode; print() # Driver Codeif __name__=='__main__': # Creating the list 3.5.8.10 head = getNode(3); head.nextNode = getNode(5); head.nextNode.nextNode = getNode(8); head.nextNode.nextNode.nextNode = getNode(10); print("Linked list before insertion: ", end='') printList(head); data = 12 position = 3; head = insertPos(head, position, data); print("Linked list after insertion of 12 at position 3: ", end = '') printList(head); # front of the linked list data = 1 position = 1; head = insertPos(head, position, data); print("Linked list after insertion of 1 at position 1: ", end = '') printList(head); # insertion at end of the linked list data = 15 position = 7; head = insertPos(head, position, data); print("Linked list after insertion of 15 at position 7: ", end='') printList(head); # This code iscontributed by rutvik_56
// C# program for insertion in a single linked // list at a specified position using System; namespace InsertIntoLinkedList{ class Program { // A linked list Node private class Node { public int data; public Node nextNode; // inserting the required data public Node(int data) => this.data = data; } // function to create and return a Node static Node GetNode(int data) => new Node(data); // function to insert a Node at required position static Node InsertPos(Node headNode, int position, int data) { var head = headNode; if (position < 1) Console.WriteLine("Invalid position"); //if position is 1 then new node is // set infornt of head node //head node is changing. if (position == 1) { var newNode = new Node(data); newNode.nextNode = headNode; head = newNode; } else { while (position-- != 0) { if (position == 1) { // adding Node at required position Node newNode = GetNode(data); // Making the new Node to point to // the old Node at the same position newNode.nextNode = headNode.nextNode; // Replacing current with new Node // to the old Node to point to the new Node headNode.nextNode = newNode; break; } headNode = headNode.nextNode; } if (position != 1) Console.WriteLine("Position out of range"); } return head; } static void PrintList(Node node) { while (node != null) { Console.Write(node.data); node = node.nextNode; if(node != null) Console.Write(","); } Console.WriteLine(); } // Driver code static void Main(string[] args) { var head = GetNode(3); head.nextNode = GetNode(5); head.nextNode.nextNode = GetNode(8); head.nextNode.nextNode.nextNode = GetNode(10); Console.WriteLine("Linked list before insertion: "); PrintList(head); int data = 12, pos = 3; head = InsertPos(head, pos, data); Console.WriteLine("Linked list after" + " insertion of 12 at position 3: "); PrintList(head); // front of the linked list data = 1; pos = 1; head = InsertPos(head, pos, data); Console.WriteLine("Linked list after" + "insertion of 1 at position 1: "); PrintList(head); // insertion at end of the linked list data = 15; pos = 7; head = InsertPos(head, pos, data); Console.WriteLine("Linked list after" + " insertion of 15 at position 7: "); PrintList(head); } }} // This code is contributed by dhirucoool
<script>// javascript program for insertion in a single linked // list at a specified position // A linked list Node class Node { // inserting the required data constructor(val) { this.data = val; this.nextNode = null; } } // function to create and return a Node function GetNode(data) { return new Node(data); } // function to insert a Node at required position function InsertPos( headNode , position , data) { head = headNode; if (position < 1) document.write("Invalid position"); // if position is 1 then new node is // set infront of head node // head node is changing. if (position == 1) { newNode = new Node(data); newNode.nextNode = headNode; head = newNode; } else { while (position-- != 0) { if (position == 1) { // adding Node at required position newNode = GetNode(data); // Making the new Node to point to // the old Node at the same position newNode.nextNode = headNode.nextNode; // Replacing current with new Node // to the old Node to point to the new Node headNode.nextNode = newNode; break; } headNode = headNode.nextNode; } if (position != 1) document.write("Position out of range"); } return head; } function PrintList( node) { while (node != null) { document.write(node.data); node = node.nextNode; if (node != null) document.write(","); } document.write("<br/>"); } // Driver code head = GetNode(3); head.nextNode = GetNode(5); head.nextNode.nextNode = GetNode(8); head.nextNode.nextNode.nextNode = GetNode(10); document.write("Linked list before insertion: "); PrintList(head); var data = 12, pos = 3; head = InsertPos(head, pos, data); document.write("Linked list after" + " insertion of 12 at position 3: "); PrintList(head); // front of the linked list data = 1; pos = 1; head = InsertPos(head, pos, data); document.write("Linked list after" + "insertion of 1 at position 1: "); PrintList(head); // insertion at end of the linked list data = 15; pos = 7; head = InsertPos(head, pos, data); document.write("Linked list after" + " insertion of 15 at position 7: "); PrintList(head); // This code is contributed by gauravrajput1.</script>
Time Complexity: O(N)
Kirti_Mangal
dhirucoool
Rajput-Ji
rutvik_56
GauravRajput1
simmytarika5
arorakashish0911
cpp-double-pointer
Data Structures
Linked List
Data Structures
Linked List
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n24 Jun, 2022"
},
{
"code": null,
"e": 202,
"s": 54,
"text": "Given a singly linked list, a position and an element, the task is to write a program to insert that element in a linked list at a given position. "
},
{
"code": null,
"e": 213,
"s": 202,
"text": "Examples: "
},
{
"code": null,
"e": 349,
"s": 213,
"text": "Input: 3->5->8->10, data = 2, position = 2\nOutput: 3->2->5->8->10\n\nInput: 3->5->8->10, data = 11, position = 5\nOutput: 3->5->8->10->11 "
},
{
"code": null,
"e": 448,
"s": 349,
"text": "Approach: To insert a given data at a specified position, the below algorithm is to be followed: "
},
{
"code": null,
"e": 496,
"s": 448,
"text": "Traverse the Linked list upto position-1 nodes."
},
{
"code": null,
"e": 593,
"s": 496,
"text": "Once all the position-1 nodes are traversed, allocate memory and the given data to the new node."
},
{
"code": null,
"e": 661,
"s": 593,
"text": "Point the next pointer of the new node to the next of current node."
},
{
"code": null,
"e": 717,
"s": 661,
"text": "Point the next pointer of current node to the new node."
},
{
"code": null,
"e": 770,
"s": 717,
"text": "Below is the implementation of the above algorithm. "
},
{
"code": null,
"e": 774,
"s": 770,
"text": "C++"
},
{
"code": null,
"e": 779,
"s": 774,
"text": "Java"
},
{
"code": null,
"e": 787,
"s": 779,
"text": "Python3"
},
{
"code": null,
"e": 790,
"s": 787,
"text": "C#"
},
{
"code": null,
"e": 801,
"s": 790,
"text": "Javascript"
},
{
"code": "// C++ program for insertion in a single linked// list at a specified position#include <bits/stdc++.h>using namespace std; // A linked list Nodestruct Node { int data; struct Node* next;}; // Size of linked listint size = 0; // function to create and return a NodeNode* getNode(int data){ // allocating space Node* newNode = new Node(); // inserting the required data newNode->data = data; newNode->next = NULL; return newNode;} // function to insert a Node at required positionvoid insertPos(Node** current, int pos, int data){ // This condition to check whether the // position given is valid or not. if (pos < 1 || pos > size + 1) cout << \"Invalid position!\" << endl; else { // Keep looping until the pos is zero while (pos--) { if (pos == 0) { // adding Node at required position Node* temp = getNode(data); // Making the new Node to point to // the old Node at the same position temp->next = *current; // Changing the pointer of the Node previous // to the old Node to point to the new Node *current = temp; } else // Assign double pointer variable to point to the // pointer pointing to the address of next Node current = &(*current)->next; } size++; }} // This function prints contents // of the linked list void printList(struct Node* head){ while (head != NULL) { cout << \" \" << head->data; head = head->next; } cout << endl;} // Driver Codeint main(){ // Creating the list 3->5->8->10 Node* head = NULL; head = getNode(3); head->next = getNode(5); head->next->next = getNode(8); head->next->next->next = getNode(10); size = 4; cout << \"Linked list before insertion: \"; printList(head); int data = 12, pos = 3; insertPos(&head, pos, data); cout << \"Linked list after insertion of 12 at position 3: \"; printList(head); // front of the linked list data = 1, pos = 1; insertPos(&head, pos, data); cout << \"Linked list after insertion of 1 at position 1: \"; printList(head); // insertion at end of the linked list data = 15, pos = 7; insertPos(&head, pos, data); cout << \"Linked list after insertion of 15 at position 7: \"; printList(head); return 0;}",
"e": 3253,
"s": 801,
"text": null
},
{
"code": "// Java program for insertion in a single linked // list at a specified position class GFG { // A linked list Node static class Node { public int data; public Node nextNode; // inserting the required data public Node(int data) { this.data = data; } } // function to create and return a Node static Node GetNode(int data) { return new Node(data); } // function to insert a Node at required position static Node InsertPos(Node headNode, int position, int data) { Node head = headNode; if (position < 1) System.out.print(\"Invalid position\"); // if position is 1 then new node is // set infornt of head node // head node is changing. if (position == 1) { Node newNode = new Node(data); newNode.nextNode = headNode; head = newNode; } else { while (position-- != 0) { if (position == 1) { // adding Node at required position Node newNode = GetNode(data); // Making the new Node to point to // the old Node at the same position newNode.nextNode = headNode.nextNode; // Replacing current with new Node // to the old Node to point to the new Node headNode.nextNode = newNode; break; } headNode = headNode.nextNode; } if (position != 1) System.out.print(\"Position out of range\"); } return head; } static void PrintList(Node node) { while (node != null) { System.out.print(node.data); node = node.nextNode; if (node != null) System.out.print(\",\"); } System.out.println(); } // Driver code public static void main(String[] args) { Node head = GetNode(3); head.nextNode = GetNode(5); head.nextNode.nextNode = GetNode(8); head.nextNode.nextNode.nextNode = GetNode(10); System.out.print(\"Linked list before insertion: \"); PrintList(head); int data = 12, pos = 3; head = InsertPos(head, pos, data); System.out.print(\"Linked list after\" + \" insertion of 12 at position 3: \"); PrintList(head); // front of the linked list data = 1; pos = 1; head = InsertPos(head, pos, data); System.out.print(\"Linked list after\" + \"insertion of 1 at position 1: \"); PrintList(head); // insertion at end of the linked list data = 15; pos = 7; head = InsertPos(head, pos, data); System.out.print(\"Linked list after\" + \" insertion of 15 at position 7: \"); PrintList(head); }} // This code is contributed by Rajput-Ji",
"e": 6151,
"s": 3253,
"text": null
},
{
"code": "# Python3 program for insertion in a single linked# list at a specified position # A linked list Nodeclass Node: def __init__(self, data): self.data = data self.nextNode = None # function to create and return a Nodedef getNode(data): # allocating space newNode = Node(data) return newNode; # function to insert a Node at required positiondef insertPos(headNode, position, data): head = headNode # This condition to check whether the # position given is valid or not. if (position < 1): print(\"Invalid position!\") if position == 1: newNode = Node(data) newNode.nextNode = headNode head = newNode else: # Keep looping until the position is zero while (position != 0): position -= 1 if (position == 1): # adding Node at required position newNode = getNode(data) # Making the new Node to point to # the old Node at the same position newNode.nextNode = headNode.nextNode # Replacing headNode with new Node # to the old Node to point to the new Node headNode.nextNode = newNode break headNode = headNode.nextNode if headNode == None: break if position != 1: print(\"position out of range\") return head # This function prints contents # of the linked list def printList(head): while (head != None): print(' ' + str(head.data), end = '') head = head.nextNode; print() # Driver Codeif __name__=='__main__': # Creating the list 3.5.8.10 head = getNode(3); head.nextNode = getNode(5); head.nextNode.nextNode = getNode(8); head.nextNode.nextNode.nextNode = getNode(10); print(\"Linked list before insertion: \", end='') printList(head); data = 12 position = 3; head = insertPos(head, position, data); print(\"Linked list after insertion of 12 at position 3: \", end = '') printList(head); # front of the linked list data = 1 position = 1; head = insertPos(head, position, data); print(\"Linked list after insertion of 1 at position 1: \", end = '') printList(head); # insertion at end of the linked list data = 15 position = 7; head = insertPos(head, position, data); print(\"Linked list after insertion of 15 at position 7: \", end='') printList(head); # This code iscontributed by rutvik_56",
"e": 8757,
"s": 6151,
"text": null
},
{
"code": "// C# program for insertion in a single linked // list at a specified position using System; namespace InsertIntoLinkedList{ class Program { // A linked list Node private class Node { public int data; public Node nextNode; // inserting the required data public Node(int data) => this.data = data; } // function to create and return a Node static Node GetNode(int data) => new Node(data); // function to insert a Node at required position static Node InsertPos(Node headNode, int position, int data) { var head = headNode; if (position < 1) Console.WriteLine(\"Invalid position\"); //if position is 1 then new node is // set infornt of head node //head node is changing. if (position == 1) { var newNode = new Node(data); newNode.nextNode = headNode; head = newNode; } else { while (position-- != 0) { if (position == 1) { // adding Node at required position Node newNode = GetNode(data); // Making the new Node to point to // the old Node at the same position newNode.nextNode = headNode.nextNode; // Replacing current with new Node // to the old Node to point to the new Node headNode.nextNode = newNode; break; } headNode = headNode.nextNode; } if (position != 1) Console.WriteLine(\"Position out of range\"); } return head; } static void PrintList(Node node) { while (node != null) { Console.Write(node.data); node = node.nextNode; if(node != null) Console.Write(\",\"); } Console.WriteLine(); } // Driver code static void Main(string[] args) { var head = GetNode(3); head.nextNode = GetNode(5); head.nextNode.nextNode = GetNode(8); head.nextNode.nextNode.nextNode = GetNode(10); Console.WriteLine(\"Linked list before insertion: \"); PrintList(head); int data = 12, pos = 3; head = InsertPos(head, pos, data); Console.WriteLine(\"Linked list after\" + \" insertion of 12 at position 3: \"); PrintList(head); // front of the linked list data = 1; pos = 1; head = InsertPos(head, pos, data); Console.WriteLine(\"Linked list after\" + \"insertion of 1 at position 1: \"); PrintList(head); // insertion at end of the linked list data = 15; pos = 7; head = InsertPos(head, pos, data); Console.WriteLine(\"Linked list after\" + \" insertion of 15 at position 7: \"); PrintList(head); } }} // This code is contributed by dhirucoool",
"e": 12167,
"s": 8757,
"text": null
},
{
"code": "<script>// javascript program for insertion in a single linked // list at a specified position // A linked list Node class Node { // inserting the required data constructor(val) { this.data = val; this.nextNode = null; } } // function to create and return a Node function GetNode(data) { return new Node(data); } // function to insert a Node at required position function InsertPos( headNode , position , data) { head = headNode; if (position < 1) document.write(\"Invalid position\"); // if position is 1 then new node is // set infront of head node // head node is changing. if (position == 1) { newNode = new Node(data); newNode.nextNode = headNode; head = newNode; } else { while (position-- != 0) { if (position == 1) { // adding Node at required position newNode = GetNode(data); // Making the new Node to point to // the old Node at the same position newNode.nextNode = headNode.nextNode; // Replacing current with new Node // to the old Node to point to the new Node headNode.nextNode = newNode; break; } headNode = headNode.nextNode; } if (position != 1) document.write(\"Position out of range\"); } return head; } function PrintList( node) { while (node != null) { document.write(node.data); node = node.nextNode; if (node != null) document.write(\",\"); } document.write(\"<br/>\"); } // Driver code head = GetNode(3); head.nextNode = GetNode(5); head.nextNode.nextNode = GetNode(8); head.nextNode.nextNode.nextNode = GetNode(10); document.write(\"Linked list before insertion: \"); PrintList(head); var data = 12, pos = 3; head = InsertPos(head, pos, data); document.write(\"Linked list after\" + \" insertion of 12 at position 3: \"); PrintList(head); // front of the linked list data = 1; pos = 1; head = InsertPos(head, pos, data); document.write(\"Linked list after\" + \"insertion of 1 at position 1: \"); PrintList(head); // insertion at end of the linked list data = 15; pos = 7; head = InsertPos(head, pos, data); document.write(\"Linked list after\" + \" insertion of 15 at position 7: \"); PrintList(head); // This code is contributed by gauravrajput1.</script>",
"e": 15026,
"s": 12167,
"text": null
},
{
"code": null,
"e": 15049,
"s": 15026,
"text": "Time Complexity: O(N) "
},
{
"code": null,
"e": 15064,
"s": 15051,
"text": "Kirti_Mangal"
},
{
"code": null,
"e": 15075,
"s": 15064,
"text": "dhirucoool"
},
{
"code": null,
"e": 15085,
"s": 15075,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 15095,
"s": 15085,
"text": "rutvik_56"
},
{
"code": null,
"e": 15109,
"s": 15095,
"text": "GauravRajput1"
},
{
"code": null,
"e": 15122,
"s": 15109,
"text": "simmytarika5"
},
{
"code": null,
"e": 15139,
"s": 15122,
"text": "arorakashish0911"
},
{
"code": null,
"e": 15158,
"s": 15139,
"text": "cpp-double-pointer"
},
{
"code": null,
"e": 15174,
"s": 15158,
"text": "Data Structures"
},
{
"code": null,
"e": 15186,
"s": 15174,
"text": "Linked List"
},
{
"code": null,
"e": 15202,
"s": 15186,
"text": "Data Structures"
},
{
"code": null,
"e": 15214,
"s": 15202,
"text": "Linked List"
}
] |
Shell Script to Split a String
|
20 Jun, 2021
Shell Scripting or Shell Programming is just like any other programming language. A shell is a special program that provides an interface between the user and the operating system.
In Linux/Unix the default shell used is bash and in windows, it is cmd(command prompt). We use the terminal to run a shell command. Shell scripts are saved with .sh file extension, and we can run the script with the help of the following command.
bash path/to/the/filename.sh
Example:
A simple shell program to print Hello Geeks!!.
#! /bin/bash
# echo is used to print
echo "Hello Geeks!!"
Here, #! /bin/bash is used to let know the Linux/Unix that it is a Bash Script and use the bash interpreter which resides in /bin to execute it.
Output:
First Shell Program
Let’s discuss how we can split a string take the following string for an example:
string = “Lelouch,Akame,Kakashi,Wrath”
And we would like to split the string by “,” delimiter so that we have :
name=”Lelouch”
name =”Akame”
name=”Kakashi”
name=”Wrath”
Approach 1: Using IFS (Input Field Separator).
IFS stands for Internal Field Separator or Input Field separator variable is used to separate a string into tokens.
Original String :
string=”Lelouch,Akame,Kakashi,Wrath”
After Splitting :
name = Lelouch
name = Akame
name = Kakashi
name = Wrath
String holds the input string value and IFS variable the delimiter on that we are going to separate the string. read -ra arr <<< “$string” convert the separated strings into an array, after that we are using for loop to traverse the array and print the value.“@” in arr subscript shows that we are going through the whole array.
Script :
#! /bin/bash
# Given string
string="Lelouch,Akame,Kakashi,Wrath"
# Setting IFS (input field separator) value as ","
IFS=','
# Reading the split string into array
read -ra arr <<< "$string"
# Print each value of the array by using the loop
for val in "${arr[@]}";
do
printf "name = $val\n"
done
To run the script use the following command :
bash path/to/the/filename.sh
Output:
Script Output
Approach 2: Without using the IFS
Suppose input string is containing a particular word “anime” and we want to split the string on seeing “anime”
string = “anime Bleach anime Naruto anime Pokemon anime Monster anime Dororo”
Output :
Anime name is = Bleach
Anime name is = Naruto
Anime name is = Pokemon
Anime name is = Monster
Anime name is = Dororo
We can do this using Parameter Expansion.
Script :
#! /bin/bash
# Given string
string="anime Bleach anime Naruto anime Pokemon anime Monster anime Dororo"
# Syntax to replace all occurrences of "anime" with " "
arr=(${string//"anime"/ })
# Print each value of the array by using the loop
for val in "${arr[@]}";
do
printf "Anime name is = $val\n"
done
Output:
Script Output
simranarora5sos
Picked
Shell Script
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Jun, 2021"
},
{
"code": null,
"e": 209,
"s": 28,
"text": "Shell Scripting or Shell Programming is just like any other programming language. A shell is a special program that provides an interface between the user and the operating system."
},
{
"code": null,
"e": 456,
"s": 209,
"text": "In Linux/Unix the default shell used is bash and in windows, it is cmd(command prompt). We use the terminal to run a shell command. Shell scripts are saved with .sh file extension, and we can run the script with the help of the following command."
},
{
"code": null,
"e": 485,
"s": 456,
"text": "bash path/to/the/filename.sh"
},
{
"code": null,
"e": 494,
"s": 485,
"text": "Example:"
},
{
"code": null,
"e": 541,
"s": 494,
"text": "A simple shell program to print Hello Geeks!!."
},
{
"code": null,
"e": 600,
"s": 541,
"text": "#! /bin/bash\n\n# echo is used to print\necho \"Hello Geeks!!\""
},
{
"code": null,
"e": 745,
"s": 600,
"text": "Here, #! /bin/bash is used to let know the Linux/Unix that it is a Bash Script and use the bash interpreter which resides in /bin to execute it."
},
{
"code": null,
"e": 753,
"s": 745,
"text": "Output:"
},
{
"code": null,
"e": 773,
"s": 753,
"text": "First Shell Program"
},
{
"code": null,
"e": 855,
"s": 773,
"text": "Let’s discuss how we can split a string take the following string for an example:"
},
{
"code": null,
"e": 895,
"s": 855,
"text": "string = “Lelouch,Akame,Kakashi,Wrath”"
},
{
"code": null,
"e": 969,
"s": 895,
"text": "And we would like to split the string by “,” delimiter so that we have :"
},
{
"code": null,
"e": 984,
"s": 969,
"text": "name=”Lelouch”"
},
{
"code": null,
"e": 998,
"s": 984,
"text": "name =”Akame”"
},
{
"code": null,
"e": 1013,
"s": 998,
"text": "name=”Kakashi”"
},
{
"code": null,
"e": 1026,
"s": 1013,
"text": "name=”Wrath”"
},
{
"code": null,
"e": 1073,
"s": 1026,
"text": "Approach 1: Using IFS (Input Field Separator)."
},
{
"code": null,
"e": 1189,
"s": 1073,
"text": "IFS stands for Internal Field Separator or Input Field separator variable is used to separate a string into tokens."
},
{
"code": null,
"e": 1208,
"s": 1189,
"text": "Original String : "
},
{
"code": null,
"e": 1245,
"s": 1208,
"text": "string=”Lelouch,Akame,Kakashi,Wrath”"
},
{
"code": null,
"e": 1263,
"s": 1245,
"text": "After Splitting :"
},
{
"code": null,
"e": 1278,
"s": 1263,
"text": "name = Lelouch"
},
{
"code": null,
"e": 1291,
"s": 1278,
"text": "name = Akame"
},
{
"code": null,
"e": 1306,
"s": 1291,
"text": "name = Kakashi"
},
{
"code": null,
"e": 1319,
"s": 1306,
"text": "name = Wrath"
},
{
"code": null,
"e": 1649,
"s": 1319,
"text": " String holds the input string value and IFS variable the delimiter on that we are going to separate the string. read -ra arr <<< “$string” convert the separated strings into an array, after that we are using for loop to traverse the array and print the value.“@” in arr subscript shows that we are going through the whole array."
},
{
"code": null,
"e": 1658,
"s": 1649,
"text": "Script :"
},
{
"code": null,
"e": 1959,
"s": 1658,
"text": "#! /bin/bash\n\n# Given string \nstring=\"Lelouch,Akame,Kakashi,Wrath\"\n\n# Setting IFS (input field separator) value as \",\"\nIFS=','\n\n# Reading the split string into array\nread -ra arr <<< \"$string\"\n\n# Print each value of the array by using the loop\nfor val in \"${arr[@]}\";\ndo\n printf \"name = $val\\n\"\ndone"
},
{
"code": null,
"e": 2005,
"s": 1959,
"text": "To run the script use the following command :"
},
{
"code": null,
"e": 2034,
"s": 2005,
"text": "bash path/to/the/filename.sh"
},
{
"code": null,
"e": 2042,
"s": 2034,
"text": "Output:"
},
{
"code": null,
"e": 2056,
"s": 2042,
"text": "Script Output"
},
{
"code": null,
"e": 2090,
"s": 2056,
"text": "Approach 2: Without using the IFS"
},
{
"code": null,
"e": 2202,
"s": 2090,
"text": " Suppose input string is containing a particular word “anime” and we want to split the string on seeing “anime”"
},
{
"code": null,
"e": 2280,
"s": 2202,
"text": "string = “anime Bleach anime Naruto anime Pokemon anime Monster anime Dororo”"
},
{
"code": null,
"e": 2289,
"s": 2280,
"text": "Output :"
},
{
"code": null,
"e": 2312,
"s": 2289,
"text": "Anime name is = Bleach"
},
{
"code": null,
"e": 2335,
"s": 2312,
"text": "Anime name is = Naruto"
},
{
"code": null,
"e": 2359,
"s": 2335,
"text": "Anime name is = Pokemon"
},
{
"code": null,
"e": 2383,
"s": 2359,
"text": "Anime name is = Monster"
},
{
"code": null,
"e": 2406,
"s": 2383,
"text": "Anime name is = Dororo"
},
{
"code": null,
"e": 2448,
"s": 2406,
"text": "We can do this using Parameter Expansion."
},
{
"code": null,
"e": 2457,
"s": 2448,
"text": "Script :"
},
{
"code": null,
"e": 2765,
"s": 2457,
"text": "#! /bin/bash\n\n# Given string \nstring=\"anime Bleach anime Naruto anime Pokemon anime Monster anime Dororo\"\n\n# Syntax to replace all occurrences of \"anime\" with \" \"\narr=(${string//\"anime\"/ })\n\n# Print each value of the array by using the loop\nfor val in \"${arr[@]}\";\ndo\n\n printf \"Anime name is = $val\\n\"\ndone"
},
{
"code": null,
"e": 2773,
"s": 2765,
"text": "Output:"
},
{
"code": null,
"e": 2787,
"s": 2773,
"text": "Script Output"
},
{
"code": null,
"e": 2803,
"s": 2787,
"text": "simranarora5sos"
},
{
"code": null,
"e": 2810,
"s": 2803,
"text": "Picked"
},
{
"code": null,
"e": 2823,
"s": 2810,
"text": "Shell Script"
},
{
"code": null,
"e": 2834,
"s": 2823,
"text": "Linux-Unix"
}
] |
Python calendar module | setfirstweekday() method
|
22 Oct, 2018
Calendar module allows to output calendars like program, and provides additional useful functions related to the calendar. Functions and classes defined in Calendar module use an idealized calendar, the current Gregorian calendar extended indefinitely in both directions.
In Python, calendar.setfirstweekday(weekday) is a function provided in calendar module for simple text calendars.
setfirstweekday() method sets the weekday (0 is Monday, 6 is Sunday) to start each week. The values MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, and SUNDAY are provided for convenience.For example, to set the first weekday to Sunday.
Syntax: setfirstweekday()
Parameter: no parameter
Returns: None
Code #1:
# Python program to explain working of setfirstweekday() method # importing calendar moduleimport calendar # calling setfirstweekday() functionval = calendar.setfirstweekday(calendar.SUNDAY) # returns Noneprint(val)
Output:
None
Code #2: Explaining working of setfirstweekday() method with prmonth() method
# Python code to demonstrate the working of # setfirstweekday() with prmonth() method # importing calendar module for calendar operations import calendar # using prmonth() to print calendar of 1997 print ("The 4th month of 1997 is : ") calendar.prmonth(1997, 4, 2, 1) # using setfirstweekday() to set first week day number calendar.setfirstweekday(4) print ("\r") # using firstweekday() to check the changed day print ("The new week day number is : ", end ="") print (calendar.firstweekday())
Output:
The 4th month of 1997 is :
April 1997
Mo Tu We Th Fr Sa Su
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
The new week day number is : 4
Python Calander-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Introduction To PYTHON
Python OOPs Concepts
Convert integer to string in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Oct, 2018"
},
{
"code": null,
"e": 300,
"s": 28,
"text": "Calendar module allows to output calendars like program, and provides additional useful functions related to the calendar. Functions and classes defined in Calendar module use an idealized calendar, the current Gregorian calendar extended indefinitely in both directions."
},
{
"code": null,
"e": 414,
"s": 300,
"text": "In Python, calendar.setfirstweekday(weekday) is a function provided in calendar module for simple text calendars."
},
{
"code": null,
"e": 659,
"s": 414,
"text": "setfirstweekday() method sets the weekday (0 is Monday, 6 is Sunday) to start each week. The values MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, and SUNDAY are provided for convenience.For example, to set the first weekday to Sunday."
},
{
"code": null,
"e": 723,
"s": 659,
"text": "Syntax: setfirstweekday()\nParameter: no parameter\nReturns: None"
},
{
"code": null,
"e": 732,
"s": 723,
"text": "Code #1:"
},
{
"code": "# Python program to explain working of setfirstweekday() method # importing calendar moduleimport calendar # calling setfirstweekday() functionval = calendar.setfirstweekday(calendar.SUNDAY) # returns Noneprint(val)",
"e": 951,
"s": 732,
"text": null
},
{
"code": null,
"e": 959,
"s": 951,
"text": "Output:"
},
{
"code": null,
"e": 964,
"s": 959,
"text": "None"
},
{
"code": null,
"e": 1043,
"s": 964,
"text": " Code #2: Explaining working of setfirstweekday() method with prmonth() method"
},
{
"code": "# Python code to demonstrate the working of # setfirstweekday() with prmonth() method # importing calendar module for calendar operations import calendar # using prmonth() to print calendar of 1997 print (\"The 4th month of 1997 is : \") calendar.prmonth(1997, 4, 2, 1) # using setfirstweekday() to set first week day number calendar.setfirstweekday(4) print (\"\\r\") # using firstweekday() to check the changed day print (\"The new week day number is : \", end =\"\") print (calendar.firstweekday()) ",
"e": 1548,
"s": 1043,
"text": null
},
{
"code": null,
"e": 1556,
"s": 1548,
"text": "Output:"
},
{
"code": null,
"e": 1747,
"s": 1556,
"text": "The 4th month of 1997 is : \n April 1997\nMo Tu We Th Fr Sa Su\n 1 2 3 4 5 6\n 7 8 9 10 11 12 13\n14 15 16 17 18 19 20\n21 22 23 24 25 26 27\n28 29 30\n \nThe new week day number is : 4"
},
{
"code": null,
"e": 1770,
"s": 1747,
"text": "Python Calander-module"
},
{
"code": null,
"e": 1777,
"s": 1770,
"text": "Python"
},
{
"code": null,
"e": 1875,
"s": 1777,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1893,
"s": 1875,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1935,
"s": 1893,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1957,
"s": 1935,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1983,
"s": 1957,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2015,
"s": 1983,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2044,
"s": 2015,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2071,
"s": 2044,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2094,
"s": 2071,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2115,
"s": 2094,
"text": "Python OOPs Concepts"
}
] |
Remove border from IFrame using CSS
|
04 Dec, 2018
The Iframe is used to display a web page on the webpage. Remove border from iframe tag in the webpage could be done by using one of the CSS properties of the iframe tag called frameBorder and set its value to “0”.
Syntax:
frameBorder = "value";
Note: In the frameBorder property the B letter must be in capital otherwise it will not be recognized by the browser. The value taken by the frameBorder property are 0 and 1, where 0 is used to disable the border and 1 is used for enabling the border property. By default, the value is set to 1.
Example 1:
<!DOCTYPE html><html> <head> <title>Disable Iframe Border</title> <style> iframe { height:200px; width:400px; background-color:lightgreen; } h1 { color:green; } body { text-align:center; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>iframe border property</h2> <!-- We do not use border by specifying value 0 --> <iframe src=# frameBorder="0"></iframe> </body></html>
Output:
Example 2:
<!DOCTYPE html><html> <head> <title>Disable Iframe Border</title> <style> iframe { height:200px; width:400px; background-color:green; } h1 { color:green; } body { text-align:center; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>iframe border property</h2> <!-- We use border by specifying a non-zero value --> <iframe src=# frameBorder="1"></iframe> </body></html>
Output:
CSS-Misc
Picked
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n04 Dec, 2018"
},
{
"code": null,
"e": 242,
"s": 28,
"text": "The Iframe is used to display a web page on the webpage. Remove border from iframe tag in the webpage could be done by using one of the CSS properties of the iframe tag called frameBorder and set its value to “0”."
},
{
"code": null,
"e": 250,
"s": 242,
"text": "Syntax:"
},
{
"code": null,
"e": 273,
"s": 250,
"text": "frameBorder = \"value\";"
},
{
"code": null,
"e": 569,
"s": 273,
"text": "Note: In the frameBorder property the B letter must be in capital otherwise it will not be recognized by the browser. The value taken by the frameBorder property are 0 and 1, where 0 is used to disable the border and 1 is used for enabling the border property. By default, the value is set to 1."
},
{
"code": null,
"e": 580,
"s": 569,
"text": "Example 1:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Disable Iframe Border</title> <style> iframe { height:200px; width:400px; background-color:lightgreen; } h1 { color:green; } body { text-align:center; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>iframe border property</h2> <!-- We do not use border by specifying value 0 --> <iframe src=# frameBorder=\"0\"></iframe> </body></html> ",
"e": 1180,
"s": 580,
"text": null
},
{
"code": null,
"e": 1188,
"s": 1180,
"text": "Output:"
},
{
"code": null,
"e": 1199,
"s": 1188,
"text": "Example 2:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Disable Iframe Border</title> <style> iframe { height:200px; width:400px; background-color:green; } h1 { color:green; } body { text-align:center; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>iframe border property</h2> <!-- We use border by specifying a non-zero value --> <iframe src=# frameBorder=\"1\"></iframe> </body></html> ",
"e": 1796,
"s": 1199,
"text": null
},
{
"code": null,
"e": 1804,
"s": 1796,
"text": "Output:"
},
{
"code": null,
"e": 1813,
"s": 1804,
"text": "CSS-Misc"
},
{
"code": null,
"e": 1820,
"s": 1813,
"text": "Picked"
},
{
"code": null,
"e": 1824,
"s": 1820,
"text": "CSS"
},
{
"code": null,
"e": 1829,
"s": 1824,
"text": "HTML"
},
{
"code": null,
"e": 1846,
"s": 1829,
"text": "Web Technologies"
},
{
"code": null,
"e": 1851,
"s": 1846,
"text": "HTML"
}
] |
Twin Prime Numbers between 1 and n
|
05 Apr, 2021
Given an integer n. we need to print all twin prime number pairs between 1 to n. A Twin prime are those numbers which are prime and having a difference of two ( 2 ) between the two prime numbers. In other words, a twin prime is a prime that has a prime gap of two. Sometimes the term twin prime is used for a pair of twin primes; an alternative name for this is prime twin or prime pair. Usually, the pair (2, 3) is not considered to be a pair of twin primes. Since 2 is the only even prime, this pair is the only pair of prime numbers that differ by one; thus twin primes are as closely spaced as possible for any other two primes.The first few twin prime pairs are :
(3, 5), (5, 7), (11, 13), (17, 19), (29, 31),
(41, 43), (59, 61), (71, 73), (101, 103),
(107, 109), (137, 139), ...etc.
FACT : There are 409 Twin primes below 10, 000.Examples:
Input : n = 15
Output : (3, 5), (5, 7), (11, 13)
Input : 25
Output :(3, 5), (5, 7), (11, 13), (17, 19)
Approach: Using Sieve of Eratosthenes find the list of all primes smaller than or equal to n and then iterate list again till n and just checks the ith number and heck its (i+2)th number if both are prime then print both the numbers else proceed to next number to find Twin prime.
C++
Java
Python
C#
PHP
Javascript
// C++ program print all twin primes// using Sieve of Eratosthenes.#include <bits/stdc++.h>using namespace std; void printTwinPrime(int n){ // Create a boolean array "prime[0..n]" // and initialize all entries it as true. // A value in prime[i] will finally be false // if i is Not a prime, else true. bool prime[n + 1]; memset(prime, true, sizeof(prime)); for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= n; i += p) prime[i] = false; } } // to check for twin prime numbers // display the twin primes for (int p = 2; p <= n - 2; p++) if (prime[p] && prime[p + 2]) cout << "(" << p << ", " << p + 2 << ")" ;} // Driver Program to test above functionint main(){ int n = 25; // Calling the function printTwinPrime(n); return 0;}
// Java program to print all Twin Prime// Numbers using Sieve of Eratosthenesimport java.io.*; class GFG { static void printTwinPrime(int n) { // Create a boolean array "prime[0..n]" // and initialize all entries it as // true. A value in prime[i] will // finally be false if i is Not a // prime, else true. boolean prime[] = new boolean[n + 1]; for (int i = 0; i <= n; i++) prime[i] = true; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= n; i += p) prime[i] = false; } } // to check for twin prime numbers // display th twin prime for (int i = 2; i <= n - 2; i++) { if (prime[i] == true && prime[i + 2] == true) // Display the result System.out.print(" (" + i + ", " + (i + 2) + ")"); } } // Driver Program to test above function public static void main(String args[]) { int n = 25; printTwinPrime(n); }}
# Python program to illustrate...# To print total number of twin prime# using Sieve of Eratosthenes def printTwinPrime(n): # Create a boolean array "prime[0..n]" # and initialize all entries it as # true. A value in prime[i] will # finally be false if i is Not a prime, # else true. prime = [True for i in range(n + 2)] p = 2 while (p * p <= n + 1): # If prime[p] is not changed, # then it is a prime if (prime[p] == True): # Update all multiples of p for i in range(p * 2, n + 2, p): prime[i] = False p += 1 # check twin prime numbers # display the twin prime numbers for p in range(2, n-1): if prime[p] and prime[p + 2]: print("(",p,",", (p + 2), ")" ,end='') # driver programif __name__=='__main__': # static input n = 25 # Calling the function printTwinPrime(n)
// C# program to illustrate..// print all twin primes// Using Sieve of Eratosthenesusing System; public class GFG { public static void printtwinprime(int n) { // Create a boolean array "prime[0..n]" // and initialize all entries it as // true. A value in prime[i] will // finally be false if i is Not a // prime, else true. bool[] prime = new bool[n + 1]; for (int i = 0; i < n + 1; i++) prime[i] = true; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= n; i += p) prime[i] = false; } } // check for twin prime numbers // To display th result for (int i = 2; i <= n - 2; i++) { if (prime[i] == true && prime[i + 2] == true) Console.Write(" (" + i + ", " + (i + 2) + ")"); } } // Driver Code public static void Main() { // static input int n = 25; // calling the function printtwinprime(n); } }
<?php// PHP program to print// all twin primes using// Sieve of Eratosthenes.function printTwinPrime($n){ // Create a boolean array // "prime[0..n]" and // initialize all entries // it as true. A value in // prime[i] will finally be // false if i is Not a prime, // else true. $prime = array_fill(0, $n + 1, true); for ($p = 2; $p * $p <= $n; $p++) { // If prime[p] is not // changed, then it // is a prime if ($prime[$p] == true) { // Update all // multiples of p for ($i = $p * 2; $i <= $n; $i += $p) $prime[$i] = false; } } // to check for twin // prime numbers display // the twin primes for ($p = 2; $p <= $n - 2; $p++) if ($prime[$p] && $prime[$p + 2]) echo "(". $p . ", " . ($p + 2). ")" ;} // Driver Code$n = 25; // Calling the functionprintTwinPrime($n); // This code is contributed by mits.?>
<script> // JavaScript program to print all Twin Prime// Numbers using Sieve of Eratosthenes function printTwinPrime(n) { // Create a boolean array "prime[0..n]" // and initialize all entries it as // true. A value in prime[i] will // finally be false if i is Not a // prime, else true. let prime = []; for (let i = 0; i <= n; i++) prime[i] = true; for (let p = 2; p * p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p for (let i = p * 2; i <= n; i += p) prime[i] = false; } } // to check for twin prime numbers // display th twin prime for (let i = 2; i <= n - 2; i++) { if (prime[i] == true && prime[i + 2] == true) // Display the result document.write(" (" + i + ", " + (i + 2) + ")"); } }// Driver program let n = 25; printTwinPrime(n); // This code is contributed by susmitakundugoaldanga.</script>
(3, 5)(5, 7)(11, 13)(17, 19)
Mithun Kumar
susmitakundugoaldanga
Prime Number
sieve
Mathematical
Mathematical
Prime Number
sieve
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n05 Apr, 2021"
},
{
"code": null,
"e": 723,
"s": 52,
"text": "Given an integer n. we need to print all twin prime number pairs between 1 to n. A Twin prime are those numbers which are prime and having a difference of two ( 2 ) between the two prime numbers. In other words, a twin prime is a prime that has a prime gap of two. Sometimes the term twin prime is used for a pair of twin primes; an alternative name for this is prime twin or prime pair. Usually, the pair (2, 3) is not considered to be a pair of twin primes. Since 2 is the only even prime, this pair is the only pair of prime numbers that differ by one; thus twin primes are as closely spaced as possible for any other two primes.The first few twin prime pairs are : "
},
{
"code": null,
"e": 845,
"s": 723,
"text": "(3, 5), (5, 7), (11, 13), (17, 19), (29, 31), \n(41, 43), (59, 61), (71, 73), (101, 103), \n(107, 109), (137, 139), ...etc."
},
{
"code": null,
"e": 904,
"s": 845,
"text": "FACT : There are 409 Twin primes below 10, 000.Examples: "
},
{
"code": null,
"e": 1008,
"s": 904,
"text": "Input : n = 15\nOutput : (3, 5), (5, 7), (11, 13)\n\nInput : 25\nOutput :(3, 5), (5, 7), (11, 13), (17, 19)"
},
{
"code": null,
"e": 1293,
"s": 1010,
"text": "Approach: Using Sieve of Eratosthenes find the list of all primes smaller than or equal to n and then iterate list again till n and just checks the ith number and heck its (i+2)th number if both are prime then print both the numbers else proceed to next number to find Twin prime. "
},
{
"code": null,
"e": 1297,
"s": 1293,
"text": "C++"
},
{
"code": null,
"e": 1302,
"s": 1297,
"text": "Java"
},
{
"code": null,
"e": 1309,
"s": 1302,
"text": "Python"
},
{
"code": null,
"e": 1312,
"s": 1309,
"text": "C#"
},
{
"code": null,
"e": 1316,
"s": 1312,
"text": "PHP"
},
{
"code": null,
"e": 1327,
"s": 1316,
"text": "Javascript"
},
{
"code": "// C++ program print all twin primes// using Sieve of Eratosthenes.#include <bits/stdc++.h>using namespace std; void printTwinPrime(int n){ // Create a boolean array \"prime[0..n]\" // and initialize all entries it as true. // A value in prime[i] will finally be false // if i is Not a prime, else true. bool prime[n + 1]; memset(prime, true, sizeof(prime)); for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= n; i += p) prime[i] = false; } } // to check for twin prime numbers // display the twin primes for (int p = 2; p <= n - 2; p++) if (prime[p] && prime[p + 2]) cout << \"(\" << p << \", \" << p + 2 << \")\" ;} // Driver Program to test above functionint main(){ int n = 25; // Calling the function printTwinPrime(n); return 0;}",
"e": 2328,
"s": 1327,
"text": null
},
{
"code": "// Java program to print all Twin Prime// Numbers using Sieve of Eratosthenesimport java.io.*; class GFG { static void printTwinPrime(int n) { // Create a boolean array \"prime[0..n]\" // and initialize all entries it as // true. A value in prime[i] will // finally be false if i is Not a // prime, else true. boolean prime[] = new boolean[n + 1]; for (int i = 0; i <= n; i++) prime[i] = true; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= n; i += p) prime[i] = false; } } // to check for twin prime numbers // display th twin prime for (int i = 2; i <= n - 2; i++) { if (prime[i] == true && prime[i + 2] == true) // Display the result System.out.print(\" (\" + i + \", \" + (i + 2) + \")\"); } } // Driver Program to test above function public static void main(String args[]) { int n = 25; printTwinPrime(n); }}",
"e": 3630,
"s": 2328,
"text": null
},
{
"code": "# Python program to illustrate...# To print total number of twin prime# using Sieve of Eratosthenes def printTwinPrime(n): # Create a boolean array \"prime[0..n]\" # and initialize all entries it as # true. A value in prime[i] will # finally be false if i is Not a prime, # else true. prime = [True for i in range(n + 2)] p = 2 while (p * p <= n + 1): # If prime[p] is not changed, # then it is a prime if (prime[p] == True): # Update all multiples of p for i in range(p * 2, n + 2, p): prime[i] = False p += 1 # check twin prime numbers # display the twin prime numbers for p in range(2, n-1): if prime[p] and prime[p + 2]: print(\"(\",p,\",\", (p + 2), \")\" ,end='') # driver programif __name__=='__main__': # static input n = 25 # Calling the function printTwinPrime(n)",
"e": 4572,
"s": 3630,
"text": null
},
{
"code": "// C# program to illustrate..// print all twin primes// Using Sieve of Eratosthenesusing System; public class GFG { public static void printtwinprime(int n) { // Create a boolean array \"prime[0..n]\" // and initialize all entries it as // true. A value in prime[i] will // finally be false if i is Not a // prime, else true. bool[] prime = new bool[n + 1]; for (int i = 0; i < n + 1; i++) prime[i] = true; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= n; i += p) prime[i] = false; } } // check for twin prime numbers // To display th result for (int i = 2; i <= n - 2; i++) { if (prime[i] == true && prime[i + 2] == true) Console.Write(\" (\" + i + \", \" + (i + 2) + \")\"); } } // Driver Code public static void Main() { // static input int n = 25; // calling the function printtwinprime(n); } }",
"e": 5796,
"s": 4572,
"text": null
},
{
"code": "<?php// PHP program to print// all twin primes using// Sieve of Eratosthenes.function printTwinPrime($n){ // Create a boolean array // \"prime[0..n]\" and // initialize all entries // it as true. A value in // prime[i] will finally be // false if i is Not a prime, // else true. $prime = array_fill(0, $n + 1, true); for ($p = 2; $p * $p <= $n; $p++) { // If prime[p] is not // changed, then it // is a prime if ($prime[$p] == true) { // Update all // multiples of p for ($i = $p * 2; $i <= $n; $i += $p) $prime[$i] = false; } } // to check for twin // prime numbers display // the twin primes for ($p = 2; $p <= $n - 2; $p++) if ($prime[$p] && $prime[$p + 2]) echo \"(\". $p . \", \" . ($p + 2). \")\" ;} // Driver Code$n = 25; // Calling the functionprintTwinPrime($n); // This code is contributed by mits.?>",
"e": 6822,
"s": 5796,
"text": null
},
{
"code": "<script> // JavaScript program to print all Twin Prime// Numbers using Sieve of Eratosthenes function printTwinPrime(n) { // Create a boolean array \"prime[0..n]\" // and initialize all entries it as // true. A value in prime[i] will // finally be false if i is Not a // prime, else true. let prime = []; for (let i = 0; i <= n; i++) prime[i] = true; for (let p = 2; p * p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p for (let i = p * 2; i <= n; i += p) prime[i] = false; } } // to check for twin prime numbers // display th twin prime for (let i = 2; i <= n - 2; i++) { if (prime[i] == true && prime[i + 2] == true) // Display the result document.write(\" (\" + i + \", \" + (i + 2) + \")\"); } }// Driver program let n = 25; printTwinPrime(n); // This code is contributed by susmitakundugoaldanga.</script>",
"e": 8092,
"s": 6822,
"text": null
},
{
"code": null,
"e": 8121,
"s": 8092,
"text": "(3, 5)(5, 7)(11, 13)(17, 19)"
},
{
"code": null,
"e": 8136,
"s": 8123,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 8158,
"s": 8136,
"text": "susmitakundugoaldanga"
},
{
"code": null,
"e": 8171,
"s": 8158,
"text": "Prime Number"
},
{
"code": null,
"e": 8177,
"s": 8171,
"text": "sieve"
},
{
"code": null,
"e": 8190,
"s": 8177,
"text": "Mathematical"
},
{
"code": null,
"e": 8203,
"s": 8190,
"text": "Mathematical"
},
{
"code": null,
"e": 8216,
"s": 8203,
"text": "Prime Number"
},
{
"code": null,
"e": 8222,
"s": 8216,
"text": "sieve"
}
] |
How to Build a Photo Viewing Application in Android?
|
20 Jun, 2022
Gallery app is one of the most used apps which comes pre-installed on many android devices and there are several different apps that are present in Google Play to view the media files present in your device. In this article, we will be simply creating a Gallery app in which we can view all the photos which we have stored on our device. Along with that, we can view the individual photos in our app as well.
We will be building a simple application in which we will be simply displaying the list of photos in the grid format and on clicking on the photo we can view that photo and can zoom in the photo to view it properly. Below is the vide0 in which we will get to see what we are going to build in this article.
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 the dependency in build.gradle file
Navigate to the app > Gradle Scripts > build.gradle(:app) and add the below dependency to it. We are using Picasso for loading images from paths in our ImageView.
// below dependency for using Picasso image loading library
implementation ‘com.squareup.picasso:picasso:2.71828’
Now sync your project and we will move towards adding permissions in our AndroidManifest.xml file.
Step 3: Adding permissions in our AndroidManifest.xml file
Navigate to the app > AndroidManifest.xml file and add the below permissions to it.
XML
<!-- permissions for reading external storage --><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
As we are loading all the images from our storage at a time so we have to add 2 attributes to our application tag in the AndroidManifest.xml file. Navigate to the AndroidManifest.xml file and add below two lines in your application tag of Manifest file.
XML
android:hardwareAccelerated="false"android:largeHeap="true"
Step 4: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="center" android:gravity="center" android:orientation="vertical" tools:context=".MainActivity"> <!--recycler view for displaying the list of images--> <androidx.recyclerview.widget.RecyclerView android:id="@+id/idRVImages" android:layout_width="match_parent" android:layout_height="match_parent" /> </RelativeLayout>
Step 5: Creating an item for displaying in a RecyclerView
Navigate to the app > res > layout > Right-click on it > New > layout Resource file and create a new layout resource file. Name the file as card_layout and add the below code to it. Comments are added in the code to get to know in more detail.
XML
<?xml version="1.0" encoding="utf-8"?><androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_margin="3dp" android:elevation="8dp" app:cardCornerRadius="8dp"> <!--Image view for displaying the image in our card layout in recycler view--> <ImageView android:id="@+id/idIVImage" android:layout_width="100dp" android:layout_height="100dp" android:layout_gravity="center" android:scaleType="centerCrop" /> </androidx.cardview.widget.CardView>
Step 6: Creating a new activity for displaying a single image
Navigate to the app > java > your app’s package name > Right-click on it > New > Empty Activity and name your activity as ImageDetailActivity and create a new activity. We will be using this activity to display our single image from the list of different images.
Step 7: Creating an adapter class for setting data to each item in our RecyclerView
Navigate to the app > java > your app’s package name > Right-click on it > New Java class and name your class as RecyclerViewAdapter and add the below code to it. Comments are added in the code to get to know in more detail.
Java
import android.content.Context;import android.content.Intent;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView; import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView; import com.squareup.picasso.Picasso; import java.io.File;import java.util.ArrayList; public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.RecyclerViewHolder> { // creating a variable for our context and array list. private final Context context; private final ArrayList<String> imagePathArrayList; // on below line we have created a constructor. public RecyclerViewAdapter(Context context, ArrayList<String> imagePathArrayList) { this.context = context; this.imagePathArrayList = imagePathArrayList; } @NonNull @Override public RecyclerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { // Inflate Layout in this method which we have created. View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_layout, parent, false); return new RecyclerViewHolder(view); } @Override public void onBindViewHolder(@NonNull RecyclerViewHolder holder, int position) { // on below line we are getting th file from the // path which we have stored in our list. File imgFile = new File(imagePathArrayList.get(position)); // on below line we are checking if the file exists or not. if (imgFile.exists()) { // if the file exists then we are displaying that file in our image view using picasso library. Picasso.get().load(imgFile).placeholder(R.drawable.ic_launcher_background).into(holder.imageIV); // on below line we are adding click listener to our item of recycler view. holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // inside on click listener we are creating a new intent Intent i = new Intent(context, ImageDetailActivity.class); // on below line we are passing the image path to our new activity. i.putExtra("imgPath", imagePathArrayList.get(position)); // at last we are starting our activity. context.startActivity(i); } }); } } @Override public int getItemCount() { // this method returns // the size of recyclerview return imagePathArrayList.size(); } // View Holder Class to handle Recycler View. public static class RecyclerViewHolder extends RecyclerView.ViewHolder { // creating variables for our views. private final ImageView imageIV; public RecyclerViewHolder(@NonNull View itemView) { super(itemView); // initializing our views with their ids. imageIV = itemView.findViewById(R.id.idIVImage); } }}
Step 8: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.content.pm.PackageManager;import android.database.Cursor;import android.os.Bundle;import android.provider.MediaStore;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity;import androidx.core.app.ActivityCompat;import androidx.core.content.ContextCompat;import androidx.recyclerview.widget.GridLayoutManager;import androidx.recyclerview.widget.RecyclerView; import java.util.ArrayList; import static android.Manifest.permission.READ_EXTERNAL_STORAGE; public class MainActivity extends AppCompatActivity { // on below line we are creating variables for // our array list, recycler view and adapter class. private static final int PERMISSION_REQUEST_CODE = 200; private ArrayList<String> imagePaths; private RecyclerView imagesRV; private RecyclerViewAdapter imageRVAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // we are calling a method to request // the permissions to read external storage. requestPermissions(); // creating a new array list and // initializing our recycler view. imagePaths = new ArrayList<>(); imagesRV = findViewById(R.id.idRVImages); // calling a method to // prepare our recycler view. prepareRecyclerView(); } private boolean checkPermission() { // in this method we are checking if the permissions are granted or not and returning the result. int result = ContextCompat.checkSelfPermission(getApplicationContext(), READ_EXTERNAL_STORAGE); return result == PackageManager.PERMISSION_GRANTED; } private void requestPermissions() { if (checkPermission()) { // if the permissions are already granted we are calling // a method to get all images from our external storage. Toast.makeText(this, "Permissions granted..", Toast.LENGTH_SHORT).show(); getImagePath(); } else { // if the permissions are not granted we are // calling a method to request permissions. requestPermission(); } } private void requestPermission() { //on below line we are requesting the rea external storage permissions. ActivityCompat.requestPermissions(this, new String[]{READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE); } private void prepareRecyclerView() { // in this method we are preparing our recycler view. // on below line we are initializing our adapter class. imageRVAdapter = new RecyclerViewAdapter(MainActivity.this, imagePaths); // on below line we are creating a new grid layout manager. GridLayoutManager manager = new GridLayoutManager(MainActivity.this, 4); // on below line we are setting layout // manager and adapter to our recycler view. imagesRV.setLayoutManager(manager); imagesRV.setAdapter(imageRVAdapter); } private void getImagePath() { // in this method we are adding all our image paths // in our arraylist which we have created. // on below line we are checking if the device is having an sd card or not. boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); if (isSDPresent) { // if the sd card is present we are creating a new list in // which we are getting our images data with their ids. final String[] columns = {MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID}; // on below line we are creating a new // string to order our images by string. final String orderBy = MediaStore.Images.Media._ID; // this method will stores all the images // from the gallery in Cursor Cursor cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null, null, orderBy); // below line is to get total number of images int count = cursor.getCount(); // on below line we are running a loop to add // the image file path in our array list. for (int i = 0; i < count; i++) { // on below line we are moving our cursor position cursor.moveToPosition(i); // on below line we are getting image file path int dataColumnIndex = cursor.getColumnIndex(MediaStore.Images.Media.DATA); // after that we are getting the image file path // and adding that path in our array list. imagePaths.add(cursor.getString(dataColumnIndex)); } imageRVAdapter.notifyDataSetChanged(); // after adding the data to our // array list we are closing our cursor. cursor.close(); } } @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { // this method is called after permissions has been granted. switch (requestCode) { // we are checking the permission code. case PERMISSION_REQUEST_CODE: // in this case we are checking if the permissions are accepted or not. if (grantResults.length > 0) { boolean storageAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED; if (storageAccepted) { // if the permissions are accepted we are displaying a toast message // and calling a method to get image path. Toast.makeText(this, "Permissions Granted..", Toast.LENGTH_SHORT).show(); getImagePath(); } else { // if permissions are denied we are closing the app and displaying the toast message. Toast.makeText(this, "Permissions denied, Permissions are required to use the app..", Toast.LENGTH_SHORT).show(); } } break; } }}
Step 9: Working with the activity_image_detail.xml file.
Navigate to the app > res > layout > activity_image_detail.xml and add the below code to that file. Below is the code for the activity_image_detail.xml file.
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=".ImageDetailActivity"> <!--image view to display our image--> <ImageView android:id="@+id/idIVImage" android:layout_width="match_parent" android:layout_height="300dp" android:layout_centerInParent="true" /> </RelativeLayout>
Step 10: Working with ImageDetailActivity.java file
Go to the ImageDetailActivity.java file and refer to the following code. Below is the code for the ImageDetailActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.os.Bundle;import android.view.MotionEvent;import android.view.ScaleGestureDetector;import android.widget.ImageView; import androidx.appcompat.app.AppCompatActivity; import com.squareup.picasso.Picasso; import java.io.File; public class ImageDetailActivity extends AppCompatActivity { // creating a string variable, image view variable // and a variable for our scale gesture detector class. String imgPath; private ImageView imageView; private ScaleGestureDetector scaleGestureDetector; // on below line we are defining our scale factor. private float mScaleFactor = 1.0f; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_image_detail); // on below line getting data which we have passed from our adapter class. imgPath = getIntent().getStringExtra("imgPath"); // initializing our image view. imageView = findViewById(R.id.idIVImage); // on below line we are initializing our scale gesture detector for zoom in and out for our image. scaleGestureDetector = new ScaleGestureDetector(this, new ScaleListener()); // on below line we are getting our image file from its path. File imgFile = new File(imgPath); // if the file exists then we are loading that image in our image view. if (imgFile.exists()) { Picasso.get().load(imgFile).placeholder(R.drawable.ic_launcher_background).into(imageView); } } @Override public boolean onTouchEvent(MotionEvent motionEvent) { // inside on touch event method we are calling on // touch event method and passing our motion event to it. scaleGestureDetector.onTouchEvent(motionEvent); return true; } private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener { // on below line we are creating a class for our scale // listener and extending it with gesture listener. @Override public boolean onScale(ScaleGestureDetector scaleGestureDetector) { // inside on scale method we are setting scale // for our image in our image view. mScaleFactor *= scaleGestureDetector.getScaleFactor(); mScaleFactor = Math.max(0.1f, Math.min(mScaleFactor, 10.0f)); // on below line we are setting // scale x and scale y to our image view. imageView.setScaleX(mScaleFactor); imageView.setScaleY(mScaleFactor); return true; } }}
Now run your app and see the output of the app.
Output:
Note: Make sure to grant read storage permissions.
ruhelaa48
sagar0719kumar
varshagumber28
simmytarika5
germanshephered48
Picked
Android
Java
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Android SDK and it's Components
Flutter - Custom Bottom Navigation Bar
Retrofit with Kotlin Coroutine in Android
How to Post Data to API using Retrofit in Android?
Flutter - Stack Widget
Arrays in Java
Split() String method in Java with examples
Arrays.sort() in Java with examples
Reverse a string in Java
For-each loop in Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Jun, 2022"
},
{
"code": null,
"e": 438,
"s": 28,
"text": "Gallery app is one of the most used apps which comes pre-installed on many android devices and there are several different apps that are present in Google Play to view the media files present in your device. In this article, we will be simply creating a Gallery app in which we can view all the photos which we have stored on our device. Along with that, we can view the individual photos in our app as well. "
},
{
"code": null,
"e": 746,
"s": 438,
"text": "We will be building a simple application in which we will be simply displaying the list of photos in the grid format and on clicking on the photo we can view that photo and can zoom in the photo to view it properly. Below is the vide0 in which we will get to see what we are going to build in this article. "
},
{
"code": null,
"e": 775,
"s": 746,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 937,
"s": 775,
"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": 985,
"s": 937,
"text": "Step 2: Add the dependency in build.gradle file"
},
{
"code": null,
"e": 1149,
"s": 985,
"text": "Navigate to the app > Gradle Scripts > build.gradle(:app) and add the below dependency to it. We are using Picasso for loading images from paths in our ImageView. "
},
{
"code": null,
"e": 1209,
"s": 1149,
"text": "// below dependency for using Picasso image loading library"
},
{
"code": null,
"e": 1263,
"s": 1209,
"text": "implementation ‘com.squareup.picasso:picasso:2.71828’"
},
{
"code": null,
"e": 1363,
"s": 1263,
"text": "Now sync your project and we will move towards adding permissions in our AndroidManifest.xml file. "
},
{
"code": null,
"e": 1422,
"s": 1363,
"text": "Step 3: Adding permissions in our AndroidManifest.xml file"
},
{
"code": null,
"e": 1506,
"s": 1422,
"text": "Navigate to the app > AndroidManifest.xml file and add the below permissions to it."
},
{
"code": null,
"e": 1510,
"s": 1506,
"text": "XML"
},
{
"code": "<!-- permissions for reading external storage --><uses-permission android:name=\"android.permission.READ_EXTERNAL_STORAGE\" />",
"e": 1635,
"s": 1510,
"text": null
},
{
"code": null,
"e": 1893,
"s": 1638,
"text": "As we are loading all the images from our storage at a time so we have to add 2 attributes to our application tag in the AndroidManifest.xml file. Navigate to the AndroidManifest.xml file and add below two lines in your application tag of Manifest file. "
},
{
"code": null,
"e": 1899,
"s": 1895,
"text": "XML"
},
{
"code": "android:hardwareAccelerated=\"false\"android:largeHeap=\"true\"",
"e": 1959,
"s": 1899,
"text": null
},
{
"code": null,
"e": 2010,
"s": 1962,
"text": "Step 4: Working with the activity_main.xml file"
},
{
"code": null,
"e": 2155,
"s": 2012,
"text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. "
},
{
"code": null,
"e": 2161,
"s": 2157,
"text": "XML"
},
{
"code": "<?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_gravity=\"center\" android:gravity=\"center\" android:orientation=\"vertical\" tools:context=\".MainActivity\"> <!--recycler view for displaying the list of images--> <androidx.recyclerview.widget.RecyclerView android:id=\"@+id/idRVImages\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" /> </RelativeLayout>",
"e": 2786,
"s": 2161,
"text": null
},
{
"code": null,
"e": 2848,
"s": 2789,
"text": "Step 5: Creating an item for displaying in a RecyclerView "
},
{
"code": null,
"e": 3095,
"s": 2850,
"text": "Navigate to the app > res > layout > Right-click on it > New > layout Resource file and create a new layout resource file. Name the file as card_layout and add the below code to it. Comments are added in the code to get to know in more detail. "
},
{
"code": null,
"e": 3101,
"s": 3097,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.cardview.widget.CardView xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center\" android:layout_margin=\"3dp\" android:elevation=\"8dp\" app:cardCornerRadius=\"8dp\"> <!--Image view for displaying the image in our card layout in recycler view--> <ImageView android:id=\"@+id/idIVImage\" android:layout_width=\"100dp\" android:layout_height=\"100dp\" android:layout_gravity=\"center\" android:scaleType=\"centerCrop\" /> </androidx.cardview.widget.CardView>",
"e": 3823,
"s": 3101,
"text": null
},
{
"code": null,
"e": 3888,
"s": 3826,
"text": "Step 6: Creating a new activity for displaying a single image"
},
{
"code": null,
"e": 4154,
"s": 3890,
"text": "Navigate to the app > java > your app’s package name > Right-click on it > New > Empty Activity and name your activity as ImageDetailActivity and create a new activity. We will be using this activity to display our single image from the list of different images. "
},
{
"code": null,
"e": 4241,
"s": 4156,
"text": "Step 7: Creating an adapter class for setting data to each item in our RecyclerView "
},
{
"code": null,
"e": 4469,
"s": 4243,
"text": "Navigate to the app > java > your app’s package name > Right-click on it > New Java class and name your class as RecyclerViewAdapter and add the below code to it. Comments are added in the code to get to know in more detail. "
},
{
"code": null,
"e": 4476,
"s": 4471,
"text": "Java"
},
{
"code": "import android.content.Context;import android.content.Intent;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView; import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView; import com.squareup.picasso.Picasso; import java.io.File;import java.util.ArrayList; public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.RecyclerViewHolder> { // creating a variable for our context and array list. private final Context context; private final ArrayList<String> imagePathArrayList; // on below line we have created a constructor. public RecyclerViewAdapter(Context context, ArrayList<String> imagePathArrayList) { this.context = context; this.imagePathArrayList = imagePathArrayList; } @NonNull @Override public RecyclerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { // Inflate Layout in this method which we have created. View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_layout, parent, false); return new RecyclerViewHolder(view); } @Override public void onBindViewHolder(@NonNull RecyclerViewHolder holder, int position) { // on below line we are getting th file from the // path which we have stored in our list. File imgFile = new File(imagePathArrayList.get(position)); // on below line we are checking if the file exists or not. if (imgFile.exists()) { // if the file exists then we are displaying that file in our image view using picasso library. Picasso.get().load(imgFile).placeholder(R.drawable.ic_launcher_background).into(holder.imageIV); // on below line we are adding click listener to our item of recycler view. holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // inside on click listener we are creating a new intent Intent i = new Intent(context, ImageDetailActivity.class); // on below line we are passing the image path to our new activity. i.putExtra(\"imgPath\", imagePathArrayList.get(position)); // at last we are starting our activity. context.startActivity(i); } }); } } @Override public int getItemCount() { // this method returns // the size of recyclerview return imagePathArrayList.size(); } // View Holder Class to handle Recycler View. public static class RecyclerViewHolder extends RecyclerView.ViewHolder { // creating variables for our views. private final ImageView imageIV; public RecyclerViewHolder(@NonNull View itemView) { super(itemView); // initializing our views with their ids. imageIV = itemView.findViewById(R.id.idIVImage); } }}",
"e": 7629,
"s": 4476,
"text": null
},
{
"code": null,
"e": 7680,
"s": 7632,
"text": "Step 8: Working with the MainActivity.java file"
},
{
"code": null,
"e": 7872,
"s": 7682,
"text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 7879,
"s": 7874,
"text": "Java"
},
{
"code": "import android.content.pm.PackageManager;import android.database.Cursor;import android.os.Bundle;import android.provider.MediaStore;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity;import androidx.core.app.ActivityCompat;import androidx.core.content.ContextCompat;import androidx.recyclerview.widget.GridLayoutManager;import androidx.recyclerview.widget.RecyclerView; import java.util.ArrayList; import static android.Manifest.permission.READ_EXTERNAL_STORAGE; public class MainActivity extends AppCompatActivity { // on below line we are creating variables for // our array list, recycler view and adapter class. private static final int PERMISSION_REQUEST_CODE = 200; private ArrayList<String> imagePaths; private RecyclerView imagesRV; private RecyclerViewAdapter imageRVAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // we are calling a method to request // the permissions to read external storage. requestPermissions(); // creating a new array list and // initializing our recycler view. imagePaths = new ArrayList<>(); imagesRV = findViewById(R.id.idRVImages); // calling a method to // prepare our recycler view. prepareRecyclerView(); } private boolean checkPermission() { // in this method we are checking if the permissions are granted or not and returning the result. int result = ContextCompat.checkSelfPermission(getApplicationContext(), READ_EXTERNAL_STORAGE); return result == PackageManager.PERMISSION_GRANTED; } private void requestPermissions() { if (checkPermission()) { // if the permissions are already granted we are calling // a method to get all images from our external storage. Toast.makeText(this, \"Permissions granted..\", Toast.LENGTH_SHORT).show(); getImagePath(); } else { // if the permissions are not granted we are // calling a method to request permissions. requestPermission(); } } private void requestPermission() { //on below line we are requesting the rea external storage permissions. ActivityCompat.requestPermissions(this, new String[]{READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE); } private void prepareRecyclerView() { // in this method we are preparing our recycler view. // on below line we are initializing our adapter class. imageRVAdapter = new RecyclerViewAdapter(MainActivity.this, imagePaths); // on below line we are creating a new grid layout manager. GridLayoutManager manager = new GridLayoutManager(MainActivity.this, 4); // on below line we are setting layout // manager and adapter to our recycler view. imagesRV.setLayoutManager(manager); imagesRV.setAdapter(imageRVAdapter); } private void getImagePath() { // in this method we are adding all our image paths // in our arraylist which we have created. // on below line we are checking if the device is having an sd card or not. boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); if (isSDPresent) { // if the sd card is present we are creating a new list in // which we are getting our images data with their ids. final String[] columns = {MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID}; // on below line we are creating a new // string to order our images by string. final String orderBy = MediaStore.Images.Media._ID; // this method will stores all the images // from the gallery in Cursor Cursor cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null, null, orderBy); // below line is to get total number of images int count = cursor.getCount(); // on below line we are running a loop to add // the image file path in our array list. for (int i = 0; i < count; i++) { // on below line we are moving our cursor position cursor.moveToPosition(i); // on below line we are getting image file path int dataColumnIndex = cursor.getColumnIndex(MediaStore.Images.Media.DATA); // after that we are getting the image file path // and adding that path in our array list. imagePaths.add(cursor.getString(dataColumnIndex)); } imageRVAdapter.notifyDataSetChanged(); // after adding the data to our // array list we are closing our cursor. cursor.close(); } } @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { // this method is called after permissions has been granted. switch (requestCode) { // we are checking the permission code. case PERMISSION_REQUEST_CODE: // in this case we are checking if the permissions are accepted or not. if (grantResults.length > 0) { boolean storageAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED; if (storageAccepted) { // if the permissions are accepted we are displaying a toast message // and calling a method to get image path. Toast.makeText(this, \"Permissions Granted..\", Toast.LENGTH_SHORT).show(); getImagePath(); } else { // if permissions are denied we are closing the app and displaying the toast message. Toast.makeText(this, \"Permissions denied, Permissions are required to use the app..\", Toast.LENGTH_SHORT).show(); } } break; } }}",
"e": 14192,
"s": 7879,
"text": null
},
{
"code": null,
"e": 14253,
"s": 14195,
"text": "Step 9: Working with the activity_image_detail.xml file. "
},
{
"code": null,
"e": 14414,
"s": 14255,
"text": "Navigate to the app > res > layout > activity_image_detail.xml and add the below code to that file. Below is the code for the activity_image_detail.xml file. "
},
{
"code": null,
"e": 14420,
"s": 14416,
"text": "XML"
},
{
"code": "<?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=\".ImageDetailActivity\"> <!--image view to display our image--> <ImageView android:id=\"@+id/idIVImage\" android:layout_width=\"match_parent\" android:layout_height=\"300dp\" android:layout_centerInParent=\"true\" /> </RelativeLayout>",
"e": 14943,
"s": 14420,
"text": null
},
{
"code": null,
"e": 14999,
"s": 14946,
"text": "Step 10: Working with ImageDetailActivity.java file "
},
{
"code": null,
"e": 15205,
"s": 15001,
"text": "Go to the ImageDetailActivity.java file and refer to the following code. Below is the code for the ImageDetailActivity.java file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 15212,
"s": 15207,
"text": "Java"
},
{
"code": "import android.os.Bundle;import android.view.MotionEvent;import android.view.ScaleGestureDetector;import android.widget.ImageView; import androidx.appcompat.app.AppCompatActivity; import com.squareup.picasso.Picasso; import java.io.File; public class ImageDetailActivity extends AppCompatActivity { // creating a string variable, image view variable // and a variable for our scale gesture detector class. String imgPath; private ImageView imageView; private ScaleGestureDetector scaleGestureDetector; // on below line we are defining our scale factor. private float mScaleFactor = 1.0f; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_image_detail); // on below line getting data which we have passed from our adapter class. imgPath = getIntent().getStringExtra(\"imgPath\"); // initializing our image view. imageView = findViewById(R.id.idIVImage); // on below line we are initializing our scale gesture detector for zoom in and out for our image. scaleGestureDetector = new ScaleGestureDetector(this, new ScaleListener()); // on below line we are getting our image file from its path. File imgFile = new File(imgPath); // if the file exists then we are loading that image in our image view. if (imgFile.exists()) { Picasso.get().load(imgFile).placeholder(R.drawable.ic_launcher_background).into(imageView); } } @Override public boolean onTouchEvent(MotionEvent motionEvent) { // inside on touch event method we are calling on // touch event method and passing our motion event to it. scaleGestureDetector.onTouchEvent(motionEvent); return true; } private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener { // on below line we are creating a class for our scale // listener and extending it with gesture listener. @Override public boolean onScale(ScaleGestureDetector scaleGestureDetector) { // inside on scale method we are setting scale // for our image in our image view. mScaleFactor *= scaleGestureDetector.getScaleFactor(); mScaleFactor = Math.max(0.1f, Math.min(mScaleFactor, 10.0f)); // on below line we are setting // scale x and scale y to our image view. imageView.setScaleX(mScaleFactor); imageView.setScaleY(mScaleFactor); return true; } }}",
"e": 17871,
"s": 15212,
"text": null
},
{
"code": null,
"e": 17923,
"s": 17874,
"text": "Now run your app and see the output of the app. "
},
{
"code": null,
"e": 17933,
"s": 17925,
"text": "Output:"
},
{
"code": null,
"e": 17987,
"s": 17935,
"text": "Note: Make sure to grant read storage permissions. "
},
{
"code": null,
"e": 17999,
"s": 17989,
"text": "ruhelaa48"
},
{
"code": null,
"e": 18014,
"s": 17999,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 18029,
"s": 18014,
"text": "varshagumber28"
},
{
"code": null,
"e": 18042,
"s": 18029,
"text": "simmytarika5"
},
{
"code": null,
"e": 18060,
"s": 18042,
"text": "germanshephered48"
},
{
"code": null,
"e": 18067,
"s": 18060,
"text": "Picked"
},
{
"code": null,
"e": 18075,
"s": 18067,
"text": "Android"
},
{
"code": null,
"e": 18080,
"s": 18075,
"text": "Java"
},
{
"code": null,
"e": 18085,
"s": 18080,
"text": "Java"
},
{
"code": null,
"e": 18093,
"s": 18085,
"text": "Android"
},
{
"code": null,
"e": 18191,
"s": 18093,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 18223,
"s": 18191,
"text": "Android SDK and it's Components"
},
{
"code": null,
"e": 18262,
"s": 18223,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 18304,
"s": 18262,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 18355,
"s": 18304,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 18378,
"s": 18355,
"text": "Flutter - Stack Widget"
},
{
"code": null,
"e": 18393,
"s": 18378,
"text": "Arrays in Java"
},
{
"code": null,
"e": 18437,
"s": 18393,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 18473,
"s": 18437,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 18498,
"s": 18473,
"text": "Reverse a string in Java"
}
] |
Stream anyMatch() in Java with examples
|
06 Dec, 2018
Stream anyMatch(Predicate predicate) returns whether any elements of this stream match the provided predicate. It may not evaluate the predicate on all elements if not necessary for determining the result. This is a short-circuiting terminal operation. A terminal operation is short-circuiting if, when presented with infinite input, it may terminate in finite time.Syntax :
boolean anyMatch(Predicate<? super T> predicate)
Where, T is the type of the input to the predicate
and the function returns true if any elements of
the stream match the provided predicate,
otherwise false.
Note : If the stream is empty then false is returned and the predicate is not evaluated.Below given are some examples to understand the implementation of the function in a better way.
Example 1 : anyMatch() function to check whether any element in list satisfy given condition.
// Java code for Stream anyMatch// (Predicate predicate) to check whether // any element of this stream match // the provided predicate.import java.util.*; class GFG { // Driver code public static void main(String[] args) { // Creating a list of Integers List<Integer> list = Arrays.asList(3, 4, 6, 12, 20); // Stream anyMatch(Predicate predicate) boolean answer = list.stream().anyMatch(n -> (n * (n + 1)) / 4 == 5); // Displaying the result System.out.println(answer);}}
Output :
true
Example 2 : anyMatch() function to check whether any element in list having UpperCase at 1st index.
// Java code for Stream anyMatch// (Predicate predicate) to check whether// any element of this stream match// the provided predicate.import java.util.stream.Stream; class GFG { // Driver code public static void main(String[] args) { // Creating a Stream of Strings Stream<String> stream = Stream.of("Geeks", "fOr", "GEEKSQUIZ", "GeeksforGeeks"); // Check if Character at 1st index is // UpperCase in any string or not using // Stream anyMatch(Predicate predicate) boolean answer = stream.anyMatch(str -> Character.isUpperCase(str.charAt(1))); // Displaying the result System.out.println(answer); }}
Output :
true
Java - util package
Java-Functions
java-stream
Java-Stream interface
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n06 Dec, 2018"
},
{
"code": null,
"e": 427,
"s": 52,
"text": "Stream anyMatch(Predicate predicate) returns whether any elements of this stream match the provided predicate. It may not evaluate the predicate on all elements if not necessary for determining the result. This is a short-circuiting terminal operation. A terminal operation is short-circuiting if, when presented with infinite input, it may terminate in finite time.Syntax :"
},
{
"code": null,
"e": 637,
"s": 427,
"text": "boolean anyMatch(Predicate<? super T> predicate)\n\nWhere, T is the type of the input to the predicate\nand the function returns true if any elements of\nthe stream match the provided predicate, \notherwise false.\n"
},
{
"code": null,
"e": 821,
"s": 637,
"text": "Note : If the stream is empty then false is returned and the predicate is not evaluated.Below given are some examples to understand the implementation of the function in a better way."
},
{
"code": null,
"e": 915,
"s": 821,
"text": "Example 1 : anyMatch() function to check whether any element in list satisfy given condition."
},
{
"code": "// Java code for Stream anyMatch// (Predicate predicate) to check whether // any element of this stream match // the provided predicate.import java.util.*; class GFG { // Driver code public static void main(String[] args) { // Creating a list of Integers List<Integer> list = Arrays.asList(3, 4, 6, 12, 20); // Stream anyMatch(Predicate predicate) boolean answer = list.stream().anyMatch(n -> (n * (n + 1)) / 4 == 5); // Displaying the result System.out.println(answer);}}",
"e": 1459,
"s": 915,
"text": null
},
{
"code": null,
"e": 1468,
"s": 1459,
"text": "Output :"
},
{
"code": null,
"e": 1474,
"s": 1468,
"text": "true\n"
},
{
"code": null,
"e": 1574,
"s": 1474,
"text": "Example 2 : anyMatch() function to check whether any element in list having UpperCase at 1st index."
},
{
"code": "// Java code for Stream anyMatch// (Predicate predicate) to check whether// any element of this stream match// the provided predicate.import java.util.stream.Stream; class GFG { // Driver code public static void main(String[] args) { // Creating a Stream of Strings Stream<String> stream = Stream.of(\"Geeks\", \"fOr\", \"GEEKSQUIZ\", \"GeeksforGeeks\"); // Check if Character at 1st index is // UpperCase in any string or not using // Stream anyMatch(Predicate predicate) boolean answer = stream.anyMatch(str -> Character.isUpperCase(str.charAt(1))); // Displaying the result System.out.println(answer); }}",
"e": 2293,
"s": 1574,
"text": null
},
{
"code": null,
"e": 2302,
"s": 2293,
"text": "Output :"
},
{
"code": null,
"e": 2308,
"s": 2302,
"text": "true\n"
},
{
"code": null,
"e": 2328,
"s": 2308,
"text": "Java - util package"
},
{
"code": null,
"e": 2343,
"s": 2328,
"text": "Java-Functions"
},
{
"code": null,
"e": 2355,
"s": 2343,
"text": "java-stream"
},
{
"code": null,
"e": 2377,
"s": 2355,
"text": "Java-Stream interface"
},
{
"code": null,
"e": 2382,
"s": 2377,
"text": "Java"
},
{
"code": null,
"e": 2387,
"s": 2382,
"text": "Java"
}
] |
Remove all leaf nodes from a Generic Tree or N-ary Tree
|
13 Aug, 2021
Given a Generic tree, the task is to delete the leaf nodes from the tree.
Examples:
Input:
5
/ / \ \
1 2 3 8
/ / \ \
15 4 5 6
Output:
5 : 1 2 3
1 :
2 :
3 :
Explanation:
Deleted leafs are:
8, 15, 4, 5, 6
Input:
8
/ | \
9 7 2
/ | \ | / / | \ \
4 5 6 10 11 1 2 2 3
Output:
8: 9 7 2
9:
7:
2:
Approach: Follow the steps given below to solve the problem
Consider a function returning root of the updated tree.
Traverse the tree and check the condition:
If the root is NULL return NULL.
If the root itself is a leaf then delete the root and return NULL.
Moving onto its children If the child node is a leaf thenDelete that node and update the children vector as well.
Delete that node and update the children vector as well.
Recursively call for every child.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to delete the// leaf from the generic tree #include <bits/stdc++.h>using namespace std; // a treenode classclass TreeNode {public: int data; vector<TreeNode*> children; TreeNode(int data) { this->data = data; }}; // Recursive function which delete// the leaf from tree TreeNode* deleteleafnodes(TreeNode* root){ if(root==NULL)return NULL; //if root is NULL return NULL if(root->children.size()==0){ //if root itself is leaf then return NULL delete root; return NULL; } for(int i=0;i<root->children.size();i++){//moving onto its children TreeNode* child=root->children[i]; if(child->children.size()==0){ // if leaf then delete that node delete child; for(int j=i;j<root->children.size()-1;j++){// update the children vector as well root->children[j]=root->children[j+1]; } root->children.pop_back(); i--; } } for(int i=0;i<root->children.size();i++){ //recursive call root->children[i]=deleteleafnodes(root->children[i]); } return root;} // Function which will print the// tree level wisevoid printTheTree(TreeNode* root){ if (root == NULL) return; cout << root->data << " " << ":"; for (int i = 0; i < root->children.size(); i++) cout << root->children[i]->data << " "; cout << endl; for (int i = 0; i < root->children.size(); i++) printTheTree(root->children[i]);} // Driver codeint main(){ // 5 // / / \ \ // 1 2 3 8 // / /\ \ // 15 4 5 6 TreeNode* root = new TreeNode(5); TreeNode* child1 = new TreeNode(1); root->children.push_back(child1); TreeNode* child11 = new TreeNode(15); child1->children.push_back(child11); TreeNode* child2 = new TreeNode(2); root->children.push_back(child2); TreeNode* child21 = new TreeNode(4); TreeNode* child22 = new TreeNode(5); child2->children.push_back(child21); child2->children.push_back(child22); TreeNode* child3 = new TreeNode(3); root->children.push_back(child3); TreeNode* child31 = new TreeNode(6); child3->children.push_back(child31); TreeNode* child4 = new TreeNode(8); root->children.push_back(child4); TreeNode* temp=deleteleafnodes(root); printTheTree(temp);}
// Java program to delete the// leaf from the generic treeimport java.util.*; class GFG{ // a treenode classstatic class TreeNode { int data; ArrayList<TreeNode> children; TreeNode(int data) { this.data = data; this.children = new ArrayList<>(); }}; // Recursive function which delete// the leaf from treestatic TreeNode removeLeaf(TreeNode root){ if(root==null){ return null;}// if root is null return null if(root.children.size()==0){// if root itself is leaf return null return null;} // if root.children is a leaf node // then delete it from children vector for (int i = 0; i < root.children.size(); i++) { TreeNode child= root.children.get(i); // if it is a leaf if (child.children.size() == 0) { // shifting the vector to left // after the point i for (int j = i; j < root.children.size() - 1; j++) root.children.set(j, root.children.get(j + 1)); // delete the last element root.children.remove(root.children.size()-1); i--; } } // Remove all leaf node // of children of root for (int i = 0; i < root.children.size(); i++) { // call function for root.children root.children.set(i,removeLeaf(root.children.get(i))); } return root;} // Function which will print the// tree level wisestatic void printTheTree(TreeNode root){ if (root == null) return; System.out.print(root.data+" :"); for (int i = 0; i < root.children.size(); i++) System.out.print(root.children.get(i).data+" "); System.out.println(); for (int i = 0; i < root.children.size(); i++) printTheTree(root.children.get(i));} // Driver codepublic static void main(String []args){ // 5 // / / \ \ // 1 2 3 8 // / /\ \ // 15 4 5 6 TreeNode root = new TreeNode(5); TreeNode child1 = new TreeNode(1); root.children.add(child1); TreeNode child11 = new TreeNode(15); child1.children.add(child11); TreeNode child2 = new TreeNode(2); root.children.add(child2); TreeNode child21 = new TreeNode(4); TreeNode child22 = new TreeNode(5); child2.children.add(child21); child2.children.add(child22); TreeNode child3 = new TreeNode(3); root.children.add(child3); TreeNode child31 = new TreeNode(6); child3.children.add(child31); TreeNode child4 = new TreeNode(8); root.children.add(child4); root=removeLeaf(root); printTheTree(root);}} // This code is contributed by rutvik_56
# Python program to delete the# leaf from the generic tree # a treenode classclass TreeNode: def __init__(self, data): self.data = data self.children = [] # Recursive function which delete# the leaf from treedef removeLeaf(root): if(root==None): return None #if root is None return None if(len(root.children)==0):return None #if root itself is leaf return None # if root.children is a leaf node # then delete it from children vector i = 0 while i < len(root.children): child = root.children[i] # if it is a leaf if (len(child.children) == 0): # shifting the vector to left # after the point i for j in range(i, len(root.children) - 1): root.children[j] = root.children[j + 1] # delete the last element root.children.pop() i -= 1 i += 1 # Remove all leaf node # of children of root for i in range(len(root.children)): # call function for root.children root.children[i]=removeLeaf(root.children[i]) return root# Function which will print the# tree level wisedef printTheTree(root): if (root == None): return print("{} :".format(root.data), end="") for i in range(len(root.children)): print("{} ".format(root.children[i].data), end="") print() for i in range(len(root.children)): printTheTree(root.children[i]) # Driver codeif __name__ == "__main__": # 5 # / / \ \ # 1 2 3 8 # / /\ \ # 15 4 5 6 root = TreeNode(5) child1 = TreeNode(1) root.children.append(child1) child11 = TreeNode(15) child1.children.append(child11) child2 = TreeNode(2) root.children.append(child2) child21 = TreeNode(4) child22 = TreeNode(5) child2.children.append(child21) child2.children.append(child22) child3 = TreeNode(3) root.children.append(child3) child31 = TreeNode(6) child3.children.append(child31) child4 = TreeNode(8) root.children.append(child4) root=removeLeaf(root) printTheTree(root) # This code is contributed by sanjeev2552
// C# program to delete the// leaf from the generic treeusing System;using System.Collections;using System.Collections.Generic; class GFG{ // a treenode classpublic class TreeNode { public int data; public ArrayList children; public TreeNode(int data) { this.data = data; this.children = new ArrayList(); }}; // Recursive function which delete// the leaf from treepublic static TreeNode removeLeaf(TreeNode root){ if(root==null) {return null;}//if root is null return null if(root.children.Count==0){//if root itself is leaf return null return null;} // if root.children is a leaf node // then delete it from children vector for (int i = 0; i < root.children.Count; i++) { TreeNode child= (TreeNode)root.children[i]; // if it is a leaf if (child.children.Count == 0) { // shifting the vector to left // after the point i for (int j = i; j < root.children.Count - 1; j++) { root.children[j]= root.children[j + 1]; } // delete the last element root.children.RemoveAt(root.children.Count - 1); i--; } } // Remove all leaf node // of children of root for (int i = 0; i < root.children.Count; i++) { // call function for root.children root.children[i]=removeLeaf((TreeNode)root.children[i]); } return root;} // Function which will print the// tree level wisestatic void printTheTree(TreeNode root){ if (root == null) return; Console.Write(root.data+" :"); for (int i = 0; i < root.children.Count; i++) Console.Write(((TreeNode)root.children[i]).data + " "); Console.WriteLine(); for (int i = 0; i < root.children.Count; i++) printTheTree((TreeNode)root.children[i]);} // Driver codepublic static void Main(string []args){ // 5 // / / \ \ // 1 2 3 8 // / /\ \ // 15 4 5 6 TreeNode root = new TreeNode(5); TreeNode child1 = new TreeNode(1); root.children.Add(child1); TreeNode child11 = new TreeNode(15); child1.children.Add(child11); TreeNode child2 = new TreeNode(2); root.children.Add(child2); TreeNode child21 = new TreeNode(4); TreeNode child22 = new TreeNode(5); child2.children.Add(child21); child2.children.Add(child22); TreeNode child3 = new TreeNode(3); root.children.Add(child3); TreeNode child31 = new TreeNode(6); child3.children.Add(child31); TreeNode child4 = new TreeNode(8); root.children.Add(child4); root=removeLeaf(root); printTheTree(root);}} // This code is contributed by pratham76
<script> // Javascript program to delete the// leaf from the generic tree // a treenode classclass TreeNode { constructor(data) { this.data = data; this.children = [] }}; // Recursive function which delete// the leaf from treefunction removeLeaf(root){ if(root==null){ return null; } //if root is null return null if(root.children.length==0){ //if root itself is leaf return null return null; } // if root.children is a leaf node // then delete it from children vector for (var i = 0; i < root.children.length; i++) { var child= root.children[i]; // if it is a leaf if (child.children.length == 0) { // shifting the vector to left // after the point i for (var j = i; j < root.children.length - 1; j++) { root.children[j]= root.children[j + 1]; } // delete the last element root.children.pop(); i--; } } // Remove all leaf node // of children of root for (var i = 0; i < root.children.length; i++) { // call function for root.children root.children[i]=removeLeaf(root.children[i]); } return root;} // Function which will print the// tree level wisefunction printTheTree(root){ if (root == null) return; document.write(root.data+" :"); for (var i = 0; i < root.children.length; i++) document.write((root.children[i]).data + " "); document.write("<br>"); for (var i = 0; i < root.children.length; i++) printTheTree(root.children[i]);} // Driver code// 5// / / \ \// 1 2 3 8// / /\ \// 15 4 5 6 var root = new TreeNode(5);var child1 = new TreeNode(1);root.children.push(child1);var child11 = new TreeNode(15);child1.children.push(child11);var child2 = new TreeNode(2);root.children.push(child2);var child21 = new TreeNode(4);var child22 = new TreeNode(5);child2.children.push(child21);child2.children.push(child22);var child3 = new TreeNode(3);root.children.push(child3);var child31 = new TreeNode(6);child3.children.push(child31);var child4 = new TreeNode(8);root.children.push(child4); root=removeLeaf(root);printTheTree(root); </script>
5 :1 2 3
1 :
2 :
3 :
Time Complexity: O(N) Auxiliary Space: O(N)
rutvik_56
pratham76
sanjeev2552
abhik02
famously
pankajsharmagfg
n-ary-tree
tree-traversal
Data Structures
Recursion
Tree
Data Structures
Recursion
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n13 Aug, 2021"
},
{
"code": null,
"e": 126,
"s": 52,
"text": "Given a Generic tree, the task is to delete the leaf nodes from the tree."
},
{
"code": null,
"e": 137,
"s": 126,
"text": " Examples:"
},
{
"code": null,
"e": 491,
"s": 137,
"text": "Input: \n 5\n / / \\ \\\n 1 2 3 8\n / / \\ \\\n 15 4 5 6 \n\nOutput: \n5 : 1 2 3\n1 :\n2 :\n3 :\n\nExplanation: \nDeleted leafs are:\n8, 15, 4, 5, 6\n\nInput: \n 8\n / | \\\n 9 7 2\n / | \\ | / / | \\ \\\n 4 5 6 10 11 1 2 2 3\nOutput: \n8: 9 7 2\n9:\n7:\n2:"
},
{
"code": null,
"e": 551,
"s": 491,
"text": "Approach: Follow the steps given below to solve the problem"
},
{
"code": null,
"e": 608,
"s": 551,
"text": "Consider a function returning root of the updated tree."
},
{
"code": null,
"e": 651,
"s": 608,
"text": "Traverse the tree and check the condition:"
},
{
"code": null,
"e": 684,
"s": 651,
"text": "If the root is NULL return NULL."
},
{
"code": null,
"e": 751,
"s": 684,
"text": "If the root itself is a leaf then delete the root and return NULL."
},
{
"code": null,
"e": 865,
"s": 751,
"text": "Moving onto its children If the child node is a leaf thenDelete that node and update the children vector as well."
},
{
"code": null,
"e": 922,
"s": 865,
"text": "Delete that node and update the children vector as well."
},
{
"code": null,
"e": 956,
"s": 922,
"text": "Recursively call for every child."
},
{
"code": null,
"e": 1007,
"s": 956,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1011,
"s": 1007,
"text": "C++"
},
{
"code": null,
"e": 1016,
"s": 1011,
"text": "Java"
},
{
"code": null,
"e": 1024,
"s": 1016,
"text": "Python3"
},
{
"code": null,
"e": 1027,
"s": 1024,
"text": "C#"
},
{
"code": null,
"e": 1038,
"s": 1027,
"text": "Javascript"
},
{
"code": "// C++ program to delete the// leaf from the generic tree #include <bits/stdc++.h>using namespace std; // a treenode classclass TreeNode {public: int data; vector<TreeNode*> children; TreeNode(int data) { this->data = data; }}; // Recursive function which delete// the leaf from tree TreeNode* deleteleafnodes(TreeNode* root){ if(root==NULL)return NULL; //if root is NULL return NULL if(root->children.size()==0){ //if root itself is leaf then return NULL delete root; return NULL; } for(int i=0;i<root->children.size();i++){//moving onto its children TreeNode* child=root->children[i]; if(child->children.size()==0){ // if leaf then delete that node delete child; for(int j=i;j<root->children.size()-1;j++){// update the children vector as well root->children[j]=root->children[j+1]; } root->children.pop_back(); i--; } } for(int i=0;i<root->children.size();i++){ //recursive call root->children[i]=deleteleafnodes(root->children[i]); } return root;} // Function which will print the// tree level wisevoid printTheTree(TreeNode* root){ if (root == NULL) return; cout << root->data << \" \" << \":\"; for (int i = 0; i < root->children.size(); i++) cout << root->children[i]->data << \" \"; cout << endl; for (int i = 0; i < root->children.size(); i++) printTheTree(root->children[i]);} // Driver codeint main(){ // 5 // / / \\ \\ // 1 2 3 8 // / /\\ \\ // 15 4 5 6 TreeNode* root = new TreeNode(5); TreeNode* child1 = new TreeNode(1); root->children.push_back(child1); TreeNode* child11 = new TreeNode(15); child1->children.push_back(child11); TreeNode* child2 = new TreeNode(2); root->children.push_back(child2); TreeNode* child21 = new TreeNode(4); TreeNode* child22 = new TreeNode(5); child2->children.push_back(child21); child2->children.push_back(child22); TreeNode* child3 = new TreeNode(3); root->children.push_back(child3); TreeNode* child31 = new TreeNode(6); child3->children.push_back(child31); TreeNode* child4 = new TreeNode(8); root->children.push_back(child4); TreeNode* temp=deleteleafnodes(root); printTheTree(temp);}",
"e": 3418,
"s": 1038,
"text": null
},
{
"code": "// Java program to delete the// leaf from the generic treeimport java.util.*; class GFG{ // a treenode classstatic class TreeNode { int data; ArrayList<TreeNode> children; TreeNode(int data) { this.data = data; this.children = new ArrayList<>(); }}; // Recursive function which delete// the leaf from treestatic TreeNode removeLeaf(TreeNode root){ if(root==null){ return null;}// if root is null return null if(root.children.size()==0){// if root itself is leaf return null return null;} // if root.children is a leaf node // then delete it from children vector for (int i = 0; i < root.children.size(); i++) { TreeNode child= root.children.get(i); // if it is a leaf if (child.children.size() == 0) { // shifting the vector to left // after the point i for (int j = i; j < root.children.size() - 1; j++) root.children.set(j, root.children.get(j + 1)); // delete the last element root.children.remove(root.children.size()-1); i--; } } // Remove all leaf node // of children of root for (int i = 0; i < root.children.size(); i++) { // call function for root.children root.children.set(i,removeLeaf(root.children.get(i))); } return root;} // Function which will print the// tree level wisestatic void printTheTree(TreeNode root){ if (root == null) return; System.out.print(root.data+\" :\"); for (int i = 0; i < root.children.size(); i++) System.out.print(root.children.get(i).data+\" \"); System.out.println(); for (int i = 0; i < root.children.size(); i++) printTheTree(root.children.get(i));} // Driver codepublic static void main(String []args){ // 5 // / / \\ \\ // 1 2 3 8 // / /\\ \\ // 15 4 5 6 TreeNode root = new TreeNode(5); TreeNode child1 = new TreeNode(1); root.children.add(child1); TreeNode child11 = new TreeNode(15); child1.children.add(child11); TreeNode child2 = new TreeNode(2); root.children.add(child2); TreeNode child21 = new TreeNode(4); TreeNode child22 = new TreeNode(5); child2.children.add(child21); child2.children.add(child22); TreeNode child3 = new TreeNode(3); root.children.add(child3); TreeNode child31 = new TreeNode(6); child3.children.add(child31); TreeNode child4 = new TreeNode(8); root.children.add(child4); root=removeLeaf(root); printTheTree(root);}} // This code is contributed by rutvik_56",
"e": 6003,
"s": 3418,
"text": null
},
{
"code": "# Python program to delete the# leaf from the generic tree # a treenode classclass TreeNode: def __init__(self, data): self.data = data self.children = [] # Recursive function which delete# the leaf from treedef removeLeaf(root): if(root==None): return None #if root is None return None if(len(root.children)==0):return None #if root itself is leaf return None # if root.children is a leaf node # then delete it from children vector i = 0 while i < len(root.children): child = root.children[i] # if it is a leaf if (len(child.children) == 0): # shifting the vector to left # after the point i for j in range(i, len(root.children) - 1): root.children[j] = root.children[j + 1] # delete the last element root.children.pop() i -= 1 i += 1 # Remove all leaf node # of children of root for i in range(len(root.children)): # call function for root.children root.children[i]=removeLeaf(root.children[i]) return root# Function which will print the# tree level wisedef printTheTree(root): if (root == None): return print(\"{} :\".format(root.data), end=\"\") for i in range(len(root.children)): print(\"{} \".format(root.children[i].data), end=\"\") print() for i in range(len(root.children)): printTheTree(root.children[i]) # Driver codeif __name__ == \"__main__\": # 5 # / / \\ \\ # 1 2 3 8 # / /\\ \\ # 15 4 5 6 root = TreeNode(5) child1 = TreeNode(1) root.children.append(child1) child11 = TreeNode(15) child1.children.append(child11) child2 = TreeNode(2) root.children.append(child2) child21 = TreeNode(4) child22 = TreeNode(5) child2.children.append(child21) child2.children.append(child22) child3 = TreeNode(3) root.children.append(child3) child31 = TreeNode(6) child3.children.append(child31) child4 = TreeNode(8) root.children.append(child4) root=removeLeaf(root) printTheTree(root) # This code is contributed by sanjeev2552",
"e": 8129,
"s": 6003,
"text": null
},
{
"code": "// C# program to delete the// leaf from the generic treeusing System;using System.Collections;using System.Collections.Generic; class GFG{ // a treenode classpublic class TreeNode { public int data; public ArrayList children; public TreeNode(int data) { this.data = data; this.children = new ArrayList(); }}; // Recursive function which delete// the leaf from treepublic static TreeNode removeLeaf(TreeNode root){ if(root==null) {return null;}//if root is null return null if(root.children.Count==0){//if root itself is leaf return null return null;} // if root.children is a leaf node // then delete it from children vector for (int i = 0; i < root.children.Count; i++) { TreeNode child= (TreeNode)root.children[i]; // if it is a leaf if (child.children.Count == 0) { // shifting the vector to left // after the point i for (int j = i; j < root.children.Count - 1; j++) { root.children[j]= root.children[j + 1]; } // delete the last element root.children.RemoveAt(root.children.Count - 1); i--; } } // Remove all leaf node // of children of root for (int i = 0; i < root.children.Count; i++) { // call function for root.children root.children[i]=removeLeaf((TreeNode)root.children[i]); } return root;} // Function which will print the// tree level wisestatic void printTheTree(TreeNode root){ if (root == null) return; Console.Write(root.data+\" :\"); for (int i = 0; i < root.children.Count; i++) Console.Write(((TreeNode)root.children[i]).data + \" \"); Console.WriteLine(); for (int i = 0; i < root.children.Count; i++) printTheTree((TreeNode)root.children[i]);} // Driver codepublic static void Main(string []args){ // 5 // / / \\ \\ // 1 2 3 8 // / /\\ \\ // 15 4 5 6 TreeNode root = new TreeNode(5); TreeNode child1 = new TreeNode(1); root.children.Add(child1); TreeNode child11 = new TreeNode(15); child1.children.Add(child11); TreeNode child2 = new TreeNode(2); root.children.Add(child2); TreeNode child21 = new TreeNode(4); TreeNode child22 = new TreeNode(5); child2.children.Add(child21); child2.children.Add(child22); TreeNode child3 = new TreeNode(3); root.children.Add(child3); TreeNode child31 = new TreeNode(6); child3.children.Add(child31); TreeNode child4 = new TreeNode(8); root.children.Add(child4); root=removeLeaf(root); printTheTree(root);}} // This code is contributed by pratham76",
"e": 10813,
"s": 8129,
"text": null
},
{
"code": "<script> // Javascript program to delete the// leaf from the generic tree // a treenode classclass TreeNode { constructor(data) { this.data = data; this.children = [] }}; // Recursive function which delete// the leaf from treefunction removeLeaf(root){ if(root==null){ return null; } //if root is null return null if(root.children.length==0){ //if root itself is leaf return null return null; } // if root.children is a leaf node // then delete it from children vector for (var i = 0; i < root.children.length; i++) { var child= root.children[i]; // if it is a leaf if (child.children.length == 0) { // shifting the vector to left // after the point i for (var j = i; j < root.children.length - 1; j++) { root.children[j]= root.children[j + 1]; } // delete the last element root.children.pop(); i--; } } // Remove all leaf node // of children of root for (var i = 0; i < root.children.length; i++) { // call function for root.children root.children[i]=removeLeaf(root.children[i]); } return root;} // Function which will print the// tree level wisefunction printTheTree(root){ if (root == null) return; document.write(root.data+\" :\"); for (var i = 0; i < root.children.length; i++) document.write((root.children[i]).data + \" \"); document.write(\"<br>\"); for (var i = 0; i < root.children.length; i++) printTheTree(root.children[i]);} // Driver code// 5// / / \\ \\// 1 2 3 8// / /\\ \\// 15 4 5 6 var root = new TreeNode(5);var child1 = new TreeNode(1);root.children.push(child1);var child11 = new TreeNode(15);child1.children.push(child11);var child2 = new TreeNode(2);root.children.push(child2);var child21 = new TreeNode(4);var child22 = new TreeNode(5);child2.children.push(child21);child2.children.push(child22);var child3 = new TreeNode(3);root.children.push(child3);var child31 = new TreeNode(6);child3.children.push(child31);var child4 = new TreeNode(8);root.children.push(child4); root=removeLeaf(root);printTheTree(root); </script>",
"e": 13079,
"s": 10813,
"text": null
},
{
"code": null,
"e": 13101,
"s": 13079,
"text": "5 :1 2 3 \n1 :\n2 :\n3 :"
},
{
"code": null,
"e": 13149,
"s": 13103,
"text": "Time Complexity: O(N) Auxiliary Space: O(N) "
},
{
"code": null,
"e": 13159,
"s": 13149,
"text": "rutvik_56"
},
{
"code": null,
"e": 13169,
"s": 13159,
"text": "pratham76"
},
{
"code": null,
"e": 13181,
"s": 13169,
"text": "sanjeev2552"
},
{
"code": null,
"e": 13189,
"s": 13181,
"text": "abhik02"
},
{
"code": null,
"e": 13198,
"s": 13189,
"text": "famously"
},
{
"code": null,
"e": 13214,
"s": 13198,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 13225,
"s": 13214,
"text": "n-ary-tree"
},
{
"code": null,
"e": 13240,
"s": 13225,
"text": "tree-traversal"
},
{
"code": null,
"e": 13256,
"s": 13240,
"text": "Data Structures"
},
{
"code": null,
"e": 13266,
"s": 13256,
"text": "Recursion"
},
{
"code": null,
"e": 13271,
"s": 13266,
"text": "Tree"
},
{
"code": null,
"e": 13287,
"s": 13271,
"text": "Data Structures"
},
{
"code": null,
"e": 13297,
"s": 13287,
"text": "Recursion"
},
{
"code": null,
"e": 13302,
"s": 13297,
"text": "Tree"
}
] |
Private bytes, Virtual bytes, Working set
|
31 Aug, 2021
In this article, we are going to understand private bytes, virtual bytes, and working sets.
Private Bytes :As a result of completely paging out the process’s private memory footprint to swap, Private Bytes summarizes the amount of RAM allocated to the process (though not necessarily used).
Process executables use Private Bytes only to request memory. It doesn’t mean that they are actually using the memory they have requested. Private Bytes are considered “private” since they (usually) exclude memory-mapped files (e.g. shared DLLs). They do exclude some memory, however, but not all memory allocated by those files. Neither the executable nor the linked library is able to determine when private bytes change. In addition, private bytes are not just restricted to physical memory. They can also be paged to disk or listed in the standby page list (not in use yet, but not yet paged either).
Private Bytes are the actual bytes allocated by your app, including pagefile usage. in general, private bytes are the overall committed memory. while the working set refers to the memory that is backed by RAM.
Private Bytes [Committed Memory] = Private Bytes + Page File
Virtual Bytes :Virtual Bytes are the total amount of virtual address space that a process occupies. Similar to the working set, this set includes memory-mapped files (shared DLLs), as well as data that has already been paged out and resides on a disk somewhere. When a system is under heavy load, the total virtual memory used by all processes is significantly greater than actually available memory.
virtual bytes=working set+private bytes+standby list.
Working Set :It refers to the amount of physical memory (RAM) the process uses. The measurement is less accurate since it also includes memory-mapped files and other resources, unlike private bytes. In recent years, Task Manager’s “Mem Usage” also reports the same value that has caused endless amounts of confusion. The Working Set runs on physical memory. However, the standby page list does not appear in the Working Set as it is still in memory, so when you minimize an application, the “Mem Usage” might suddenly drop.
It includes non-paged Private Bytes as well as memory-mapped files;
Under any process, By default Task Manager displays the Working Set:
and Process Explorer shows all Private Bytes, Working Set, and Virtual Bytes.
Blogathon-2021
Picked
Blogathon
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": "\n31 Aug, 2021"
},
{
"code": null,
"e": 144,
"s": 52,
"text": "In this article, we are going to understand private bytes, virtual bytes, and working sets."
},
{
"code": null,
"e": 343,
"s": 144,
"text": "Private Bytes :As a result of completely paging out the process’s private memory footprint to swap, Private Bytes summarizes the amount of RAM allocated to the process (though not necessarily used)."
},
{
"code": null,
"e": 948,
"s": 343,
"text": "Process executables use Private Bytes only to request memory. It doesn’t mean that they are actually using the memory they have requested. Private Bytes are considered “private” since they (usually) exclude memory-mapped files (e.g. shared DLLs). They do exclude some memory, however, but not all memory allocated by those files. Neither the executable nor the linked library is able to determine when private bytes change. In addition, private bytes are not just restricted to physical memory. They can also be paged to disk or listed in the standby page list (not in use yet, but not yet paged either)."
},
{
"code": null,
"e": 1158,
"s": 948,
"text": "Private Bytes are the actual bytes allocated by your app, including pagefile usage. in general, private bytes are the overall committed memory. while the working set refers to the memory that is backed by RAM."
},
{
"code": null,
"e": 1221,
"s": 1158,
"text": "Private Bytes [Committed Memory] = Private Bytes + Page File "
},
{
"code": null,
"e": 1622,
"s": 1221,
"text": "Virtual Bytes :Virtual Bytes are the total amount of virtual address space that a process occupies. Similar to the working set, this set includes memory-mapped files (shared DLLs), as well as data that has already been paged out and resides on a disk somewhere. When a system is under heavy load, the total virtual memory used by all processes is significantly greater than actually available memory."
},
{
"code": null,
"e": 1676,
"s": 1622,
"text": "virtual bytes=working set+private bytes+standby list."
},
{
"code": null,
"e": 2200,
"s": 1676,
"text": "Working Set :It refers to the amount of physical memory (RAM) the process uses. The measurement is less accurate since it also includes memory-mapped files and other resources, unlike private bytes. In recent years, Task Manager’s “Mem Usage” also reports the same value that has caused endless amounts of confusion. The Working Set runs on physical memory. However, the standby page list does not appear in the Working Set as it is still in memory, so when you minimize an application, the “Mem Usage” might suddenly drop."
},
{
"code": null,
"e": 2268,
"s": 2200,
"text": "It includes non-paged Private Bytes as well as memory-mapped files;"
},
{
"code": null,
"e": 2337,
"s": 2268,
"text": "Under any process, By default Task Manager displays the Working Set:"
},
{
"code": null,
"e": 2415,
"s": 2337,
"text": "and Process Explorer shows all Private Bytes, Working Set, and Virtual Bytes."
},
{
"code": null,
"e": 2430,
"s": 2415,
"text": "Blogathon-2021"
},
{
"code": null,
"e": 2437,
"s": 2430,
"text": "Picked"
},
{
"code": null,
"e": 2447,
"s": 2437,
"text": "Blogathon"
},
{
"code": null,
"e": 2455,
"s": 2447,
"text": "GATE CS"
},
{
"code": null,
"e": 2473,
"s": 2455,
"text": "Operating Systems"
},
{
"code": null,
"e": 2491,
"s": 2473,
"text": "Operating Systems"
}
] |
Geek and Books | Practice | GeeksforGeeks
|
Geek has several competitive programming books and he wants to place books one on another (like a stack). There are total Q queries of two types.
Type 1: This query is represented by "place x", where x is an integer represents a number of the book geek wants to place on the top of the stack.
Type 2: This query is represented by "remove". After this query, print a book number which is at the top of the stack (If the stack is empty then print -1) and remove it from the stack.
Note: There can be multiple books with the same number.
Input:
1. The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.
2. The first line of each test case contains a single integer Q.
3. The next Q lines contain queries
Output: For each test case, for each query of type 2, print the top book number of the stack (space separated)
Constraints:
1. 1 <= T <= 100
2. 1 <= Q <= 104
3. 1 <= x <= 109
Example:
Input:
2
5
place 6
place 2
remove
place 3
remove
3
remove
place 5
remove
Output:
2 3
-1 5
Explanation:
Test Case 1:
First Consider an empty satck: []
1st operation: Geek place a book number 6. So now Stack: [6]
2nd operation: Geek place a book number 2. So now Stack [6,2]
3rd operation: Geek wants to remove book which is top of the stack.
i.e. Book no 2. So now Stack: [6]
4th operation: Geek place a book number 3. So now Stack [6,3]
5th operation: Geek wants to remove book which is top of the stack.
i.e. Book no 3. So now Stack: [6]
Hence the output will be 2, 3
0
mohankrishnapeddineni5 months ago
JAVA SOLUTION
import java.util.*;import java.lang.*;import java.io.*;
class GFG {public static void main (String[] args) {Scanner scan = new Scanner (System.in);int t= scan.nextInt();while(t-->0){ int q = scan.nextInt(); Stack <Integer> stack = new Stack<Integer>(); while(q-->0){ String str = scan.next(); if(str.equals("place")){ int a= scan.nextInt(); stack.push(a); } else if(stack.size()>0){ System.out.print(stack.pop()+" "); } else{ System.out.print("-1"+" "); } } System.out.println();}scan.close();}}
0
imranwahid7 months ago
Easy C++ solution
0
Panyam Chaitanya Reddy10 months ago
Panyam Chaitanya Reddy
for _ in range(int(input())): s=[] n=int(input()) for i in range(n): x=input() p=x.split(" ") if p[0]=='place': s.append(p[1]) else: if len(s)==0: print("-1",end=" ") else: print(s.pop(),end=" ") print()
0
MD MAHDOOD AHMAD1 year ago
MD MAHDOOD AHMAD
0
MD MAHDOOD AHMAD
This comment was deleted.
0
MD MAHDOOD AHMAD
This comment was deleted.
0
MD MAHDOOD AHMAD
This comment was deleted.
0
MD MAHDOOD AHMAD
This comment was deleted.
0
MD MAHDOOD AHMAD
This comment was deleted.
0
MD MAHDOOD AHMAD
This comment was deleted.
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
|
[
{
"code": null,
"e": 766,
"s": 226,
"text": "Geek has several competitive programming books and he wants to place books one on another (like a stack). There are total Q queries of two types.\n\nType 1: This query is represented by \"place x\", where x is an integer represents a number of the book geek wants to place on the top of the stack.\nType 2: This query is represented by \"remove\". After this query, print a book number which is at the top of the stack (If the stack is empty then print -1) and remove it from the stack.\n\nNote: There can be multiple books with the same number. "
},
{
"code": null,
"e": 1011,
"s": 766,
"text": "Input: \n1. The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.\n2. The first line of each test case contains a single integer Q.\n3. The next Q lines contain queries"
},
{
"code": null,
"e": 1271,
"s": 1011,
"text": "\nOutput: For each test case, for each query of type 2, print the top book number of the stack (space separated)\n\nConstraints:\n1. 1 <= T <= 100\n2. 1 <= Q <= 104\n3. 1 <= x <= 109\n\nExample:\nInput:\n2\n5\nplace 6\nplace 2\nremove\nplace 3\nremove\n3\nremove\nplace 5\nremove"
},
{
"code": null,
"e": 1769,
"s": 1271,
"text": "Output:\n2 3\n-1 5\n\nExplanation:\nTest Case 1: \nFirst Consider an empty satck: []\n1st operation: Geek place a book number 6. So now Stack: [6]\n2nd operation: Geek place a book number 2. So now Stack [6,2]\n3rd operation: Geek wants to remove book which is top of the stack.\ni.e. Book no 2. So now Stack: [6]\n4th operation: Geek place a book number 3. So now Stack [6,3]\n5th operation: Geek wants to remove book which is top of the stack.\ni.e. Book no 3. So now Stack: [6]\nHence the output will be 2, 3"
},
{
"code": null,
"e": 1771,
"s": 1769,
"text": "0"
},
{
"code": null,
"e": 1805,
"s": 1771,
"text": "mohankrishnapeddineni5 months ago"
},
{
"code": null,
"e": 1819,
"s": 1805,
"text": "JAVA SOLUTION"
},
{
"code": null,
"e": 1877,
"s": 1821,
"text": "import java.util.*;import java.lang.*;import java.io.*;"
},
{
"code": null,
"e": 2425,
"s": 1877,
"text": "class GFG {public static void main (String[] args) {Scanner scan = new Scanner (System.in);int t= scan.nextInt();while(t-->0){ int q = scan.nextInt(); Stack <Integer> stack = new Stack<Integer>(); while(q-->0){ String str = scan.next(); if(str.equals(\"place\")){ int a= scan.nextInt(); stack.push(a); } else if(stack.size()>0){ System.out.print(stack.pop()+\" \"); } else{ System.out.print(\"-1\"+\" \"); } } System.out.println();}scan.close();}}"
},
{
"code": null,
"e": 2427,
"s": 2425,
"text": "0"
},
{
"code": null,
"e": 2450,
"s": 2427,
"text": "imranwahid7 months ago"
},
{
"code": null,
"e": 2468,
"s": 2450,
"text": "Easy C++ solution"
},
{
"code": null,
"e": 2470,
"s": 2468,
"text": "0"
},
{
"code": null,
"e": 2506,
"s": 2470,
"text": "Panyam Chaitanya Reddy10 months ago"
},
{
"code": null,
"e": 2529,
"s": 2506,
"text": "Panyam Chaitanya Reddy"
},
{
"code": null,
"e": 2836,
"s": 2529,
"text": "for _ in range(int(input())): s=[] n=int(input()) for i in range(n): x=input() p=x.split(\" \") if p[0]=='place': s.append(p[1]) else: if len(s)==0: print(\"-1\",end=\" \") else: print(s.pop(),end=\" \") print()"
},
{
"code": null,
"e": 2838,
"s": 2836,
"text": "0"
},
{
"code": null,
"e": 2865,
"s": 2838,
"text": "MD MAHDOOD AHMAD1 year ago"
},
{
"code": null,
"e": 2882,
"s": 2865,
"text": "MD MAHDOOD AHMAD"
},
{
"code": null,
"e": 2884,
"s": 2882,
"text": "0"
},
{
"code": null,
"e": 2901,
"s": 2884,
"text": "MD MAHDOOD AHMAD"
},
{
"code": null,
"e": 2927,
"s": 2901,
"text": "This comment was deleted."
},
{
"code": null,
"e": 2929,
"s": 2927,
"text": "0"
},
{
"code": null,
"e": 2946,
"s": 2929,
"text": "MD MAHDOOD AHMAD"
},
{
"code": null,
"e": 2972,
"s": 2946,
"text": "This comment was deleted."
},
{
"code": null,
"e": 2974,
"s": 2972,
"text": "0"
},
{
"code": null,
"e": 2991,
"s": 2974,
"text": "MD MAHDOOD AHMAD"
},
{
"code": null,
"e": 3017,
"s": 2991,
"text": "This comment was deleted."
},
{
"code": null,
"e": 3019,
"s": 3017,
"text": "0"
},
{
"code": null,
"e": 3036,
"s": 3019,
"text": "MD MAHDOOD AHMAD"
},
{
"code": null,
"e": 3062,
"s": 3036,
"text": "This comment was deleted."
},
{
"code": null,
"e": 3064,
"s": 3062,
"text": "0"
},
{
"code": null,
"e": 3081,
"s": 3064,
"text": "MD MAHDOOD AHMAD"
},
{
"code": null,
"e": 3107,
"s": 3081,
"text": "This comment was deleted."
},
{
"code": null,
"e": 3109,
"s": 3107,
"text": "0"
},
{
"code": null,
"e": 3126,
"s": 3109,
"text": "MD MAHDOOD AHMAD"
},
{
"code": null,
"e": 3152,
"s": 3126,
"text": "This comment was deleted."
},
{
"code": null,
"e": 3298,
"s": 3152,
"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": 3334,
"s": 3298,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 3344,
"s": 3334,
"text": "\nProblem\n"
},
{
"code": null,
"e": 3354,
"s": 3344,
"text": "\nContest\n"
},
{
"code": null,
"e": 3417,
"s": 3354,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 3565,
"s": 3417,
"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": 3773,
"s": 3565,
"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": 3879,
"s": 3773,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
smartd - Unix, Linux Command
|
smartd will attempt to enable SMART monitoring on ATA devices
(equivalent to smartctl -s on) and polls these and SCSI devices
every 30 minutes (configurable), logging SMART errors and changes of
SMART Attributes via the SYSLOG interface. The default location for
these SYSLOG notifications and warnings is /var/log/messages.
To change this default location, please see the '-l'
command-line option described below.
In addition to logging to a file, smartd can also be configured
to send email warnings if problems are detected. Depending upon the
type of problem, you may want to run self-tests on the disk, back up
the disk, replace the disk, or use a manufacturer's utility to force
reallocation of bad or unreadable disk sectors. If disk problems are
detected, please see the smartctl manual page and the
smartmontools web page/FAQ for further guidance.
If you send a USR1 signal to smartd it will immediately
check the status of the disks, and then return to polling the disks
every 30 minutes. See the '-i' option below for additional
details.
smartd can be configured at start-up using the configuration
file /etc/smartd.conf (Windows: ./smartd.conf).
If the configuration file is subsequently modified, smartd
can be told to re-read the configuration file by sending it a
HUP signal, for example with the command:
killall -HUP smartd.
(Windows: See NOTES below.)
On startup, if smartd finds a syntax error in the configuration
file, it will print an error message and then exit. However if
smartd is already running, then is told with a HUP signal
to re-read the configuration file, and then find a syntax error in
this file, it will print an error message and then continue, ignoring
the contents of the (faulty) configuration file, as if the HUP
signal had never been received.
When smartd is running in debug mode, the INT signal
(normally generated from a shell with CONTROL-C) is treated in the
same way as a HUP signal: it makes smartd reload its
configuration file. To exit smartd use CONTROL-\
(Cygwin: 2x CONTROL-C, Windows: CONTROL-Break).
On startup, in the absence of the configuration file
/etc/smartd.conf, the smartd daemon first scans for all
devices that support SMART. The scanning is done as follows:
If a 3ware 9000 controller is installed, examine all entries
"/dev/sdX,N" for the first logical drive ('unit'
"/dev/sdX") and all physical disks ('ports' ",N")
detected behind this controller. Same for a second controller if present.
Read smartd configuration Directives from FILE, instead of from
the default location /etc/smartd.conf (Windows: ./smartd.conf).
If FILE does not exist, then smartd will print an error
message and exit with nonzero status. Thus, '-c /etc/smartd.conf'
can be used to verify the existence of the default configuration file.
By using '-' for FILE, the configuration is read from standard
input. This is useful for commands like:
echo /dev/hdb -m user@home -M test | smartd -c - -q onecheck
Windows only: The "debug" mode can be toggled by the command
smartd sigusr2. A new console for debug output is opened when
debug mode is enabled.
Note that the superuser can make smartd check the status of the
disks at any time by sending it the SIGUSR1 signal, for example
with the command:
kill -SIGUSR1 <pid>
killall -USR1 smartd
If you would like to have smartd messages logged somewhere other
than the default /var/log/messages location, this can typically
be accomplished with (for example) the following steps:
local3.* /var/log/smartd.log
Cygwin: Support for syslogd as described above is available starting with Cygwin 1.5.15.
On older releases or if no local syslogd is running, the '-l' option has no effect.
In this case, all syslog messages are written to Windows event log
or to file C:/CYGWIN_SYSLOG.TXT if the event log is not available.
Windows: Some syslog functionality is implemented
internally in smartd as follows: If no '-l' option
(or '-l daemon') is specified, messages are written to Windows
event log or to file ./smartd.log if event log is not available
(Win9x/ME or access denied). By specifying other values of FACILITY,
log output is redirected as follows:
'-l local0' to file ./smartd.log,
'-l local1' to standard output (redirect with '>' to any file),
'-l local2' to standard error,
'-l local[3-7]': to file ./smartd[1-5].log.
When using the event log, the enclosed utility syslogevt.exe
should be registered as an event message file to avoid error
messages from the event viewer. Use 'syslogevt -r smartd'
to register, 'syslogevt -u smartd' to unregister and
'syslogevt' for more help.
On Cygwin, this allows running smartd as service via cygrunsrv,
see NOTES below.
On Windows, this option is not available, use '--service' instead.
nodev - Exit if there are no devices to monitor, or if any errors are found
at startup in the configuration file. This is the default.
errors - Exit if there are no devices to monitor, or if any errors are found
in the configuration file /etc/smartd.conf at startup or whenever it
is reloaded.
nodevstartup - Exit if there are no devices to monitor at startup. But continue
to run if no devices are found whenever the configuration file is
reloaded.
never - Only exit if a fatal error occurs (no remaining system memory,
invalid command line arguments). In this mode, even if there are no
devices to monitor, or if the configuration file
/etc/smartd.conf has errors, smartd will continue to run,
waiting to load a configuration file listing valid devices.
onecheck - Start smartd in debug mode, then register devices, then check
device's SMART status once, and then exit with zero exit status if all
of these steps worked correctly.
This last option is intended for 'distribution-writers' who want to
create automated scripts to determine whether or not to automatically
start up smartd after installing smartmontools. After starting
smartd with this command-line option, the distribution's install
scripts should wait a reasonable length of time (say ten seconds). If
smartd has not exited with zero status by that time, the script
should send smartd a SIGTERM or SIGKILL and assume that
smartd will not operate correctly on the host. Conversely, if
smartd exits with zero status, then it is safe to run
smartd in normal daemon mode. If smartd is unable to
monitor any devices or encounters other problems then it will return
with non-zero exit status.
showtests - Start smartd in debug mode, then register devices, then write
a list of future scheduled self tests to stdout, and then exit with zero
exit status if all of these steps worked correctly.
Device’s SMART status is not checked.
This option is intended to test whether the ’-s REGEX’ directives in
smartd.conf will have the desired effect. The output lists the next test
schedules, limited to 5 tests per type and device. This is followed by a
summary of all tests of each device within the next 90 days.
ioctl - report all ioctl() transactions.
ataioctl - report only ioctl() transactions with ATA devices.
scsiioctl - report only ioctl() transactions with SCSI devices.
Any argument may include a positive integer to specify the level of
detail that should be reported. The argument should be followed by a
comma then the integer with no spaces. For example, ataioctl,2
The default level is 1, so '-r ataioctl,1' and '-r ataioctl' are
equivalent.
On Cygwin, this option is kept for backward compatibility only.
It has the same effect as '-n, --no-fork', see above.
On Windows, this option enables the buildin service support.
The option must be specified in the service command line as the first
argument. It should not be used from console.
See NOTES below for details.
smartd
Runs the daemon in forked mode. This is the normal way to run
smartd.
Entries are logged to SYSLOG (by default
/var/log/messages.)
smartd -d -i 30
Run in foreground (debug) mode, checking the disk status
every 30 seconds.
smartd -q onecheck
Registers devices, and checks the status of the devices exactly
once. The exit status (the bash
$? variable) will be zero if all went well, and nonzero if no devices
were detected or some other problem was encountered.
Note that smartmontools provides a start-up script in
/etc/rc.d/init.d/smartd which is responsible for starting and
stopping the daemon via the normal init interface. Using this script,
you can start smartd by giving the command:
/etc/rc.d/init.d/smartd start
/etc/rc.d/init.d/smartd stop
/sbin/chkconfig --add smartd
/sbin/chkconfig --del smartd
This can be annoying if you have an ATA or SCSI device that hangs or
misbehaves when receiving SMART commands. Even if this causes no
problems, you may be annoyed by the string of error log messages about
block-major devices that can't be found, and SCSI devices that can't
be opened.
One can avoid this problem, and gain more control over the types of
events monitored by
smartd,
by using the configuration file
/etc/smartd.conf. This file contains a list of devices to monitor, with one device per
line. An example file is included with the
smartmontools distribution. You will find this sample configuration file in
/usr/share/doc/smartmontools-5.38/. For security, the configuration file
should not be writable by anyone but root. The syntax of the file is as
follows:
################################################
# This is an example smartd startup config file
# /etc/smartd.conf for monitoring three
# ATA disks, three SCSI disks, six ATA disks
# behind two 3ware controllers, three SATA disks
# directly connected to the highpoint rocket-
# raid controller, two SATA disks connected to
# the highpoint rocketraid controller via a pmport
# device and one SATA disk.
#
# First ATA disk on two different interfaces. On
# the second disk, start a long self-test every
# Sunday between 3 and 4 am.
#
/dev/hda -a -m admin@example.com,root@localhost
/dev/hdc -a -I 194 -I 5 -i 12 -s L/../../7/03
#
# SCSI disks. Send a TEST warning email to admin on
# startup.
#
/dev/sda
/dev/sdb -m admin@example.com -M test
#
# Strange device. It's SCSI. Start a scheduled
# long self test between 5 and 6 am Monday/Thursday
/dev/weird -d scsi -s L/../../(1|4)/05
#
# An ATA disk may appear as a SCSI device to the
# OS. If a SCSI to ATA Translation (SAT) layer
# is between the OS and the device then this can be
# flagged with the ’-d sat’ option. This situation
# may become common with SATA disks in SAS and FC
# environments.
/dev/sda -a -d sat
#
# Four ATA disks on a 3ware 6/7/8000 controller.
# Start short self-tests daily between midnight and 1am,
# 1-2, 2-3, and 3-4 am. Starting with the Linux 2.6
# kernel series, /dev/sdX is deprecated in favor of
# /dev/tweN. For example replace /dev/sdc by /dev/twe0
# and /dev/sdd by /dev/twe1.
/dev/sdc -d 3ware,0 -a -s S/../.././00
/dev/sdc -d 3ware,1 -a -s S/../.././01
/dev/sdd -d 3ware,2 -a -s S/../.././02
/dev/sdd -d 3ware,3 -a -s S/../.././03
#
# Two ATA disks on a 3ware 9000 controller.
# Start long self-tests Sundays between midnight and
# 1am and 2-3 am
/dev/twa0 -d 3ware,0 -a -s L/../../7/00
/dev/twa0 -d 3ware,1 -a -s L/../../7/02
#
# Three SATA disks on a highpoint rocketraid controller.
# Start short self-tests daily between 1-2, 2-3, and
# 3-4 am.
/dev/sde -d hpt,1/1 -a -s S/../.././01
/dev/sde -d hpt,1/2 -a -s S/../.././02
/dev/sde -d hpt,1/3 -a -s S/../.././03
#
# Two SATA disks connected to a highpoint rocketraid
# via a pmport device. Start long self-tests Sundays
# between midnight and 1am and 2-3 am.
/dev/sde -d hpt,1/4/1 -a -s L/../../7/00
/dev/sde -d hpt,1/4/2 -a -s L/../../7/02
#
# The following line enables monitoring of the
# ATA Error Log and the Self-Test Error Log.
# It also tracks changes in both Prefailure
# and Usage Attributes, apart from Attributes
# 9, 194, and 231, and shows continued lines:
#
/dev/hdd -l error \
-l selftest \
-t \ # Attributes not tracked:
-I 194 \ # temperature
-I 231 \ # also temperature
-I 9 # power-on hours
#
################################################
If the first non-comment entry in the configuration file is the text
string
DEVICESCAN in capital letters, then
smartd
will ignore any remaining lines in the configuration file, and will
scan for devices.
DEVICESCAN may optionally be followed by Directives that will apply to all
devices that are found in the scan. Please see below for additional
details.
The following are the Directives that may appear following the device
name or
DEVICESCAN on any line of the
/etc/smartd.conf configuration file. Note that
these are NOT command-line options for smartd.
The Directives below may appear in any order, following the device
name.
For an ATA device, if no Directives appear, then the device will be monitored
as if the '-a' Directive (monitor all SMART properties) had been given.
If a SCSI disk is listed, it will be monitored at the maximum implemented level: roughly
equivalent to using the '-H -l selftest' options for an ATA disk.
So with the exception of '-d', '-m', '-l selftest', '-s', and
'-M', the Directives below are ignored for SCSI disks. For SCSI
disks, the '-m' Directive sends a warning email if the SMART status
indicates a disk failure or problem, if the SCSI inquiry about disk
status fails, or if new errors appear in the self-test log.
If a 3ware controller is used then the corresponding SCSI (/dev/sd?) or character device (/dev/twe?
or /dev/twa?) must be listed, along with the '-d 3ware,N' Directive
(see below). The individual ATA disks hosted by the 3ware controller
appear to smartd as normal ATA devices. Hence all the ATA
directives can be used for these disks (but see note below).
If none of these three arguments is given, then smartd will
first attempt to guess the device type by looking at whether the sixth
character in the device name is an 's' or an 'h'. This will work for
device names like /dev/hda or /dev/sdb, and corresponds to choosing
ata or scsi respectively. If
smartd
can't guess from this sixth character, then it will simply try to
access the device using first ATA and then SCSI ioctl()s.
The valid arguments to this Directive are:
ata - the device type is ATA. This prevents
smartd
from issuing SCSI commands to an ATA device.
scsi - the device type is SCSI. This prevents
smartd
from issuing ATA commands to a SCSI device.
sat - the device type is SCSI to ATA Translation (SAT).
smartd
will generate ATA (smart) commands and then package them in
the SAT defined ATA PASS THROUGH SCSI commands. The commands
are then routed through the SCSI pass through interface to the
operating system. There are two types of ATA PASS THROUGH
SCSI commands: a 12 byte and 16 byte variant.
smartd
can use either and defaults to the 16 byte variant. This can
be overridden with this syntax: '-d sat,12' or '-d sat,16'.
marvell - Under Linux, interact with SATA disks behind Marvell chip-set
controllers (using the Marvell rather than libata driver).
3ware,N - the device consists of one or more ATA disks connected to a 3ware
RAID controller. The non-negative integer N (in the range from 0 to 31
inclusive) denotes which disk on the controller is monitored. In log
files and email messages this disk will be identified as 3ware_disk_XX
with XX in the range from 00 to 31 inclusive.
This Directive may at first appear confusing, because the 3ware
controller is a SCSI device (such as /dev/sda) and should be listed as
such in the the configuration file.
However when the '-d 3ware,N'
Directive is used, then the corresponding disk is addressed using
native ATA commands which are 'passed through' the SCSI driver. All
ATA Directives listed in this man page may be used. Note that while
you may use any of the 3ware SCSI logical devices /dev/sd? to
address any of the physical disks (3ware ports), error and log
messages will make the most sense if you always list the 3ware SCSI
logical device corresponding to the particular physical disks. Please
see the smartctl man page for further details.
ATA disks behind 3ware controllers may alternatively be accessed via a
character device interface /dev/twe0-15 (3ware 6000/7000/8000
controllers) and /dev/twa0-15 (3ware 9000 series controllers). Note
that the 9000 series controllers may only be accessed using the
character device interface /dev/twa0-15 and not the SCSI device
interface /dev/sd?. Please see the smartctl man page for
further details.
Note that older 3w-xxxx drivers do not pass the 'Enable Autosave'
(-S on) and 'Enable Automatic Offline' (-o on) commands
to the disk, if the SCSI interface is used, and produce these types of
harmless syslog error messages instead: '3w-xxxx: tw_ioctl():
Passthru size (123392) too big'. This can be fixed by upgrading to
version 1.02.00.037 or later of the 3w-xxxx driver, or by applying a
patch to older versions. See
http://smartmontools.sourceforge.net/ for instructions.
Alternatively use the character device interfaces /dev/twe0-15 (3ware
6/7/8000 series controllers) or /dev/twa0-15 (3ware 9000 series
controllers).
cciss,N - the device consists of one or more SCSI disks connected to a cciss
RAID controller. The non-negative integer N (in the range from 0 to 15
inclusive) denotes which disk on the controller is monitored. In log
files and email messages this disk will be identified as cciss_disk_XX
with XX in the range from 00 to 15 inclusive.
3ware and cciss controllers are currently ONLY supported under Linux.
hpt,L/M/N - the device consists of one or more ATA disks connected to a HighPoint
RocketRAID controller. The integer L is the controller id, the integer M
is the channel number, and the integer N is the PMPort number if it is
available. The allowed values of L are from 1 to 4 inclusive, M are from
1 to 8 inclusive and N from 1 to 4 if PMPort available. And also these
values are limited by the model of the HighPoint RocketRAID controller.
In log files and email messages this disk will be identified as
hpt_X/X/X and X/X/X is the same as L/M/N, note if no N indicated, N set
to the default value 1.
HighPoint RocketRAID controllers are currently ONLY supported under Linux.
removable - the device or its media is removable. This indicates to
smartd
that it should continue (instead of exiting, which is the default
behavior) if the device does not appear to be present when
smartd is started. This Directive may be used in conjunction
with the other '-d' Directives.
ATA disks have five different power states. In order of increasing
power consumption they are: 'OFF', 'SLEEP', 'STANDBY', 'IDLE',
and 'ACTIVE'. Typically in the OFF, SLEEP, and STANDBY modes the
disk's platters are not spinning. But usually, in response to SMART
commands issued by smartd, the disk platters are spun up. So if
this option is not used, then a disk which is in a low-power mode may
be spun up and put into a higher-power mode when it is periodically
polled by smartd.
Note that if the disk is in SLEEP mode when smartd is started,
then it won’t respond to smartd commands, and so the disk won’t
be registered as a device for smartd to monitor. If a disk is in
any other low-power mode, then the commands issued by smartd to
register the disk will probably cause it to spin-up.
The '-n' (nocheck) Directive specifies if smartd's
periodic checks should still be carried out when the device is in a
low-power mode. It may be used to prevent a disk from being spun-up
by periodic smartd polling. The allowed values of POWERMODE
are:
never - smartd will poll (check) the device regardless of its power
mode. This may cause a disk which is spun-down to be spun-up when
smartd checks it. This is the default behavior if the ’-n’
Directive is not given.
sleep - check the device unless it is in SLEEP mode.
standby - check the device unless it is in SLEEP or STANDBY mode. In
these modes most disks are not spinning, so if you want to prevent
a laptop disk from spinning up each time that smartd polls,
this is probably what you want.
idle - check the device unless it is in SLEEP, STANDBY or IDLE mode.
In the IDLE state, most disks are still spinning, so this is probably
not what you want.
When a self test is scheduled (see '-s' Directive below), the
'-n' Directive is ignored, and all tests are carried out.
When a periodic test is skipped, smartd normally writes an
informal log message. The message can be suppressed by appending
the option ',q' to POWERMODE (like '-n standby,q').
This prevents a laptop disk from spinning up due to this message.
normal - do not try to monitor the disk if a mandatory SMART command fails, but
continue if an optional SMART command fails. This is the default.
permissive - try to monitor the disk even if it appears to lack SMART
capabilities. This may be required for some old disks (prior to
ATA-3 revision 4) that implemented SMART before the SMART standards
were incorporated into the ATA/ATAPI Specifications. This may also be
needed for some Maxtor disks which fail to comply with the ATA
Specifications and don’t properly indicate support for error- or
self-test logging.
[Please see the smartctl -T command-line option.]
The delay between tests is vendor-specific, but is typically four
hours.
Note that SMART Automatic Offline Testing is not part of the ATA
Specification. Please see the
smartctl -o command-line option documentation for further information about this
feature.
error - report if the number of ATA errors reported in the ATA Error Log
has increased since the last check.
selftest - report if the number of failed tests reported in the SMART
Self-Test Log has increased since the last check, or if the timestamp
associated with the most recent failed test has increased. Note that
such errors will only be logged if you run self-tests on the
disk (and it fails a test!). Self-Tests can be run automatically by
smartd: please see the '-s' Directive below.
Self-Tests can also be run manually by using the '-t short'
and '-t long' options of smartctl and the results of
the testing can be observed using the smartctl '-l selftest'
command-line option.]
[Please see the smartctl -l and -t command-line
options.]
To schedule a short Self-Test between 2-3am every morning, use:
-s S/../.././02
-s L/../../7/04
-s L/../(01|15)/./22
-s (O/../.././(00|06|12|18)|S/../.././01|L/../../6/03)
Scheduled tests are run immediately following the regularly-scheduled
device polling, if the current local date, time, and test type, match
REGEXP. By default the regularly-scheduled device polling
occurs every thirty minutes after starting smartd. Take caution
if you use the '-i' option to make this polling interval more than
sixty minutes: the poll times may fail to coincide with any of the
testing times that you have specified with REGEXP, and so the
self tests may not take place as you wish.
Before running an offline or self-test, smartd checks to be sure
that a self-test is not already running. If a self-test is
already running, then this running self test will not be
interrupted to begin another test.
smartd will not attempt to run any type of test if another
test was already started or run in the same hour.
To avoid performance problems during system boot, smartd will
not attempt to run any scheduled tests following the very first
device polling (unless '-q onecheck' is specified).
Each time a test is run, smartd will log an entry to SYSLOG.
You can use these or the ’-q showtests’ command-line option to verify
that you constructed REGEXP correctly. The matching order
(L before S before C before O) ensures that
if multiple test types are all scheduled for the same hour, the
longer test type has precedence. This is usually the desired behavior.
Unix users: please beware that the rules for extended regular
expressions [regex(7)] are not the same as the rules for
file-name pattern matching by the shell [glob(7)]. smartd will
issue harmless informational warning messages if it detects characters
in REGEXP that appear to indicate that you have made this
mistake.
To prevent your email in-box from getting filled up with warning
messages, by default only a single warning will be sent for each of
the enabled alert types, '-H', '-l', '-f', '-C', or
'-O' even if more than one failure or error is detected or if the
failure or error persists. [This behavior can be modified; see the
'-M' Directive below.]
To send email to more than one user, please use the following "comma
separated" form for the address: user1@add1,user2@add2,...,userN@addN
(with no spaces).
To test that email is being sent correctly, use the '-M test'
Directive described below to send one test email message on
smartd
startup.
By default, email is sent using the system
mail command. In order that
smartd
find the mail command (normally /bin/mail) an executable named
'mail' must be in the path of the shell or environment from which
smartd
was started. If you wish to specify an explicit path to the mail
executable (for example /usr/local/bin/mail) or a custom script to
run, please use the '-M exec' Directive below.
Note that by default under Solaris, in the previous paragraph,
'mailx' and '/bin/mailx' are used, since Solaris
'/bin/mail' does not accept a '-s' (Subject) command-line
argument.
On Windows, the 'Blat' mailer
(http://blat.sourceforge.net/) is used by default.
This mailer uses a different command line syntax, see
'-M exec' below.
Note also that there is a special argument
<nomailer> which can be given to the '-m' Directive in conjunction with the '-M
exec' Directive. Please see below for an explanation of its effect.
If the mailer or the shell running it produces any STDERR/STDOUT
output, then a snippet of that output will be copied to SYSLOG. The
remainder of the output is discarded. If problems are encountered in
sending mail, this should help you to understand and fix them. If
you have mail problems, we recommend running smartd in debug
mode with the '-d' flag, using the '-M test' Directive described
below.
The following extension is available on Windows:
By specifying 'msgbox' as a mail address, a warning
"email" is displayed as a message box on the screen.
Using both 'msgbox' and regular mail addresses is possible,
if 'msgbox' is the first word in the comma separated list.
With 'sysmsgbox', a system modal (always on top) message box
is used. If running as a service, a service notification message box
(always shown on current visible desktop) is used.
Multiple -M Directives may be given. If more than one of the
following three -M Directives are given (example: -M once -M daily)
then the final one (in the example, -M daily) is used.
The valid arguments to the -M Directive are (one of the following
three):
once - send only one warning email for each type of disk problem detected. This
is the default.
daily - send additional warning reminder emails, once per day, for each type
of disk problem detected.
diminishing - send additional warning reminder emails, after a one-day interval,
then a two-day interval, then a four-day interval, and so on for each
type of disk problem detected. Each interval is twice as long as the
previous interval.
In addition, one may add zero or more of the following Directives:
test - send a single test email
immediately upon
smartd
startup. This allows one to verify that email is delivered correctly.
Note that if this Directive is used,
smartd
will also send the normal email warnings that were enabled with the '-m' Directive,
in addition to the single test email!
exec PATH - run the executable PATH instead of the default mail command, when
smartd
needs to send email. PATH must point to an executable binary file or
script.
By setting PATH to point to a customized script, you can make
smartd perform useful tricks when a disk problem is detected
(beeping the console, shutting down the machine, broadcasting warnings
to all logged-in users, etc.) But please be careful. smartd
will block until the executable PATH returns, so if your
executable hangs, then smartd will also hang. Some sample
scripts are included in
/usr/share/doc/smartmontools-5.38/examplescripts/.
The return status of the executable is recorded by smartd in
SYSLOG. The executable is not expected to write to STDOUT or
STDERR. If it does, then this is interpreted as indicating that
something is going wrong with your executable, and a fragment of this
output is logged to SYSLOG to help you to understand the problem.
Normally, if you wish to leave some record behind, the executable
should send mail or write to a file or device.
Before running the executable, smartd sets a number of
environment variables. These environment variables may be used to
control the executable's behavior. The environment variables
exported by smartd are:
If the '-m ADD' Directive is given with a normal address argument,
then the executable pointed to by PATH will be run in a shell with
STDIN receiving the body of the email message, and with the same
command-line arguments:
-s "$SMARTD_SUBJECT" $SMARTD_ADDRESS
-m user@home -M exec /bin/mail
-m admin@work -M exec /usr/local/bin/mailto
-m root -M exec /Example_1/bash/script/below
Note that on Windows, the syntax of the 'Blat' mailer is
used:
- -q -subject "$SMARTD_SUBJECT" -to "$SMARTD_ADDRESS"
If the '-m ADD' Directive is given with the special address argument
<nomailer> then the executable pointed to by PATH is run in a shell with
no STDIN and
no command-line arguments, for example:
-m <nomailer> -M exec /Example_2/bash/script/below
Some EXAMPLES of scripts that can be used with the '-M exec'
Directive are given below. Some sample scripts are also included in
/usr/share/doc/smartmontools-5.38/examplescripts/.
This is useful, for example, if you have a very old disk and don't
want to keep getting messages about the hours-on-lifetime Attribute
(usually Attribute 9) failing. This Directive may appear multiple
times for a single device, if you want to ignore multiple Attributes.
This is useful, for example, if one of the device Attributes is the disk
temperature (usually Attribute 194 or 231). It's annoying to get reports
each time the temperature changes. This Directive may appear multiple
times for a single device, if you want to ignore multiple Attributes.
A common use of this Directive is to track the device Temperature
(often ID=194 or 231).
If this Directive is given, it automatically implies the '-r'
Directive for the same Attribute, so that the Raw value of the
Attribute is reported.
A common use of this Directive is to track the device Temperature
(often ID=194 or 231). It is also useful for understanding how
different types of system behavior affects the values of certain
Attributes.
A pending sector is a disk sector (containing 512 bytes of your data)
which the device would like to mark as ‘‘bad" and reallocate.
Typically this is because your computer tried to read that sector, and
the read failed because the data on it has been corrupted and has
inconsistent Error Checking and Correction (ECC) codes. This is
important to know, because it means that there is some unreadable data
on the disk. The problem of figuring out what file this data belongs
to is operating system and file system specific. You can typically
force the sector to reallocate by writing to it (translation: make the
device substitute a spare good sector for the bad one) but at the
price of losing the 512 bytes of data stored there.
An offline uncorrectable sector is a disk sector which was not
readable during an off-line scan or a self-test. This is important
to know, because if you have data stored in this disk sector, and you
need to read it, the read will fail. Please see the previous '-C'
option for more details.
To disable any of the 3 reports, set the corresponding limit to 0.
Trailing zero arguments may be omitted. By default, all temperature
reports are disabled ('-W 0').
To track temperature changes of at least 2 degrees, use:
-W 2
-W 0,40
-W 0,0,45
-W 2,40,45
For ATA devices, smartd interprets Attribute 194 as Temperature Celsius
by default. This can be changed to Attribute 9 or 220 by the drive
database or by the '-v' directive, see below.
none - Assume that the device firmware obeys the ATA specifications. This is
the default, unless the device has presets for '-F' in the device
database.
samsung - In some Samsung disks (example: model SV4012H Firmware Version:
RM100-08) some of the two- and four-byte quantities in the SMART data
structures are byte-swapped (relative to the ATA specification).
Enabling this option tells smartd to evaluate these quantities
in byte-reversed order. Some signs that your disk needs this option
are (1) no self-test log printed, even though you have run self-tests;
(2) very large numbers of ATA errors reported in the ATA error log;
(3) strange and impossible values for the ATA error log timestamps.
samsung2 - In more recent Samsung disks (firmware revisions ending in "-23") the
number of ATA errors reported is byte swapped. Enabling this option
tells smartd to evaluate this quantity in byte-reversed order.
samsung3 - Some Samsung disks (at least SP2514N with Firmware VF100-37) report
a self-test still in progress with 0% remaining when the test was already
completed. If this directive is specified, smartd will not skip the
next scheduled self-test (see Directive '-s' above) in this case.
Note that an explicit '-F' Directive will over-ride any preset
values for '-F' (see the '-P' option below).
[Please see the smartctl -F command-line option.]
This Directive may appear multiple times. Valid arguments to this
Directive are:
9,minutes - Raw Attribute number 9 is power-on time in minutes. Its raw value
will be displayed in the form 'Xh+Ym'. Here X is hours, and Y is
minutes in the range 0-59 inclusive. Y is always printed with two
digits, for example '06' or '31' or '00'.
9,seconds - Raw Attribute number 9 is power-on time in seconds. Its raw value
will be displayed in the form 'Xh+Ym+Zs'. Here X is hours, Y is
minutes in the range 0-59 inclusive, and Z is seconds in the range
0-59 inclusive. Y and Z are always printed with two digits, for
example '06' or '31' or '00'.
9,halfminutes - Raw Attribute number 9 is power-on time, measured in units of 30
seconds. This format is used by some Samsung disks. Its raw value
will be displayed in the form 'Xh+Ym'. Here X is hours, and Y is
minutes in the range 0-59 inclusive. Y is always printed with two
digits, for example '06' or '31' or '00'.
9,temp - Raw Attribute number 9 is the disk temperature in Celsius.
192,emergencyretractcyclect - Raw Attribute number 192 is the Emergency Retract Cycle Count.
193,loadunload - Raw Attribute number 193 contains two values. The first is the
number of load cycles. The second is the number of unload cycles.
The difference between these two values is the number of times that
the drive was unexpectedly powered off (also called an emergency
unload). As a rule of thumb, the mechanical stress created by one
emergency unload is equivalent to that created by one hundred normal
unloads.
194,10xCelsius - Raw Attribute number 194 is ten times the disk temperature in
Celsius. This is used by some Samsung disks (example: model SV1204H
with RK100-13 firmware).
194,unknown - Raw Attribute number 194 is NOT the disk temperature, and its
interpretation is unknown. This is primarily useful for the -P
(presets) Directive.
198,offlinescanuncsectorct - Raw Attribute number 198 is the Offline Scan UNC Sector Count.
200,writeerrorcount - Raw Attribute number 200 is the Write Error Count.
201,detectedtacount - Raw Attribute number 201 is the Detected TA Count.
220,temp - Raw Attribute number 220 is the disk temperature in Celsius.
Note: a table of hard drive models, listing which Attribute
corresponds to temperature, can be found at:
http://www.guzu.net/linux/hddtemp.db
N,raw8 - Print the Raw value of Attribute N as six 8-bit unsigned base-10
integers. This may be useful for decoding the meaning of the Raw
value. The form 'N,raw8' prints Raw values for ALL Attributes in this
form. The form (for example) '123,raw8' only prints the Raw value for
Attribute 123 in this form.
N,raw16 - Print the Raw value of Attribute N as three 16-bit unsigned base-10
integers. This may be useful for decoding the meaning of the Raw
value. The form 'N,raw16' prints Raw values for ALL Attributes in this
form. The form (for example) '123,raw16' only prints the Raw value for
Attribute 123 in this form.
N,raw48 - Print the Raw value of Attribute N as a 48-bit unsigned base-10
integer. This may be useful for decoding the meaning of the Raw
value. The form 'N,raw48' prints Raw values for ALL Attributes in
this form. The form (for example) '123,raw48' only prints the Raw
value for Attribute 123 in this form.
use - use any presets that are available for this drive. This is the default.
ignore - do not use any presets for this drive.
show - show the presets listed for this drive in the database.
showall - show the presets that are available for all drives and then exit.
[Please see the
smartctl -P command-line option.]
Note that -a is the default for ATA devices. If none of these other
Directives is given, then -a is assumed.
-H -l selftest -l error -f.
If DEVICESCAN is not followed by any Directives, then smartd
will scan for both ATA and SCSI devices, and will monitor all possible
SMART properties of any devices that are found.
DEVICESCAN may optionally be followed by any valid Directives,
which will be applied to all devices that are found in the scan. For
example
DEVICESCAN -m root@example.com
DEVICESCAN -d ata -m root@example.com
DEVICESCAN -H -d ata -m root@example.com
Example 1: This script is for use with '-m ADDRESS -M exec PATH'. It appends
the output of
smartctl -a to the output of the smartd email warning message and sends it to ADDRESS.
#! /bin/bash
# Save the email message (STDIN) to a file:
cat > /root/msg
# Append the output of smartctl -a to the message:
/usr/sbin/smartctl -a -d $SMART_DEVICETYPE $SMARTD_DEVICE >> /root/msg
# Now email the message to the user at address ADD:
/bin/mail -s "$SMARTD_SUBJECT" $SMARTD_ADDRESS < /root/msg
# Save the email message (STDIN) to a file:
cat > /root/msg
# Append the output of smartctl -a to the message:
/usr/sbin/smartctl -a -d $SMART_DEVICETYPE $SMARTD_DEVICE >> /root/msg
# Now email the message to the user at address ADD:
/bin/mail -s "$SMARTD_SUBJECT" $SMARTD_ADDRESS < /root/msg
Example 2: This script is for use with '-m <nomailer> -M exec
PATH'. It warns all users about a disk problem, waits 30 seconds, and
then powers down the machine.
#! /bin/bash
# Warn all users of a problem
wall 'Problem detected with disk: ' "$SMARTD_DEVICESTRING"
wall 'Warning message from smartd is: ' "$SMARTD_MESSAGE"
wall 'Shutting down machine in 30 seconds... '
# Wait half a minute
sleep 30
# Power down the machine
/sbin/shutdown -hf now
# Warn all users of a problem
wall 'Problem detected with disk: ' "$SMARTD_DEVICESTRING"
wall 'Warning message from smartd is: ' "$SMARTD_MESSAGE"
wall 'Shutting down machine in 30 seconds... '
# Wait half a minute
sleep 30
# Power down the machine
/sbin/shutdown -hf now
Some example scripts are distributed with the smartmontools package,
in /usr/share/doc/smartmontools-5.38/examplescripts/.
Please note that these scripts typically run as root, so any files
that they read/write should not be writable by ordinary users or
reside in directories like /tmp that are writable by ordinary users
and may expose your system to symlink attacks.
As previously described, if the scripts write to STDOUT or STDERR,
this is interpreted as indicating that there was an internal error
within the script, and a snippet of STDOUT/STDERR is logged to SYSLOG.
The remainder is flushed.
'Device: /dev/hda, SMART Attribute: 194 Temperature_Celsius changed from 94 to 93'
'Device: /dev/hda, SMART Attribute: 194 Temperature_Celsius changed from 94 [Raw 22] to 93 [Raw 23]'
Please see the
smartctl manual page for further explanation of the differences between
Normalized and Raw Attribute values.
smartd
will make log entries at loglevel
LOG_CRIT if a SMART Attribute has failed, for example:
'Device: /dev/hdc, Failed SMART Attribute: 5 Reallocated_Sector_Ct'
Under Solaris with the default /etc/syslog.conf configuration,
messages below loglevel LOG_NOTICE will not be recorded.
Hence all smartd messages with loglevel LOG_INFO will be
lost. If you want to use the existing daemon facility to log all
messages from smartd, you should change /etc/syslog.conf
from:
...;daemon.notice;... /var/adm/messages
...;daemon.info;... /var/adm/messages
On Cygwin and Windows, the log messages are written to the event log
or to a file. See documentation of the ’-l FACILITY’ option above for
details.
On Windows, the following built-in commands can be used to control
smartd, if running as a daemon:
'smartd status' - check status
'smartd stop' - stop smartd
'smartd reload' - reread config file
'smartd restart' - restart smartd
'smartd sigusr1' - check disks now
'smartd sigusr2' - toggle debug mode
On WinNT4/2000/XP, smartd can also be run as a Windows service:
The Cygwin Version of smartd can be run as a service via the
cygrunsrv tool. The start-up script provides Cygwin-specific commands
to install and remove the service:
/etc/rc.d/init.d/smartd install [options]
/etc/rc.d/init.d/smartd remove
The Windows Version of smartd has buildin support for services:
'smartd install [options]' installs a service
named "smartd" (display name "SmartD Service") using the command line
'/installpath/smartd.exe --service [options]'.
'smartd remove' can later be used to remove the service entry
from registry.
Upon startup, the smartd service changes the working directory
to its own installation path. If smartd.conf and blat.exe are stored
in this directory, no '-c' option and '-M exec' directive is needed.
The debug mode ('-d', '-q onecheck') does not work if smartd is
running as service.
The service can be controlled as usual with Windows commands 'net'
or 'sc' ('net start smartd', 'net stop smartd').
Pausing the service ('net pause smartd') sets the interval between
disk checks ('-i N') to infinite.
Continuing the paused service ('net continue smartd') resets the
interval and rereads the configuration file immediately (like SIGHUP):
Continuing a still running service ('net continue smartd' without
preceding 'net pause smartd') does not reread configuration but
checks disks immediately (like SIGUSR1).
When smartd makes log entries, these are time-stamped. The time
stamps are in the computer’s local time zone, which is generally set
using either the environment variable 'TZ' or using a
time-zone file such as /etc/localtime. You may wish to change
the timezone while smartd is running (for example, if you carry
a laptop to a new time-zone and don’t reboot it). Due to a bug in the
tzset(3) function of many unix standard C libraries, the
time-zone stamps of smartd might not change. For some systems,
smartd will work around this problem if the time-zone is
set using /etc/localtime. The work-around fails if the
time-zone is set using the 'TZ' variable (or a file that it
points to).
Casper Dik (Solaris SCSI interface)
Christian Franke (Windows interface and Cygwin package)
Douglas Gilbert (SCSI subsystem)
Guido Guenther (Autoconf/Automake packaging)
Geoffrey Keating (Darwin ATA interface)
Eduard Martinescu (FreeBSD interface)
Frédéric L. W. Meunier (Web site and Mailing list)
Keiji Sawada (Solaris ATA interface)
Sergey Svishchev (NetBSD interface)
David Snyder and Sergey Svishchev (OpenBSD interface)
Phil Williams (User interface and drive database)
Shengfeng Zhou (Linux Highpoint RocketRaid interface)
If you would like to understand better how SMART works, and what it
does, a good place to start is with Sections 4.8 and 6.54 of the first
volume of the 'AT Attachment with Packet Interface-7' (ATA/ATAPI-7)
specification. This documents the SMART functionality which the
smartmontools utilities provide access to. You can find
Revision 4b of this document at
http://www.t13.org/docs2004/d1532v1r4b-ATA-ATAPI-7.pdf .
Earlier and later versions of this Specification are available from
the T13 web site http://www.t13.org/ .
The functioning of SMART was originally defined by the SFF-8035i
revision 2 and the SFF-8055i revision 1.4 specifications. These are
publications of the Small Form Factors (SFF) Committee. Links to
these documents may be found in the References section of the
smartmontools home page at http://smartmontools.sourceforge.net/#references .
Advertisements
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": 11003,
"s": 10585,
"text": "\nsmartd will attempt to enable SMART monitoring on ATA devices\n(equivalent to smartctl -s on) and polls these and SCSI devices\nevery 30 minutes (configurable), logging SMART errors and changes of\nSMART Attributes via the SYSLOG interface. The default location for\nthese SYSLOG notifications and warnings is /var/log/messages.\nTo change this default location, please see the '-l'\ncommand-line option described below.\n"
},
{
"code": null,
"e": 11449,
"s": 11003,
"text": "\nIn addition to logging to a file, smartd can also be configured\nto send email warnings if problems are detected. Depending upon the\ntype of problem, you may want to run self-tests on the disk, back up\nthe disk, replace the disk, or use a manufacturer's utility to force\nreallocation of bad or unreadable disk sectors. If disk problems are\ndetected, please see the smartctl manual page and the\nsmartmontools web page/FAQ for further guidance.\n"
},
{
"code": null,
"e": 11643,
"s": 11449,
"text": "\nIf you send a USR1 signal to smartd it will immediately\ncheck the status of the disks, and then return to polling the disks\nevery 30 minutes. See the '-i' option below for additional\ndetails.\n"
},
{
"code": null,
"e": 11966,
"s": 11643,
"text": "\nsmartd can be configured at start-up using the configuration\nfile /etc/smartd.conf (Windows: ./smartd.conf).\nIf the configuration file is subsequently modified, smartd\ncan be told to re-read the configuration file by sending it a\nHUP signal, for example with the command:\nkillall -HUP smartd.\n(Windows: See NOTES below.)\n"
},
{
"code": null,
"e": 12385,
"s": 11966,
"text": "\nOn startup, if smartd finds a syntax error in the configuration\nfile, it will print an error message and then exit. However if\nsmartd is already running, then is told with a HUP signal\nto re-read the configuration file, and then find a syntax error in\nthis file, it will print an error message and then continue, ignoring\nthe contents of the (faulty) configuration file, as if the HUP\nsignal had never been received.\n"
},
{
"code": null,
"e": 12657,
"s": 12385,
"text": "\nWhen smartd is running in debug mode, the INT signal\n(normally generated from a shell with CONTROL-C) is treated in the\nsame way as a HUP signal: it makes smartd reload its\nconfiguration file. To exit smartd use CONTROL-\\\n(Cygwin: 2x CONTROL-C, Windows: CONTROL-Break).\n"
},
{
"code": null,
"e": 12830,
"s": 12657,
"text": "\nOn startup, in the absence of the configuration file\n/etc/smartd.conf, the smartd daemon first scans for all\ndevices that support SMART. The scanning is done as follows:\n"
},
{
"code": null,
"e": 13066,
"s": 12830,
"text": "\nIf a 3ware 9000 controller is installed, examine all entries\n\"/dev/sdX,N\" for the first logical drive ('unit'\n\"/dev/sdX\") and all physical disks ('ports' \",N\")\ndetected behind this controller. Same for a second controller if present.\n"
},
{
"code": null,
"e": 13392,
"s": 13068,
"text": "\nRead smartd configuration Directives from FILE, instead of from\nthe default location /etc/smartd.conf (Windows: ./smartd.conf).\nIf FILE does not exist, then smartd will print an error\nmessage and exit with nonzero status. Thus, '-c /etc/smartd.conf'\ncan be used to verify the existence of the default configuration file.\n"
},
{
"code": null,
"e": 13498,
"s": 13392,
"text": "\nBy using '-' for FILE, the configuration is read from standard\ninput. This is useful for commands like:\n"
},
{
"code": null,
"e": 13561,
"s": 13498,
"text": "echo /dev/hdb -m user@home -M test | smartd -c - -q onecheck \n"
},
{
"code": null,
"e": 13711,
"s": 13563,
"text": "\nWindows only: The \"debug\" mode can be toggled by the command\nsmartd sigusr2. A new console for debug output is opened when\ndebug mode is enabled.\n"
},
{
"code": null,
"e": 13859,
"s": 13711,
"text": "\nNote that the superuser can make smartd check the status of the\ndisks at any time by sending it the SIGUSR1 signal, for example\nwith the command:\n"
},
{
"code": null,
"e": 13881,
"s": 13859,
"text": "kill -SIGUSR1 <pid> \n"
},
{
"code": null,
"e": 13904,
"s": 13881,
"text": "killall -USR1 smartd \n"
},
{
"code": null,
"e": 14093,
"s": 13906,
"text": "\nIf you would like to have smartd messages logged somewhere other\nthan the default /var/log/messages location, this can typically\nbe accomplished with (for example) the following steps:\n"
},
{
"code": null,
"e": 14123,
"s": 14093,
"text": "local3.* /var/log/smartd.log\n"
},
{
"code": null,
"e": 14432,
"s": 14123,
"text": "\nCygwin: Support for syslogd as described above is available starting with Cygwin 1.5.15.\nOn older releases or if no local syslogd is running, the '-l' option has no effect.\nIn this case, all syslog messages are written to Windows event log\nor to file C:/CYGWIN_SYSLOG.TXT if the event log is not available.\n"
},
{
"code": null,
"e": 14941,
"s": 14432,
"text": "\nWindows: Some syslog functionality is implemented\ninternally in smartd as follows: If no '-l' option\n(or '-l daemon') is specified, messages are written to Windows\nevent log or to file ./smartd.log if event log is not available\n(Win9x/ME or access denied). By specifying other values of FACILITY,\nlog output is redirected as follows:\n'-l local0' to file ./smartd.log,\n'-l local1' to standard output (redirect with '>' to any file),\n'-l local2' to standard error,\n'-l local[3-7]': to file ./smartd[1-5].log.\n"
},
{
"code": null,
"e": 15203,
"s": 14941,
"text": "\nWhen using the event log, the enclosed utility syslogevt.exe\nshould be registered as an event message file to avoid error\nmessages from the event viewer. Use 'syslogevt -r smartd'\nto register, 'syslogevt -u smartd' to unregister and\n'syslogevt' for more help.\n"
},
{
"code": null,
"e": 15288,
"s": 15205,
"text": "\nOn Cygwin, this allows running smartd as service via cygrunsrv,\nsee NOTES below.\n"
},
{
"code": null,
"e": 15357,
"s": 15288,
"text": "\nOn Windows, this option is not available, use '--service' instead.\n"
},
{
"code": null,
"e": 15497,
"s": 15359,
"text": "\nnodev - Exit if there are no devices to monitor, or if any errors are found\nat startup in the configuration file. This is the default.\n"
},
{
"code": null,
"e": 15658,
"s": 15497,
"text": "\nerrors - Exit if there are no devices to monitor, or if any errors are found\nin the configuration file /etc/smartd.conf at startup or whenever it\nis reloaded.\n"
},
{
"code": null,
"e": 15817,
"s": 15658,
"text": "\nnodevstartup - Exit if there are no devices to monitor at startup. But continue\nto run if no devices are found whenever the configuration file is\nreloaded.\n"
},
{
"code": null,
"e": 16125,
"s": 15817,
"text": "\nnever - Only exit if a fatal error occurs (no remaining system memory,\ninvalid command line arguments). In this mode, even if there are no\ndevices to monitor, or if the configuration file\n/etc/smartd.conf has errors, smartd will continue to run,\nwaiting to load a configuration file listing valid devices.\n"
},
{
"code": null,
"e": 16304,
"s": 16125,
"text": "\nonecheck - Start smartd in debug mode, then register devices, then check\ndevice's SMART status once, and then exit with zero exit status if all\nof these steps worked correctly.\n"
},
{
"code": null,
"e": 17030,
"s": 16304,
"text": "\nThis last option is intended for 'distribution-writers' who want to\ncreate automated scripts to determine whether or not to automatically\nstart up smartd after installing smartmontools. After starting\nsmartd with this command-line option, the distribution's install\nscripts should wait a reasonable length of time (say ten seconds). If\nsmartd has not exited with zero status by that time, the script\nshould send smartd a SIGTERM or SIGKILL and assume that\nsmartd will not operate correctly on the host. Conversely, if\nsmartd exits with zero status, then it is safe to run\nsmartd in normal daemon mode. If smartd is unable to\nmonitor any devices or encounters other problems then it will return\nwith non-zero exit status.\n"
},
{
"code": null,
"e": 17269,
"s": 17030,
"text": "\nshowtests - Start smartd in debug mode, then register devices, then write\na list of future scheduled self tests to stdout, and then exit with zero\nexit status if all of these steps worked correctly.\nDevice’s SMART status is not checked.\n"
},
{
"code": null,
"e": 17547,
"s": 17269,
"text": "\nThis option is intended to test whether the ’-s REGEX’ directives in\nsmartd.conf will have the desired effect. The output lists the next test\nschedules, limited to 5 tests per type and device. This is followed by a\nsummary of all tests of each device within the next 90 days.\n"
},
{
"code": null,
"e": 17590,
"s": 17547,
"text": "\nioctl - report all ioctl() transactions.\n"
},
{
"code": null,
"e": 17654,
"s": 17590,
"text": "\nataioctl - report only ioctl() transactions with ATA devices.\n"
},
{
"code": null,
"e": 17720,
"s": 17654,
"text": "\nscsiioctl - report only ioctl() transactions with SCSI devices.\n"
},
{
"code": null,
"e": 18001,
"s": 17720,
"text": "\nAny argument may include a positive integer to specify the level of\ndetail that should be reported. The argument should be followed by a\ncomma then the integer with no spaces. For example, ataioctl,2\nThe default level is 1, so '-r ataioctl,1' and '-r ataioctl' are\nequivalent.\n"
},
{
"code": null,
"e": 18123,
"s": 18003,
"text": "\nOn Cygwin, this option is kept for backward compatibility only.\nIt has the same effect as '-n, --no-fork', see above.\n"
},
{
"code": null,
"e": 18331,
"s": 18123,
"text": "\nOn Windows, this option enables the buildin service support.\nThe option must be specified in the service command line as the first\nargument. It should not be used from console.\nSee NOTES below for details.\n"
},
{
"code": null,
"e": 18476,
"s": 18335,
"text": "\n smartd\nRuns the daemon in forked mode. This is the normal way to run\nsmartd.\nEntries are logged to SYSLOG (by default\n/var/log/messages.) "
},
{
"code": null,
"e": 18570,
"s": 18476,
"text": "\n smartd -d -i 30\nRun in foreground (debug) mode, checking the disk status\nevery 30 seconds.\n"
},
{
"code": null,
"e": 18811,
"s": 18570,
"text": "\n smartd -q onecheck\nRegisters devices, and checks the status of the devices exactly\nonce. The exit status (the bash\n$? variable) will be zero if all went well, and nonzero if no devices\nwere detected or some other problem was encountered.\n"
},
{
"code": null,
"e": 19044,
"s": 18811,
"text": "\nNote that smartmontools provides a start-up script in\n/etc/rc.d/init.d/smartd which is responsible for starting and\nstopping the daemon via the normal init interface. Using this script,\nyou can start smartd by giving the command:\n"
},
{
"code": null,
"e": 19076,
"s": 19044,
"text": "/etc/rc.d/init.d/smartd start \n"
},
{
"code": null,
"e": 19108,
"s": 19076,
"text": "/etc/rc.d/init.d/smartd stop \n\n"
},
{
"code": null,
"e": 19141,
"s": 19110,
"text": "/sbin/chkconfig --add smartd \n"
},
{
"code": null,
"e": 19172,
"s": 19141,
"text": "/sbin/chkconfig --del smartd \n"
},
{
"code": null,
"e": 19464,
"s": 19176,
"text": "\nThis can be annoying if you have an ATA or SCSI device that hangs or\nmisbehaves when receiving SMART commands. Even if this causes no\nproblems, you may be annoyed by the string of error log messages about\nblock-major devices that can't be found, and SCSI devices that can't\nbe opened.\n"
},
{
"code": null,
"e": 19955,
"s": 19464,
"text": "\nOne can avoid this problem, and gain more control over the types of\nevents monitored by\nsmartd,\nby using the configuration file\n/etc/smartd.conf. This file contains a list of devices to monitor, with one device per\nline. An example file is included with the\nsmartmontools distribution. You will find this sample configuration file in\n/usr/share/doc/smartmontools-5.38/. For security, the configuration file\nshould not be writable by anyone but root. The syntax of the file is as\nfollows:\n"
},
{
"code": null,
"e": 22844,
"s": 19957,
"text": "################################################ \n# This is an example smartd startup config file \n# /etc/smartd.conf for monitoring three \n# ATA disks, three SCSI disks, six ATA disks \n# behind two 3ware controllers, three SATA disks \n# directly connected to the highpoint rocket- \n# raid controller, two SATA disks connected to \n# the highpoint rocketraid controller via a pmport \n# device and one SATA disk. \n# \n# First ATA disk on two different interfaces. On \n# the second disk, start a long self-test every \n# Sunday between 3 and 4 am. \n# \n /dev/hda -a -m admin@example.com,root@localhost \n /dev/hdc -a -I 194 -I 5 -i 12 -s L/../../7/03 \n# \n# SCSI disks. Send a TEST warning email to admin on \n# startup. \n# \n /dev/sda \n /dev/sdb -m admin@example.com -M test \n# \n# Strange device. It's SCSI. Start a scheduled \n# long self test between 5 and 6 am Monday/Thursday \n /dev/weird -d scsi -s L/../../(1|4)/05 \n# \n# An ATA disk may appear as a SCSI device to the \n# OS. If a SCSI to ATA Translation (SAT) layer \n# is between the OS and the device then this can be \n# flagged with the ’-d sat’ option. This situation \n# may become common with SATA disks in SAS and FC \n# environments. \n /dev/sda -a -d sat \n# \n# Four ATA disks on a 3ware 6/7/8000 controller. \n# Start short self-tests daily between midnight and 1am, \n# 1-2, 2-3, and 3-4 am. Starting with the Linux 2.6 \n# kernel series, /dev/sdX is deprecated in favor of \n# /dev/tweN. For example replace /dev/sdc by /dev/twe0 \n# and /dev/sdd by /dev/twe1. \n /dev/sdc -d 3ware,0 -a -s S/../.././00 \n /dev/sdc -d 3ware,1 -a -s S/../.././01 \n /dev/sdd -d 3ware,2 -a -s S/../.././02 \n /dev/sdd -d 3ware,3 -a -s S/../.././03 \n# \n# Two ATA disks on a 3ware 9000 controller. \n# Start long self-tests Sundays between midnight and \n# 1am and 2-3 am \n /dev/twa0 -d 3ware,0 -a -s L/../../7/00 \n /dev/twa0 -d 3ware,1 -a -s L/../../7/02 \n# \n# Three SATA disks on a highpoint rocketraid controller. \n# Start short self-tests daily between 1-2, 2-3, and \n# 3-4 am. \n /dev/sde -d hpt,1/1 -a -s S/../.././01 \n /dev/sde -d hpt,1/2 -a -s S/../.././02 \n /dev/sde -d hpt,1/3 -a -s S/../.././03 \n# \n# Two SATA disks connected to a highpoint rocketraid \n# via a pmport device. Start long self-tests Sundays \n# between midnight and 1am and 2-3 am. \n /dev/sde -d hpt,1/4/1 -a -s L/../../7/00 \n /dev/sde -d hpt,1/4/2 -a -s L/../../7/02 \n# \n# The following line enables monitoring of the \n# ATA Error Log and the Self-Test Error Log. \n# It also tracks changes in both Prefailure \n# and Usage Attributes, apart from Attributes \n# 9, 194, and 231, and shows continued lines: \n# \n /dev/hdd -l error \\ \n -l selftest \\ \n -t \\ # Attributes not tracked: \n -I 194 \\ # temperature \n -I 231 \\ # also temperature \n -I 9 # power-on hours \n# \n################################################ \n"
},
{
"code": null,
"e": 23210,
"s": 22850,
"text": "\nIf the first non-comment entry in the configuration file is the text\nstring\nDEVICESCAN in capital letters, then\nsmartd\nwill ignore any remaining lines in the configuration file, and will\nscan for devices.\nDEVICESCAN may optionally be followed by Directives that will apply to all\ndevices that are found in the scan. Please see below for additional\ndetails.\n"
},
{
"code": null,
"e": 23489,
"s": 23212,
"text": "\nThe following are the Directives that may appear following the device\nname or\nDEVICESCAN on any line of the\n/etc/smartd.conf configuration file. Note that\nthese are NOT command-line options for smartd.\nThe Directives below may appear in any order, following the device\nname.\n"
},
{
"code": null,
"e": 23641,
"s": 23489,
"text": "\nFor an ATA device, if no Directives appear, then the device will be monitored\nas if the '-a' Directive (monitor all SMART properties) had been given.\n"
},
{
"code": null,
"e": 24121,
"s": 23641,
"text": "\nIf a SCSI disk is listed, it will be monitored at the maximum implemented level: roughly\nequivalent to using the '-H -l selftest' options for an ATA disk.\nSo with the exception of '-d', '-m', '-l selftest', '-s', and\n'-M', the Directives below are ignored for SCSI disks. For SCSI\ndisks, the '-m' Directive sends a warning email if the SMART status\nindicates a disk failure or problem, if the SCSI inquiry about disk\nstatus fails, or if new errors appear in the self-test log.\n"
},
{
"code": null,
"e": 24481,
"s": 24121,
"text": "\nIf a 3ware controller is used then the corresponding SCSI (/dev/sd?) or character device (/dev/twe?\nor /dev/twa?) must be listed, along with the '-d 3ware,N' Directive\n(see below). The individual ATA disks hosted by the 3ware controller\nappear to smartd as normal ATA devices. Hence all the ATA\ndirectives can be used for these disks (but see note below).\n"
},
{
"code": null,
"e": 24914,
"s": 24483,
"text": "\nIf none of these three arguments is given, then smartd will\nfirst attempt to guess the device type by looking at whether the sixth\ncharacter in the device name is an 's' or an 'h'. This will work for\ndevice names like /dev/hda or /dev/sdb, and corresponds to choosing\nata or scsi respectively. If\nsmartd\ncan't guess from this sixth character, then it will simply try to\naccess the device using first ATA and then SCSI ioctl()s.\n"
},
{
"code": null,
"e": 24959,
"s": 24914,
"text": "\nThe valid arguments to this Directive are:\n"
},
{
"code": null,
"e": 25058,
"s": 24959,
"text": "\nata - the device type is ATA. This prevents\nsmartd\nfrom issuing SCSI commands to an ATA device.\n"
},
{
"code": null,
"e": 25158,
"s": 25058,
"text": "\nscsi - the device type is SCSI. This prevents\nsmartd\nfrom issuing ATA commands to a SCSI device.\n"
},
{
"code": null,
"e": 25639,
"s": 25158,
"text": "\nsat - the device type is SCSI to ATA Translation (SAT).\nsmartd\nwill generate ATA (smart) commands and then package them in\nthe SAT defined ATA PASS THROUGH SCSI commands. The commands\nare then routed through the SCSI pass through interface to the\noperating system. There are two types of ATA PASS THROUGH\nSCSI commands: a 12 byte and 16 byte variant.\nsmartd\ncan use either and defaults to the 16 byte variant. This can\nbe overridden with this syntax: '-d sat,12' or '-d sat,16'.\n"
},
{
"code": null,
"e": 25772,
"s": 25639,
"text": "\nmarvell - Under Linux, interact with SATA disks behind Marvell chip-set\ncontrollers (using the Marvell rather than libata driver).\n"
},
{
"code": null,
"e": 26108,
"s": 25772,
"text": "\n3ware,N - the device consists of one or more ATA disks connected to a 3ware\nRAID controller. The non-negative integer N (in the range from 0 to 31\ninclusive) denotes which disk on the controller is monitored. In log\nfiles and email messages this disk will be identified as 3ware_disk_XX\nwith XX in the range from 00 to 31 inclusive.\n"
},
{
"code": null,
"e": 26825,
"s": 26108,
"text": "\nThis Directive may at first appear confusing, because the 3ware\ncontroller is a SCSI device (such as /dev/sda) and should be listed as\nsuch in the the configuration file.\nHowever when the '-d 3ware,N'\nDirective is used, then the corresponding disk is addressed using\nnative ATA commands which are 'passed through' the SCSI driver. All\nATA Directives listed in this man page may be used. Note that while\nyou may use any of the 3ware SCSI logical devices /dev/sd? to\naddress any of the physical disks (3ware ports), error and log\nmessages will make the most sense if you always list the 3ware SCSI\nlogical device corresponding to the particular physical disks. Please\nsee the smartctl man page for further details.\n"
},
{
"code": null,
"e": 27232,
"s": 26825,
"text": "\nATA disks behind 3ware controllers may alternatively be accessed via a\ncharacter device interface /dev/twe0-15 (3ware 6000/7000/8000\ncontrollers) and /dev/twa0-15 (3ware 9000 series controllers). Note\nthat the 9000 series controllers may only be accessed using the\ncharacter device interface /dev/twa0-15 and not the SCSI device\ninterface /dev/sd?. Please see the smartctl man page for\nfurther details.\n"
},
{
"code": null,
"e": 27859,
"s": 27232,
"text": "\nNote that older 3w-xxxx drivers do not pass the 'Enable Autosave'\n(-S on) and 'Enable Automatic Offline' (-o on) commands\nto the disk, if the SCSI interface is used, and produce these types of\nharmless syslog error messages instead: '3w-xxxx: tw_ioctl():\nPassthru size (123392) too big'. This can be fixed by upgrading to\nversion 1.02.00.037 or later of the 3w-xxxx driver, or by applying a\npatch to older versions. See\nhttp://smartmontools.sourceforge.net/ for instructions.\nAlternatively use the character device interfaces /dev/twe0-15 (3ware\n6/7/8000 series controllers) or /dev/twa0-15 (3ware 9000 series\ncontrollers).\n"
},
{
"code": null,
"e": 28196,
"s": 27859,
"text": "\ncciss,N - the device consists of one or more SCSI disks connected to a cciss\nRAID controller. The non-negative integer N (in the range from 0 to 15\ninclusive) denotes which disk on the controller is monitored. In log\nfiles and email messages this disk will be identified as cciss_disk_XX\nwith XX in the range from 00 to 15 inclusive.\n"
},
{
"code": null,
"e": 28268,
"s": 28196,
"text": "\n3ware and cciss controllers are currently ONLY supported under Linux. "
},
{
"code": null,
"e": 28874,
"s": 28268,
"text": "\nhpt,L/M/N - the device consists of one or more ATA disks connected to a HighPoint\nRocketRAID controller. The integer L is the controller id, the integer M\nis the channel number, and the integer N is the PMPort number if it is\navailable. The allowed values of L are from 1 to 4 inclusive, M are from\n1 to 8 inclusive and N from 1 to 4 if PMPort available. And also these\nvalues are limited by the model of the HighPoint RocketRAID controller.\nIn log files and email messages this disk will be identified as\nhpt_X/X/X and X/X/X is the same as L/M/N, note if no N indicated, N set\nto the default value 1.\n"
},
{
"code": null,
"e": 28951,
"s": 28874,
"text": "\nHighPoint RocketRAID controllers are currently ONLY supported under Linux. "
},
{
"code": null,
"e": 29248,
"s": 28951,
"text": "\nremovable - the device or its media is removable. This indicates to\nsmartd\nthat it should continue (instead of exiting, which is the default\nbehavior) if the device does not appear to be present when\nsmartd is started. This Directive may be used in conjunction\nwith the other '-d' Directives.\n"
},
{
"code": null,
"e": 29737,
"s": 29250,
"text": "\nATA disks have five different power states. In order of increasing\npower consumption they are: 'OFF', 'SLEEP', 'STANDBY', 'IDLE',\nand 'ACTIVE'. Typically in the OFF, SLEEP, and STANDBY modes the\ndisk's platters are not spinning. But usually, in response to SMART\ncommands issued by smartd, the disk platters are spun up. So if\nthis option is not used, then a disk which is in a low-power mode may\nbe spun up and put into a higher-power mode when it is periodically\npolled by smartd.\n"
},
{
"code": null,
"e": 30048,
"s": 29737,
"text": "\nNote that if the disk is in SLEEP mode when smartd is started,\nthen it won’t respond to smartd commands, and so the disk won’t\nbe registered as a device for smartd to monitor. If a disk is in\nany other low-power mode, then the commands issued by smartd to\nregister the disk will probably cause it to spin-up.\n"
},
{
"code": null,
"e": 30304,
"s": 30048,
"text": "\nThe '-n' (nocheck) Directive specifies if smartd's\nperiodic checks should still be carried out when the device is in a\nlow-power mode. It may be used to prevent a disk from being spun-up\nby periodic smartd polling. The allowed values of POWERMODE\nare:\n"
},
{
"code": null,
"e": 30524,
"s": 30304,
"text": "\nnever - smartd will poll (check) the device regardless of its power\nmode. This may cause a disk which is spun-down to be spun-up when\nsmartd checks it. This is the default behavior if the ’-n’\nDirective is not given.\n"
},
{
"code": null,
"e": 30579,
"s": 30524,
"text": "\nsleep - check the device unless it is in SLEEP mode.\n"
},
{
"code": null,
"e": 30810,
"s": 30579,
"text": "\nstandby - check the device unless it is in SLEEP or STANDBY mode. In\nthese modes most disks are not spinning, so if you want to prevent\na laptop disk from spinning up each time that smartd polls,\nthis is probably what you want.\n"
},
{
"code": null,
"e": 30970,
"s": 30810,
"text": "\nidle - check the device unless it is in SLEEP, STANDBY or IDLE mode.\nIn the IDLE state, most disks are still spinning, so this is probably\nnot what you want.\n"
},
{
"code": null,
"e": 31092,
"s": 30970,
"text": "\nWhen a self test is scheduled (see '-s' Directive below), the\n'-n' Directive is ignored, and all tests are carried out.\n"
},
{
"code": null,
"e": 31336,
"s": 31092,
"text": "\nWhen a periodic test is skipped, smartd normally writes an\ninformal log message. The message can be suppressed by appending\nthe option ',q' to POWERMODE (like '-n standby,q').\nThis prevents a laptop disk from spinning up due to this message.\n"
},
{
"code": null,
"e": 31487,
"s": 31338,
"text": "\nnormal - do not try to monitor the disk if a mandatory SMART command fails, but\ncontinue if an optional SMART command fails. This is the default.\n"
},
{
"code": null,
"e": 31910,
"s": 31487,
"text": "\npermissive - try to monitor the disk even if it appears to lack SMART\ncapabilities. This may be required for some old disks (prior to\nATA-3 revision 4) that implemented SMART before the SMART standards\nwere incorporated into the ATA/ATAPI Specifications. This may also be\nneeded for some Maxtor disks which fail to comply with the ATA\nSpecifications and don’t properly indicate support for error- or\nself-test logging.\n"
},
{
"code": null,
"e": 31962,
"s": 31910,
"text": "\n[Please see the smartctl -T command-line option.]\n"
},
{
"code": null,
"e": 32037,
"s": 31962,
"text": "\nThe delay between tests is vendor-specific, but is typically four\nhours.\n"
},
{
"code": null,
"e": 32225,
"s": 32037,
"text": "\nNote that SMART Automatic Offline Testing is not part of the ATA\nSpecification. Please see the\nsmartctl -o command-line option documentation for further information about this\nfeature.\n"
},
{
"code": null,
"e": 32336,
"s": 32225,
"text": "\nerror - report if the number of ATA errors reported in the ATA Error Log\nhas increased since the last check.\n"
},
{
"code": null,
"e": 32919,
"s": 32336,
"text": "\nselftest - report if the number of failed tests reported in the SMART\nSelf-Test Log has increased since the last check, or if the timestamp\nassociated with the most recent failed test has increased. Note that\nsuch errors will only be logged if you run self-tests on the\ndisk (and it fails a test!). Self-Tests can be run automatically by\nsmartd: please see the '-s' Directive below.\nSelf-Tests can also be run manually by using the '-t short'\nand '-t long' options of smartctl and the results of\nthe testing can be observed using the smartctl '-l selftest'\ncommand-line option.]\n"
},
{
"code": null,
"e": 32979,
"s": 32919,
"text": "\n[Please see the smartctl -l and -t command-line\noptions.]\n"
},
{
"code": null,
"e": 33045,
"s": 32979,
"text": "\nTo schedule a short Self-Test between 2-3am every morning, use:\n"
},
{
"code": null,
"e": 33063,
"s": 33045,
"text": " -s S/../.././02\n"
},
{
"code": null,
"e": 33081,
"s": 33063,
"text": " -s L/../../7/04\n"
},
{
"code": null,
"e": 33104,
"s": 33081,
"text": " -s L/../(01|15)/./22\n"
},
{
"code": null,
"e": 33161,
"s": 33104,
"text": " -s (O/../.././(00|06|12|18)|S/../.././01|L/../../6/03)\n"
},
{
"code": null,
"e": 33666,
"s": 33161,
"text": "\nScheduled tests are run immediately following the regularly-scheduled\ndevice polling, if the current local date, time, and test type, match\nREGEXP. By default the regularly-scheduled device polling\noccurs every thirty minutes after starting smartd. Take caution\nif you use the '-i' option to make this polling interval more than\nsixty minutes: the poll times may fail to coincide with any of the\ntesting times that you have specified with REGEXP, and so the\nself tests may not take place as you wish.\n"
},
{
"code": null,
"e": 33885,
"s": 33666,
"text": "\nBefore running an offline or self-test, smartd checks to be sure\nthat a self-test is not already running. If a self-test is\nalready running, then this running self test will not be\ninterrupted to begin another test.\n"
},
{
"code": null,
"e": 33996,
"s": 33885,
"text": "\nsmartd will not attempt to run any type of test if another\ntest was already started or run in the same hour.\n"
},
{
"code": null,
"e": 34176,
"s": 33996,
"text": "\nTo avoid performance problems during system boot, smartd will\nnot attempt to run any scheduled tests following the very first\ndevice polling (unless '-q onecheck' is specified).\n"
},
{
"code": null,
"e": 34548,
"s": 34176,
"text": "\nEach time a test is run, smartd will log an entry to SYSLOG.\nYou can use these or the ’-q showtests’ command-line option to verify\nthat you constructed REGEXP correctly. The matching order\n(L before S before C before O) ensures that\nif multiple test types are all scheduled for the same hour, the\nlonger test type has precedence. This is usually the desired behavior.\n"
},
{
"code": null,
"e": 34871,
"s": 34548,
"text": "\nUnix users: please beware that the rules for extended regular\nexpressions [regex(7)] are not the same as the rules for\nfile-name pattern matching by the shell [glob(7)]. smartd will\nissue harmless informational warning messages if it detects characters\nin REGEXP that appear to indicate that you have made this\nmistake.\n"
},
{
"code": null,
"e": 35217,
"s": 34873,
"text": "\nTo prevent your email in-box from getting filled up with warning\nmessages, by default only a single warning will be sent for each of\nthe enabled alert types, '-H', '-l', '-f', '-C', or\n'-O' even if more than one failure or error is detected or if the\nfailure or error persists. [This behavior can be modified; see the\n'-M' Directive below.]\n"
},
{
"code": null,
"e": 35376,
"s": 35217,
"text": "\nTo send email to more than one user, please use the following \"comma\nseparated\" form for the address: user1@add1,user2@add2,...,userN@addN\n(with no spaces).\n"
},
{
"code": null,
"e": 35516,
"s": 35376,
"text": "\nTo test that email is being sent correctly, use the '-M test'\nDirective described below to send one test email message on\nsmartd\nstartup.\n"
},
{
"code": null,
"e": 35913,
"s": 35516,
"text": "\nBy default, email is sent using the system\nmail command. In order that\nsmartd\nfind the mail command (normally /bin/mail) an executable named\n'mail' must be in the path of the shell or environment from which\nsmartd\nwas started. If you wish to specify an explicit path to the mail\nexecutable (for example /usr/local/bin/mail) or a custom script to\nrun, please use the '-M exec' Directive below.\n"
},
{
"code": null,
"e": 36095,
"s": 35913,
"text": "\nNote that by default under Solaris, in the previous paragraph,\n'mailx' and '/bin/mailx' are used, since Solaris\n'/bin/mail' does not accept a '-s' (Subject) command-line\nargument.\n"
},
{
"code": null,
"e": 36249,
"s": 36095,
"text": "\nOn Windows, the 'Blat' mailer\n(http://blat.sourceforge.net/) is used by default.\nThis mailer uses a different command line syntax, see\n'-M exec' below.\n"
},
{
"code": null,
"e": 36442,
"s": 36249,
"text": "\nNote also that there is a special argument\n<nomailer> which can be given to the '-m' Directive in conjunction with the '-M\nexec' Directive. Please see below for an explanation of its effect.\n"
},
{
"code": null,
"e": 36847,
"s": 36442,
"text": "\nIf the mailer or the shell running it produces any STDERR/STDOUT\noutput, then a snippet of that output will be copied to SYSLOG. The\nremainder of the output is discarded. If problems are encountered in\nsending mail, this should help you to understand and fix them. If\nyou have mail problems, we recommend running smartd in debug\nmode with the '-d' flag, using the '-M test' Directive described\nbelow.\n"
},
{
"code": null,
"e": 37303,
"s": 36847,
"text": "\nThe following extension is available on Windows:\nBy specifying 'msgbox' as a mail address, a warning\n\"email\" is displayed as a message box on the screen.\nUsing both 'msgbox' and regular mail addresses is possible,\nif 'msgbox' is the first word in the comma separated list.\nWith 'sysmsgbox', a system modal (always on top) message box\nis used. If running as a service, a service notification message box\n(always shown on current visible desktop) is used.\n"
},
{
"code": null,
"e": 37492,
"s": 37305,
"text": "\nMultiple -M Directives may be given. If more than one of the\nfollowing three -M Directives are given (example: -M once -M daily)\nthen the final one (in the example, -M daily) is used.\n"
},
{
"code": null,
"e": 37568,
"s": 37492,
"text": "\nThe valid arguments to the -M Directive are (one of the following\nthree):\n"
},
{
"code": null,
"e": 37667,
"s": 37568,
"text": "\nonce - send only one warning email for each type of disk problem detected. This\nis the default.\n"
},
{
"code": null,
"e": 37772,
"s": 37667,
"text": "\ndaily - send additional warning reminder emails, once per day, for each type\nof disk problem detected.\n"
},
{
"code": null,
"e": 38013,
"s": 37772,
"text": "\ndiminishing - send additional warning reminder emails, after a one-day interval,\nthen a two-day interval, then a four-day interval, and so on for each\ntype of disk problem detected. Each interval is twice as long as the\nprevious interval.\n"
},
{
"code": null,
"e": 38082,
"s": 38013,
"text": "\nIn addition, one may add zero or more of the following Directives:\n"
},
{
"code": null,
"e": 38377,
"s": 38082,
"text": "\ntest - send a single test email\nimmediately upon\nsmartd\nstartup. This allows one to verify that email is delivered correctly.\nNote that if this Directive is used,\nsmartd\nwill also send the normal email warnings that were enabled with the '-m' Directive,\nin addition to the single test email!\n"
},
{
"code": null,
"e": 38542,
"s": 38377,
"text": "\nexec PATH - run the executable PATH instead of the default mail command, when\nsmartd\nneeds to send email. PATH must point to an executable binary file or\nscript.\n"
},
{
"code": null,
"e": 38989,
"s": 38542,
"text": "\nBy setting PATH to point to a customized script, you can make\nsmartd perform useful tricks when a disk problem is detected\n(beeping the console, shutting down the machine, broadcasting warnings\nto all logged-in users, etc.) But please be careful. smartd\nwill block until the executable PATH returns, so if your\nexecutable hangs, then smartd will also hang. Some sample\nscripts are included in\n/usr/share/doc/smartmontools-5.38/examplescripts/.\n"
},
{
"code": null,
"e": 39427,
"s": 38989,
"text": "\nThe return status of the executable is recorded by smartd in\nSYSLOG. The executable is not expected to write to STDOUT or\nSTDERR. If it does, then this is interpreted as indicating that\nsomething is going wrong with your executable, and a fragment of this\noutput is logged to SYSLOG to help you to understand the problem.\nNormally, if you wish to leave some record behind, the executable\nshould send mail or write to a file or device.\n"
},
{
"code": null,
"e": 39637,
"s": 39427,
"text": "\nBefore running the executable, smartd sets a number of\nenvironment variables. These environment variables may be used to\ncontrol the executable's behavior. The environment variables\nexported by smartd are:\n"
},
{
"code": null,
"e": 39862,
"s": 39637,
"text": "\nIf the '-m ADD' Directive is given with a normal address argument,\nthen the executable pointed to by PATH will be run in a shell with\nSTDIN receiving the body of the email message, and with the same\ncommand-line arguments:\n"
},
{
"code": null,
"e": 39900,
"s": 39862,
"text": "-s \"$SMARTD_SUBJECT\" $SMARTD_ADDRESS\n"
},
{
"code": null,
"e": 40024,
"s": 39900,
"text": "-m user@home -M exec /bin/mail \n-m admin@work -M exec /usr/local/bin/mailto \n-m root -M exec /Example_1/bash/script/below \n"
},
{
"code": null,
"e": 40089,
"s": 40024,
"text": "\nNote that on Windows, the syntax of the 'Blat' mailer is\nused:\n"
},
{
"code": null,
"e": 40144,
"s": 40089,
"text": "- -q -subject \"$SMARTD_SUBJECT\" -to \"$SMARTD_ADDRESS\"\n"
},
{
"code": null,
"e": 40341,
"s": 40144,
"text": "\nIf the '-m ADD' Directive is given with the special address argument\n<nomailer> then the executable pointed to by PATH is run in a shell with\nno STDIN and\nno command-line arguments, for example:\n"
},
{
"code": null,
"e": 40394,
"s": 40341,
"text": "-m <nomailer> -M exec /Example_2/bash/script/below \n"
},
{
"code": null,
"e": 40576,
"s": 40394,
"text": "\nSome EXAMPLES of scripts that can be used with the '-M exec'\nDirective are given below. Some sample scripts are also included in\n/usr/share/doc/smartmontools-5.38/examplescripts/.\n"
},
{
"code": null,
"e": 40852,
"s": 40578,
"text": "\nThis is useful, for example, if you have a very old disk and don't\nwant to keep getting messages about the hours-on-lifetime Attribute\n(usually Attribute 9) failing. This Directive may appear multiple\ntimes for a single device, if you want to ignore multiple Attributes.\n"
},
{
"code": null,
"e": 41141,
"s": 40852,
"text": "\nThis is useful, for example, if one of the device Attributes is the disk\ntemperature (usually Attribute 194 or 231). It's annoying to get reports\neach time the temperature changes. This Directive may appear multiple\ntimes for a single device, if you want to ignore multiple Attributes.\n"
},
{
"code": null,
"e": 41232,
"s": 41141,
"text": "\nA common use of this Directive is to track the device Temperature\n(often ID=194 or 231).\n"
},
{
"code": null,
"e": 41384,
"s": 41234,
"text": "\nIf this Directive is given, it automatically implies the '-r'\nDirective for the same Attribute, so that the Raw value of the\nAttribute is reported.\n"
},
{
"code": null,
"e": 41593,
"s": 41384,
"text": "\nA common use of this Directive is to track the device Temperature\n(often ID=194 or 231). It is also useful for understanding how\ndifferent types of system behavior affects the values of certain\nAttributes.\n"
},
{
"code": null,
"e": 42329,
"s": 41595,
"text": "\nA pending sector is a disk sector (containing 512 bytes of your data)\nwhich the device would like to mark as ‘‘bad\" and reallocate.\nTypically this is because your computer tried to read that sector, and\nthe read failed because the data on it has been corrupted and has\ninconsistent Error Checking and Correction (ECC) codes. This is\nimportant to know, because it means that there is some unreadable data\non the disk. The problem of figuring out what file this data belongs\nto is operating system and file system specific. You can typically\nforce the sector to reallocate by writing to it (translation: make the\ndevice substitute a spare good sector for the bad one) but at the\nprice of losing the 512 bytes of data stored there.\n"
},
{
"code": null,
"e": 42628,
"s": 42333,
"text": "\nAn offline uncorrectable sector is a disk sector which was not\nreadable during an off-line scan or a self-test. This is important\nto know, because if you have data stored in this disk sector, and you\nneed to read it, the read will fail. Please see the previous '-C'\noption for more details.\n"
},
{
"code": null,
"e": 42798,
"s": 42630,
"text": "\nTo disable any of the 3 reports, set the corresponding limit to 0.\nTrailing zero arguments may be omitted. By default, all temperature\nreports are disabled ('-W 0').\n"
},
{
"code": null,
"e": 42857,
"s": 42798,
"text": "\nTo track temperature changes of at least 2 degrees, use:\n"
},
{
"code": null,
"e": 42864,
"s": 42857,
"text": " -W 2\n"
},
{
"code": null,
"e": 42874,
"s": 42864,
"text": " -W 0,40\n"
},
{
"code": null,
"e": 42886,
"s": 42874,
"text": " -W 0,0,45\n"
},
{
"code": null,
"e": 42899,
"s": 42886,
"text": " -W 2,40,45\n"
},
{
"code": null,
"e": 43086,
"s": 42899,
"text": "\nFor ATA devices, smartd interprets Attribute 194 as Temperature Celsius\nby default. This can be changed to Attribute 9 or 220 by the drive\ndatabase or by the '-v' directive, see below.\n"
},
{
"code": null,
"e": 43244,
"s": 43088,
"text": "\nnone - Assume that the device firmware obeys the ATA specifications. This is\nthe default, unless the device has presets for '-F' in the device\ndatabase.\n"
},
{
"code": null,
"e": 43794,
"s": 43244,
"text": "\nsamsung - In some Samsung disks (example: model SV4012H Firmware Version:\nRM100-08) some of the two- and four-byte quantities in the SMART data\nstructures are byte-swapped (relative to the ATA specification).\nEnabling this option tells smartd to evaluate these quantities\nin byte-reversed order. Some signs that your disk needs this option\nare (1) no self-test log printed, even though you have run self-tests;\n(2) very large numbers of ATA errors reported in the ATA error log;\n(3) strange and impossible values for the ATA error log timestamps.\n"
},
{
"code": null,
"e": 44009,
"s": 43794,
"text": "\nsamsung2 - In more recent Samsung disks (firmware revisions ending in \"-23\") the\nnumber of ATA errors reported is byte swapped. Enabling this option\ntells smartd to evaluate this quantity in byte-reversed order.\n"
},
{
"code": null,
"e": 44298,
"s": 44009,
"text": "\nsamsung3 - Some Samsung disks (at least SP2514N with Firmware VF100-37) report\na self-test still in progress with 0% remaining when the test was already\ncompleted. If this directive is specified, smartd will not skip the\nnext scheduled self-test (see Directive '-s' above) in this case.\n"
},
{
"code": null,
"e": 44408,
"s": 44298,
"text": "\nNote that an explicit '-F' Directive will over-ride any preset\nvalues for '-F' (see the '-P' option below).\n"
},
{
"code": null,
"e": 44462,
"s": 44410,
"text": "\n[Please see the smartctl -F command-line option.]\n"
},
{
"code": null,
"e": 44547,
"s": 44464,
"text": "\nThis Directive may appear multiple times. Valid arguments to this\nDirective are:\n"
},
{
"code": null,
"e": 44803,
"s": 44547,
"text": "\n9,minutes - Raw Attribute number 9 is power-on time in minutes. Its raw value\nwill be displayed in the form 'Xh+Ym'. Here X is hours, and Y is\nminutes in the range 0-59 inclusive. Y is always printed with two\ndigits, for example '06' or '31' or '00'.\n"
},
{
"code": null,
"e": 45111,
"s": 44803,
"text": "\n9,seconds - Raw Attribute number 9 is power-on time in seconds. Its raw value\nwill be displayed in the form 'Xh+Ym+Zs'. Here X is hours, Y is\nminutes in the range 0-59 inclusive, and Z is seconds in the range\n0-59 inclusive. Y and Z are always printed with two digits, for\nexample '06' or '31' or '00'.\n"
},
{
"code": null,
"e": 45437,
"s": 45111,
"text": "\n9,halfminutes - Raw Attribute number 9 is power-on time, measured in units of 30\nseconds. This format is used by some Samsung disks. Its raw value\nwill be displayed in the form 'Xh+Ym'. Here X is hours, and Y is\nminutes in the range 0-59 inclusive. Y is always printed with two\ndigits, for example '06' or '31' or '00'.\n"
},
{
"code": null,
"e": 45507,
"s": 45437,
"text": "\n9,temp - Raw Attribute number 9 is the disk temperature in Celsius.\n"
},
{
"code": null,
"e": 45602,
"s": 45507,
"text": "\n192,emergencyretractcyclect - Raw Attribute number 192 is the Emergency Retract Cycle Count.\n"
},
{
"code": null,
"e": 46028,
"s": 45602,
"text": "\n193,loadunload - Raw Attribute number 193 contains two values. The first is the\nnumber of load cycles. The second is the number of unload cycles.\nThe difference between these two values is the number of times that\nthe drive was unexpectedly powered off (also called an emergency\nunload). As a rule of thumb, the mechanical stress created by one\nemergency unload is equivalent to that created by one hundred normal\nunloads.\n"
},
{
"code": null,
"e": 46203,
"s": 46028,
"text": "\n194,10xCelsius - Raw Attribute number 194 is ten times the disk temperature in\nCelsius. This is used by some Samsung disks (example: model SV1204H\nwith RK100-13 firmware).\n"
},
{
"code": null,
"e": 46365,
"s": 46203,
"text": "\n194,unknown - Raw Attribute number 194 is NOT the disk temperature, and its\ninterpretation is unknown. This is primarily useful for the -P\n(presets) Directive.\n"
},
{
"code": null,
"e": 46459,
"s": 46365,
"text": "\n198,offlinescanuncsectorct - Raw Attribute number 198 is the Offline Scan UNC Sector Count.\n"
},
{
"code": null,
"e": 46534,
"s": 46459,
"text": "\n200,writeerrorcount - Raw Attribute number 200 is the Write Error Count.\n"
},
{
"code": null,
"e": 46609,
"s": 46534,
"text": "\n201,detectedtacount - Raw Attribute number 201 is the Detected TA Count.\n"
},
{
"code": null,
"e": 46683,
"s": 46609,
"text": "\n220,temp - Raw Attribute number 220 is the disk temperature in Celsius.\n"
},
{
"code": null,
"e": 46827,
"s": 46683,
"text": "\nNote: a table of hard drive models, listing which Attribute\ncorresponds to temperature, can be found at:\nhttp://www.guzu.net/linux/hddtemp.db\n"
},
{
"code": null,
"e": 47139,
"s": 46827,
"text": "\nN,raw8 - Print the Raw value of Attribute N as six 8-bit unsigned base-10\nintegers. This may be useful for decoding the meaning of the Raw\nvalue. The form 'N,raw8' prints Raw values for ALL Attributes in this\nform. The form (for example) '123,raw8' only prints the Raw value for\nAttribute 123 in this form.\n"
},
{
"code": null,
"e": 47457,
"s": 47139,
"text": "\nN,raw16 - Print the Raw value of Attribute N as three 16-bit unsigned base-10\nintegers. This may be useful for decoding the meaning of the Raw\nvalue. The form 'N,raw16' prints Raw values for ALL Attributes in this\nform. The form (for example) '123,raw16' only prints the Raw value for\nAttribute 123 in this form.\n"
},
{
"code": null,
"e": 47770,
"s": 47457,
"text": "\nN,raw48 - Print the Raw value of Attribute N as a 48-bit unsigned base-10\ninteger. This may be useful for decoding the meaning of the Raw\nvalue. The form 'N,raw48' prints Raw values for ALL Attributes in\nthis form. The form (for example) '123,raw48' only prints the Raw\nvalue for Attribute 123 in this form.\n"
},
{
"code": null,
"e": 47853,
"s": 47772,
"text": "\nuse - use any presets that are available for this drive. This is the default.\n"
},
{
"code": null,
"e": 47903,
"s": 47853,
"text": "\nignore - do not use any presets for this drive.\n"
},
{
"code": null,
"e": 47968,
"s": 47903,
"text": "\nshow - show the presets listed for this drive in the database.\n"
},
{
"code": null,
"e": 48046,
"s": 47968,
"text": "\nshowall - show the presets that are available for all drives and then exit.\n"
},
{
"code": null,
"e": 48098,
"s": 48046,
"text": "\n[Please see the\nsmartctl -P command-line option.]\n"
},
{
"code": null,
"e": 48212,
"s": 48100,
"text": "\nNote that -a is the default for ATA devices. If none of these other\nDirectives is given, then -a is assumed.\n"
},
{
"code": null,
"e": 48244,
"s": 48214,
"text": "-H -l selftest -l error -f. \n"
},
{
"code": null,
"e": 48428,
"s": 48246,
"text": "\nIf DEVICESCAN is not followed by any Directives, then smartd\nwill scan for both ATA and SCSI devices, and will monitor all possible\nSMART properties of any devices that are found.\n"
},
{
"code": null,
"e": 48571,
"s": 48428,
"text": "\nDEVICESCAN may optionally be followed by any valid Directives,\nwhich will be applied to all devices that are found in the scan. For\nexample\n"
},
{
"code": null,
"e": 48604,
"s": 48571,
"text": "DEVICESCAN -m root@example.com \n"
},
{
"code": null,
"e": 48644,
"s": 48604,
"text": "DEVICESCAN -d ata -m root@example.com \n"
},
{
"code": null,
"e": 48687,
"s": 48644,
"text": "DEVICESCAN -H -d ata -m root@example.com \n"
},
{
"code": null,
"e": 48870,
"s": 48689,
"text": "\nExample 1: This script is for use with '-m ADDRESS -M exec PATH'. It appends\nthe output of\nsmartctl -a to the output of the smartd email warning message and sends it to ADDRESS.\n"
},
{
"code": null,
"e": 49184,
"s": 48872,
"text": "\n#! /bin/bash\n\n# Save the email message (STDIN) to a file:\ncat > /root/msg\n\n# Append the output of smartctl -a to the message:\n/usr/sbin/smartctl -a -d $SMART_DEVICETYPE $SMARTD_DEVICE >> /root/msg\n\n# Now email the message to the user at address ADD:\n/bin/mail -s \"$SMARTD_SUBJECT\" $SMARTD_ADDRESS < /root/msg\n\n"
},
{
"code": null,
"e": 49246,
"s": 49184,
"text": "\n# Save the email message (STDIN) to a file:\ncat > /root/msg\n"
},
{
"code": null,
"e": 49370,
"s": 49246,
"text": "\n# Append the output of smartctl -a to the message:\n/usr/sbin/smartctl -a -d $SMART_DEVICETYPE $SMARTD_DEVICE >> /root/msg\n"
},
{
"code": null,
"e": 49484,
"s": 49370,
"text": "\n# Now email the message to the user at address ADD:\n/bin/mail -s \"$SMARTD_SUBJECT\" $SMARTD_ADDRESS < /root/msg\n\n"
},
{
"code": null,
"e": 49648,
"s": 49484,
"text": "\nExample 2: This script is for use with '-m <nomailer> -M exec\nPATH'. It warns all users about a disk problem, waits 30 seconds, and\nthen powers down the machine.\n"
},
{
"code": null,
"e": 49941,
"s": 49650,
"text": "\n#! /bin/bash\n\n# Warn all users of a problem\nwall 'Problem detected with disk: ' \"$SMARTD_DEVICESTRING\"\nwall 'Warning message from smartd is: ' \"$SMARTD_MESSAGE\"\nwall 'Shutting down machine in 30 seconds... '\n\n# Wait half a minute\nsleep 30\n\n# Power down the machine\n/sbin/shutdown -hf now\n\n"
},
{
"code": null,
"e": 50137,
"s": 49941,
"text": "\n# Warn all users of a problem\nwall 'Problem detected with disk: ' \"$SMARTD_DEVICESTRING\"\nwall 'Warning message from smartd is: ' \"$SMARTD_MESSAGE\"\nwall 'Shutting down machine in 30 seconds... '\n"
},
{
"code": null,
"e": 50169,
"s": 50137,
"text": "\n# Wait half a minute\nsleep 30\n"
},
{
"code": null,
"e": 50220,
"s": 50169,
"text": "\n# Power down the machine\n/sbin/shutdown -hf now\n\n"
},
{
"code": null,
"e": 50345,
"s": 50220,
"text": "\nSome example scripts are distributed with the smartmontools package,\nin /usr/share/doc/smartmontools-5.38/examplescripts/.\n"
},
{
"code": null,
"e": 50594,
"s": 50345,
"text": "\nPlease note that these scripts typically run as root, so any files\nthat they read/write should not be writable by ordinary users or\nreside in directories like /tmp that are writable by ordinary users\nand may expose your system to symlink attacks.\n"
},
{
"code": null,
"e": 50827,
"s": 50594,
"text": "\nAs previously described, if the scripts write to STDOUT or STDERR,\nthis is interpreted as indicating that there was an internal error\nwithin the script, and a snippet of STDOUT/STDERR is logged to SYSLOG.\nThe remainder is flushed.\n"
},
{
"code": null,
"e": 50916,
"s": 50831,
"text": "'Device: /dev/hda, SMART Attribute: 194 Temperature_Celsius changed from 94 to 93' \n"
},
{
"code": null,
"e": 51019,
"s": 50916,
"text": "'Device: /dev/hda, SMART Attribute: 194 Temperature_Celsius changed from 94 [Raw 22] to 93 [Raw 23]' \n"
},
{
"code": null,
"e": 51145,
"s": 51019,
"text": "\nPlease see the\nsmartctl manual page for further explanation of the differences between\nNormalized and Raw Attribute values.\n"
},
{
"code": null,
"e": 51243,
"s": 51145,
"text": "\nsmartd\nwill make log entries at loglevel\nLOG_CRIT if a SMART Attribute has failed, for example:\n"
},
{
"code": null,
"e": 51313,
"s": 51243,
"text": "'Device: /dev/hdc, Failed SMART Attribute: 5 Reallocated_Sector_Ct' \n"
},
{
"code": null,
"e": 51621,
"s": 51313,
"text": "\nUnder Solaris with the default /etc/syslog.conf configuration,\nmessages below loglevel LOG_NOTICE will not be recorded.\nHence all smartd messages with loglevel LOG_INFO will be\nlost. If you want to use the existing daemon facility to log all\nmessages from smartd, you should change /etc/syslog.conf\nfrom:\n"
},
{
"code": null,
"e": 51676,
"s": 51621,
"text": " ...;daemon.notice;... /var/adm/messages\n"
},
{
"code": null,
"e": 51731,
"s": 51676,
"text": " ...;daemon.info;... /var/adm/messages\n"
},
{
"code": null,
"e": 51881,
"s": 51731,
"text": "\nOn Cygwin and Windows, the log messages are written to the event log\nor to a file. See documentation of the ’-l FACILITY’ option above for\ndetails.\n"
},
{
"code": null,
"e": 51982,
"s": 51881,
"text": "\nOn Windows, the following built-in commands can be used to control\nsmartd, if running as a daemon:\n"
},
{
"code": null,
"e": 52015,
"s": 51982,
"text": "\n'smartd status' - check status\n"
},
{
"code": null,
"e": 52045,
"s": 52015,
"text": "\n'smartd stop' - stop smartd\n"
},
{
"code": null,
"e": 52084,
"s": 52045,
"text": "\n'smartd reload' - reread config file\n"
},
{
"code": null,
"e": 52120,
"s": 52084,
"text": "\n'smartd restart' - restart smartd\n"
},
{
"code": null,
"e": 52157,
"s": 52120,
"text": "\n'smartd sigusr1' - check disks now\n"
},
{
"code": null,
"e": 52196,
"s": 52157,
"text": "\n'smartd sigusr2' - toggle debug mode\n"
},
{
"code": null,
"e": 52262,
"s": 52196,
"text": "\nOn WinNT4/2000/XP, smartd can also be run as a Windows service:\n"
},
{
"code": null,
"e": 52432,
"s": 52264,
"text": "\nThe Cygwin Version of smartd can be run as a service via the\ncygrunsrv tool. The start-up script provides Cygwin-specific commands\nto install and remove the service:\n"
},
{
"code": null,
"e": 52508,
"s": 52432,
"text": "/etc/rc.d/init.d/smartd install [options] \n/etc/rc.d/init.d/smartd remove \n"
},
{
"code": null,
"e": 52576,
"s": 52510,
"text": "\nThe Windows Version of smartd has buildin support for services:\n"
},
{
"code": null,
"e": 52741,
"s": 52576,
"text": "\n'smartd install [options]' installs a service\nnamed \"smartd\" (display name \"SmartD Service\") using the command line\n'/installpath/smartd.exe --service [options]'.\n"
},
{
"code": null,
"e": 52820,
"s": 52741,
"text": "\n'smartd remove' can later be used to remove the service entry\nfrom registry.\n"
},
{
"code": null,
"e": 53023,
"s": 52820,
"text": "\nUpon startup, the smartd service changes the working directory\nto its own installation path. If smartd.conf and blat.exe are stored\nin this directory, no '-c' option and '-M exec' directive is needed.\n"
},
{
"code": null,
"e": 53109,
"s": 53023,
"text": "\nThe debug mode ('-d', '-q onecheck') does not work if smartd is\nrunning as service.\n"
},
{
"code": null,
"e": 53227,
"s": 53109,
"text": "\nThe service can be controlled as usual with Windows commands 'net'\nor 'sc' ('net start smartd', 'net stop smartd').\n"
},
{
"code": null,
"e": 53330,
"s": 53227,
"text": "\nPausing the service ('net pause smartd') sets the interval between\ndisk checks ('-i N') to infinite.\n"
},
{
"code": null,
"e": 53468,
"s": 53330,
"text": "\nContinuing the paused service ('net continue smartd') resets the\ninterval and rereads the configuration file immediately (like SIGHUP):\n"
},
{
"code": null,
"e": 53641,
"s": 53468,
"text": "\nContinuing a still running service ('net continue smartd' without\npreceding 'net pause smartd') does not reread configuration but\nchecks disks immediately (like SIGUSR1).\n"
},
{
"code": null,
"e": 54336,
"s": 53643,
"text": "\nWhen smartd makes log entries, these are time-stamped. The time\nstamps are in the computer’s local time zone, which is generally set\nusing either the environment variable 'TZ' or using a\ntime-zone file such as /etc/localtime. You may wish to change\nthe timezone while smartd is running (for example, if you carry\na laptop to a new time-zone and don’t reboot it). Due to a bug in the\ntzset(3) function of many unix standard C libraries, the\ntime-zone stamps of smartd might not change. For some systems,\nsmartd will work around this problem if the time-zone is\nset using /etc/localtime. The work-around fails if the\ntime-zone is set using the 'TZ' variable (or a file that it\npoints to).\n"
},
{
"code": null,
"e": 54879,
"s": 54346,
"text": "Casper Dik (Solaris SCSI interface)\nChristian Franke (Windows interface and Cygwin package)\nDouglas Gilbert (SCSI subsystem)\nGuido Guenther (Autoconf/Automake packaging)\nGeoffrey Keating (Darwin ATA interface)\nEduard Martinescu (FreeBSD interface)\nFrédéric L. W. Meunier (Web site and Mailing list)\nKeiji Sawada (Solaris ATA interface)\nSergey Svishchev (NetBSD interface)\nDavid Snyder and Sergey Svishchev (OpenBSD interface)\nPhil Williams (User interface and drive database)\nShengfeng Zhou (Linux Highpoint RocketRaid interface)\n"
},
{
"code": null,
"e": 55414,
"s": 54887,
"text": "\nIf you would like to understand better how SMART works, and what it\ndoes, a good place to start is with Sections 4.8 and 6.54 of the first\nvolume of the 'AT Attachment with Packet Interface-7' (ATA/ATAPI-7)\nspecification. This documents the SMART functionality which the\nsmartmontools utilities provide access to. You can find\nRevision 4b of this document at\nhttp://www.t13.org/docs2004/d1532v1r4b-ATA-ATAPI-7.pdf .\nEarlier and later versions of this Specification are available from\nthe T13 web site http://www.t13.org/ .\n"
},
{
"code": null,
"e": 55756,
"s": 55414,
"text": "\nThe functioning of SMART was originally defined by the SFF-8035i\nrevision 2 and the SFF-8055i revision 1.4 specifications. These are\npublications of the Small Form Factors (SFF) Committee. Links to\nthese documents may be found in the References section of the\nsmartmontools home page at http://smartmontools.sourceforge.net/#references .\n"
},
{
"code": null,
"e": 55775,
"s": 55758,
"text": "\nAdvertisements\n"
},
{
"code": null,
"e": 55810,
"s": 55775,
"text": "\n 129 Lectures \n 23 hours \n"
},
{
"code": null,
"e": 55838,
"s": 55810,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 55872,
"s": 55838,
"text": "\n 5 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 55889,
"s": 55872,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 55922,
"s": 55889,
"text": "\n 35 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 55933,
"s": 55922,
"text": " Pradeep D"
},
{
"code": null,
"e": 55968,
"s": 55933,
"text": "\n 41 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 55984,
"s": 55968,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 56017,
"s": 55984,
"text": "\n 46 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 56029,
"s": 56017,
"text": " GUHARAJANM"
},
{
"code": null,
"e": 56061,
"s": 56029,
"text": "\n 6 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 56069,
"s": 56061,
"text": " Uplatz"
},
{
"code": null,
"e": 56076,
"s": 56069,
"text": " Print"
},
{
"code": null,
"e": 56087,
"s": 56076,
"text": " Add Notes"
}
] |
How do we use Python in script mode?
|
It is possible to execute Python script from command line. Python program can be written by any text editor (preferably a Python aware text editor) and saved with .py extension. To write basic Hello World program using IDLE, the Python IDE shipped with standard Python distribution, open the editor choosing File->New.
Type following lines and save as test.py
#!/usr/bin/python
Print (“Hello World”)
Execute the script using following command line
C:\users>python test.py
You can also run the script from Run Menu of IDLE file editor
|
[
{
"code": null,
"e": 1381,
"s": 1062,
"text": "It is possible to execute Python script from command line. Python program can be written by any text editor (preferably a Python aware text editor) and saved with .py extension. To write basic Hello World program using IDLE, the Python IDE shipped with standard Python distribution, open the editor choosing File->New."
},
{
"code": null,
"e": 1422,
"s": 1381,
"text": "Type following lines and save as test.py"
},
{
"code": null,
"e": 1463,
"s": 1422,
"text": "#!/usr/bin/python\n Print (“Hello World”)"
},
{
"code": null,
"e": 1512,
"s": 1463,
"text": "Execute the script using following command line "
},
{
"code": null,
"e": 1536,
"s": 1512,
"text": "C:\\users>python test.py"
},
{
"code": null,
"e": 1598,
"s": 1536,
"text": "You can also run the script from Run Menu of IDLE file editor"
}
] |
Extracting (digitising) data from plots in scientific papers or images | by Daniel Ellis | Towards Data Science
|
Often we see a graphic of interest and want to apply the data to our own interest and designs. This frequently occurs within academia, where research needs to be compared to that already existing within scientific journals and in data visualisation where historic figures can be built upon and improved (with the addition of new data/designs).
The extraction of data from images is called digitization. This is the conversion of an analogue figure into a quantized digital (numerical) format — to be used for manipulation and analysis.
The simplest process works by defining the range of data within a plot and calculating the value of the points on a plotted line within it. To do this we can make use of the WebPlotDigitizer (WPD).
This can with a range of plots ranging from 2D (X-Y) plot to Bar Plots, Ternary and Polar Diagrams. The web-based nature of WPD means that it can run on a range of operating systems or even an online interface. Access to this can be found at :
https://automeris.io/WebPlotDigitizer/
In this article, we take a figure showing the import and export profits from trades to the West Indies between 1700 and 1780. This is a lovely figure which was hand plotted by W. Playfair. In the sections below we describe the process of digitizing the figure and then provide a couple of quick plots in python of the extracted data.
The general digitization process is relatively simple using the WPD software. The algorithmic functions are hidden in the background, and the user only needs to change a handful of ‘point and click’ parameters on the interface. The procedure for this is outlined below:
Click on file > Load Image > select the type of plotand upload your image.For an x-y plot select your boundaries. These begin with the minimal known x value, then the maximum known x value, followed by the minimum and maximum known y valuesEnter the values for the known points and select if a log scale has been used (You may add additional configuration points after pressing the confirm button.)Adjust settings such as mask (selecting the area to explore), foreground (line) and background colours, and the pixel samplingintervals — note sometimes a larger averaging area within the pixel sampling intervals gives a better result (in the example case 30 pixels was used).Click run within the algorithm box.
Click on file > Load Image > select the type of plotand upload your image.
For an x-y plot select your boundaries. These begin with the minimal known x value, then the maximum known x value, followed by the minimum and maximum known y values
Enter the values for the known points and select if a log scale has been used (You may add additional configuration points after pressing the confirm button.)
Adjust settings such as mask (selecting the area to explore), foreground (line) and background colours, and the pixel samplingintervals — note sometimes a larger averaging area within the pixel sampling intervals gives a better result (in the example case 30 pixels was used).
Click run within the algorithm box.
This produces a selection as shown below.
Finally, we can extract the generated comma separated file (CSV) for plotting in another program (e.g. JS, Python, R ...). A quick example in python using pandas gives the following:
The WebPlotDigitizer is very simple to use program with many practical applications. Its HTML and javascript nature makes it capable of running both online and on most popular operating systems. Finally, the ability to extract data from publications (especially ones where the raw data has been lost) makes it an invaluable tool for the modern-day scientist.
|
[
{
"code": null,
"e": 515,
"s": 171,
"text": "Often we see a graphic of interest and want to apply the data to our own interest and designs. This frequently occurs within academia, where research needs to be compared to that already existing within scientific journals and in data visualisation where historic figures can be built upon and improved (with the addition of new data/designs)."
},
{
"code": null,
"e": 707,
"s": 515,
"text": "The extraction of data from images is called digitization. This is the conversion of an analogue figure into a quantized digital (numerical) format — to be used for manipulation and analysis."
},
{
"code": null,
"e": 905,
"s": 707,
"text": "The simplest process works by defining the range of data within a plot and calculating the value of the points on a plotted line within it. To do this we can make use of the WebPlotDigitizer (WPD)."
},
{
"code": null,
"e": 1149,
"s": 905,
"text": "This can with a range of plots ranging from 2D (X-Y) plot to Bar Plots, Ternary and Polar Diagrams. The web-based nature of WPD means that it can run on a range of operating systems or even an online interface. Access to this can be found at :"
},
{
"code": null,
"e": 1188,
"s": 1149,
"text": "https://automeris.io/WebPlotDigitizer/"
},
{
"code": null,
"e": 1522,
"s": 1188,
"text": "In this article, we take a figure showing the import and export profits from trades to the West Indies between 1700 and 1780. This is a lovely figure which was hand plotted by W. Playfair. In the sections below we describe the process of digitizing the figure and then provide a couple of quick plots in python of the extracted data."
},
{
"code": null,
"e": 1792,
"s": 1522,
"text": "The general digitization process is relatively simple using the WPD software. The algorithmic functions are hidden in the background, and the user only needs to change a handful of ‘point and click’ parameters on the interface. The procedure for this is outlined below:"
},
{
"code": null,
"e": 2502,
"s": 1792,
"text": "Click on file > Load Image > select the type of plotand upload your image.For an x-y plot select your boundaries. These begin with the minimal known x value, then the maximum known x value, followed by the minimum and maximum known y valuesEnter the values for the known points and select if a log scale has been used (You may add additional configuration points after pressing the confirm button.)Adjust settings such as mask (selecting the area to explore), foreground (line) and background colours, and the pixel samplingintervals — note sometimes a larger averaging area within the pixel sampling intervals gives a better result (in the example case 30 pixels was used).Click run within the algorithm box."
},
{
"code": null,
"e": 2577,
"s": 2502,
"text": "Click on file > Load Image > select the type of plotand upload your image."
},
{
"code": null,
"e": 2744,
"s": 2577,
"text": "For an x-y plot select your boundaries. These begin with the minimal known x value, then the maximum known x value, followed by the minimum and maximum known y values"
},
{
"code": null,
"e": 2903,
"s": 2744,
"text": "Enter the values for the known points and select if a log scale has been used (You may add additional configuration points after pressing the confirm button.)"
},
{
"code": null,
"e": 3180,
"s": 2903,
"text": "Adjust settings such as mask (selecting the area to explore), foreground (line) and background colours, and the pixel samplingintervals — note sometimes a larger averaging area within the pixel sampling intervals gives a better result (in the example case 30 pixels was used)."
},
{
"code": null,
"e": 3216,
"s": 3180,
"text": "Click run within the algorithm box."
},
{
"code": null,
"e": 3258,
"s": 3216,
"text": "This produces a selection as shown below."
},
{
"code": null,
"e": 3441,
"s": 3258,
"text": "Finally, we can extract the generated comma separated file (CSV) for plotting in another program (e.g. JS, Python, R ...). A quick example in python using pandas gives the following:"
}
] |
Time and Space Complexity in Data Structure
|
Analysis of efficiency of an algorithm can be performed at two different stages, before implementation and after implementation, as
A priori analysis − This is defined as theoretical analysis of an algorithm. Efficiency of algorithm is measured by assuming that all other factors e.g. speed of processor, are constant and have no effect on implementation.
A posterior analysis − This is defined as empirical analysis of an algorithm. The chosen algorithm is implemented using programming language. Next the chosen algorithm is executed on target computer machine. In this analysis, actual statistics like running time and space needed are collected.
Algorithm analysis is dealt with the execution or running time of various operations involved. Running time of an operation can be defined as number of computer instructions executed per operation.
Suppose X is treated as an algorithm and N is treated as the size of input data, the time and space implemented by the Algorithm X are the two main factors which determine the efficiency of X.
Time Factor − The time is calculated or measured by counting the number of key operations such as comparisons in sorting algorithm.
Space Factor − The space is calculated or measured by counting the maximum memory space required by the algorithm.
The complexity of an algorithm f(N) provides the running time and / or storage space needed by the algorithm with respect of N as the size of input data.
Space complexity of an algorithm represents the amount of memory space needed the algorithm in its life cycle.
Space needed by an algorithm is equal to the sum of the following two components
A fixed part that is a space required to store certain data and variables (i.e. simple variables and constants, program size etc.), that are not dependent of the size of the problem.
A variable part is a space required by variables, whose size is totally dependent on the size of the problem. For example, recursion stack space, dynamic memory allocation etc.
Space complexity S(p) of any algorithm p is S(p) = A + Sp(I) Where A is treated as the fixed part and S(I) is treated as the variable part of the algorithm which depends on instance characteristic I. Following is a simple example that tries to explain the concept
SUM(P, Q)
Step 1 - START
Step 2 - R ← P + Q + 10
Step 3 - Stop
Here we have three variables P, Q and R and one constant. Hence S(p) = 1+3. Now space is dependent on data types of given constant types and variables and it will be multiplied accordingly.
Time Complexity of an algorithm is the representation of the amount of time required by the algorithm to execute to completion. Time requirements can be denoted or defined as a numerical function t(N), where t(N) can be measured as the number of steps, provided each step takes constant time.
For example, in case of addition of two n-bit integers, N steps are taken. Consequently, the total computational time is t(N) = c*n, where c is the time consumed for addition of two bits. Here, we observe that t(N) grows linearly as input size increases.
|
[
{
"code": null,
"e": 1194,
"s": 1062,
"text": "Analysis of efficiency of an algorithm can be performed at two different stages, before implementation and after implementation, as"
},
{
"code": null,
"e": 1418,
"s": 1194,
"text": "A priori analysis − This is defined as theoretical analysis of an algorithm. Efficiency of algorithm is measured by assuming that all other factors e.g. speed of processor, are constant and have no effect on implementation."
},
{
"code": null,
"e": 1712,
"s": 1418,
"text": "A posterior analysis − This is defined as empirical analysis of an algorithm. The chosen algorithm is implemented using programming language. Next the chosen algorithm is executed on target computer machine. In this analysis, actual statistics like running time and space needed are collected."
},
{
"code": null,
"e": 1910,
"s": 1712,
"text": "Algorithm analysis is dealt with the execution or running time of various operations involved. Running time of an operation can be defined as number of computer instructions executed per operation."
},
{
"code": null,
"e": 2103,
"s": 1910,
"text": "Suppose X is treated as an algorithm and N is treated as the size of input data, the time and space implemented by the Algorithm X are the two main factors which determine the efficiency of X."
},
{
"code": null,
"e": 2235,
"s": 2103,
"text": "Time Factor − The time is calculated or measured by counting the number of key operations such as comparisons in sorting algorithm."
},
{
"code": null,
"e": 2350,
"s": 2235,
"text": "Space Factor − The space is calculated or measured by counting the maximum memory space required by the algorithm."
},
{
"code": null,
"e": 2504,
"s": 2350,
"text": "The complexity of an algorithm f(N) provides the running time and / or storage space needed by the algorithm with respect of N as the size of input data."
},
{
"code": null,
"e": 2615,
"s": 2504,
"text": "Space complexity of an algorithm represents the amount of memory space needed the algorithm in its life cycle."
},
{
"code": null,
"e": 2696,
"s": 2615,
"text": "Space needed by an algorithm is equal to the sum of the following two components"
},
{
"code": null,
"e": 2879,
"s": 2696,
"text": "A fixed part that is a space required to store certain data and variables (i.e. simple variables and constants, program size etc.), that are not dependent of the size of the problem."
},
{
"code": null,
"e": 3056,
"s": 2879,
"text": "A variable part is a space required by variables, whose size is totally dependent on the size of the problem. For example, recursion stack space, dynamic memory allocation etc."
},
{
"code": null,
"e": 3320,
"s": 3056,
"text": "Space complexity S(p) of any algorithm p is S(p) = A + Sp(I) Where A is treated as the fixed part and S(I) is treated as the variable part of the algorithm which depends on instance characteristic I. Following is a simple example that tries to explain the concept"
},
{
"code": null,
"e": 3383,
"s": 3320,
"text": "SUM(P, Q)\nStep 1 - START\nStep 2 - R ← P + Q + 10\nStep 3 - Stop"
},
{
"code": null,
"e": 3573,
"s": 3383,
"text": "Here we have three variables P, Q and R and one constant. Hence S(p) = 1+3. Now space is dependent on data types of given constant types and variables and it will be multiplied accordingly."
},
{
"code": null,
"e": 3866,
"s": 3573,
"text": "Time Complexity of an algorithm is the representation of the amount of time required by the algorithm to execute to completion. Time requirements can be denoted or defined as a numerical function t(N), where t(N) can be measured as the number of steps, provided each step takes constant time."
},
{
"code": null,
"e": 4121,
"s": 3866,
"text": "For example, in case of addition of two n-bit integers, N steps are taken. Consequently, the total computational time is t(N) = c*n, where c is the time consumed for addition of two bits. Here, we observe that t(N) grows linearly as input size increases."
}
] |
CNNs for Audio Classification. A primer in deep learning for audio... | by Papia Nandi | Towards Data Science
|
CNNs or convolutional neural nets are a type of deep learning algorithm that does really well at learning images.
That’s because they can learn patterns that are translation invariant and have spatial hierarchies (F. Chollet, 2018).
That means if If the CNN learns the dog in the left corner of the image above, then it can identify the dog in the other two pictures that have been moved around (translation invariance).
If the CNN learns the dog from the left corner of the image above, it will recognize pieces of the original image in the other two pictures because it has learned what the edges of the her eye with heterochromia looks like, her wolf-like snout and the shape of her stylish headphones (spatial hierarchies).
These properties make CNNs formidable learners for images because the real world doesn’t always look exactly like the training data.
Yes. You can extract features which look like images and shape them in a way in order to feed them into a CNN.
The data for this example are bird and frog recordings from the Kaggle competition Rainforest Connection Species Audio Detection.
To get started, load the necessary inputs:
import pandas as pdimport osimport librosaimport librosa.displayimport matplotlib.pyplot as pltfrom sklearn.preprocessing import normalizeimport warningswarnings.filterwarnings('ignore')import numpy as npimport pickleimport joblibfrom sklearn.model_selection import train_test_splitfrom tensorflow.keras import models, layersimport tensorflow as tf
Then the dataframe:
os.chdir('/kaggle/input/rfcx-species-audio-detection')df = pd.read_csv('train_tp.csv')
This dataset comes as a csv file with the names of audio files listed under recording_id, labels under species_id, and the start/end of the audio sample under t_min and t_max:
df.head()
Use the librosa package to load and display an audio file like this:
sample_num=3 #pick a file to display#get the filename filename=df.recording_id[sample_num]+str('.flac')#define the beginning time of the signaltstart = df.t_min[sample_num] tend = df.t_max[sample_num] #define the end time of the signaly,sr=librosa.load('train/'+str(filename)) #load the filelibrosa.display.waveplot(y,sr=sr, x_axis='time', color='cyan')
The CNN is expecting an image:
a grayscale image (1 channel)
a color image with three channels: red, green and blue (RGB)
So you have to make your audio features look like an image.
Choose either 1D for a grayscale image (one feature) or 3D for a color image (to represent multiple features).
Scale and pad the audio features so that every “channel” is the same size.
#This code was adapted from Nicolas Gervais on https://stackoverflow.com/questions/59241216/padding-numpy-arrays-to-a-specific-size on 1/10/2021def padding(array, xx, yy): """ :param array: numpy array :param xx: desired height :param yy: desirex width :return: padded array """h = array.shape[0] w = array.shape[1]a = max((xx - h) // 2,0) aa = max(0,xx - a - h)b = max(0,(yy - w) // 2) bb = max(yy - b - w,0)return np.pad(array, pad_width=((a, aa), (b, bb)), mode='constant')
They’re just numbers after all.
No. It has to make visual sense. Garbage in, garbage out.
Librosa has great tutorials for how to extract features here.
For this example, I’m going to calculate:
Mel spectrogram (MFCCs)
spectral bandwidth
spectral centroid
chromagram (chroma stft)
short-time Fourier transform (stft)
The first axis will be the audio file id, representing the batch in tensorflow-speak. In this example, the second axis is the spectral bandwidth, centroid and chromagram repeated, padded and fit into the shape of the third axis (the stft) and the fourth axis (the MFCCs).
#The eventual shape of the featuresprint(X_train.shape,X_test.shape)
The first axis 1226 is the batch size, 128 is the height, 1000 is the width (set by max_size in the code below) and 3 is the number of channels in the training data. If I have 1226 audio files, then the batch size is 1226. If we only extracted features for the 5 audio files pictured in the dataframe.head() figure, the shape of the input would be 5x128x1000x3. You can make the batch size smaller if you want to use less memory when training. For this example, the batch size is set to the number of audio files.
def generate_features(y_cut): max_size=1000 #my max audio file feature width stft = padding(np.abs(librosa.stft(y_cut, n_fft=255, hop_length = 512)), 128, max_size) MFCCs = padding(librosa.feature.mfcc(y_cut, n_fft=n_fft, hop_length=hop_length,n_mfcc=128),128,max_size) spec_centroid = librosa.feature.spectral_centroid(y=y_cut, sr=sr) chroma_stft = librosa.feature.chroma_stft(y=y_cut, sr=sr) spec_bw = librosa.feature.spectral_bandwidth(y=y_cut, sr=sr) #Now the padding part image = np.array([padding(normalize(spec_bw),1, max_size)]).reshape(1,max_size) image = np.append(image,padding(normalize(spec_centroid),1, max_size), axis=0) #repeat the padded spec_bw,spec_centroid and chroma stft until they are stft and MFCC-sized for i in range(0,9): image = np.append(image,padding(normalize(spec_bw),1, max_size), axis=0) image = np.append(image, padding(normalize(spec_centroid),1, max_size), axis=0) image = np.append(image, padding(normalize(chroma_stft),12, max_size), axis=0) image=np.dstack((image,np.abs(stft))) image=np.dstack((image,MFCCs)) return image
The following three features get squished and padded and repeated...
...into the following axis:
The last two axis are designed to be the same shape:
No. As long as you pad them to be the same shape, use what works the best in modeling.
X=df.drop('species_id',axis=1)y=df.species_id
#Split once to get the test and training setX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=123, stratify=y)print(X_train.shape,X_test.shape)
#Split twice to get the validation setX_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=0.25, random_state=123)print(X_train.shape, X_test.shape, X_val.shape, len(y_train), len(y_test), len(y_val))
Calculate these features for every audio file and store as features and labels:
def get_features(df_in): features=[] labels = [] #empty array to store labels #For each species, determine how many augmentations are needed df_in=df_in.reset_index() for i in df_in.species_id.unique(): print('species_id:',i) #all the file indices with the same species_id filelist = df_in.loc[df_in.species_id == i].index for j in range(0,len(filelist)): filename = df_in.iloc[filelist[j]].recording_id +str('.flac') #get the filename #define the beginning time of the signal tstart = df_in.iloc[filelist[j]].t_min tend = df_in.iloc[filelist[j]].t_max #end of signal recording_id = df_in.iloc[filelist[j]].recording_id species_id = i songtype_id = df_in.iloc[filelist[j]].songtype_id #Load the file y, sr = librosa.load(filename,sr=28000) #cut the file to signal start and end y_cut=y[int(round(tstart*sr)):int(round(tend*sr))] #generate features & output numpy array data = generate_features(y_cut) features.append(data[np.newaxis,...]) labels.append(species_id) output=np.concatenate(features,axis=0) return(np.array(output), labels)#use get_features to calculate and store the featurestest_features, test_labels = get_features(pd.concat([X_test,y_test],axis=1))train_features, train_labels = get_features_noOS(pd.concat([X_train,y_train],axis=1))
X_train = np.array((X_train-np.min(X_train))/(np.max(X_train)-np.min(X_train)))X_test = np.array((X_test-np.min(X_test))/(np.max(X_test)-np.min(X_test)))X_train = X_train/np.std(X_train)X_test = X_test/np.std(X_test)y_train = np.array(y_train)y_test = np.array(y_test)
In the example model below, a 2D Convolutional Layer (Conv2D) unit is the portion that learns the translation invariant spatial patterns and their spatial hierarchies.
The Max Pooling Layer halves the size of the feature maps by downsampling them to the max value inside a window. Why downsample? Because otherwise it would result in a ginormous number of parameters and your computer would blow up and after all that the model would massively overfit the data. This magical layer is the reason that a CNN can handle the huge amounts of data in images. Max Pooling does a model good.
The Dropout Layer guards against overfitting by randomly setting the weights of a portion of the data to zero, and the Dense units contain hidden layers tied to the degrees of freedom the model has to try and fit the data. The more complex the data, the more degrees of freedom the model needs. Take care not to add a bunch of these and end up overfitting the data.
The Flatten Layer squishes all the feature map information into a single column in order to feed in into a Dense layer, the last of which outputs the 24 species that the model is supposed to classify the audio recordings into.
input_shape=(128,1000,3)CNNmodel = models.Sequential()CNNmodel.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=input_shape))CNNmodel.add(layers.MaxPooling2D((2, 2)))CNNmodel.add(layers.Dropout(0.2))CNNmodel.add(layers.Conv2D(64, (3, 3), activation='relu'))CNNmodel.add(layers.MaxPooling2D((2, 2)))CNNmodel.add(layers.Dropout(0.2))CNNmodel.add(layers.Conv2D(64, (3, 3), activation='relu'))CNNmodel.add(layers.Flatten())CNNmodel.add(layers.Dense(64, activation='relu'))CNNmodel.add(layers.Dropout(0.2))CNNmodel.add(layers.Dense(32, activation='relu'))CNNmodel.add(layers.Dense(24, activation='softmax'))
The activation functions give the model the ability to add nonlinearity to the model. Here, the relu function is used, which zeros out negative weights. You can read about other activation functions here, but this is a good one to start with. The last Dense layer’s activation function type is softmax, which outputs a probability for each class.
CNNmodel.compile(optimizer='adam',loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),metrics=['accuracy'])
The Adam optimizer manages the learning rate for you, the loss function is used to evaluate how different the predicted and actual data are and penalizes the model for poor predictions. In this example, the loss function is SparseCategoricalCrossentropy, which is used when each sample belongs to one label, as opposed to more than one, and it’s not binary classification. This is an appropriate choice because each audio sample belongs to one species and there are 24 of them.
history = CNNmodel.fit(X_train, y_train, epochs=20, validation_data= (X_val, y_val))
This is because if the model is overly complex, it will learn your training data exactly, and fail to generalize to unseen data.
Try this:
input_shape=(128,1000,3)CNNmodel = models.Sequential()CNNmodel.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=input_shape))CNNmodel.add(layers.MaxPooling2D((2, 2)))CNNmodel.add(layers.Flatten())CNNmodel.add(layers.Dense(32, activation='relu'))CNNmodel.add(layers.Dense(24, activation='softmax'))CNNmodel.summary()
Note: This model was too simple and was not able to predict the data at all (as in single digit accuracy).
Watch for big differences in performance between the training and test set. If the training set performs markedly better, it won’t generalize well to unseen data.If performance on the validation set begins to decline, stop iterating.
Watch for big differences in performance between the training and test set. If the training set performs markedly better, it won’t generalize well to unseen data.
If performance on the validation set begins to decline, stop iterating.
#Adapted from Deep Learning with Python by Francois Chollet, 2018history_dict=history.historyloss_values=history_dict['loss']acc_values=history_dict['accuracy']val_loss_values = history_dict['val_loss']val_acc_values=history_dict['val_accuracy']epochs=range(1,21)fig,(ax1,ax2)=plt.subplots(1,2,figsize=(15,5))ax1.plot(epochs,loss_values,'bo',label='Training Loss')ax1.plot(epochs,val_loss_values,'orange', label='Validation Loss')ax1.set_title('Training and validation loss')ax1.set_xlabel('Epochs')ax1.set_ylabel('Loss')ax1.legend()ax2.plot(epochs,acc_values,'bo', label='Training accuracy')ax2.plot(epochs,val_acc_values,'orange',label='Validation accuracy')ax2.set_title('Training and validation accuracy')ax2.set_xlabel('Epochs')ax2.set_ylabel('Accuracy')ax2.legend()plt.show()
You now know how to create a CNN for use in audio classification. Start with a simple model, and then add layers until it is you start seeing signs that the training data is performing better than the test data. Add Dropout and Max Pooling layers to prevent overfitting. Lastly, stop iterating when you note a decrease in performance in the validation data in comparison to the training data.
Sarkar, Dipanjan (2021) Personal communication.
Chollet, F. Deep Learning with Python (2018), v. 361, New York: Manning.
Gervias, Nicolas, (2021) Code adopted from https://stackoverflow.com/questions/59241216/padding-numpy-arrays-to-a-specific-size, retrieved on 1/10/2021.
frenzykryger (2021) https://datascience.stackexchange.com/questions/41921/sparse-categorical-crossentropy-vs-categorical-crossentropy-keras-accuracy#:~:text=Use%20sparse%20categorical%20crossentropy%20when,0.5%2C%200.3%2C%200.2%5D, retrieved on 2/21/2021.
|
[
{
"code": null,
"e": 286,
"s": 172,
"text": "CNNs or convolutional neural nets are a type of deep learning algorithm that does really well at learning images."
},
{
"code": null,
"e": 405,
"s": 286,
"text": "That’s because they can learn patterns that are translation invariant and have spatial hierarchies (F. Chollet, 2018)."
},
{
"code": null,
"e": 593,
"s": 405,
"text": "That means if If the CNN learns the dog in the left corner of the image above, then it can identify the dog in the other two pictures that have been moved around (translation invariance)."
},
{
"code": null,
"e": 900,
"s": 593,
"text": "If the CNN learns the dog from the left corner of the image above, it will recognize pieces of the original image in the other two pictures because it has learned what the edges of the her eye with heterochromia looks like, her wolf-like snout and the shape of her stylish headphones (spatial hierarchies)."
},
{
"code": null,
"e": 1033,
"s": 900,
"text": "These properties make CNNs formidable learners for images because the real world doesn’t always look exactly like the training data."
},
{
"code": null,
"e": 1144,
"s": 1033,
"text": "Yes. You can extract features which look like images and shape them in a way in order to feed them into a CNN."
},
{
"code": null,
"e": 1274,
"s": 1144,
"text": "The data for this example are bird and frog recordings from the Kaggle competition Rainforest Connection Species Audio Detection."
},
{
"code": null,
"e": 1317,
"s": 1274,
"text": "To get started, load the necessary inputs:"
},
{
"code": null,
"e": 1666,
"s": 1317,
"text": "import pandas as pdimport osimport librosaimport librosa.displayimport matplotlib.pyplot as pltfrom sklearn.preprocessing import normalizeimport warningswarnings.filterwarnings('ignore')import numpy as npimport pickleimport joblibfrom sklearn.model_selection import train_test_splitfrom tensorflow.keras import models, layersimport tensorflow as tf"
},
{
"code": null,
"e": 1686,
"s": 1666,
"text": "Then the dataframe:"
},
{
"code": null,
"e": 1773,
"s": 1686,
"text": "os.chdir('/kaggle/input/rfcx-species-audio-detection')df = pd.read_csv('train_tp.csv')"
},
{
"code": null,
"e": 1949,
"s": 1773,
"text": "This dataset comes as a csv file with the names of audio files listed under recording_id, labels under species_id, and the start/end of the audio sample under t_min and t_max:"
},
{
"code": null,
"e": 1959,
"s": 1949,
"text": "df.head()"
},
{
"code": null,
"e": 2028,
"s": 1959,
"text": "Use the librosa package to load and display an audio file like this:"
},
{
"code": null,
"e": 2382,
"s": 2028,
"text": "sample_num=3 #pick a file to display#get the filename filename=df.recording_id[sample_num]+str('.flac')#define the beginning time of the signaltstart = df.t_min[sample_num] tend = df.t_max[sample_num] #define the end time of the signaly,sr=librosa.load('train/'+str(filename)) #load the filelibrosa.display.waveplot(y,sr=sr, x_axis='time', color='cyan')"
},
{
"code": null,
"e": 2413,
"s": 2382,
"text": "The CNN is expecting an image:"
},
{
"code": null,
"e": 2443,
"s": 2413,
"text": "a grayscale image (1 channel)"
},
{
"code": null,
"e": 2504,
"s": 2443,
"text": "a color image with three channels: red, green and blue (RGB)"
},
{
"code": null,
"e": 2564,
"s": 2504,
"text": "So you have to make your audio features look like an image."
},
{
"code": null,
"e": 2675,
"s": 2564,
"text": "Choose either 1D for a grayscale image (one feature) or 3D for a color image (to represent multiple features)."
},
{
"code": null,
"e": 2750,
"s": 2675,
"text": "Scale and pad the audio features so that every “channel” is the same size."
},
{
"code": null,
"e": 3254,
"s": 2750,
"text": "#This code was adapted from Nicolas Gervais on https://stackoverflow.com/questions/59241216/padding-numpy-arrays-to-a-specific-size on 1/10/2021def padding(array, xx, yy): \"\"\" :param array: numpy array :param xx: desired height :param yy: desirex width :return: padded array \"\"\"h = array.shape[0] w = array.shape[1]a = max((xx - h) // 2,0) aa = max(0,xx - a - h)b = max(0,(yy - w) // 2) bb = max(yy - b - w,0)return np.pad(array, pad_width=((a, aa), (b, bb)), mode='constant')"
},
{
"code": null,
"e": 3286,
"s": 3254,
"text": "They’re just numbers after all."
},
{
"code": null,
"e": 3344,
"s": 3286,
"text": "No. It has to make visual sense. Garbage in, garbage out."
},
{
"code": null,
"e": 3406,
"s": 3344,
"text": "Librosa has great tutorials for how to extract features here."
},
{
"code": null,
"e": 3448,
"s": 3406,
"text": "For this example, I’m going to calculate:"
},
{
"code": null,
"e": 3472,
"s": 3448,
"text": "Mel spectrogram (MFCCs)"
},
{
"code": null,
"e": 3491,
"s": 3472,
"text": "spectral bandwidth"
},
{
"code": null,
"e": 3509,
"s": 3491,
"text": "spectral centroid"
},
{
"code": null,
"e": 3534,
"s": 3509,
"text": "chromagram (chroma stft)"
},
{
"code": null,
"e": 3570,
"s": 3534,
"text": "short-time Fourier transform (stft)"
},
{
"code": null,
"e": 3842,
"s": 3570,
"text": "The first axis will be the audio file id, representing the batch in tensorflow-speak. In this example, the second axis is the spectral bandwidth, centroid and chromagram repeated, padded and fit into the shape of the third axis (the stft) and the fourth axis (the MFCCs)."
},
{
"code": null,
"e": 3911,
"s": 3842,
"text": "#The eventual shape of the featuresprint(X_train.shape,X_test.shape)"
},
{
"code": null,
"e": 4425,
"s": 3911,
"text": "The first axis 1226 is the batch size, 128 is the height, 1000 is the width (set by max_size in the code below) and 3 is the number of channels in the training data. If I have 1226 audio files, then the batch size is 1226. If we only extracted features for the 5 audio files pictured in the dataframe.head() figure, the shape of the input would be 5x128x1000x3. You can make the batch size smaller if you want to use less memory when training. For this example, the batch size is set to the number of audio files."
},
{
"code": null,
"e": 5555,
"s": 4425,
"text": "def generate_features(y_cut): max_size=1000 #my max audio file feature width stft = padding(np.abs(librosa.stft(y_cut, n_fft=255, hop_length = 512)), 128, max_size) MFCCs = padding(librosa.feature.mfcc(y_cut, n_fft=n_fft, hop_length=hop_length,n_mfcc=128),128,max_size) spec_centroid = librosa.feature.spectral_centroid(y=y_cut, sr=sr) chroma_stft = librosa.feature.chroma_stft(y=y_cut, sr=sr) spec_bw = librosa.feature.spectral_bandwidth(y=y_cut, sr=sr) #Now the padding part image = np.array([padding(normalize(spec_bw),1, max_size)]).reshape(1,max_size) image = np.append(image,padding(normalize(spec_centroid),1, max_size), axis=0) #repeat the padded spec_bw,spec_centroid and chroma stft until they are stft and MFCC-sized for i in range(0,9): image = np.append(image,padding(normalize(spec_bw),1, max_size), axis=0) image = np.append(image, padding(normalize(spec_centroid),1, max_size), axis=0) image = np.append(image, padding(normalize(chroma_stft),12, max_size), axis=0) image=np.dstack((image,np.abs(stft))) image=np.dstack((image,MFCCs)) return image"
},
{
"code": null,
"e": 5624,
"s": 5555,
"text": "The following three features get squished and padded and repeated..."
},
{
"code": null,
"e": 5652,
"s": 5624,
"text": "...into the following axis:"
},
{
"code": null,
"e": 5705,
"s": 5652,
"text": "The last two axis are designed to be the same shape:"
},
{
"code": null,
"e": 5792,
"s": 5705,
"text": "No. As long as you pad them to be the same shape, use what works the best in modeling."
},
{
"code": null,
"e": 5838,
"s": 5792,
"text": "X=df.drop('species_id',axis=1)y=df.species_id"
},
{
"code": null,
"e": 6019,
"s": 5838,
"text": "#Split once to get the test and training setX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=123, stratify=y)print(X_train.shape,X_test.shape)"
},
{
"code": null,
"e": 6245,
"s": 6019,
"text": "#Split twice to get the validation setX_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=0.25, random_state=123)print(X_train.shape, X_test.shape, X_val.shape, len(y_train), len(y_test), len(y_val))"
},
{
"code": null,
"e": 6325,
"s": 6245,
"text": "Calculate these features for every audio file and store as features and labels:"
},
{
"code": null,
"e": 7916,
"s": 6325,
"text": "def get_features(df_in): features=[] labels = [] #empty array to store labels #For each species, determine how many augmentations are needed df_in=df_in.reset_index() for i in df_in.species_id.unique(): print('species_id:',i) #all the file indices with the same species_id filelist = df_in.loc[df_in.species_id == i].index for j in range(0,len(filelist)): filename = df_in.iloc[filelist[j]].recording_id +str('.flac') #get the filename #define the beginning time of the signal tstart = df_in.iloc[filelist[j]].t_min tend = df_in.iloc[filelist[j]].t_max #end of signal recording_id = df_in.iloc[filelist[j]].recording_id species_id = i songtype_id = df_in.iloc[filelist[j]].songtype_id #Load the file y, sr = librosa.load(filename,sr=28000) #cut the file to signal start and end y_cut=y[int(round(tstart*sr)):int(round(tend*sr))] #generate features & output numpy array data = generate_features(y_cut) features.append(data[np.newaxis,...]) labels.append(species_id) output=np.concatenate(features,axis=0) return(np.array(output), labels)#use get_features to calculate and store the featurestest_features, test_labels = get_features(pd.concat([X_test,y_test],axis=1))train_features, train_labels = get_features_noOS(pd.concat([X_train,y_train],axis=1))"
},
{
"code": null,
"e": 8185,
"s": 7916,
"text": "X_train = np.array((X_train-np.min(X_train))/(np.max(X_train)-np.min(X_train)))X_test = np.array((X_test-np.min(X_test))/(np.max(X_test)-np.min(X_test)))X_train = X_train/np.std(X_train)X_test = X_test/np.std(X_test)y_train = np.array(y_train)y_test = np.array(y_test)"
},
{
"code": null,
"e": 8353,
"s": 8185,
"text": "In the example model below, a 2D Convolutional Layer (Conv2D) unit is the portion that learns the translation invariant spatial patterns and their spatial hierarchies."
},
{
"code": null,
"e": 8769,
"s": 8353,
"text": "The Max Pooling Layer halves the size of the feature maps by downsampling them to the max value inside a window. Why downsample? Because otherwise it would result in a ginormous number of parameters and your computer would blow up and after all that the model would massively overfit the data. This magical layer is the reason that a CNN can handle the huge amounts of data in images. Max Pooling does a model good."
},
{
"code": null,
"e": 9135,
"s": 8769,
"text": "The Dropout Layer guards against overfitting by randomly setting the weights of a portion of the data to zero, and the Dense units contain hidden layers tied to the degrees of freedom the model has to try and fit the data. The more complex the data, the more degrees of freedom the model needs. Take care not to add a bunch of these and end up overfitting the data."
},
{
"code": null,
"e": 9362,
"s": 9135,
"text": "The Flatten Layer squishes all the feature map information into a single column in order to feed in into a Dense layer, the last of which outputs the 24 species that the model is supposed to classify the audio recordings into."
},
{
"code": null,
"e": 9977,
"s": 9362,
"text": "input_shape=(128,1000,3)CNNmodel = models.Sequential()CNNmodel.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=input_shape))CNNmodel.add(layers.MaxPooling2D((2, 2)))CNNmodel.add(layers.Dropout(0.2))CNNmodel.add(layers.Conv2D(64, (3, 3), activation='relu'))CNNmodel.add(layers.MaxPooling2D((2, 2)))CNNmodel.add(layers.Dropout(0.2))CNNmodel.add(layers.Conv2D(64, (3, 3), activation='relu'))CNNmodel.add(layers.Flatten())CNNmodel.add(layers.Dense(64, activation='relu'))CNNmodel.add(layers.Dropout(0.2))CNNmodel.add(layers.Dense(32, activation='relu'))CNNmodel.add(layers.Dense(24, activation='softmax'))"
},
{
"code": null,
"e": 10324,
"s": 9977,
"text": "The activation functions give the model the ability to add nonlinearity to the model. Here, the relu function is used, which zeros out negative weights. You can read about other activation functions here, but this is a good one to start with. The last Dense layer’s activation function type is softmax, which outputs a probability for each class."
},
{
"code": null,
"e": 10450,
"s": 10324,
"text": "CNNmodel.compile(optimizer='adam',loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),metrics=['accuracy'])"
},
{
"code": null,
"e": 10928,
"s": 10450,
"text": "The Adam optimizer manages the learning rate for you, the loss function is used to evaluate how different the predicted and actual data are and penalizes the model for poor predictions. In this example, the loss function is SparseCategoricalCrossentropy, which is used when each sample belongs to one label, as opposed to more than one, and it’s not binary classification. This is an appropriate choice because each audio sample belongs to one species and there are 24 of them."
},
{
"code": null,
"e": 11013,
"s": 10928,
"text": "history = CNNmodel.fit(X_train, y_train, epochs=20, validation_data= (X_val, y_val))"
},
{
"code": null,
"e": 11142,
"s": 11013,
"text": "This is because if the model is overly complex, it will learn your training data exactly, and fail to generalize to unseen data."
},
{
"code": null,
"e": 11152,
"s": 11142,
"text": "Try this:"
},
{
"code": null,
"e": 11480,
"s": 11152,
"text": "input_shape=(128,1000,3)CNNmodel = models.Sequential()CNNmodel.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=input_shape))CNNmodel.add(layers.MaxPooling2D((2, 2)))CNNmodel.add(layers.Flatten())CNNmodel.add(layers.Dense(32, activation='relu'))CNNmodel.add(layers.Dense(24, activation='softmax'))CNNmodel.summary()"
},
{
"code": null,
"e": 11587,
"s": 11480,
"text": "Note: This model was too simple and was not able to predict the data at all (as in single digit accuracy)."
},
{
"code": null,
"e": 11821,
"s": 11587,
"text": "Watch for big differences in performance between the training and test set. If the training set performs markedly better, it won’t generalize well to unseen data.If performance on the validation set begins to decline, stop iterating."
},
{
"code": null,
"e": 11984,
"s": 11821,
"text": "Watch for big differences in performance between the training and test set. If the training set performs markedly better, it won’t generalize well to unseen data."
},
{
"code": null,
"e": 12056,
"s": 11984,
"text": "If performance on the validation set begins to decline, stop iterating."
},
{
"code": null,
"e": 12838,
"s": 12056,
"text": "#Adapted from Deep Learning with Python by Francois Chollet, 2018history_dict=history.historyloss_values=history_dict['loss']acc_values=history_dict['accuracy']val_loss_values = history_dict['val_loss']val_acc_values=history_dict['val_accuracy']epochs=range(1,21)fig,(ax1,ax2)=plt.subplots(1,2,figsize=(15,5))ax1.plot(epochs,loss_values,'bo',label='Training Loss')ax1.plot(epochs,val_loss_values,'orange', label='Validation Loss')ax1.set_title('Training and validation loss')ax1.set_xlabel('Epochs')ax1.set_ylabel('Loss')ax1.legend()ax2.plot(epochs,acc_values,'bo', label='Training accuracy')ax2.plot(epochs,val_acc_values,'orange',label='Validation accuracy')ax2.set_title('Training and validation accuracy')ax2.set_xlabel('Epochs')ax2.set_ylabel('Accuracy')ax2.legend()plt.show()"
},
{
"code": null,
"e": 13231,
"s": 12838,
"text": "You now know how to create a CNN for use in audio classification. Start with a simple model, and then add layers until it is you start seeing signs that the training data is performing better than the test data. Add Dropout and Max Pooling layers to prevent overfitting. Lastly, stop iterating when you note a decrease in performance in the validation data in comparison to the training data."
},
{
"code": null,
"e": 13279,
"s": 13231,
"text": "Sarkar, Dipanjan (2021) Personal communication."
},
{
"code": null,
"e": 13352,
"s": 13279,
"text": "Chollet, F. Deep Learning with Python (2018), v. 361, New York: Manning."
},
{
"code": null,
"e": 13505,
"s": 13352,
"text": "Gervias, Nicolas, (2021) Code adopted from https://stackoverflow.com/questions/59241216/padding-numpy-arrays-to-a-specific-size, retrieved on 1/10/2021."
}
] |
Python program to find all close matches of input string from a list
|
In this tutorial, we are going to find a solution to a problem. Let's see what the problem is. We have a list of strings and an element. We have to find strings from a list in which they must closely match to the given element. See the example.
Inputs
strings = ["Lion", "Li", "Tiger", "Tig"] element = "Lion"
Ouput
Lion Li
We can achieve this by using the startswith built-in method. See the steps to find the strings.
Initialize string list and a string.
Loop through the list.If string from list startswith element or element startswith the string from the list
If string from list startswith element or element startswith the string from the list
Print the string
## initializing the string list
strings = ["Lion", "Li", "Tiger", "Tig"]
element = "Lion"
for string in strings:
## checking for the condition mentioned above
if string.startswith(element) or element.startswith(string):
## printing the eligible string
print(string, end = " ")
print()
If you run the above program,
Lion Li
If you have any doubts regarding the program, please do mention them in the comment section.
|
[
{
"code": null,
"e": 1307,
"s": 1062,
"text": "In this tutorial, we are going to find a solution to a problem. Let's see what the problem is. We have a list of strings and an element. We have to find strings from a list in which they must closely match to the given element. See the example."
},
{
"code": null,
"e": 1386,
"s": 1307,
"text": "Inputs\nstrings = [\"Lion\", \"Li\", \"Tiger\", \"Tig\"] element = \"Lion\"\nOuput\nLion Li"
},
{
"code": null,
"e": 1482,
"s": 1386,
"text": "We can achieve this by using the startswith built-in method. See the steps to find the strings."
},
{
"code": null,
"e": 1519,
"s": 1482,
"text": "Initialize string list and a string."
},
{
"code": null,
"e": 1627,
"s": 1519,
"text": "Loop through the list.If string from list startswith element or element startswith the string from the list"
},
{
"code": null,
"e": 1713,
"s": 1627,
"text": "If string from list startswith element or element startswith the string from the list"
},
{
"code": null,
"e": 1730,
"s": 1713,
"text": "Print the string"
},
{
"code": null,
"e": 2033,
"s": 1730,
"text": "## initializing the string list\nstrings = [\"Lion\", \"Li\", \"Tiger\", \"Tig\"]\nelement = \"Lion\"\nfor string in strings:\n ## checking for the condition mentioned above\n if string.startswith(element) or element.startswith(string):\n ## printing the eligible string\n print(string, end = \" \")\nprint()"
},
{
"code": null,
"e": 2063,
"s": 2033,
"text": "If you run the above program,"
},
{
"code": null,
"e": 2071,
"s": 2063,
"text": "Lion Li"
},
{
"code": null,
"e": 2164,
"s": 2071,
"text": "If you have any doubts regarding the program, please do mention them in the comment section."
}
] |
What is the purpose and usage of “WHERE CURRENT OF” clause in a COBOL-DB2 program?
|
The “WHERE CURRENT OF” clause will place the exclusive lock on the row once the UPDATE statement is executed. The “WHERE CURRENT OF” clause will point to the most recently fetched row of the cursor.
We can update the rows in cursor using “WHERE CURRENT OF” in the following way.
CURSOR definition.
CURSOR definition.
EXEC SQL
DECLARE ORDER_CUR CURSOR FOR
SELECT ORDER_ID, TRANSACTION_ID FROM ORDERS
WHERE ORDER_DATE = ‘2020-07-28’
END-EXEC
OPEN cursor
OPEN cursor
EXEC SQL
OPEN ORDER_CUR
END-EXEC
FETCH cursor and Update row
FETCH cursor and Update row
SET WF-END-CURSOR-N TO TRUE
PERFORM UNTIL WF-END-CURSOR-Y
EXEC SQL
FETCH ORDER_CUR INTO :ORDER-ID, :TRANSACTION-ID
END-EXEC
IF TRANSACTION-ID NOT = SPACES
EXEC SQL
UPDATE ORDERS SET IS_PAID = ‘YES’
WHERE CURRENT OF ORDER_CUR
END-EXEC
ELSE
CONTINUE
END-IF
END-PERFORM
|
[
{
"code": null,
"e": 1261,
"s": 1062,
"text": "The “WHERE CURRENT OF” clause will place the exclusive lock on the row once the UPDATE statement is executed. The “WHERE CURRENT OF” clause will point to the most recently fetched row of the cursor."
},
{
"code": null,
"e": 1341,
"s": 1261,
"text": "We can update the rows in cursor using “WHERE CURRENT OF” in the following way."
},
{
"code": null,
"e": 1360,
"s": 1341,
"text": "CURSOR definition."
},
{
"code": null,
"e": 1379,
"s": 1360,
"text": "CURSOR definition."
},
{
"code": null,
"e": 1502,
"s": 1379,
"text": "EXEC SQL\nDECLARE ORDER_CUR CURSOR FOR\nSELECT ORDER_ID, TRANSACTION_ID FROM ORDERS\nWHERE ORDER_DATE = ‘2020-07-28’\nEND-EXEC"
},
{
"code": null,
"e": 1514,
"s": 1502,
"text": "OPEN cursor"
},
{
"code": null,
"e": 1526,
"s": 1514,
"text": "OPEN cursor"
},
{
"code": null,
"e": 1559,
"s": 1526,
"text": "EXEC SQL\nOPEN ORDER_CUR\nEND-EXEC"
},
{
"code": null,
"e": 1587,
"s": 1559,
"text": "FETCH cursor and Update row"
},
{
"code": null,
"e": 1615,
"s": 1587,
"text": "FETCH cursor and Update row"
},
{
"code": null,
"e": 1896,
"s": 1615,
"text": "SET WF-END-CURSOR-N TO TRUE\n PERFORM UNTIL WF-END-CURSOR-Y\n EXEC SQL\n FETCH ORDER_CUR INTO :ORDER-ID, :TRANSACTION-ID\nEND-EXEC\nIF TRANSACTION-ID NOT = SPACES\n EXEC SQL\n UPDATE ORDERS SET IS_PAID = ‘YES’\nWHERE CURRENT OF ORDER_CUR\nEND-EXEC\nELSE\nCONTINUE\nEND-IF\nEND-PERFORM"
}
] |
Implementing Strassen’s Algorithm in Java - GeeksforGeeks
|
13 Aug, 2021
Strassen’s algorithm is used for the multiplication of Square Matrices that is the order of matrices should be (N x N). Strassen’s Algorithm is based on the divide and conquer technique. In simpler terms, it is used for matrix multiplication. Strassen’s method of matrix multiplication is a typical divide and conquer algorithm. However, let’s get again on what’s behind the divide and conquer approach and implement it considering an illustration as follows For example: Let A and B are two matrices then the resultant matrix C such that
Matrix C = Matrix A * Matrix B
Consider for now the mathematical computation of matrices is that it can be concluded out why the implementation for the Strassen matrices comes out into play. Suppose two matrices are operated to be multiplied then the approach would have been
Take input of two matrices.Check the compatibility of matrix multiplication which holds true only and only if the number of rows of the first matrix equals the number of columns of the second matrix.Multiply the matrix and assign multiplication of two matrices to another matrix known as the resultant matrix.Print the resultant matrix.
Take input of two matrices.
Check the compatibility of matrix multiplication which holds true only and only if the number of rows of the first matrix equals the number of columns of the second matrix.
Multiply the matrix and assign multiplication of two matrices to another matrix known as the resultant matrix.
Print the resultant matrix.
In the above approach, two assumptions are drawn which show why Strassen’s algorithm need arises into play
Firstly, the time complexity of the algorithm is O(n3) which is too high.
Secondly, the multiplication of more than two matrices will not only increase the confusion and complexity of the program but also increase the time complexity accordingly.
Purpose:
Volker Strassen’s is a name who published his algorithm to prove that the time complexity O(n3) of general matrix multiplication wasn’t optimal. So it was published Strassen’s matrix chain multiplication and reduced the time complexity. This algorithm is faster than standard matrix multiplication and is useful when numerous large matrices multiplication is computed in the daily world.
Strassen’s Algorithm for Matrix Multiplication
Step 1: Take three matrices to suppose A, B, C where C is the resultant matrix and A and B are Matrix which is to be multiplied using Strassen’s Method.
Step 2: Divide A, B, C Matrix into four (n/2)×(n/2) matrices and take the first part of each as shown below
Step 3: Use the below formulas for solving part 1 of the matrix
M1:=(A1+A3)×(B1+B2)
M2:=(A2+A4)×(B3+B4)
M3:=(A1−A4)×(B1+A4)
M4:=A1×(B2−B4)
M5:=(A3+A4)×(B1)
M6:=(A1+A2)×(B4)
M7:=A4×(B3−B1)
Then,
P:=M2+M3−M6−M7
Q:=M4+M6
R:=M5+M7
S:=M1−M3−M4−M5
Step 4: After Solving the first part, compute the second, third, and fourth, and as well as final output, a multiplied matrix is generated as a result as shown in the above image.
Step 5: Print the resultant matrix.
Implementation:
Example
Java
// Java Program to Implement Strassen Algorithm // Class Strassen matrix multiplicationpublic class GFG { // Method 1 // Function to multiply matrices public int[][] multiply(int[][] A, int[][] B) { // Order of matrix int n = A.length; // Creating a 2D square matrix with size n // n is input from the user int[][] R = new int[n][n]; // Base case // If there is only single element if (n == 1) // Returning the simple multiplication of // two elements in matrices R[0][0] = A[0][0] * B[0][0]; // Matrix else { // Step 1: Dividing Matrix into parts // by storing sub-parts to variables int[][] A11 = new int[n / 2][n / 2]; int[][] A12 = new int[n / 2][n / 2]; int[][] A21 = new int[n / 2][n / 2]; int[][] A22 = new int[n / 2][n / 2]; int[][] B11 = new int[n / 2][n / 2]; int[][] B12 = new int[n / 2][n / 2]; int[][] B21 = new int[n / 2][n / 2]; int[][] B22 = new int[n / 2][n / 2]; // Step 2: Dividing matrix A into 4 halves split(A, A11, 0, 0); split(A, A12, 0, n / 2); split(A, A21, n / 2, 0); split(A, A22, n / 2, n / 2); // Step 2: Dividing matrix B into 4 halves split(B, B11, 0, 0); split(B, B12, 0, n / 2); split(B, B21, n / 2, 0); split(B, B22, n / 2, n / 2); // Using Formulas as described in algorithm // M1:=(A1+A3)×(B1+B2) int[][] M1 = multiply(add(A11, A22), add(B11, B22)); // M2:=(A2+A4)×(B3+B4) int[][] M2 = multiply(add(A21, A22), B11); // M3:=(A1−A4)×(B1+A4) int[][] M3 = multiply(A11, sub(B12, B22)); // M4:=A1×(B2−B4) int[][] M4 = multiply(A22, sub(B21, B11)); // M5:=(A3+A4)×(B1) int[][] M5 = multiply(add(A11, A12), B22); // M6:=(A1+A2)×(B4) int[][] M6 = multiply(sub(A21, A11), add(B11, B12)); // M7:=A4×(B3−B1) int[][] M7 = multiply(sub(A12, A22), add(B21, B22)); // P:=M2+M3−M6−M7 int[][] C11 = add(sub(add(M1, M4), M5), M7); // Q:=M4+M6 int[][] C12 = add(M3, M5); // R:=M5+M7 int[][] C21 = add(M2, M4); // S:=M1−M3−M4−M5 int[][] C22 = add(sub(add(M1, M3), M2), M6); // Step 3: Join 4 halves into one result matrix join(C11, R, 0, 0); join(C12, R, 0, n / 2); join(C21, R, n / 2, 0); join(C22, R, n / 2, n / 2); } // Step 4: Return result return R; } // Method 2 // Function to subtract two matrices public int[][] sub(int[][] A, int[][] B) { // int n = A.length; // int[][] C = new int[n][n]; // Iterating over elements of 2D matrix // using nested for loops // Outer loop for rows for (int i = 0; i < n; i++) // Inner loop for columns for (int j = 0; j < n; j++) // Subtracting corresponding elements // from matrices C[i][j] = A[i][j] - B[i][j]; // Returning the resultant matrix return C; } // Method 3 // Function to add two matrices public int[][] add(int[][] A, int[][] B) { // int n = A.length; // Creating a 2D square matrix int[][] C = new int[n][n]; // Iterating over elements of 2D matrix // using nested for loops // Outer loop for rows for (int i = 0; i < n; i++) // Inner loop for columns for (int j = 0; j < n; j++) // Adding corresponding elements // of matrices C[i][j] = A[i][j] + B[i][j]; // Returning the resultant matrix return C; } // Method 4 // Function to split parent matrix // into child matrices public void split(int[][] P, int[][] C, int iB, int jB) { // Iterating over elements of 2D matrix // using nested for loops // Outer loop for rows for (int i1 = 0, i2 = iB; i1 < C.length; i1++, i2++) // Inner loop for columns for (int j1 = 0, j2 = jB; j1 < C.length; j1++, j2++) C[i1][j1] = P[i2][j2]; } // Method 5 // Function to join child matrices // into (to) parent matrix public void join(int[][] C, int[][] P, int iB, int jB) { // Iterating over elements of 2D matrix // using nested for loops // Outer loop for rows for (int i1 = 0, i2 = iB; i1 < C.length; i1++, i2++) // Inner loop for columns for (int j1 = 0, j2 = jB; j1 < C.length; j1++, j2++) P[i2][j2] = C[i1][j1]; } // Method 5 // Main driver method public static void main(String[] args) { // Display message System.out.println( "Strassen Multiplication Algorithm Implementation For Matrix Multiplication :\n"); // Create an object of Strassen class // in he main function GFG s = new GFG(); // Size of matrix // Considering size as 4 in order to illustrate int N = 4; // Matrix A // Custom input to matrix int[][] A = { { 1, 2, 3, 4 }, { 4, 3, 0, 1 }, { 5, 6, 1, 1 }, { 0, 2, 5, 6 } }; // Matrix B // Custom input to matrix int[][] B = { { 1, 0, 5, 1 }, { 1, 2, 0, 2 }, { 0, 3, 2, 3 }, { 1, 2, 1, 2 } }; // Matrix C computations // Matrix C calling method to get Result int[][] C = s.multiply(A, B); // Display message System.out.println( "\nProduct of matrices A and B : "); // Iterating over elements of 2D matrix // using nested for loops // Outer loop for rows for (int i = 0; i < N; i++) { // Inner loop for columns for (int j = 0; j < N; j++) // Printing elements of resultant matrix // with whitespaces in between System.out.print(C[i][j] + " "); // New line once the all elements // are printed for specific row System.out.println(); } }}
Strassen Multiplication Algorithm Implementation For Matrix Multiplication :
Product of matrices A and B :
7 21 15 22
8 8 21 12
12 17 28 22
8 31 16 31
Time Complexity Of Strassen’s Method
By Analysis the time complexity Function can be written as:
T(N) = 7T(N/2) + O(N2)
By Solving this using Master Theorem we get :
T(n)=O(nlog7)
Thus time Complexity Of Strassen’s Algorithm for matrix multiplication is derived as:
O(nlog7) = O (n2.81)
O(n3) Vs O(n2.81)
mikaeljeanpierre31
varshagumber28
kk9826225
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Hashtable in Java
Constructors in Java
Different ways of Reading a text file in Java
Comparator Interface in Java with Examples
Java Math random() method with Examples
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
|
[
{
"code": null,
"e": 23581,
"s": 23553,
"text": "\n13 Aug, 2021"
},
{
"code": null,
"e": 24123,
"s": 23581,
"text": "Strassen’s algorithm is used for the multiplication of Square Matrices that is the order of matrices should be (N x N). Strassen’s Algorithm is based on the divide and conquer technique. In simpler terms, it is used for matrix multiplication. Strassen’s method of matrix multiplication is a typical divide and conquer algorithm. However, let’s get again on what’s behind the divide and conquer approach and implement it considering an illustration as follows For example: Let A and B are two matrices then the resultant matrix C such that "
},
{
"code": null,
"e": 24154,
"s": 24123,
"text": "Matrix C = Matrix A * Matrix B"
},
{
"code": null,
"e": 24399,
"s": 24154,
"text": "Consider for now the mathematical computation of matrices is that it can be concluded out why the implementation for the Strassen matrices comes out into play. Suppose two matrices are operated to be multiplied then the approach would have been"
},
{
"code": null,
"e": 24736,
"s": 24399,
"text": "Take input of two matrices.Check the compatibility of matrix multiplication which holds true only and only if the number of rows of the first matrix equals the number of columns of the second matrix.Multiply the matrix and assign multiplication of two matrices to another matrix known as the resultant matrix.Print the resultant matrix."
},
{
"code": null,
"e": 24764,
"s": 24736,
"text": "Take input of two matrices."
},
{
"code": null,
"e": 24937,
"s": 24764,
"text": "Check the compatibility of matrix multiplication which holds true only and only if the number of rows of the first matrix equals the number of columns of the second matrix."
},
{
"code": null,
"e": 25048,
"s": 24937,
"text": "Multiply the matrix and assign multiplication of two matrices to another matrix known as the resultant matrix."
},
{
"code": null,
"e": 25076,
"s": 25048,
"text": "Print the resultant matrix."
},
{
"code": null,
"e": 25183,
"s": 25076,
"text": "In the above approach, two assumptions are drawn which show why Strassen’s algorithm need arises into play"
},
{
"code": null,
"e": 25257,
"s": 25183,
"text": "Firstly, the time complexity of the algorithm is O(n3) which is too high."
},
{
"code": null,
"e": 25430,
"s": 25257,
"text": "Secondly, the multiplication of more than two matrices will not only increase the confusion and complexity of the program but also increase the time complexity accordingly."
},
{
"code": null,
"e": 25439,
"s": 25430,
"text": "Purpose:"
},
{
"code": null,
"e": 25827,
"s": 25439,
"text": "Volker Strassen’s is a name who published his algorithm to prove that the time complexity O(n3) of general matrix multiplication wasn’t optimal. So it was published Strassen’s matrix chain multiplication and reduced the time complexity. This algorithm is faster than standard matrix multiplication and is useful when numerous large matrices multiplication is computed in the daily world."
},
{
"code": null,
"e": 25874,
"s": 25827,
"text": "Strassen’s Algorithm for Matrix Multiplication"
},
{
"code": null,
"e": 26028,
"s": 25874,
"text": "Step 1: Take three matrices to suppose A, B, C where C is the resultant matrix and A and B are Matrix which is to be multiplied using Strassen’s Method."
},
{
"code": null,
"e": 26136,
"s": 26028,
"text": "Step 2: Divide A, B, C Matrix into four (n/2)×(n/2) matrices and take the first part of each as shown below"
},
{
"code": null,
"e": 26200,
"s": 26136,
"text": "Step 3: Use the below formulas for solving part 1 of the matrix"
},
{
"code": null,
"e": 26380,
"s": 26200,
"text": "M1:=(A1+A3)×(B1+B2)\nM2:=(A2+A4)×(B3+B4)\nM3:=(A1−A4)×(B1+A4)\nM4:=A1×(B2−B4)\nM5:=(A3+A4)×(B1)\nM6:=(A1+A2)×(B4)\nM7:=A4×(B3−B1)\n\nThen,\n\nP:=M2+M3−M6−M7\nQ:=M4+M6\nR:=M5+M7\nS:=M1−M3−M4−M5"
},
{
"code": null,
"e": 26560,
"s": 26380,
"text": "Step 4: After Solving the first part, compute the second, third, and fourth, and as well as final output, a multiplied matrix is generated as a result as shown in the above image."
},
{
"code": null,
"e": 26596,
"s": 26560,
"text": "Step 5: Print the resultant matrix."
},
{
"code": null,
"e": 26613,
"s": 26596,
"text": "Implementation: "
},
{
"code": null,
"e": 26621,
"s": 26613,
"text": "Example"
},
{
"code": null,
"e": 26626,
"s": 26621,
"text": "Java"
},
{
"code": "// Java Program to Implement Strassen Algorithm // Class Strassen matrix multiplicationpublic class GFG { // Method 1 // Function to multiply matrices public int[][] multiply(int[][] A, int[][] B) { // Order of matrix int n = A.length; // Creating a 2D square matrix with size n // n is input from the user int[][] R = new int[n][n]; // Base case // If there is only single element if (n == 1) // Returning the simple multiplication of // two elements in matrices R[0][0] = A[0][0] * B[0][0]; // Matrix else { // Step 1: Dividing Matrix into parts // by storing sub-parts to variables int[][] A11 = new int[n / 2][n / 2]; int[][] A12 = new int[n / 2][n / 2]; int[][] A21 = new int[n / 2][n / 2]; int[][] A22 = new int[n / 2][n / 2]; int[][] B11 = new int[n / 2][n / 2]; int[][] B12 = new int[n / 2][n / 2]; int[][] B21 = new int[n / 2][n / 2]; int[][] B22 = new int[n / 2][n / 2]; // Step 2: Dividing matrix A into 4 halves split(A, A11, 0, 0); split(A, A12, 0, n / 2); split(A, A21, n / 2, 0); split(A, A22, n / 2, n / 2); // Step 2: Dividing matrix B into 4 halves split(B, B11, 0, 0); split(B, B12, 0, n / 2); split(B, B21, n / 2, 0); split(B, B22, n / 2, n / 2); // Using Formulas as described in algorithm // M1:=(A1+A3)×(B1+B2) int[][] M1 = multiply(add(A11, A22), add(B11, B22)); // M2:=(A2+A4)×(B3+B4) int[][] M2 = multiply(add(A21, A22), B11); // M3:=(A1−A4)×(B1+A4) int[][] M3 = multiply(A11, sub(B12, B22)); // M4:=A1×(B2−B4) int[][] M4 = multiply(A22, sub(B21, B11)); // M5:=(A3+A4)×(B1) int[][] M5 = multiply(add(A11, A12), B22); // M6:=(A1+A2)×(B4) int[][] M6 = multiply(sub(A21, A11), add(B11, B12)); // M7:=A4×(B3−B1) int[][] M7 = multiply(sub(A12, A22), add(B21, B22)); // P:=M2+M3−M6−M7 int[][] C11 = add(sub(add(M1, M4), M5), M7); // Q:=M4+M6 int[][] C12 = add(M3, M5); // R:=M5+M7 int[][] C21 = add(M2, M4); // S:=M1−M3−M4−M5 int[][] C22 = add(sub(add(M1, M3), M2), M6); // Step 3: Join 4 halves into one result matrix join(C11, R, 0, 0); join(C12, R, 0, n / 2); join(C21, R, n / 2, 0); join(C22, R, n / 2, n / 2); } // Step 4: Return result return R; } // Method 2 // Function to subtract two matrices public int[][] sub(int[][] A, int[][] B) { // int n = A.length; // int[][] C = new int[n][n]; // Iterating over elements of 2D matrix // using nested for loops // Outer loop for rows for (int i = 0; i < n; i++) // Inner loop for columns for (int j = 0; j < n; j++) // Subtracting corresponding elements // from matrices C[i][j] = A[i][j] - B[i][j]; // Returning the resultant matrix return C; } // Method 3 // Function to add two matrices public int[][] add(int[][] A, int[][] B) { // int n = A.length; // Creating a 2D square matrix int[][] C = new int[n][n]; // Iterating over elements of 2D matrix // using nested for loops // Outer loop for rows for (int i = 0; i < n; i++) // Inner loop for columns for (int j = 0; j < n; j++) // Adding corresponding elements // of matrices C[i][j] = A[i][j] + B[i][j]; // Returning the resultant matrix return C; } // Method 4 // Function to split parent matrix // into child matrices public void split(int[][] P, int[][] C, int iB, int jB) { // Iterating over elements of 2D matrix // using nested for loops // Outer loop for rows for (int i1 = 0, i2 = iB; i1 < C.length; i1++, i2++) // Inner loop for columns for (int j1 = 0, j2 = jB; j1 < C.length; j1++, j2++) C[i1][j1] = P[i2][j2]; } // Method 5 // Function to join child matrices // into (to) parent matrix public void join(int[][] C, int[][] P, int iB, int jB) { // Iterating over elements of 2D matrix // using nested for loops // Outer loop for rows for (int i1 = 0, i2 = iB; i1 < C.length; i1++, i2++) // Inner loop for columns for (int j1 = 0, j2 = jB; j1 < C.length; j1++, j2++) P[i2][j2] = C[i1][j1]; } // Method 5 // Main driver method public static void main(String[] args) { // Display message System.out.println( \"Strassen Multiplication Algorithm Implementation For Matrix Multiplication :\\n\"); // Create an object of Strassen class // in he main function GFG s = new GFG(); // Size of matrix // Considering size as 4 in order to illustrate int N = 4; // Matrix A // Custom input to matrix int[][] A = { { 1, 2, 3, 4 }, { 4, 3, 0, 1 }, { 5, 6, 1, 1 }, { 0, 2, 5, 6 } }; // Matrix B // Custom input to matrix int[][] B = { { 1, 0, 5, 1 }, { 1, 2, 0, 2 }, { 0, 3, 2, 3 }, { 1, 2, 1, 2 } }; // Matrix C computations // Matrix C calling method to get Result int[][] C = s.multiply(A, B); // Display message System.out.println( \"\\nProduct of matrices A and B : \"); // Iterating over elements of 2D matrix // using nested for loops // Outer loop for rows for (int i = 0; i < N; i++) { // Inner loop for columns for (int j = 0; j < N; j++) // Printing elements of resultant matrix // with whitespaces in between System.out.print(C[i][j] + \" \"); // New line once the all elements // are printed for specific row System.out.println(); } }}",
"e": 33281,
"s": 26626,
"text": null
},
{
"code": null,
"e": 33440,
"s": 33281,
"text": "Strassen Multiplication Algorithm Implementation For Matrix Multiplication :\n\n\nProduct of matrices A and B : \n7 21 15 22 \n8 8 21 12 \n12 17 28 22 \n8 31 16 31 "
},
{
"code": null,
"e": 33478,
"s": 33440,
"text": " Time Complexity Of Strassen’s Method"
},
{
"code": null,
"e": 33539,
"s": 33478,
"text": "By Analysis the time complexity Function can be written as: "
},
{
"code": null,
"e": 33563,
"s": 33539,
"text": "T(N) = 7T(N/2) + O(N2)"
},
{
"code": null,
"e": 33611,
"s": 33563,
"text": "By Solving this using Master Theorem we get : "
},
{
"code": null,
"e": 33625,
"s": 33611,
"text": "T(n)=O(nlog7)"
},
{
"code": null,
"e": 33713,
"s": 33625,
"text": "Thus time Complexity Of Strassen’s Algorithm for matrix multiplication is derived as: "
},
{
"code": null,
"e": 33734,
"s": 33713,
"text": "O(nlog7) = O (n2.81)"
},
{
"code": null,
"e": 33753,
"s": 33734,
"text": "O(n3) Vs O(n2.81)"
},
{
"code": null,
"e": 33774,
"s": 33755,
"text": "mikaeljeanpierre31"
},
{
"code": null,
"e": 33789,
"s": 33774,
"text": "varshagumber28"
},
{
"code": null,
"e": 33799,
"s": 33789,
"text": "kk9826225"
},
{
"code": null,
"e": 33806,
"s": 33799,
"text": "Picked"
},
{
"code": null,
"e": 33830,
"s": 33806,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 33835,
"s": 33830,
"text": "Java"
},
{
"code": null,
"e": 33849,
"s": 33835,
"text": "Java Programs"
},
{
"code": null,
"e": 33868,
"s": 33849,
"text": "Technical Scripter"
},
{
"code": null,
"e": 33873,
"s": 33868,
"text": "Java"
},
{
"code": null,
"e": 33971,
"s": 33873,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33980,
"s": 33971,
"text": "Comments"
},
{
"code": null,
"e": 33993,
"s": 33980,
"text": "Old Comments"
},
{
"code": null,
"e": 34011,
"s": 33993,
"text": "Hashtable in Java"
},
{
"code": null,
"e": 34032,
"s": 34011,
"text": "Constructors in Java"
},
{
"code": null,
"e": 34078,
"s": 34032,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 34121,
"s": 34078,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 34161,
"s": 34121,
"text": "Java Math random() method with Examples"
},
{
"code": null,
"e": 34205,
"s": 34161,
"text": "Convert a String to Character array in Java"
},
{
"code": null,
"e": 34231,
"s": 34205,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 34265,
"s": 34231,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 34312,
"s": 34265,
"text": "Implementing a Linked List in Java using Class"
}
] |
Java NIO - CharSet
|
In Java for every character there is a well defined unicode code units which is internally handled by JVM.So Java NIO package defines an abstract class named as Charset which is mainly used for encoding and decoding of charset and UNICODE.
The supported Charset in java are given below.
US-ASCII − Seven bit ASCII characters.
US-ASCII − Seven bit ASCII characters.
ISO-8859-1 − ISO Latin alphabet.
ISO-8859-1 − ISO Latin alphabet.
UTF-8 − This is 8 bit UCS transformation format.
UTF-8 − This is 8 bit UCS transformation format.
UTF-16BE − This is 16 bit UCS transformation format with big endian byte order.
UTF-16BE − This is 16 bit UCS transformation format with big endian byte order.
UTF-16LE − This is 16 bit UCS transformation with little endian byte order.
UTF-16LE − This is 16 bit UCS transformation with little endian byte order.
UTF-16 − 16 bit UCS transformation format.
UTF-16 − 16 bit UCS transformation format.
forName() − This method creates a charset object for the given charset name.The name can be canonical or an alias.
forName() − This method creates a charset object for the given charset name.The name can be canonical or an alias.
displayName() − This method returns the canonical name of given charset.
displayName() − This method returns the canonical name of given charset.
canEncode() − This method checks whether the given charset supports encoding or not.
canEncode() − This method checks whether the given charset supports encoding or not.
decode() − This method decodes the string of a given charset into charbuffer of Unicode charset.
decode() − This method decodes the string of a given charset into charbuffer of Unicode charset.
encode() − This method encodes charbuffer of unicode charset into the byte buffer of given charset.
encode() − This method encodes charbuffer of unicode charset into the byte buffer of given charset.
Following example illustrate important methods of Charset class.
package com.java.nio;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
public class CharsetExample {
public static void main(String[] args) {
Charset charset = Charset.forName("US-ASCII");
System.out.println(charset.displayName());
System.out.println(charset.canEncode());
String str= "Demo text for conversion.";
//convert byte buffer in given charset to char buffer in unicode
ByteBuffer byteBuffer = ByteBuffer.wrap(str.getBytes());
CharBuffer charBuffer = charset.decode(byteBuffer);
//convert char buffer in unicode to byte buffer in given charset
ByteBuffer newByteBuffer = charset.encode(charBuffer);
while(newbb.hasRemaining()){
char ch = (char) newByteBuffer.get();
System.out.print(ch);
}
newByteBuffer.clear();
}
}
US-ASCII
Demo text for conversion.
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": 2224,
"s": 1984,
"text": "In Java for every character there is a well defined unicode code units which is internally handled by JVM.So Java NIO package defines an abstract class named as Charset which is mainly used for encoding and decoding of charset and UNICODE."
},
{
"code": null,
"e": 2271,
"s": 2224,
"text": "The supported Charset in java are given below."
},
{
"code": null,
"e": 2310,
"s": 2271,
"text": "US-ASCII − Seven bit ASCII characters."
},
{
"code": null,
"e": 2349,
"s": 2310,
"text": "US-ASCII − Seven bit ASCII characters."
},
{
"code": null,
"e": 2382,
"s": 2349,
"text": "ISO-8859-1 − ISO Latin alphabet."
},
{
"code": null,
"e": 2415,
"s": 2382,
"text": "ISO-8859-1 − ISO Latin alphabet."
},
{
"code": null,
"e": 2464,
"s": 2415,
"text": "UTF-8 − This is 8 bit UCS transformation format."
},
{
"code": null,
"e": 2513,
"s": 2464,
"text": "UTF-8 − This is 8 bit UCS transformation format."
},
{
"code": null,
"e": 2593,
"s": 2513,
"text": "UTF-16BE − This is 16 bit UCS transformation format with big endian byte order."
},
{
"code": null,
"e": 2673,
"s": 2593,
"text": "UTF-16BE − This is 16 bit UCS transformation format with big endian byte order."
},
{
"code": null,
"e": 2749,
"s": 2673,
"text": "UTF-16LE − This is 16 bit UCS transformation with little endian byte order."
},
{
"code": null,
"e": 2825,
"s": 2749,
"text": "UTF-16LE − This is 16 bit UCS transformation with little endian byte order."
},
{
"code": null,
"e": 2868,
"s": 2825,
"text": "UTF-16 − 16 bit UCS transformation format."
},
{
"code": null,
"e": 2911,
"s": 2868,
"text": "UTF-16 − 16 bit UCS transformation format."
},
{
"code": null,
"e": 3028,
"s": 2913,
"text": "forName() − This method creates a charset object for the given charset name.The name can be canonical or an alias."
},
{
"code": null,
"e": 3143,
"s": 3028,
"text": "forName() − This method creates a charset object for the given charset name.The name can be canonical or an alias."
},
{
"code": null,
"e": 3217,
"s": 3143,
"text": "displayName() − This method returns the canonical name of given charset."
},
{
"code": null,
"e": 3291,
"s": 3217,
"text": "displayName() − This method returns the canonical name of given charset."
},
{
"code": null,
"e": 3376,
"s": 3291,
"text": "canEncode() − This method checks whether the given charset supports encoding or not."
},
{
"code": null,
"e": 3461,
"s": 3376,
"text": "canEncode() − This method checks whether the given charset supports encoding or not."
},
{
"code": null,
"e": 3558,
"s": 3461,
"text": "decode() − This method decodes the string of a given charset into charbuffer of Unicode charset."
},
{
"code": null,
"e": 3655,
"s": 3558,
"text": "decode() − This method decodes the string of a given charset into charbuffer of Unicode charset."
},
{
"code": null,
"e": 3755,
"s": 3655,
"text": "encode() − This method encodes charbuffer of unicode charset into the byte buffer of given charset."
},
{
"code": null,
"e": 3855,
"s": 3755,
"text": "encode() − This method encodes charbuffer of unicode charset into the byte buffer of given charset."
},
{
"code": null,
"e": 3920,
"s": 3855,
"text": "Following example illustrate important methods of Charset class."
},
{
"code": null,
"e": 4782,
"s": 3920,
"text": "package com.java.nio;\nimport java.nio.ByteBuffer;\nimport java.nio.CharBuffer;\nimport java.nio.charset.Charset;\npublic class CharsetExample {\n public static void main(String[] args) {\n Charset charset = Charset.forName(\"US-ASCII\");\n System.out.println(charset.displayName());\n System.out.println(charset.canEncode());\n String str= \"Demo text for conversion.\";\n //convert byte buffer in given charset to char buffer in unicode\n ByteBuffer byteBuffer = ByteBuffer.wrap(str.getBytes());\n CharBuffer charBuffer = charset.decode(byteBuffer);\n //convert char buffer in unicode to byte buffer in given charset\n ByteBuffer newByteBuffer = charset.encode(charBuffer);\n while(newbb.hasRemaining()){\n char ch = (char) newByteBuffer.get();\n System.out.print(ch);\n }\n newByteBuffer.clear();\n }\n}"
},
{
"code": null,
"e": 4818,
"s": 4782,
"text": "US-ASCII\nDemo text for conversion.\n"
},
{
"code": null,
"e": 4851,
"s": 4818,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4867,
"s": 4851,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 4900,
"s": 4867,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 4916,
"s": 4900,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 4951,
"s": 4916,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4965,
"s": 4951,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 4999,
"s": 4965,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 5013,
"s": 4999,
"text": " Tushar Kale"
},
{
"code": null,
"e": 5050,
"s": 5013,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 5065,
"s": 5050,
"text": " Monica Mittal"
},
{
"code": null,
"e": 5098,
"s": 5065,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 5117,
"s": 5098,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 5124,
"s": 5117,
"text": " Print"
},
{
"code": null,
"e": 5135,
"s": 5124,
"text": " Add Notes"
}
] |
Hive - Drop Table - GeeksforGeeks
|
04 Nov, 2020
Apache hive is a data warehousing tool that we use to manage our structure data on Hadoop. The tables in the hive are used for storing data in tabular format(structured). Hive is very much capable such that it can query petabytes of records stored inside the hive table.
DROP TABLE command in the hive is used to drop a table inside the hive. Hive will remove all of its data and metadata from the hive meta-store. The hive DROP TABLE statement comes with a PURGE option. In case if the PURGE option is mentioned the data will be completely lost and cannot be recovered later but if not mentioned then data will move to .Trash/current directory.
Syntax:
DROP TABLE [IF EXISTS] table_name [PURGE];
Example:
To perform the below operation make sure your hive is running. Below are the steps to launch a hive on your local system.
Step 1: Start all your Hadoop Daemon
start-dfs.sh # this will start namenode, datanode and secondary namenode
start-yarn.sh # this will start node manager and resource manager
jps # To check running daemons
Step 2: Launch Hive
hive
Let’s create a table in the hive first with the below command so that we can DROP it with the DROP TABLE statement. In our example, we are not specifying any database name so hive will use its default database.
Command:
CREATE TABLE data (
Name STRING,
ContactNo BIGINT)
ROW FORMAT DELIMITED
FIELDS TERMINATED BY ',';
We have successfully created a data table in the default database of the hive. Below is the command to check
Syntax:
SHOW TABLES IN <database-name>;
Command:
show tables in default;
DROP TABLE in Hive
With the help of the below command, all the content of the data table will be removed permanently because I have used the PURGE option with the DROP TABLE command.
Command:
DROP TABLE IF EXISTS data PURGE;
The table is successfully dropped.
Apache-Hive
Hadoop
Hadoop
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Hadoop MapReduce - Data Flow
Hadoop - Pros and Cons
Hive - Alter Table
Hadoop - Schedulers and Types of Schedulers
Import and Export Data using SQOOP
How to Create Table in Hive?
MapReduce - Combiners
Top 10 Hadoop Analytics Tools For Big Data
MapReduce - Understanding With Real-Life Example
How MapReduce completes a task?
|
[
{
"code": null,
"e": 25591,
"s": 25563,
"text": "\n04 Nov, 2020"
},
{
"code": null,
"e": 25862,
"s": 25591,
"text": "Apache hive is a data warehousing tool that we use to manage our structure data on Hadoop. The tables in the hive are used for storing data in tabular format(structured). Hive is very much capable such that it can query petabytes of records stored inside the hive table."
},
{
"code": null,
"e": 26239,
"s": 25862,
"text": "DROP TABLE command in the hive is used to drop a table inside the hive. Hive will remove all of its data and metadata from the hive meta-store. The hive DROP TABLE statement comes with a PURGE option. In case if the PURGE option is mentioned the data will be completely lost and cannot be recovered later but if not mentioned then data will move to .Trash/current directory. "
},
{
"code": null,
"e": 26247,
"s": 26239,
"text": "Syntax:"
},
{
"code": null,
"e": 26291,
"s": 26247,
"text": "DROP TABLE [IF EXISTS] table_name [PURGE];\n"
},
{
"code": null,
"e": 26300,
"s": 26291,
"text": "Example:"
},
{
"code": null,
"e": 26422,
"s": 26300,
"text": "To perform the below operation make sure your hive is running. Below are the steps to launch a hive on your local system."
},
{
"code": null,
"e": 26459,
"s": 26422,
"text": "Step 1: Start all your Hadoop Daemon"
},
{
"code": null,
"e": 26699,
"s": 26459,
"text": "start-dfs.sh # this will start namenode, datanode and secondary namenode\n\nstart-yarn.sh # this will start node manager and resource manager \n\njps # To check running daemons\n"
},
{
"code": null,
"e": 26719,
"s": 26699,
"text": "Step 2: Launch Hive"
},
{
"code": null,
"e": 26725,
"s": 26719,
"text": "hive\n"
},
{
"code": null,
"e": 26936,
"s": 26725,
"text": "Let’s create a table in the hive first with the below command so that we can DROP it with the DROP TABLE statement. In our example, we are not specifying any database name so hive will use its default database."
},
{
"code": null,
"e": 26945,
"s": 26936,
"text": "Command:"
},
{
"code": null,
"e": 27044,
"s": 26945,
"text": "CREATE TABLE data (\nName STRING,\nContactNo BIGINT)\nROW FORMAT DELIMITED\nFIELDS TERMINATED BY ',';\n"
},
{
"code": null,
"e": 27153,
"s": 27044,
"text": "We have successfully created a data table in the default database of the hive. Below is the command to check"
},
{
"code": null,
"e": 27161,
"s": 27153,
"text": "Syntax:"
},
{
"code": null,
"e": 27194,
"s": 27161,
"text": "SHOW TABLES IN <database-name>;\n"
},
{
"code": null,
"e": 27203,
"s": 27194,
"text": "Command:"
},
{
"code": null,
"e": 27228,
"s": 27203,
"text": "show tables in default;\n"
},
{
"code": null,
"e": 27247,
"s": 27228,
"text": "DROP TABLE in Hive"
},
{
"code": null,
"e": 27411,
"s": 27247,
"text": "With the help of the below command, all the content of the data table will be removed permanently because I have used the PURGE option with the DROP TABLE command."
},
{
"code": null,
"e": 27420,
"s": 27411,
"text": "Command:"
},
{
"code": null,
"e": 27454,
"s": 27420,
"text": "DROP TABLE IF EXISTS data PURGE;\n"
},
{
"code": null,
"e": 27489,
"s": 27454,
"text": "The table is successfully dropped."
},
{
"code": null,
"e": 27501,
"s": 27489,
"text": "Apache-Hive"
},
{
"code": null,
"e": 27508,
"s": 27501,
"text": "Hadoop"
},
{
"code": null,
"e": 27515,
"s": 27508,
"text": "Hadoop"
},
{
"code": null,
"e": 27613,
"s": 27515,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27642,
"s": 27613,
"text": "Hadoop MapReduce - Data Flow"
},
{
"code": null,
"e": 27665,
"s": 27642,
"text": "Hadoop - Pros and Cons"
},
{
"code": null,
"e": 27684,
"s": 27665,
"text": "Hive - Alter Table"
},
{
"code": null,
"e": 27728,
"s": 27684,
"text": "Hadoop - Schedulers and Types of Schedulers"
},
{
"code": null,
"e": 27763,
"s": 27728,
"text": "Import and Export Data using SQOOP"
},
{
"code": null,
"e": 27792,
"s": 27763,
"text": "How to Create Table in Hive?"
},
{
"code": null,
"e": 27814,
"s": 27792,
"text": "MapReduce - Combiners"
},
{
"code": null,
"e": 27857,
"s": 27814,
"text": "Top 10 Hadoop Analytics Tools For Big Data"
},
{
"code": null,
"e": 27906,
"s": 27857,
"text": "MapReduce - Understanding With Real-Life Example"
}
] |
Android LinearLayout in Kotlin - GeeksforGeeks
|
16 Mar, 2022
Android LinearLayout is a ViewGroup subclass, used to provide child View elements one by one either in a particular direction either horizontally or vertically based on the orientation property. We can specify the linear layout orientation using android:orientation attribute.
All the child elements arranged one by one in multiple rows and multiple columns.
Horizontal list: One row, multiple columns.Vertical list: One column, multiple rows.
Horizontal list: One row, multiple columns.
Vertical list: One column, multiple rows.
In this article, we are going to discuss declaration and implementation of LinearLayout.
First of all, we should declare the LinearLayout in layout file using the below code.
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="match_parent" android:orientation="vertical" > // Add another child elements here like // EditText, button etc </LinearLayout>
Following is the code for LinearLayout in xml file.
XML
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http:// schemas.android.com/apk/res/android" xmlns:tools="http:// schemas.android.com/tools" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="16dp" android:text="Enter your name here:" android:textSize="24dp" android:id="@+id/txtVw"/> <EditText android:id="@+id/editText" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="16dp" android:hint="Name" android:inputType="text"/> <Button android:id="@+id/showInput" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:text="show" android:backgroundTint="@color/colorPrimary" android:textColor="@android:color/white"/> </LinearLayout>
When we have created layout, we need to load the XML layout resource from our activity onCreate() callback method and access the UI element form the XML using findViewById.
Kotlin
package com.geeksforgeeks.myfirstkotlinapp import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.EditText import android.widget.TextView class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // finding the UI elements val showButton = findViewById<Button>(R.id.showInput) val editText = findViewById<EditText>(R.id.editText) val textView = findViewById<TextView>(R.id.txtVw) }}
We can run the application using the Android Virtual Device(AVD) to get the output of the above code.
Akanksha_Rai
ayushpandey3july
Kotlin Android
Kotlin
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Broadcast Receiver in Android With Example
Content Providers in Android with Example
Android RecyclerView in Kotlin
Retrofit with Kotlin Coroutine in Android
How to Add and Customize Back Button of Action Bar in Android?
How to Get Current Location in Android?
Kotlin Setters and Getters
How to Change the Color of Status Bar in an Android App?
Kotlin Android Tutorial
Kotlin when expression
|
[
{
"code": null,
"e": 25721,
"s": 25693,
"text": "\n16 Mar, 2022"
},
{
"code": null,
"e": 25998,
"s": 25721,
"text": "Android LinearLayout is a ViewGroup subclass, used to provide child View elements one by one either in a particular direction either horizontally or vertically based on the orientation property. We can specify the linear layout orientation using android:orientation attribute."
},
{
"code": null,
"e": 26080,
"s": 25998,
"text": "All the child elements arranged one by one in multiple rows and multiple columns."
},
{
"code": null,
"e": 26165,
"s": 26080,
"text": "Horizontal list: One row, multiple columns.Vertical list: One column, multiple rows."
},
{
"code": null,
"e": 26209,
"s": 26165,
"text": "Horizontal list: One row, multiple columns."
},
{
"code": null,
"e": 26251,
"s": 26209,
"text": "Vertical list: One column, multiple rows."
},
{
"code": null,
"e": 26340,
"s": 26251,
"text": "In this article, we are going to discuss declaration and implementation of LinearLayout."
},
{
"code": null,
"e": 26426,
"s": 26340,
"text": "First of all, we should declare the LinearLayout in layout file using the below code."
},
{
"code": null,
"e": 26430,
"s": 26426,
"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=\"match_parent\" android:orientation=\"vertical\" > // Add another child elements here like // EditText, button etc </LinearLayout>",
"e": 26749,
"s": 26430,
"text": null
},
{
"code": null,
"e": 26801,
"s": 26749,
"text": "Following is the code for LinearLayout in xml file."
},
{
"code": null,
"e": 26805,
"s": 26801,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http:// schemas.android.com/apk/res/android\" xmlns:tools=\"http:// schemas.android.com/tools\" android:orientation=\"vertical\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"16dp\" android:text=\"Enter your name here:\" android:textSize=\"24dp\" android:id=\"@+id/txtVw\"/> <EditText android:id=\"@+id/editText\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"16dp\" android:hint=\"Name\" android:inputType=\"text\"/> <Button android:id=\"@+id/showInput\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center_horizontal\" android:text=\"show\" android:backgroundTint=\"@color/colorPrimary\" android:textColor=\"@android:color/white\"/> </LinearLayout>",
"e": 27928,
"s": 26805,
"text": null
},
{
"code": null,
"e": 28101,
"s": 27928,
"text": "When we have created layout, we need to load the XML layout resource from our activity onCreate() callback method and access the UI element form the XML using findViewById."
},
{
"code": null,
"e": 28108,
"s": 28101,
"text": "Kotlin"
},
{
"code": "package com.geeksforgeeks.myfirstkotlinapp import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.EditText import android.widget.TextView class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // finding the UI elements val showButton = findViewById<Button>(R.id.showInput) val editText = findViewById<EditText>(R.id.editText) val textView = findViewById<TextView>(R.id.txtVw) }}",
"e": 28796,
"s": 28108,
"text": null
},
{
"code": null,
"e": 28898,
"s": 28796,
"text": "We can run the application using the Android Virtual Device(AVD) to get the output of the above code."
},
{
"code": null,
"e": 28911,
"s": 28898,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 28928,
"s": 28911,
"text": "ayushpandey3july"
},
{
"code": null,
"e": 28943,
"s": 28928,
"text": "Kotlin Android"
},
{
"code": null,
"e": 28950,
"s": 28943,
"text": "Kotlin"
},
{
"code": null,
"e": 29048,
"s": 28950,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29091,
"s": 29048,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 29133,
"s": 29091,
"text": "Content Providers in Android with Example"
},
{
"code": null,
"e": 29164,
"s": 29133,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 29206,
"s": 29164,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 29269,
"s": 29206,
"text": "How to Add and Customize Back Button of Action Bar in Android?"
},
{
"code": null,
"e": 29309,
"s": 29269,
"text": "How to Get Current Location in Android?"
},
{
"code": null,
"e": 29336,
"s": 29309,
"text": "Kotlin Setters and Getters"
},
{
"code": null,
"e": 29393,
"s": 29336,
"text": "How to Change the Color of Status Bar in an Android App?"
},
{
"code": null,
"e": 29417,
"s": 29393,
"text": "Kotlin Android Tutorial"
}
] |
Class getDeclaredMethod() method in Java with Examples - GeeksforGeeks
|
16 Dec, 2019
The getDeclaredMethod() method of java.lang.Class class is used to get the specified method of this class with the specified parameter type. The method returns the specified method of this class in the form of Method object.
Syntax:
public Method getDeclaredMethod(String methodName,
Class[] parameterType)
throws NoSuchMethodException, SecurityException
Parameter: This method accepts two parameters:
methodName which is the Method to be get.
parameterType which is the array of parameter type for the specified method.
Return Value: This method returns the specified method of this class in the form of Method objects.
Exception This method throws:
NoSuchMethodException if a method with the specified name is not found.
NullPointerException if name is null
SecurityException if a security manager is present and the security conditions are not met.Below programs demonstrate the getDeclaredMethod() method.Example 1:// Java program to demonstrate// getDeclaredMethod() method import java.util.*; public class Test { public void func() {} public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException { // returns the Class object for this class Class myClass = Class.forName("Test"); System.out.println("Class represented by myClass: " + myClass.toString()); String methodName = "func"; Class[] parameterType = null; // Get the method of myClass // using getDeclaredMethod() method System.out.println( methodName + " Method of myClass: " + myClass.getDeclaredMethod( methodName, parameterType)); }}Output:Class represented by myClass: class Test
func Method of myClass: public void Test.func()
Example 2:// Java program to demonstrate// getDeclaredMethod() method import java.util.*; class Main { private void func() {} public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException { // returns the Class object for this class Class myClass = Class.forName("Main"); System.out.println("Class represented by myClass: " + myClass.toString()); String methodName = "func"; Class[] parameterType = null; try { // Get the method of myClass // using getDeclaredMethod() method System.out.println( methodName + " Method of myClass: " + myClass.getDeclaredMethod( methodName, parameterType)); } catch (Exception e) { System.out.println(e); } }}Output:Class represented by myClass: class Main
func Method of myClass: private void Main.func()
Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getDeclaredMethod-java.lang.String-java.lang.Class...-My Personal Notes
arrow_drop_upSave
Below programs demonstrate the getDeclaredMethod() method.
Example 1:
// Java program to demonstrate// getDeclaredMethod() method import java.util.*; public class Test { public void func() {} public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException { // returns the Class object for this class Class myClass = Class.forName("Test"); System.out.println("Class represented by myClass: " + myClass.toString()); String methodName = "func"; Class[] parameterType = null; // Get the method of myClass // using getDeclaredMethod() method System.out.println( methodName + " Method of myClass: " + myClass.getDeclaredMethod( methodName, parameterType)); }}
Class represented by myClass: class Test
func Method of myClass: public void Test.func()
Example 2:
// Java program to demonstrate// getDeclaredMethod() method import java.util.*; class Main { private void func() {} public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException { // returns the Class object for this class Class myClass = Class.forName("Main"); System.out.println("Class represented by myClass: " + myClass.toString()); String methodName = "func"; Class[] parameterType = null; try { // Get the method of myClass // using getDeclaredMethod() method System.out.println( methodName + " Method of myClass: " + myClass.getDeclaredMethod( methodName, parameterType)); } catch (Exception e) { System.out.println(e); } }}
Class represented by myClass: class Main
func Method of myClass: private void Main.func()
Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getDeclaredMethod-java.lang.String-java.lang.Class...-
Java-Functions
Java-lang package
Java.lang.Class
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
Generics in Java
Different ways of Reading a text file in Java
Internal Working of HashMap in Java
Introduction to Java
Comparator Interface in Java with Examples
Strings in Java
|
[
{
"code": null,
"e": 25225,
"s": 25197,
"text": "\n16 Dec, 2019"
},
{
"code": null,
"e": 25450,
"s": 25225,
"text": "The getDeclaredMethod() method of java.lang.Class class is used to get the specified method of this class with the specified parameter type. The method returns the specified method of this class in the form of Method object."
},
{
"code": null,
"e": 25458,
"s": 25450,
"text": "Syntax:"
},
{
"code": null,
"e": 25617,
"s": 25458,
"text": "public Method getDeclaredMethod(String methodName, \n Class[] parameterType)\n throws NoSuchMethodException, SecurityException\n"
},
{
"code": null,
"e": 25664,
"s": 25617,
"text": "Parameter: This method accepts two parameters:"
},
{
"code": null,
"e": 25706,
"s": 25664,
"text": "methodName which is the Method to be get."
},
{
"code": null,
"e": 25783,
"s": 25706,
"text": "parameterType which is the array of parameter type for the specified method."
},
{
"code": null,
"e": 25883,
"s": 25783,
"text": "Return Value: This method returns the specified method of this class in the form of Method objects."
},
{
"code": null,
"e": 25913,
"s": 25883,
"text": "Exception This method throws:"
},
{
"code": null,
"e": 25985,
"s": 25913,
"text": "NoSuchMethodException if a method with the specified name is not found."
},
{
"code": null,
"e": 26022,
"s": 25985,
"text": "NullPointerException if name is null"
},
{
"code": null,
"e": 28190,
"s": 26022,
"text": "SecurityException if a security manager is present and the security conditions are not met.Below programs demonstrate the getDeclaredMethod() method.Example 1:// Java program to demonstrate// getDeclaredMethod() method import java.util.*; public class Test { public void func() {} public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException { // returns the Class object for this class Class myClass = Class.forName(\"Test\"); System.out.println(\"Class represented by myClass: \" + myClass.toString()); String methodName = \"func\"; Class[] parameterType = null; // Get the method of myClass // using getDeclaredMethod() method System.out.println( methodName + \" Method of myClass: \" + myClass.getDeclaredMethod( methodName, parameterType)); }}Output:Class represented by myClass: class Test\nfunc Method of myClass: public void Test.func()\nExample 2:// Java program to demonstrate// getDeclaredMethod() method import java.util.*; class Main { private void func() {} public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException { // returns the Class object for this class Class myClass = Class.forName(\"Main\"); System.out.println(\"Class represented by myClass: \" + myClass.toString()); String methodName = \"func\"; Class[] parameterType = null; try { // Get the method of myClass // using getDeclaredMethod() method System.out.println( methodName + \" Method of myClass: \" + myClass.getDeclaredMethod( methodName, parameterType)); } catch (Exception e) { System.out.println(e); } }}Output:Class represented by myClass: class Main\nfunc Method of myClass: private void Main.func()\nReference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getDeclaredMethod-java.lang.String-java.lang.Class...-My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 28249,
"s": 28190,
"text": "Below programs demonstrate the getDeclaredMethod() method."
},
{
"code": null,
"e": 28260,
"s": 28249,
"text": "Example 1:"
},
{
"code": "// Java program to demonstrate// getDeclaredMethod() method import java.util.*; public class Test { public void func() {} public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException { // returns the Class object for this class Class myClass = Class.forName(\"Test\"); System.out.println(\"Class represented by myClass: \" + myClass.toString()); String methodName = \"func\"; Class[] parameterType = null; // Get the method of myClass // using getDeclaredMethod() method System.out.println( methodName + \" Method of myClass: \" + myClass.getDeclaredMethod( methodName, parameterType)); }}",
"e": 29027,
"s": 28260,
"text": null
},
{
"code": null,
"e": 29117,
"s": 29027,
"text": "Class represented by myClass: class Test\nfunc Method of myClass: public void Test.func()\n"
},
{
"code": null,
"e": 29128,
"s": 29117,
"text": "Example 2:"
},
{
"code": "// Java program to demonstrate// getDeclaredMethod() method import java.util.*; class Main { private void func() {} public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException { // returns the Class object for this class Class myClass = Class.forName(\"Main\"); System.out.println(\"Class represented by myClass: \" + myClass.toString()); String methodName = \"func\"; Class[] parameterType = null; try { // Get the method of myClass // using getDeclaredMethod() method System.out.println( methodName + \" Method of myClass: \" + myClass.getDeclaredMethod( methodName, parameterType)); } catch (Exception e) { System.out.println(e); } }}",
"e": 30005,
"s": 29128,
"text": null
},
{
"code": null,
"e": 30096,
"s": 30005,
"text": "Class represented by myClass: class Main\nfunc Method of myClass: private void Main.func()\n"
},
{
"code": null,
"e": 30225,
"s": 30096,
"text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getDeclaredMethod-java.lang.String-java.lang.Class...-"
},
{
"code": null,
"e": 30240,
"s": 30225,
"text": "Java-Functions"
},
{
"code": null,
"e": 30258,
"s": 30240,
"text": "Java-lang package"
},
{
"code": null,
"e": 30274,
"s": 30258,
"text": "Java.lang.Class"
},
{
"code": null,
"e": 30279,
"s": 30274,
"text": "Java"
},
{
"code": null,
"e": 30284,
"s": 30279,
"text": "Java"
},
{
"code": null,
"e": 30382,
"s": 30284,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30397,
"s": 30382,
"text": "Stream In Java"
},
{
"code": null,
"e": 30418,
"s": 30397,
"text": "Constructors in Java"
},
{
"code": null,
"e": 30437,
"s": 30418,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 30467,
"s": 30437,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 30484,
"s": 30467,
"text": "Generics in Java"
},
{
"code": null,
"e": 30530,
"s": 30484,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 30566,
"s": 30530,
"text": "Internal Working of HashMap in Java"
},
{
"code": null,
"e": 30587,
"s": 30566,
"text": "Introduction to Java"
},
{
"code": null,
"e": 30630,
"s": 30587,
"text": "Comparator Interface in Java with Examples"
}
] |
WeakHashMap Class in Java - GeeksforGeeks
|
24 Jan, 2022
WeakHashMap is an implementation of the Map interface. WeakHashMap is almost the same as HashMap except in the case of WeakHashMap if the object is specified as the key doesn’t contain any references- it is eligible for garbage collection even though it is associated with WeakHashMap. i.e Garbage Collector dominates over WeakHashMap.
WeakHashMap is the Hash table-based implementation of the Map interface, with weak keys. An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use. More precisely, the presence of a mapping for a given key will not prevent the key from being discarded by the garbage collector, that is, made finalizable, finalized, and then reclaimed. When a key has been discarded its entry is effectively removed from the map, so this class behaves somewhat differently from other Map implementations.
A few important features of a WeakHashMap Class are:
Both null values and null keys are supported in WeakHashMap.
It is not synchronized.
This class is intended primarily for use with key objects whose equals methods test for object identity using the == operator.
1. WeakHashMap(): This constructor is used to create an empty WeakHashMap with the default initial capacity-(16) and load factor (0.75).
2. WeakHashMap(int initialCapacity): This constructor is used to create an empty WeakHashMap with the given initial capacity and the default load factor (0.75).
3. WeakHashMap(int initialCapacity, float loadFactor): This constructor is used to create an empty WeakHashMap with the given initial capacity and the given load factor.
4. WeakHashMap(Map m): This constructor is used to create a new WeakHashMap with the same mappings as the specified map.
Example 1:
Java
// Java Program to Illustrate WeakHashMap class// Via close(), containsValue(), containsKey()// and isEmpty() method // Importing required classesimport java.util.Map;import java.util.WeakHashMap; // Main class// WeakHashMapdemoclass GFG { // Main driver method public static void main(String[] arg) { // Creating an empty WeakHashMap // of Number and string type Map<Number, String> weak = new WeakHashMap<Number, String>(); // Inserting custom elements // using put() method weak.put(1, "geeks"); weak.put(2, "for"); weak.put(3, "geeks"); // Printing and alongside checking weak map System.out.println("our weak map: " + weak); // Checking if "for" exist if (weak.containsValue("for")) System.out.println("for exist"); // Checking if 1 exist as a key in Map if (weak.containsKey(1)) System.out.println("1 exist"); // Removing all data // using clear() method weak.clear(); // Checking whether the Map is empty or not // using isEmpty() method if (weak.isEmpty()) // Display message for better readability System.out.println("empty map: " + weak); }}
our weak map: {3=geeks, 2=for, 1=geeks}
for exist
1 exist
empty map: {}
Example 2:
Java
// Java Program to Illustrate WeakHashMap class// Via entrySet(), keySet() and Values() Method // Importing required classesimport java.util.Collection;import java.util.Map;import java.util.Set;import java.util.WeakHashMap; // Main class// WeakHashMapdemoclass GFG { // Main driver method public static void main(String[] arg) { // Creating an empty WeakHashMap // of number and string type Map<Number, String> weak = new WeakHashMap<Number, String>(); // Inserting elements // using put() method weak.put(1, "geeks"); weak.put(2, "for"); weak.put(3, "geeks"); // Creating object of Set interface Set set1 = weak.entrySet(); // Checking above Set System.out.println(set1); // Creating set for key Set keySet = weak.keySet(); // Checking keySet System.out.println("key set: " + keySet); Collection value = weak.values(); // Checking values of map and printing them System.out.println("values: " + value); }}
[3=geeks, 2=for, 1=geeks]
key set: [3, 2, 1]
values: [geeks, for, geeks]
Example 3:
Java
// Java code remove(), putAll()// get() and size() method import java.util.Collection;import java.util.Map;import java.util.Set;import java.util.WeakHashMap; class WeakHashMapdemo { public static void main(String[] arg) { Map<Number, String> weak = new WeakHashMap<Number, String>(); weak.put(1, "geeks"); weak.put(2, "for"); weak.put(3, "geeks"); Map<Number, String> weak1 = new WeakHashMap<Number, String>(); weak1.putAll(weak); // Getting value of key 2 System.out.println(weak1.get(2)); // Printing the size of map // using size() method System.out.println("Size of map is: " + weak1.size()); // Removing second element // using standard remove() method weak1.remove(2); // Printing the size after removing key and value // pair System.out.println("Size after removing: " + weak1.size()); }}
for
Size of map is: 3
Size after removing: 2
This article is contributed by Abhishek Verma. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
solankimayank
simranarora5sos
nishkarshgandhi
Java - util package
Java-HashMap
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Interfaces in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
Multithreading in Java
Collections in Java
Queue Interface In Java
|
[
{
"code": null,
"e": 25441,
"s": 25413,
"text": "\n24 Jan, 2022"
},
{
"code": null,
"e": 25777,
"s": 25441,
"text": "WeakHashMap is an implementation of the Map interface. WeakHashMap is almost the same as HashMap except in the case of WeakHashMap if the object is specified as the key doesn’t contain any references- it is eligible for garbage collection even though it is associated with WeakHashMap. i.e Garbage Collector dominates over WeakHashMap."
},
{
"code": null,
"e": 26305,
"s": 25777,
"text": "WeakHashMap is the Hash table-based implementation of the Map interface, with weak keys. An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use. More precisely, the presence of a mapping for a given key will not prevent the key from being discarded by the garbage collector, that is, made finalizable, finalized, and then reclaimed. When a key has been discarded its entry is effectively removed from the map, so this class behaves somewhat differently from other Map implementations."
},
{
"code": null,
"e": 26358,
"s": 26305,
"text": "A few important features of a WeakHashMap Class are:"
},
{
"code": null,
"e": 26419,
"s": 26358,
"text": "Both null values and null keys are supported in WeakHashMap."
},
{
"code": null,
"e": 26443,
"s": 26419,
"text": "It is not synchronized."
},
{
"code": null,
"e": 26570,
"s": 26443,
"text": "This class is intended primarily for use with key objects whose equals methods test for object identity using the == operator."
},
{
"code": null,
"e": 26708,
"s": 26570,
"text": "1. WeakHashMap(): This constructor is used to create an empty WeakHashMap with the default initial capacity-(16) and load factor (0.75). "
},
{
"code": null,
"e": 26870,
"s": 26708,
"text": "2. WeakHashMap(int initialCapacity): This constructor is used to create an empty WeakHashMap with the given initial capacity and the default load factor (0.75). "
},
{
"code": null,
"e": 27041,
"s": 26870,
"text": "3. WeakHashMap(int initialCapacity, float loadFactor): This constructor is used to create an empty WeakHashMap with the given initial capacity and the given load factor. "
},
{
"code": null,
"e": 27162,
"s": 27041,
"text": "4. WeakHashMap(Map m): This constructor is used to create a new WeakHashMap with the same mappings as the specified map."
},
{
"code": null,
"e": 27173,
"s": 27162,
"text": "Example 1:"
},
{
"code": null,
"e": 27178,
"s": 27173,
"text": "Java"
},
{
"code": "// Java Program to Illustrate WeakHashMap class// Via close(), containsValue(), containsKey()// and isEmpty() method // Importing required classesimport java.util.Map;import java.util.WeakHashMap; // Main class// WeakHashMapdemoclass GFG { // Main driver method public static void main(String[] arg) { // Creating an empty WeakHashMap // of Number and string type Map<Number, String> weak = new WeakHashMap<Number, String>(); // Inserting custom elements // using put() method weak.put(1, \"geeks\"); weak.put(2, \"for\"); weak.put(3, \"geeks\"); // Printing and alongside checking weak map System.out.println(\"our weak map: \" + weak); // Checking if \"for\" exist if (weak.containsValue(\"for\")) System.out.println(\"for exist\"); // Checking if 1 exist as a key in Map if (weak.containsKey(1)) System.out.println(\"1 exist\"); // Removing all data // using clear() method weak.clear(); // Checking whether the Map is empty or not // using isEmpty() method if (weak.isEmpty()) // Display message for better readability System.out.println(\"empty map: \" + weak); }}",
"e": 28457,
"s": 27178,
"text": null
},
{
"code": null,
"e": 28529,
"s": 28457,
"text": "our weak map: {3=geeks, 2=for, 1=geeks}\nfor exist\n1 exist\nempty map: {}"
},
{
"code": null,
"e": 28541,
"s": 28529,
"text": " Example 2:"
},
{
"code": null,
"e": 28546,
"s": 28541,
"text": "Java"
},
{
"code": "// Java Program to Illustrate WeakHashMap class// Via entrySet(), keySet() and Values() Method // Importing required classesimport java.util.Collection;import java.util.Map;import java.util.Set;import java.util.WeakHashMap; // Main class// WeakHashMapdemoclass GFG { // Main driver method public static void main(String[] arg) { // Creating an empty WeakHashMap // of number and string type Map<Number, String> weak = new WeakHashMap<Number, String>(); // Inserting elements // using put() method weak.put(1, \"geeks\"); weak.put(2, \"for\"); weak.put(3, \"geeks\"); // Creating object of Set interface Set set1 = weak.entrySet(); // Checking above Set System.out.println(set1); // Creating set for key Set keySet = weak.keySet(); // Checking keySet System.out.println(\"key set: \" + keySet); Collection value = weak.values(); // Checking values of map and printing them System.out.println(\"values: \" + value); }}",
"e": 29629,
"s": 28546,
"text": null
},
{
"code": null,
"e": 29702,
"s": 29629,
"text": "[3=geeks, 2=for, 1=geeks]\nkey set: [3, 2, 1]\nvalues: [geeks, for, geeks]"
},
{
"code": null,
"e": 29713,
"s": 29702,
"text": "Example 3:"
},
{
"code": null,
"e": 29718,
"s": 29713,
"text": "Java"
},
{
"code": "// Java code remove(), putAll()// get() and size() method import java.util.Collection;import java.util.Map;import java.util.Set;import java.util.WeakHashMap; class WeakHashMapdemo { public static void main(String[] arg) { Map<Number, String> weak = new WeakHashMap<Number, String>(); weak.put(1, \"geeks\"); weak.put(2, \"for\"); weak.put(3, \"geeks\"); Map<Number, String> weak1 = new WeakHashMap<Number, String>(); weak1.putAll(weak); // Getting value of key 2 System.out.println(weak1.get(2)); // Printing the size of map // using size() method System.out.println(\"Size of map is: \" + weak1.size()); // Removing second element // using standard remove() method weak1.remove(2); // Printing the size after removing key and value // pair System.out.println(\"Size after removing: \" + weak1.size()); }}",
"e": 30728,
"s": 29718,
"text": null
},
{
"code": null,
"e": 30773,
"s": 30728,
"text": "for\nSize of map is: 3\nSize after removing: 2"
},
{
"code": null,
"e": 31196,
"s": 30773,
"text": "This article is contributed by Abhishek Verma. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 31210,
"s": 31196,
"text": "solankimayank"
},
{
"code": null,
"e": 31226,
"s": 31210,
"text": "simranarora5sos"
},
{
"code": null,
"e": 31242,
"s": 31226,
"text": "nishkarshgandhi"
},
{
"code": null,
"e": 31262,
"s": 31242,
"text": "Java - util package"
},
{
"code": null,
"e": 31275,
"s": 31262,
"text": "Java-HashMap"
},
{
"code": null,
"e": 31280,
"s": 31275,
"text": "Java"
},
{
"code": null,
"e": 31285,
"s": 31280,
"text": "Java"
},
{
"code": null,
"e": 31383,
"s": 31285,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31398,
"s": 31383,
"text": "Stream In Java"
},
{
"code": null,
"e": 31417,
"s": 31398,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 31435,
"s": 31417,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 31467,
"s": 31435,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 31487,
"s": 31467,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 31519,
"s": 31487,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 31543,
"s": 31519,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 31566,
"s": 31543,
"text": "Multithreading in Java"
},
{
"code": null,
"e": 31586,
"s": 31566,
"text": "Collections in Java"
}
] |
Number of Groups of Sizes Two Or Three Divisible By 3 - GeeksforGeeks
|
16 Apr, 2021
You are given N distinct numbers. You are tasked with finding the number of groups of 2 or 3 that can be formed whose sum is divisible by three.Examples :
Input : 1 5 7 2 9 14
Output : 13
The groups of two that can be
formed are:
(1, 5)
(5, 7)
(1, 2)
(2, 7)
(1, 14)
(7, 14)
The groups of three are:
(1, 5, 9)
(5, 7, 9)
(1, 2, 9)
(2, 7, 9)
(2, 5, 14)
(1, 9, 14)
(7, 9, 14)
Input : 3 6 9 12
Output : 10
All groups of 2 and 3 are valid.
Naive Approach : For each number, we can add it up with every other number and see if the sum is divisible by 3. We then store these sums, so that we can add each number again to check for groups of three. Time Complexity: O(N^2) for groups of 2, O(N^3) for groups of 3 Auxiliary Space: O(N^2)Optimum Approach If we carefully look at every number, we realize that 3 options exist:
The number is divisible by 3The number leaves a remainder of 1, when divided by 3The number leaves a remainder of 2, when divided by 3
The number is divisible by 3
The number leaves a remainder of 1, when divided by 3
The number leaves a remainder of 2, when divided by 3
Now, for groups of two being divisible by 3, either both number have to belong to category 1 (both are divisible by 3), or one number should leave a remainder 1, and the other a remainder 2. This way the remainders add up to 3, making the sum divisible by 3. To form a group of three, either all three numbers should give the same remainder, or one should give remainder 0, another should give 1, and the last should give 2.In this way, we do not care about the numbers themselves, but their respective remainders. Thus by grouping them into three categories, we can find the total possible groups using a simple formula. Let C1 be number of elements divisible by 3. Let C2 be number of elements leaving remainder 1. Let C3 be number of elements leaving remainder 2.
Answer =
C2 * C3 + C1 * (C1 - 1) / 2 --> Groups of 2
+ C1 * (C1 - 1) * (C1 - 2) / 6
+ C2 * (C2 - 1) * (C2 - 2) / 6
+ C3 * (C3 - 1) * (C3 - 2) / 6 --> Groups of 3
with elements of same remainder
+ C1 * C2 * C3 --> Groups of three with all
distinct remainders
CPP
Java
Python3
C#
PHP
Javascript
// Program to find groups of 2 or 3// whose sum is divisible by 3#include <iostream>using namespace std; int numOfCombinations(int arr[], int N){ // Initialize groups to 0 int C[3] = { 0, 0, 0 }; // Increment group with specified remainder for (int i = 0; i < N; ++i) ++C[arr[i] % 3]; // Return groups using the formula return C[1] * C[2] + C[0] * (C[0] - 1) / 2 + C[0] * (C[0] - 1) * (C[0] - 2) / 6 + C[1] * (C[1] - 1) * (C[1] - 2) / 6 + C[2] * (C[2] - 1) * (C[2] - 2) / 6 + C[0] * C[1] * C[2];} // Driver Functionint main(){ int arr1[6] = { 1, 5, 7, 2, 9, 14 }; cout << numOfCombinations(arr1, 6) << "\n"; int arr2[4] = { 3, 6, 9, 12 }; cout << numOfCombinations(arr2, 4) << "\n"; return 0;}
// Program to find groups of 2 or 3// whose sum is divisible by 3 class GFG { static int numOfCombinations(int arr[], int N) { // Initialize groups to 0 int C[] = { 0, 0, 0 }; // Increment group with specified remainder for (int i = 0; i < N; ++i) ++C[arr[i] % 3]; // Return groups using the formula return C[1] * C[2] + C[0] * (C[0] - 1) / 2 + C[0] * (C[0] - 1) * (C[0] - 2) / 6 + C[1] * (C[1] - 1) * (C[1] - 2) / 6 + C[2] * (C[2] - 1) * (C[2] - 2) / 6 + C[0] * C[1] * C[2]; } // Driver code public static void main(String[] args) { int arr1[] = { 1, 5, 7, 2, 9, 14 }; System.out.print(numOfCombinations(arr1, 6) + "\n"); int arr2[] = { 3, 6, 9, 12 }; System.out.print(numOfCombinations(arr2, 4) + "\n"); }} // This code is contributed by Anant Agarwal.
# Program to find groups of 2 or 3# whose sum is divisible by 3 def numOfCombinations(arr, N): # Initialize groups to 0 C = [0, 0, 0] # Increment group with # specified remainder for i in range(N): C[arr[i] % 3]= C[arr[i] % 3]+1 # Return groups using the formula return (C[1] * C[2] + C[0] * (C[0] - 1) / 2 + C[0] * (C[0] - 1) * (C[0] - 2) / 6 + C[1] * (C[1] - 1) * (C[1] - 2) / 6 + C[2] * (C[2] - 1) * (C[2] - 2) / 6 + C[0] * C[1] * C[2]) # Driver code arr1 = [1, 5, 7, 2, 9, 14]print(int(numOfCombinations(arr1, 6)))arr2 = [3, 6, 9, 12]print(int(numOfCombinations(arr2, 4))) # This code is contributed# by Anant Agarwal.
// C# Program to find groups of 2 or// 3 whose sum is divisible by 3using System; class GFG { // Function to find number of combinations static int numOfCombinations(int[] arr, int N) { // Initialize groups to 0 int[] C = { 0, 0, 0 }; // Increment group with specified remainder for (int i = 0; i < N; ++i) ++C[arr[i] % 3]; // Return groups using the formula return C[1] * C[2] + C[0] * (C[0] - 1) / 2 + C[0] * (C[0] - 1) * (C[0] - 2) / 6 + C[1] * (C[1] - 1) * (C[1] - 2) / 6 + C[2] * (C[2] - 1) * (C[2] - 2) / 6 + C[0] * C[1] * C[2]; } // Driver code public static void Main() { int[] arr1 = { 1, 5, 7, 2, 9, 14 }; Console.WriteLine(numOfCombinations(arr1, 6)); int[] arr2 = { 3, 6, 9, 12 }; Console.WriteLine(numOfCombinations(arr2, 4)); }} // This code is contributed by vt_m.
<?php // PHP Program to find// groups of 2 or 3// whose sum is divisible by 3 function numOfCombinations($arr, $N){ // Initialize groups to 0 $C = array(0, 0, 0); // Increment group with // specified remainder for ($i = 0; $i < $N; ++$i) ++$C[$arr[$i] % 3]; // Return groups using the formula return $C[1] * $C[2] + $C[0] * ($C[0] - 1) / 2 + $C[0] * ($C[0] - 1) * ($C[0] - 2) / 6 + $C[1] * ($C[1] - 1) * ($C[1] - 2) / 6 + $C[2] * ($C[2] - 1) * ($C[2] - 2) / 6 + $C[0] * $C[1] * $C[2];} // Driver Code$arr1 = array(1, 5, 7, 2, 9, 14);echo numOfCombinations($arr1, 6), "\n"; $arr2 = array(3, 6, 9, 12); echo numOfCombinations($arr2, 4), "\n"; // This code is contributed by ajit?>
<script>// Javascript Program to find// groups of 2 or 3// whose sum is divisible by 3function numOfCombinations(arr, N){ // Initialize groups to 0 let C = [0, 0, 0]; // Increment group with // specified remainder for (let i = 0; i < N; ++i) ++C[arr[i] % 3]; // Return groups using the formula return C[1] * C[2] + C[0] * (C[0] - 1) / 2 + C[0] * (C[0] - 1) * (C[0] - 2) / 6 + C[1] * (C[1] - 1) * (C[1] - 2) / 6 + C[2] * (C[2] - 1) * (C[2] - 2) / 6 + C[0] * C[1] * C[2];} // Driver Codelet arr1 = [1, 5, 7, 2, 9, 14];document.write(numOfCombinations(arr1, 6) + "<br>"); let arr2 = [3, 6, 9, 12];document.write(numOfCombinations(arr2, 4) + "<br>"); // This code is contributed by gfgking.</script>
Output :
13
10
Asked in AmazonThis article is contributed by Aditya Kamath. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
vt_m
jit_t
gfgking
Amazon
divisibility
Mathematical
Amazon
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program to print prime numbers from 1 to N.
Segment Tree | Set 1 (Sum of given range)
Modular multiplicative inverse
Count all possible paths from top left to bottom right of a mXn matrix
Fizz Buzz Implementation
Check if a number is Palindrome
Program to multiply two matrices
Count ways to reach the n'th stair
Merge two sorted arrays with O(1) extra space
Generate all permutation of a set in Python
|
[
{
"code": null,
"e": 25963,
"s": 25935,
"text": "\n16 Apr, 2021"
},
{
"code": null,
"e": 26120,
"s": 25963,
"text": "You are given N distinct numbers. You are tasked with finding the number of groups of 2 or 3 that can be formed whose sum is divisible by three.Examples : "
},
{
"code": null,
"e": 26403,
"s": 26120,
"text": "Input : 1 5 7 2 9 14\nOutput : 13\nThe groups of two that can be \nformed are:\n(1, 5)\n(5, 7)\n(1, 2)\n(2, 7)\n(1, 14)\n(7, 14)\nThe groups of three are:\n(1, 5, 9)\n(5, 7, 9)\n(1, 2, 9)\n(2, 7, 9)\n(2, 5, 14)\n(1, 9, 14)\n(7, 9, 14)\n\nInput : 3 6 9 12\nOutput : 10\nAll groups of 2 and 3 are valid."
},
{
"code": null,
"e": 26788,
"s": 26405,
"text": "Naive Approach : For each number, we can add it up with every other number and see if the sum is divisible by 3. We then store these sums, so that we can add each number again to check for groups of three. Time Complexity: O(N^2) for groups of 2, O(N^3) for groups of 3 Auxiliary Space: O(N^2)Optimum Approach If we carefully look at every number, we realize that 3 options exist: "
},
{
"code": null,
"e": 26923,
"s": 26788,
"text": "The number is divisible by 3The number leaves a remainder of 1, when divided by 3The number leaves a remainder of 2, when divided by 3"
},
{
"code": null,
"e": 26952,
"s": 26923,
"text": "The number is divisible by 3"
},
{
"code": null,
"e": 27006,
"s": 26952,
"text": "The number leaves a remainder of 1, when divided by 3"
},
{
"code": null,
"e": 27060,
"s": 27006,
"text": "The number leaves a remainder of 2, when divided by 3"
},
{
"code": null,
"e": 27829,
"s": 27060,
"text": "Now, for groups of two being divisible by 3, either both number have to belong to category 1 (both are divisible by 3), or one number should leave a remainder 1, and the other a remainder 2. This way the remainders add up to 3, making the sum divisible by 3. To form a group of three, either all three numbers should give the same remainder, or one should give remainder 0, another should give 1, and the last should give 2.In this way, we do not care about the numbers themselves, but their respective remainders. Thus by grouping them into three categories, we can find the total possible groups using a simple formula. Let C1 be number of elements divisible by 3. Let C2 be number of elements leaving remainder 1. Let C3 be number of elements leaving remainder 2. "
},
{
"code": null,
"e": 28138,
"s": 27829,
"text": "Answer = \nC2 * C3 + C1 * (C1 - 1) / 2 --> Groups of 2\n+ C1 * (C1 - 1) * (C1 - 2) / 6 \n+ C2 * (C2 - 1) * (C2 - 2) / 6 \n+ C3 * (C3 - 1) * (C3 - 2) / 6 --> Groups of 3 \n with elements of same remainder\n+ C1 * C2 * C3 --> Groups of three with all\n distinct remainders"
},
{
"code": null,
"e": 28144,
"s": 28140,
"text": "CPP"
},
{
"code": null,
"e": 28149,
"s": 28144,
"text": "Java"
},
{
"code": null,
"e": 28157,
"s": 28149,
"text": "Python3"
},
{
"code": null,
"e": 28160,
"s": 28157,
"text": "C#"
},
{
"code": null,
"e": 28164,
"s": 28160,
"text": "PHP"
},
{
"code": null,
"e": 28175,
"s": 28164,
"text": "Javascript"
},
{
"code": "// Program to find groups of 2 or 3// whose sum is divisible by 3#include <iostream>using namespace std; int numOfCombinations(int arr[], int N){ // Initialize groups to 0 int C[3] = { 0, 0, 0 }; // Increment group with specified remainder for (int i = 0; i < N; ++i) ++C[arr[i] % 3]; // Return groups using the formula return C[1] * C[2] + C[0] * (C[0] - 1) / 2 + C[0] * (C[0] - 1) * (C[0] - 2) / 6 + C[1] * (C[1] - 1) * (C[1] - 2) / 6 + C[2] * (C[2] - 1) * (C[2] - 2) / 6 + C[0] * C[1] * C[2];} // Driver Functionint main(){ int arr1[6] = { 1, 5, 7, 2, 9, 14 }; cout << numOfCombinations(arr1, 6) << \"\\n\"; int arr2[4] = { 3, 6, 9, 12 }; cout << numOfCombinations(arr2, 4) << \"\\n\"; return 0;}",
"e": 28911,
"s": 28175,
"text": null
},
{
"code": "// Program to find groups of 2 or 3// whose sum is divisible by 3 class GFG { static int numOfCombinations(int arr[], int N) { // Initialize groups to 0 int C[] = { 0, 0, 0 }; // Increment group with specified remainder for (int i = 0; i < N; ++i) ++C[arr[i] % 3]; // Return groups using the formula return C[1] * C[2] + C[0] * (C[0] - 1) / 2 + C[0] * (C[0] - 1) * (C[0] - 2) / 6 + C[1] * (C[1] - 1) * (C[1] - 2) / 6 + C[2] * (C[2] - 1) * (C[2] - 2) / 6 + C[0] * C[1] * C[2]; } // Driver code public static void main(String[] args) { int arr1[] = { 1, 5, 7, 2, 9, 14 }; System.out.print(numOfCombinations(arr1, 6) + \"\\n\"); int arr2[] = { 3, 6, 9, 12 }; System.out.print(numOfCombinations(arr2, 4) + \"\\n\"); }} // This code is contributed by Anant Agarwal.",
"e": 29772,
"s": 28911,
"text": null
},
{
"code": "# Program to find groups of 2 or 3# whose sum is divisible by 3 def numOfCombinations(arr, N): # Initialize groups to 0 C = [0, 0, 0] # Increment group with # specified remainder for i in range(N): C[arr[i] % 3]= C[arr[i] % 3]+1 # Return groups using the formula return (C[1] * C[2] + C[0] * (C[0] - 1) / 2 + C[0] * (C[0] - 1) * (C[0] - 2) / 6 + C[1] * (C[1] - 1) * (C[1] - 2) / 6 + C[2] * (C[2] - 1) * (C[2] - 2) / 6 + C[0] * C[1] * C[2]) # Driver code arr1 = [1, 5, 7, 2, 9, 14]print(int(numOfCombinations(arr1, 6)))arr2 = [3, 6, 9, 12]print(int(numOfCombinations(arr2, 4))) # This code is contributed# by Anant Agarwal.",
"e": 30437,
"s": 29772,
"text": null
},
{
"code": "// C# Program to find groups of 2 or// 3 whose sum is divisible by 3using System; class GFG { // Function to find number of combinations static int numOfCombinations(int[] arr, int N) { // Initialize groups to 0 int[] C = { 0, 0, 0 }; // Increment group with specified remainder for (int i = 0; i < N; ++i) ++C[arr[i] % 3]; // Return groups using the formula return C[1] * C[2] + C[0] * (C[0] - 1) / 2 + C[0] * (C[0] - 1) * (C[0] - 2) / 6 + C[1] * (C[1] - 1) * (C[1] - 2) / 6 + C[2] * (C[2] - 1) * (C[2] - 2) / 6 + C[0] * C[1] * C[2]; } // Driver code public static void Main() { int[] arr1 = { 1, 5, 7, 2, 9, 14 }; Console.WriteLine(numOfCombinations(arr1, 6)); int[] arr2 = { 3, 6, 9, 12 }; Console.WriteLine(numOfCombinations(arr2, 4)); }} // This code is contributed by vt_m.",
"e": 31359,
"s": 30437,
"text": null
},
{
"code": "<?php // PHP Program to find// groups of 2 or 3// whose sum is divisible by 3 function numOfCombinations($arr, $N){ // Initialize groups to 0 $C = array(0, 0, 0); // Increment group with // specified remainder for ($i = 0; $i < $N; ++$i) ++$C[$arr[$i] % 3]; // Return groups using the formula return $C[1] * $C[2] + $C[0] * ($C[0] - 1) / 2 + $C[0] * ($C[0] - 1) * ($C[0] - 2) / 6 + $C[1] * ($C[1] - 1) * ($C[1] - 2) / 6 + $C[2] * ($C[2] - 1) * ($C[2] - 2) / 6 + $C[0] * $C[1] * $C[2];} // Driver Code$arr1 = array(1, 5, 7, 2, 9, 14);echo numOfCombinations($arr1, 6), \"\\n\"; $arr2 = array(3, 6, 9, 12); echo numOfCombinations($arr2, 4), \"\\n\"; // This code is contributed by ajit?>",
"e": 32176,
"s": 31359,
"text": null
},
{
"code": "<script>// Javascript Program to find// groups of 2 or 3// whose sum is divisible by 3function numOfCombinations(arr, N){ // Initialize groups to 0 let C = [0, 0, 0]; // Increment group with // specified remainder for (let i = 0; i < N; ++i) ++C[arr[i] % 3]; // Return groups using the formula return C[1] * C[2] + C[0] * (C[0] - 1) / 2 + C[0] * (C[0] - 1) * (C[0] - 2) / 6 + C[1] * (C[1] - 1) * (C[1] - 2) / 6 + C[2] * (C[2] - 1) * (C[2] - 2) / 6 + C[0] * C[1] * C[2];} // Driver Codelet arr1 = [1, 5, 7, 2, 9, 14];document.write(numOfCombinations(arr1, 6) + \"<br>\"); let arr2 = [3, 6, 9, 12];document.write(numOfCombinations(arr2, 4) + \"<br>\"); // This code is contributed by gfgking.</script>",
"e": 32983,
"s": 32176,
"text": null
},
{
"code": null,
"e": 32994,
"s": 32983,
"text": "Output : "
},
{
"code": null,
"e": 33000,
"s": 32994,
"text": "13\n10"
},
{
"code": null,
"e": 33437,
"s": 33000,
"text": "Asked in AmazonThis article is contributed by Aditya Kamath. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 33442,
"s": 33437,
"text": "vt_m"
},
{
"code": null,
"e": 33448,
"s": 33442,
"text": "jit_t"
},
{
"code": null,
"e": 33456,
"s": 33448,
"text": "gfgking"
},
{
"code": null,
"e": 33463,
"s": 33456,
"text": "Amazon"
},
{
"code": null,
"e": 33476,
"s": 33463,
"text": "divisibility"
},
{
"code": null,
"e": 33489,
"s": 33476,
"text": "Mathematical"
},
{
"code": null,
"e": 33496,
"s": 33489,
"text": "Amazon"
},
{
"code": null,
"e": 33509,
"s": 33496,
"text": "Mathematical"
},
{
"code": null,
"e": 33607,
"s": 33509,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33651,
"s": 33607,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 33693,
"s": 33651,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 33724,
"s": 33693,
"text": "Modular multiplicative inverse"
},
{
"code": null,
"e": 33795,
"s": 33724,
"text": "Count all possible paths from top left to bottom right of a mXn matrix"
},
{
"code": null,
"e": 33820,
"s": 33795,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 33852,
"s": 33820,
"text": "Check if a number is Palindrome"
},
{
"code": null,
"e": 33885,
"s": 33852,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 33920,
"s": 33885,
"text": "Count ways to reach the n'th stair"
},
{
"code": null,
"e": 33966,
"s": 33920,
"text": "Merge two sorted arrays with O(1) extra space"
}
] |
Concatenate images using OpenCV in Python - GeeksforGeeks
|
28 Jul, 2020
To concatenate images vertically and horizontally with Python, cv2 library comes with two functions as:
hconcat(): It is used as cv2.hconcat() to concatenate images horizontally. Here h means horizontal.vconcat(): It is used as cv2.vconcat() to concatenate images vertically. Here v means vertical.
hconcat(): It is used as cv2.hconcat() to concatenate images horizontally. Here h means horizontal.
vconcat(): It is used as cv2.vconcat() to concatenate images vertically. Here v means vertical.
A list of images as an n-dimensional array is passed in which images in the list are concatenated vertically or horizontally. Images with different sizes can be resized. The following ways to concatenate the images is explained through below the code as:
Python3
# import cv2 libraryimport cv2 # read the imagesimg1 = cv2.imread('sea.jpg')img2 = cv2.imread('man.jpeg')
Concatenate vertically: cv2.vconcat() is used to combine images of same width vertically.
Python3
# vertically concatenates images # of same width im_v = cv2.vconcat([img1, img1]) # show the output imagecv2.imshow('sea_image.jpg', im_v)
Output:
sea_image.jpg
Concatenate horizontally: cv2.hconcat() is used to combine images of same height horizontally.
Python3
# horizontally concatenates images# of same height im_h = cv2.hconcat([img2, img2]) # show the output imagecv2.imshow('man_image.jpeg', im_h)
Output:
man_image.jpeg
Concatenate images of different widths vertically: It is used to combine images of different widths. here shape[0] represents height and shape[1] represents width.
Python3
# define a function for vertically # concatenating images of different# widths def vconcat_resize(img_list, interpolation = cv2.INTER_CUBIC): # take minimum width w_min = min(img.shape[1] for img in img_list) # resizing images im_list_resize = [cv2.resize(img, (w_min, int(img.shape[0] * w_min / img.shape[1])), interpolation = interpolation) for img in img_list] # return final image return cv2.vconcat(im_list_resize) # function callingimg_v_resize = vconcat_resize([img1, img2, img1]) # show the output imagecv2.imwrite('vconcat_resize.jpg', img_v_resize)
Output:
vconcat_resize.jpg
Concatenate images of different heights horizontally: It is used to combine images of different heights.
Python3
# define a function for horizontally # concatenating images of different# heights def hconcat_resize(img_list, interpolation = cv2.INTER_CUBIC): # take minimum hights h_min = min(img.shape[0] for img in img_list) # image resizing im_list_resize = [cv2.resize(img, (int(img.shape[1] * h_min / img.shape[0]), h_min), interpolation = interpolation) for img in img_list] # return final image return cv2.hconcat(im_list_resize) # function callingimg_h_resize = hconcat_resize([img1, img2, img1]) # show the Output imagecv2.imshow('hconcat_resize.jpg', img_h_resize)
Output:
hconcat_resize.jpg
Concatenate images of the same size vertically and horizontally: images can be combined using both cv2.hconcat() and cv2.vconcat() in tile form using a 2D list.
Python3
# define a function for vertically # concatenating images of the # same size and horizontallydef concat_vh(list_2d): # return final image return cv2.vconcat([cv2.hconcat(list_h) for list_h in list_2d])# image resizingimg1_s = cv2.resize(img1, dsize = (0,0), fx = 0.5, fy = 0.5) # function callingimg_tile = concat_vh([[img1_s, img1_s, img1_s], [img1_s, img1_s, img1_s], [img1_s, img1_s, img1_s]])# show the output imagecv2.imshow('concat_vh.jpg', img_tile)
Output:
concat_vh.jpg
Concatenate images of different sizes in vertical and horizontal tiles: Resizing and concatenating functions defined above are used to combine images of different sizes in vertical and horizontal tiles.
Python3
# define a function for concatenating# images of different sizes in# vertical and horizontal tilesdef concat_tile_resize(list_2d, interpolation = cv2.INTER_CUBIC): # function calling for every # list of images img_list_v = [hconcat_resize(list_h, interpolation = cv2.INTER_CUBIC) for list_h in list_2d] # return final image return vconcat_resize(img_list_v, interpolation=cv2.INTER_CUBIC) # function callingim_tile_resize = concat_tile_resize([[img1], [img1, img2, img1, img2, img1], [img1, img2, img1]])# show the imagecv2.imshow('concat_tile_resize.jpg', im_tile_resize)
Output:
concat_tile_resize.jpg
Python-OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
|
[
{
"code": null,
"e": 26397,
"s": 26369,
"text": "\n28 Jul, 2020"
},
{
"code": null,
"e": 26501,
"s": 26397,
"text": "To concatenate images vertically and horizontally with Python, cv2 library comes with two functions as:"
},
{
"code": null,
"e": 26696,
"s": 26501,
"text": "hconcat(): It is used as cv2.hconcat() to concatenate images horizontally. Here h means horizontal.vconcat(): It is used as cv2.vconcat() to concatenate images vertically. Here v means vertical."
},
{
"code": null,
"e": 26796,
"s": 26696,
"text": "hconcat(): It is used as cv2.hconcat() to concatenate images horizontally. Here h means horizontal."
},
{
"code": null,
"e": 26892,
"s": 26796,
"text": "vconcat(): It is used as cv2.vconcat() to concatenate images vertically. Here v means vertical."
},
{
"code": null,
"e": 27147,
"s": 26892,
"text": "A list of images as an n-dimensional array is passed in which images in the list are concatenated vertically or horizontally. Images with different sizes can be resized. The following ways to concatenate the images is explained through below the code as:"
},
{
"code": null,
"e": 27155,
"s": 27147,
"text": "Python3"
},
{
"code": "# import cv2 libraryimport cv2 # read the imagesimg1 = cv2.imread('sea.jpg')img2 = cv2.imread('man.jpeg')",
"e": 27262,
"s": 27155,
"text": null
},
{
"code": null,
"e": 27352,
"s": 27262,
"text": "Concatenate vertically: cv2.vconcat() is used to combine images of same width vertically."
},
{
"code": null,
"e": 27360,
"s": 27352,
"text": "Python3"
},
{
"code": "# vertically concatenates images # of same width im_v = cv2.vconcat([img1, img1]) # show the output imagecv2.imshow('sea_image.jpg', im_v)",
"e": 27500,
"s": 27360,
"text": null
},
{
"code": null,
"e": 27508,
"s": 27500,
"text": "Output:"
},
{
"code": null,
"e": 27522,
"s": 27508,
"text": "sea_image.jpg"
},
{
"code": null,
"e": 27617,
"s": 27522,
"text": "Concatenate horizontally: cv2.hconcat() is used to combine images of same height horizontally."
},
{
"code": null,
"e": 27625,
"s": 27617,
"text": "Python3"
},
{
"code": "# horizontally concatenates images# of same height im_h = cv2.hconcat([img2, img2]) # show the output imagecv2.imshow('man_image.jpeg', im_h)",
"e": 27768,
"s": 27625,
"text": null
},
{
"code": null,
"e": 27777,
"s": 27768,
"text": "Output: "
},
{
"code": null,
"e": 27792,
"s": 27777,
"text": "man_image.jpeg"
},
{
"code": null,
"e": 27956,
"s": 27792,
"text": "Concatenate images of different widths vertically: It is used to combine images of different widths. here shape[0] represents height and shape[1] represents width."
},
{
"code": null,
"e": 27964,
"s": 27956,
"text": "Python3"
},
{
"code": "# define a function for vertically # concatenating images of different# widths def vconcat_resize(img_list, interpolation = cv2.INTER_CUBIC): # take minimum width w_min = min(img.shape[1] for img in img_list) # resizing images im_list_resize = [cv2.resize(img, (w_min, int(img.shape[0] * w_min / img.shape[1])), interpolation = interpolation) for img in img_list] # return final image return cv2.vconcat(im_list_resize) # function callingimg_v_resize = vconcat_resize([img1, img2, img1]) # show the output imagecv2.imwrite('vconcat_resize.jpg', img_v_resize)",
"e": 28660,
"s": 27964,
"text": null
},
{
"code": null,
"e": 28668,
"s": 28660,
"text": "Output:"
},
{
"code": null,
"e": 28687,
"s": 28668,
"text": "vconcat_resize.jpg"
},
{
"code": null,
"e": 28793,
"s": 28687,
"text": "Concatenate images of different heights horizontally: It is used to combine images of different heights."
},
{
"code": null,
"e": 28801,
"s": 28793,
"text": "Python3"
},
{
"code": "# define a function for horizontally # concatenating images of different# heights def hconcat_resize(img_list, interpolation = cv2.INTER_CUBIC): # take minimum hights h_min = min(img.shape[0] for img in img_list) # image resizing im_list_resize = [cv2.resize(img, (int(img.shape[1] * h_min / img.shape[0]), h_min), interpolation = interpolation) for img in img_list] # return final image return cv2.hconcat(im_list_resize) # function callingimg_h_resize = hconcat_resize([img1, img2, img1]) # show the Output imagecv2.imshow('hconcat_resize.jpg', img_h_resize)",
"e": 29550,
"s": 28801,
"text": null
},
{
"code": null,
"e": 29558,
"s": 29550,
"text": "Output:"
},
{
"code": null,
"e": 29577,
"s": 29558,
"text": "hconcat_resize.jpg"
},
{
"code": null,
"e": 29739,
"s": 29577,
"text": "Concatenate images of the same size vertically and horizontally: images can be combined using both cv2.hconcat() and cv2.vconcat() in tile form using a 2D list."
},
{
"code": null,
"e": 29747,
"s": 29739,
"text": "Python3"
},
{
"code": "# define a function for vertically # concatenating images of the # same size and horizontallydef concat_vh(list_2d): # return final image return cv2.vconcat([cv2.hconcat(list_h) for list_h in list_2d])# image resizingimg1_s = cv2.resize(img1, dsize = (0,0), fx = 0.5, fy = 0.5) # function callingimg_tile = concat_vh([[img1_s, img1_s, img1_s], [img1_s, img1_s, img1_s], [img1_s, img1_s, img1_s]])# show the output imagecv2.imshow('concat_vh.jpg', img_tile)",
"e": 30303,
"s": 29747,
"text": null
},
{
"code": null,
"e": 30311,
"s": 30303,
"text": "Output:"
},
{
"code": null,
"e": 30325,
"s": 30311,
"text": "concat_vh.jpg"
},
{
"code": null,
"e": 30528,
"s": 30325,
"text": "Concatenate images of different sizes in vertical and horizontal tiles: Resizing and concatenating functions defined above are used to combine images of different sizes in vertical and horizontal tiles."
},
{
"code": null,
"e": 30538,
"s": 30530,
"text": "Python3"
},
{
"code": "# define a function for concatenating# images of different sizes in# vertical and horizontal tilesdef concat_tile_resize(list_2d, interpolation = cv2.INTER_CUBIC): # function calling for every # list of images img_list_v = [hconcat_resize(list_h, interpolation = cv2.INTER_CUBIC) for list_h in list_2d] # return final image return vconcat_resize(img_list_v, interpolation=cv2.INTER_CUBIC) # function callingim_tile_resize = concat_tile_resize([[img1], [img1, img2, img1, img2, img1], [img1, img2, img1]])# show the imagecv2.imshow('concat_tile_resize.jpg', im_tile_resize)",
"e": 31319,
"s": 30538,
"text": null
},
{
"code": null,
"e": 31327,
"s": 31319,
"text": "Output:"
},
{
"code": null,
"e": 31350,
"s": 31327,
"text": "concat_tile_resize.jpg"
},
{
"code": null,
"e": 31364,
"s": 31350,
"text": "Python-OpenCV"
},
{
"code": null,
"e": 31371,
"s": 31364,
"text": "Python"
},
{
"code": null,
"e": 31469,
"s": 31371,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31487,
"s": 31469,
"text": "Python Dictionary"
},
{
"code": null,
"e": 31522,
"s": 31487,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 31554,
"s": 31522,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 31576,
"s": 31554,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 31618,
"s": 31576,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 31648,
"s": 31618,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 31674,
"s": 31648,
"text": "Python String | replace()"
},
{
"code": null,
"e": 31703,
"s": 31674,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 31747,
"s": 31703,
"text": "Reading and Writing to text files in Python"
}
] |
Python VLC MediaPlayer – Setting Volume - GeeksforGeeks
|
11 Apr, 2022
In this article we will see how we can set volume of the MediaPlayer object in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. MediaPlayer object is the basic object in vlc module for playing the video. VLC offer us to change the volume of the media, it can be set in the form of percentage i.e 0 means mute and 100 means maximum sound.
In order to do this we will use audio_set_volume method with the MediaPlayer object
Syntax : media_player.audio_set_volume(n)
Argument : It takes integer as argument
Return : It returns if the volume was set, -1 if it was out of range
Below is the implementation
Python3
# importing vlc moduleimport vlc # importing time moduleimport time # creating vlc media player objectmedia_player = vlc.MediaPlayer() # media objectmedia = vlc.Media("death_note.mkv") # setting media to the media playermedia_player.set_media(media) # setting video scalemedia_player.video_set_scale(0.6) # setting volumemedia_player.audio_set_volume(50) # start playing videomedia_player.play() # wait so the video can be played for 5 seconds# irrespective for length of videotime.sleep(5)
Output : Another example Below is the implementation
Python3
# importing vlc moduleimport vlc # importing time moduleimport time # creating vlc media player objectmedia_player = vlc.MediaPlayer() # media objectmedia = vlc.Media("1mp4.mkv") # setting media to the media playermedia_player.set_media(media) # setting volumemedia_player.audio_set_volume(70) # setting video scalemedia_player.video_set_scale(0.6) # start playing videomedia_player.play() # wait so the video can be played for 5 seconds# irrespective for length of videotime.sleep(5)
Output :
simranarora5sos
Python vlc-library
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
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
|
[
{
"code": null,
"e": 25725,
"s": 25697,
"text": "\n11 Apr, 2022"
},
{
"code": null,
"e": 26188,
"s": 25725,
"text": "In this article we will see how we can set volume of the MediaPlayer object in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. MediaPlayer object is the basic object in vlc module for playing the video. VLC offer us to change the volume of the media, it can be set in the form of percentage i.e 0 means mute and 100 means maximum sound."
},
{
"code": null,
"e": 26273,
"s": 26188,
"text": "In order to do this we will use audio_set_volume method with the MediaPlayer object "
},
{
"code": null,
"e": 26316,
"s": 26273,
"text": "Syntax : media_player.audio_set_volume(n) "
},
{
"code": null,
"e": 26357,
"s": 26316,
"text": "Argument : It takes integer as argument "
},
{
"code": null,
"e": 26426,
"s": 26357,
"text": "Return : It returns if the volume was set, -1 if it was out of range"
},
{
"code": null,
"e": 26455,
"s": 26426,
"text": "Below is the implementation "
},
{
"code": null,
"e": 26463,
"s": 26455,
"text": "Python3"
},
{
"code": "# importing vlc moduleimport vlc # importing time moduleimport time # creating vlc media player objectmedia_player = vlc.MediaPlayer() # media objectmedia = vlc.Media(\"death_note.mkv\") # setting media to the media playermedia_player.set_media(media) # setting video scalemedia_player.video_set_scale(0.6) # setting volumemedia_player.audio_set_volume(50) # start playing videomedia_player.play() # wait so the video can be played for 5 seconds# irrespective for length of videotime.sleep(5)",
"e": 26956,
"s": 26463,
"text": null
},
{
"code": null,
"e": 27011,
"s": 26956,
"text": "Output : Another example Below is the implementation "
},
{
"code": null,
"e": 27019,
"s": 27011,
"text": "Python3"
},
{
"code": "# importing vlc moduleimport vlc # importing time moduleimport time # creating vlc media player objectmedia_player = vlc.MediaPlayer() # media objectmedia = vlc.Media(\"1mp4.mkv\") # setting media to the media playermedia_player.set_media(media) # setting volumemedia_player.audio_set_volume(70) # setting video scalemedia_player.video_set_scale(0.6) # start playing videomedia_player.play() # wait so the video can be played for 5 seconds# irrespective for length of videotime.sleep(5)",
"e": 27506,
"s": 27019,
"text": null
},
{
"code": null,
"e": 27516,
"s": 27506,
"text": "Output : "
},
{
"code": null,
"e": 27532,
"s": 27516,
"text": "simranarora5sos"
},
{
"code": null,
"e": 27551,
"s": 27532,
"text": "Python vlc-library"
},
{
"code": null,
"e": 27558,
"s": 27551,
"text": "Python"
},
{
"code": null,
"e": 27656,
"s": 27558,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27674,
"s": 27656,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27706,
"s": 27674,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27728,
"s": 27706,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27770,
"s": 27728,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27800,
"s": 27770,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27826,
"s": 27800,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27855,
"s": 27826,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 27899,
"s": 27855,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 27936,
"s": 27899,
"text": "Create a Pandas DataFrame from Lists"
}
] |
PyQt5 - Getting the text of selected item in ComboBox - GeeksforGeeks
|
22 Apr, 2020
In this article we will see how we can get the text i.e content of current item selected in the combo box, in order to do this we will use the currentText method.
Syntax : combo_box.currentText()
Argument : It takes no argument
Return : It return string
Steps for implementation –
1. Create a combo box2. Add items to combo box3. Create push button4. Add action to the push button5. Create label to show count5. Inside the action get the content of current item selected in combo box with the help of currentText method and store it in variable6. Show the content variable in label with the help of setText method
Below is the implementation –
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating a combo box widget self.combo_box = QComboBox(self) # setting geometry of combo box self.combo_box.setGeometry(200, 150, 120, 30) # geek list geek_list = ["Geek", "Geeky Geek", "Legend Geek", "Ultra Legend Geek"] # adding list of items to combo box self.combo_box.addItems(geek_list) # creating push button button = QPushButton("Show content ", self) print(self.combo_box.count()) # adding action to button button.pressed.connect(self.find) # creating label to self.label = QLabel(self) # setting geometry of the label self.label.setGeometry(200, 200, 200, 30) def find(self): # finding the content of current item in combo box content = self.combo_box.currentText() # showing content on the screen though label self.label.setText("Content : " + content) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
Python PyQt5-ComboBox
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
sum() function in Python
isupper(), islower(), lower(), upper() in Python and their applications
How to drop one or multiple columns in Pandas Dataframe
|
[
{
"code": null,
"e": 26071,
"s": 26043,
"text": "\n22 Apr, 2020"
},
{
"code": null,
"e": 26234,
"s": 26071,
"text": "In this article we will see how we can get the text i.e content of current item selected in the combo box, in order to do this we will use the currentText method."
},
{
"code": null,
"e": 26267,
"s": 26234,
"text": "Syntax : combo_box.currentText()"
},
{
"code": null,
"e": 26299,
"s": 26267,
"text": "Argument : It takes no argument"
},
{
"code": null,
"e": 26325,
"s": 26299,
"text": "Return : It return string"
},
{
"code": null,
"e": 26352,
"s": 26325,
"text": "Steps for implementation –"
},
{
"code": null,
"e": 26685,
"s": 26352,
"text": "1. Create a combo box2. Add items to combo box3. Create push button4. Add action to the push button5. Create label to show count5. Inside the action get the content of current item selected in combo box with the help of currentText method and store it in variable6. Show the content variable in label with the help of setText method"
},
{
"code": null,
"e": 26715,
"s": 26685,
"text": "Below is the implementation –"
},
{
"code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating a combo box widget self.combo_box = QComboBox(self) # setting geometry of combo box self.combo_box.setGeometry(200, 150, 120, 30) # geek list geek_list = [\"Geek\", \"Geeky Geek\", \"Legend Geek\", \"Ultra Legend Geek\"] # adding list of items to combo box self.combo_box.addItems(geek_list) # creating push button button = QPushButton(\"Show content \", self) print(self.combo_box.count()) # adding action to button button.pressed.connect(self.find) # creating label to self.label = QLabel(self) # setting geometry of the label self.label.setGeometry(200, 200, 200, 30) def find(self): # finding the content of current item in combo box content = self.combo_box.currentText() # showing content on the screen though label self.label.setText(\"Content : \" + content) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 28318,
"s": 26715,
"text": null
},
{
"code": null,
"e": 28327,
"s": 28318,
"text": "Output :"
},
{
"code": null,
"e": 28349,
"s": 28327,
"text": "Python PyQt5-ComboBox"
},
{
"code": null,
"e": 28360,
"s": 28349,
"text": "Python-gui"
},
{
"code": null,
"e": 28372,
"s": 28360,
"text": "Python-PyQt"
},
{
"code": null,
"e": 28379,
"s": 28372,
"text": "Python"
},
{
"code": null,
"e": 28477,
"s": 28379,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28509,
"s": 28477,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28551,
"s": 28509,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28580,
"s": 28551,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 28617,
"s": 28580,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 28653,
"s": 28617,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 28695,
"s": 28653,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28737,
"s": 28695,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28762,
"s": 28737,
"text": "sum() function in Python"
},
{
"code": null,
"e": 28834,
"s": 28762,
"text": "isupper(), islower(), lower(), upper() in Python and their applications"
}
] |
Rearrange array to obtain maximum possible value of concatenation of prefix GCDs - GeeksforGeeks
|
28 Feb, 2022
Given an array arr[] consisting of N positive integers, the task is to rearrange the array elements such that the number formed by concatenating the GCD of elements of the array arr[] from index 0 to i for each index i is the maximum possible.
Examples:
Input: arr[] = {4, 2, 5}Output: 5 4 2Explanation:X = 511 is the maximum value of X that can be obtained among all the rearrangement of arr[].Possible arrangements of arr[] are:arr[] = [2, 4, 5] → X = 221arr[] = [2, 5, 4] → X = 211arr[] = [4, 2, 5] → X = 421arr[] = [4, 5, 2] → X = 411arr[] = [5, 4, 2] → X = 511arr[] = [5, 2, 4] → X = 511
Input: arr[] = {2, 4, 6, 8}Output: 8 4 6 2Explanation: X = 842 is the maximum value of X that can be obtained among all the rearrangement of arr[].Possible arrangements of arr[] are:arr[] = [4, 6, 8] → X = 422arr[] = [4, 8, 6] → X = 442arr[] = [6, 4, 8] → X = 622arr[] = [6, 8, 4] → X = 622arr[] = [8, 4, 6] → X = 842arr[] = [8, 6, 4] → X = 822
Approach: The GCD of a number alone is the number itself, thus the first digit of X i.e., X[0] would always be equal to arr[0]. Thus, to ensure that X is maximum among all obtainable numbers, arr[0] needs to be maximum. Then proceed by keeping track of the GCD of the longest prefix of arr[] that has been already arranged and find the values of the consecutive elements to be placed after this prefix. Follow the steps below to solve the above problem:
The largest element of the array is set as the first element, thus the first prefix correctly arranged in the array arr[].Now find the element consecutive to the last element of the prefix i.e., arr[1].Here the GCD of the longest prefix(say G) is equal to arr[0], thus traverse the remaining array to find the element that gives the greatest GCD with G.Now, swap the element arr[1] with the element that gives maximum GCD with value G, update the value of G to this maximum GCD obtained i.e., G = GCD(G, arr[1]).Now the longest fixed prefix becomes arr[0], arr[1], continue this process for finding arr[2], arr[3], ..., arr[N – 1], to obtain the required array.Print rearrange array after the above steps.
The largest element of the array is set as the first element, thus the first prefix correctly arranged in the array arr[].
Now find the element consecutive to the last element of the prefix i.e., arr[1].
Here the GCD of the longest prefix(say G) is equal to arr[0], thus traverse the remaining array to find the element that gives the greatest GCD with G.
Now, swap the element arr[1] with the element that gives maximum GCD with value G, update the value of G to this maximum GCD obtained i.e., G = GCD(G, arr[1]).
Now the longest fixed prefix becomes arr[0], arr[1], continue this process for finding arr[2], arr[3], ..., arr[N – 1], to obtain the required array.
Print rearrange array after the above steps.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the maximum number// obtainable from prefix GCDsvoid prefixGCD(int arr[], int N){ // Stores the GCD of the // longest prefix int gcc; // Sort the array sort(arr, arr + N); // Reverse the array reverse(arr, arr + N); // GCD of a[0] is a[0] gcc = arr[0]; int start = 0; // Iterate to place the arr[start + 1] // element at it's correct position while (start < N - 1) { int g = 0, s1; for (int i = start + 1; i < N; i++) { // Find the element with // maximum GCD int gc = __gcd(gcc, arr[i]); // Update the value of g if (gc > g) { g = gc; s1 = i; } } // Update GCD of prefix gcc = g; // Place arr[s1] to it's // correct position swap(arr[s1], arr[start + 1]); // Increment start for the // remaining elements start++; } // Print the rearranged array for (int i = 0; i < N; i++) { cout << arr[i] << " "; }} // Driver Codeint main(){ // Given array arr[] int arr[] = { 1, 2, 3, 4 }; int N = sizeof(arr) / sizeof(arr[0]); // Function Call prefixGCD(arr, N); return 0;}
//Java program for// the above approachimport java.util.*;class GFG{ //Function to find the maximum number//obtainable from prefix GCDsstatic void prefixGCD(int arr[], int N){ // Stores the GCD of the // longest prefix int gcc; // Sort the array Arrays.sort(arr); // Reverse the array arr = reverse(arr); // GCD of a[0] is a[0] gcc = arr[0]; int start = 0; // Iterate to place // the arr[start + 1] // element at it's // correct position while (start < N - 1) { int g = 0, s1 = 0; for (int i = start + 1; i < N; i++) { // Find the element with // maximum GCD int gc = __gcd(gcc, arr[i]); // Update the value of g if (gc > g) { g = gc; s1 = i; } } // Update GCD of prefix gcc = g; // Place arr[s1] to it's // correct position arr = swap(arr, s1, start + 1); // Increment start for the // remaining elements start++; } // Print the rearranged array for (int i = 0; i < N; i++) { System.out.print(arr[i] + " "); }} static int __gcd(int a, int b) { return b == 0 ? a : __gcd(b, a % b); } static int[] reverse(int a[]){ int i, n = a.length, t; for (i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } return a;} static int[] swap(int []arr, int i, int j){ int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; return arr;} //Driver Codepublic static void main(String[] args){ // Given array arr[] int arr[] = {1, 2, 3, 4}; int N = arr.length; // Function Call prefixGCD(arr, N);}} //This code is contributed by 29AjayKumar
# Python3 program for the above approachfrom math import gcd # Function to find the maximum number# obtainable from prefix GCDsdef prefixGCD(arr, N): # Stores the GCD of the # longest prefix gcc = 0 # Sort the array arr = sorted(arr) # Reverse the array arr = arr[::-1] # GCD of a[0] is a[0] gcc = arr[0] start = 0 # Iterate to place the arr[start + 1] # element at it's correct position while (start < N - 1): g = 0 s1 = 0 for i in range(start + 1, N): # Find the element with # maximum GCD gc = gcd(gcc, arr[i]) # Update the value of g if (gc > g): g = gc s1 = i # Update GCD of prefix gcc = g # Place arr[s1] to it's # correct position arr[s1], arr[start + 1] = arr[start + 1], arr[s1] # Increment start for the # remaining elements start += 1 # Print the rearranged array for i in range(N): print(arr[i], end = " ") # Driver Codeif __name__ == '__main__': # Given array arr[] arr = [ 1, 2, 3, 4 ] N = len(arr) # Function Call prefixGCD(arr, N) # This code is contributed by mohit kumar 29
// C# program for the above approach using System;class GFG{ // Function to find the maximum number// obtainable from prefix GCDsstatic void prefixGCD(int[] arr, int N){ // Stores the GCD of the // longest prefix int gcc; // Sort the array Array.Sort(arr); // Reverse the array arr = reverse(arr); // GCD of a[0] is a[0] gcc = arr[0]; int start = 0; // Iterate to place the // arr[start + 1] element // at it's correct position while (start < N - 1) { int g = 0, s1 = 0; for(int i = start + 1; i < N; i++) { // Find the element with // maximum GCD int gc = __gcd(gcc, arr[i]); // Update the value of g if (gc > g) { g = gc; s1 = i; } } // Update GCD of prefix gcc = g; // Place arr[s1] to it's // correct position arr = swap(arr, s1, start + 1); // Increment start for the // remaining elements start++; } // Print the rearranged array for(int i = 0; i < N; i++) { Console.Write(arr[i] + " "); }} static int __gcd(int a, int b) { return b == 0 ? a : __gcd(b, a % b); } static int[] reverse(int[] a){ int i, n = a.Length, t; for(i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } return a;} static int[] swap(int []arr, int i, int j){ int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; return arr;} //Driver Codepublic static void Main(){ // Given array arr[] int[] arr = { 1, 2, 3, 4 }; int N = arr.Length; // Function call prefixGCD(arr, N);}} // This code is contributed by sanjoy_62
<script> // Javascript program to implement// the above approach //Function to find the maximum number//obtainable from prefix GCDsfunction prefixGCD(arr, N){ // Stores the GCD of the // longest prefix let gcc; // Sort the array arr.sort(); // Reverse the array arr = reverse(arr); // GCD of a[0] is a[0] gcc = arr[0]; let start = 0; // Iterate to place // the arr[start + 1] // element at it's // correct position while (start < N - 1) { let g = 0, s1 = 0; for (let i = start + 1; i < N; i++) { // Find the element with // maximum GCD let gc = __gcd(gcc, arr[i]); // Update the value of g if (gc > g) { g = gc; s1 = i; } } // Update GCD of prefix gcc = g; // Place arr[s1] to it's // correct position arr = swap(arr, s1, start + 1); // Increment start for the // remaining elements start++; } // Print the rearranged array for (let i = 0; i < N; i++) { document.write(arr[i] + " "); }} function __gcd(a, b) { return b == 0 ? a : __gcd(b, a % b); } function reverse(a){ let i, n = a.length, t; for (i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } return a;} function swap(arr, i, j){ let temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; return arr;} // Driver Code // Given array arr[] let arr = [1, 2, 3, 4]; let N = arr.length; // Function Call prefixGCD(arr, N); </script>
4 2 3 1
Time Complexity: O(N2)Auxiliary Space: O(1)
mohit kumar 29
29AjayKumar
sanjoy_62
target_2
simranarora5sos
array-rearrange
HCF
Arrays
Mathematical
Arrays
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count pairs with given sum
Chocolate Distribution Problem
Window Sliding Technique
Reversal algorithm for array rotation
Next Greater Element
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": 26041,
"s": 26013,
"text": "\n28 Feb, 2022"
},
{
"code": null,
"e": 26285,
"s": 26041,
"text": "Given an array arr[] consisting of N positive integers, the task is to rearrange the array elements such that the number formed by concatenating the GCD of elements of the array arr[] from index 0 to i for each index i is the maximum possible."
},
{
"code": null,
"e": 26295,
"s": 26285,
"text": "Examples:"
},
{
"code": null,
"e": 26634,
"s": 26295,
"text": "Input: arr[] = {4, 2, 5}Output: 5 4 2Explanation:X = 511 is the maximum value of X that can be obtained among all the rearrangement of arr[].Possible arrangements of arr[] are:arr[] = [2, 4, 5] → X = 221arr[] = [2, 5, 4] → X = 211arr[] = [4, 2, 5] → X = 421arr[] = [4, 5, 2] → X = 411arr[] = [5, 4, 2] → X = 511arr[] = [5, 2, 4] → X = 511"
},
{
"code": null,
"e": 26979,
"s": 26634,
"text": "Input: arr[] = {2, 4, 6, 8}Output: 8 4 6 2Explanation: X = 842 is the maximum value of X that can be obtained among all the rearrangement of arr[].Possible arrangements of arr[] are:arr[] = [4, 6, 8] → X = 422arr[] = [4, 8, 6] → X = 442arr[] = [6, 4, 8] → X = 622arr[] = [6, 8, 4] → X = 622arr[] = [8, 4, 6] → X = 842arr[] = [8, 6, 4] → X = 822"
},
{
"code": null,
"e": 27433,
"s": 26979,
"text": "Approach: The GCD of a number alone is the number itself, thus the first digit of X i.e., X[0] would always be equal to arr[0]. Thus, to ensure that X is maximum among all obtainable numbers, arr[0] needs to be maximum. Then proceed by keeping track of the GCD of the longest prefix of arr[] that has been already arranged and find the values of the consecutive elements to be placed after this prefix. Follow the steps below to solve the above problem:"
},
{
"code": null,
"e": 28139,
"s": 27433,
"text": "The largest element of the array is set as the first element, thus the first prefix correctly arranged in the array arr[].Now find the element consecutive to the last element of the prefix i.e., arr[1].Here the GCD of the longest prefix(say G) is equal to arr[0], thus traverse the remaining array to find the element that gives the greatest GCD with G.Now, swap the element arr[1] with the element that gives maximum GCD with value G, update the value of G to this maximum GCD obtained i.e., G = GCD(G, arr[1]).Now the longest fixed prefix becomes arr[0], arr[1], continue this process for finding arr[2], arr[3], ..., arr[N – 1], to obtain the required array.Print rearrange array after the above steps."
},
{
"code": null,
"e": 28262,
"s": 28139,
"text": "The largest element of the array is set as the first element, thus the first prefix correctly arranged in the array arr[]."
},
{
"code": null,
"e": 28343,
"s": 28262,
"text": "Now find the element consecutive to the last element of the prefix i.e., arr[1]."
},
{
"code": null,
"e": 28495,
"s": 28343,
"text": "Here the GCD of the longest prefix(say G) is equal to arr[0], thus traverse the remaining array to find the element that gives the greatest GCD with G."
},
{
"code": null,
"e": 28655,
"s": 28495,
"text": "Now, swap the element arr[1] with the element that gives maximum GCD with value G, update the value of G to this maximum GCD obtained i.e., G = GCD(G, arr[1])."
},
{
"code": null,
"e": 28805,
"s": 28655,
"text": "Now the longest fixed prefix becomes arr[0], arr[1], continue this process for finding arr[2], arr[3], ..., arr[N – 1], to obtain the required array."
},
{
"code": null,
"e": 28850,
"s": 28805,
"text": "Print rearrange array after the above steps."
},
{
"code": null,
"e": 28901,
"s": 28850,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 28905,
"s": 28901,
"text": "C++"
},
{
"code": null,
"e": 28910,
"s": 28905,
"text": "Java"
},
{
"code": null,
"e": 28918,
"s": 28910,
"text": "Python3"
},
{
"code": null,
"e": 28921,
"s": 28918,
"text": "C#"
},
{
"code": null,
"e": 28932,
"s": 28921,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the maximum number// obtainable from prefix GCDsvoid prefixGCD(int arr[], int N){ // Stores the GCD of the // longest prefix int gcc; // Sort the array sort(arr, arr + N); // Reverse the array reverse(arr, arr + N); // GCD of a[0] is a[0] gcc = arr[0]; int start = 0; // Iterate to place the arr[start + 1] // element at it's correct position while (start < N - 1) { int g = 0, s1; for (int i = start + 1; i < N; i++) { // Find the element with // maximum GCD int gc = __gcd(gcc, arr[i]); // Update the value of g if (gc > g) { g = gc; s1 = i; } } // Update GCD of prefix gcc = g; // Place arr[s1] to it's // correct position swap(arr[s1], arr[start + 1]); // Increment start for the // remaining elements start++; } // Print the rearranged array for (int i = 0; i < N; i++) { cout << arr[i] << \" \"; }} // Driver Codeint main(){ // Given array arr[] int arr[] = { 1, 2, 3, 4 }; int N = sizeof(arr) / sizeof(arr[0]); // Function Call prefixGCD(arr, N); return 0;}",
"e": 30262,
"s": 28932,
"text": null
},
{
"code": "//Java program for// the above approachimport java.util.*;class GFG{ //Function to find the maximum number//obtainable from prefix GCDsstatic void prefixGCD(int arr[], int N){ // Stores the GCD of the // longest prefix int gcc; // Sort the array Arrays.sort(arr); // Reverse the array arr = reverse(arr); // GCD of a[0] is a[0] gcc = arr[0]; int start = 0; // Iterate to place // the arr[start + 1] // element at it's // correct position while (start < N - 1) { int g = 0, s1 = 0; for (int i = start + 1; i < N; i++) { // Find the element with // maximum GCD int gc = __gcd(gcc, arr[i]); // Update the value of g if (gc > g) { g = gc; s1 = i; } } // Update GCD of prefix gcc = g; // Place arr[s1] to it's // correct position arr = swap(arr, s1, start + 1); // Increment start for the // remaining elements start++; } // Print the rearranged array for (int i = 0; i < N; i++) { System.out.print(arr[i] + \" \"); }} static int __gcd(int a, int b) { return b == 0 ? a : __gcd(b, a % b); } static int[] reverse(int a[]){ int i, n = a.length, t; for (i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } return a;} static int[] swap(int []arr, int i, int j){ int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; return arr;} //Driver Codepublic static void main(String[] args){ // Given array arr[] int arr[] = {1, 2, 3, 4}; int N = arr.length; // Function Call prefixGCD(arr, N);}} //This code is contributed by 29AjayKumar",
"e": 31873,
"s": 30262,
"text": null
},
{
"code": "# Python3 program for the above approachfrom math import gcd # Function to find the maximum number# obtainable from prefix GCDsdef prefixGCD(arr, N): # Stores the GCD of the # longest prefix gcc = 0 # Sort the array arr = sorted(arr) # Reverse the array arr = arr[::-1] # GCD of a[0] is a[0] gcc = arr[0] start = 0 # Iterate to place the arr[start + 1] # element at it's correct position while (start < N - 1): g = 0 s1 = 0 for i in range(start + 1, N): # Find the element with # maximum GCD gc = gcd(gcc, arr[i]) # Update the value of g if (gc > g): g = gc s1 = i # Update GCD of prefix gcc = g # Place arr[s1] to it's # correct position arr[s1], arr[start + 1] = arr[start + 1], arr[s1] # Increment start for the # remaining elements start += 1 # Print the rearranged array for i in range(N): print(arr[i], end = \" \") # Driver Codeif __name__ == '__main__': # Given array arr[] arr = [ 1, 2, 3, 4 ] N = len(arr) # Function Call prefixGCD(arr, N) # This code is contributed by mohit kumar 29",
"e": 33118,
"s": 31873,
"text": null
},
{
"code": "// C# program for the above approach using System;class GFG{ // Function to find the maximum number// obtainable from prefix GCDsstatic void prefixGCD(int[] arr, int N){ // Stores the GCD of the // longest prefix int gcc; // Sort the array Array.Sort(arr); // Reverse the array arr = reverse(arr); // GCD of a[0] is a[0] gcc = arr[0]; int start = 0; // Iterate to place the // arr[start + 1] element // at it's correct position while (start < N - 1) { int g = 0, s1 = 0; for(int i = start + 1; i < N; i++) { // Find the element with // maximum GCD int gc = __gcd(gcc, arr[i]); // Update the value of g if (gc > g) { g = gc; s1 = i; } } // Update GCD of prefix gcc = g; // Place arr[s1] to it's // correct position arr = swap(arr, s1, start + 1); // Increment start for the // remaining elements start++; } // Print the rearranged array for(int i = 0; i < N; i++) { Console.Write(arr[i] + \" \"); }} static int __gcd(int a, int b) { return b == 0 ? a : __gcd(b, a % b); } static int[] reverse(int[] a){ int i, n = a.Length, t; for(i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } return a;} static int[] swap(int []arr, int i, int j){ int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; return arr;} //Driver Codepublic static void Main(){ // Given array arr[] int[] arr = { 1, 2, 3, 4 }; int N = arr.Length; // Function call prefixGCD(arr, N);}} // This code is contributed by sanjoy_62",
"e": 34733,
"s": 33118,
"text": null
},
{
"code": "<script> // Javascript program to implement// the above approach //Function to find the maximum number//obtainable from prefix GCDsfunction prefixGCD(arr, N){ // Stores the GCD of the // longest prefix let gcc; // Sort the array arr.sort(); // Reverse the array arr = reverse(arr); // GCD of a[0] is a[0] gcc = arr[0]; let start = 0; // Iterate to place // the arr[start + 1] // element at it's // correct position while (start < N - 1) { let g = 0, s1 = 0; for (let i = start + 1; i < N; i++) { // Find the element with // maximum GCD let gc = __gcd(gcc, arr[i]); // Update the value of g if (gc > g) { g = gc; s1 = i; } } // Update GCD of prefix gcc = g; // Place arr[s1] to it's // correct position arr = swap(arr, s1, start + 1); // Increment start for the // remaining elements start++; } // Print the rearranged array for (let i = 0; i < N; i++) { document.write(arr[i] + \" \"); }} function __gcd(a, b) { return b == 0 ? a : __gcd(b, a % b); } function reverse(a){ let i, n = a.length, t; for (i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } return a;} function swap(arr, i, j){ let temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; return arr;} // Driver Code // Given array arr[] let arr = [1, 2, 3, 4]; let N = arr.length; // Function Call prefixGCD(arr, N); </script>",
"e": 36189,
"s": 34733,
"text": null
},
{
"code": null,
"e": 36197,
"s": 36189,
"text": "4 2 3 1"
},
{
"code": null,
"e": 36243,
"s": 36199,
"text": "Time Complexity: O(N2)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 36258,
"s": 36243,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 36270,
"s": 36258,
"text": "29AjayKumar"
},
{
"code": null,
"e": 36280,
"s": 36270,
"text": "sanjoy_62"
},
{
"code": null,
"e": 36289,
"s": 36280,
"text": "target_2"
},
{
"code": null,
"e": 36305,
"s": 36289,
"text": "simranarora5sos"
},
{
"code": null,
"e": 36321,
"s": 36305,
"text": "array-rearrange"
},
{
"code": null,
"e": 36325,
"s": 36321,
"text": "HCF"
},
{
"code": null,
"e": 36332,
"s": 36325,
"text": "Arrays"
},
{
"code": null,
"e": 36345,
"s": 36332,
"text": "Mathematical"
},
{
"code": null,
"e": 36352,
"s": 36345,
"text": "Arrays"
},
{
"code": null,
"e": 36365,
"s": 36352,
"text": "Mathematical"
},
{
"code": null,
"e": 36463,
"s": 36365,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36490,
"s": 36463,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 36521,
"s": 36490,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 36546,
"s": 36521,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 36584,
"s": 36546,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 36605,
"s": 36584,
"text": "Next Greater Element"
},
{
"code": null,
"e": 36635,
"s": 36605,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 36695,
"s": 36635,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 36710,
"s": 36695,
"text": "C++ Data Types"
},
{
"code": null,
"e": 36753,
"s": 36710,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Remove last n rows of a Pandas DataFrame - GeeksforGeeks
|
29 Jul, 2021
Let’s see the various methods to Remove last n rows of a Pandas Dataframe.First, let’s make a dataframe:
Python3
# Import Required Librariesimport pandas as pd # Create a dictionary for the dataframedict = { 'Name': ['Sukritin', 'Sumit Tyagi', 'Akriti Goel', 'Sanskriti', 'Abhishek Jain'], 'Age': [22, 20, 45, 21, 22], 'Marks': [90, 84, -33, -87, 82]} # Converting Dictionary to# Pandas Dataframedf = pd.DataFrame(dict) # Print Dataframeprint(df)
Output:
Method 1: Using Dataframe.drop() .We can remove the last n rows using the drop() method. drop() method gets an inplace argument which takes a boolean value. If inplace attribute is set to True then the dataframe gets updated with the new value of dataframe (dataframe with last n rows removed).
Example:
Python3
# Import Required Librariesimport pandas as pd # Create a dictionary for the dataframedict = { 'Name': ['Sukritin', 'Sumit Tyagi', 'Akriti Goel', 'Sanskriti', 'Abhishek Jain'], 'Age': [22, 20, 45, 21, 22], 'Marks': [90, 84, -33, -87, 82]} # Converting Dictionary to# Pandas Dataframedf = pd.DataFrame(dict) # Number of rows to dropn = 3 # Dropping last n rows using dropdf.drop(df.tail(n).index, inplace = True) # Printing dataframeprint(df)
Output:
Method 2: Using Dataframe.iloc[ ].
This method is used when the index label of a data frame is something other than numeric series of 0, 1, 2, 3....n or in case the user doesn’t know the index label.
Example:
Python3
# Import Required Librariesimport pandas as pd # Create a dictionary for the dataframedict = { 'Name': ['Sukritin', 'Sumit Tyagi', 'Akriti Goel', 'Sanskriti', 'Abhishek Jain'], 'Age': [22, 20, 45, 21, 22], 'Marks': [90, 84, -33, -87, 82]} # Converting Dictionary to# Pandas Dataframedf = pd.DataFrame(dict) # Number of rows to dropn = 3 # Removing last n rowsdf_dropped_last_n = df.iloc[:-n] # Printing dataframeprint(df_dropped_last_n)
Output:
Method 3: Using Dataframe.head().
This method is used to return top n (5 by default) rows of a data frame or series.
Example:
Python3
# Import Required Librariesimport pandas as pd # Create a dictionary for the dataframedict = { 'Name': ['Sukritin', 'Sumit Tyagi', 'Akriti Goel', 'Sanskriti', 'Abhishek Jain'], 'Age': [22, 20, 45, 21, 22], 'Marks': [90, 84, -33, -87, 82]} # Converting Dictionary to# Pandas Dataframedf = pd.DataFrame(dict) # Number of rows to dropn = 3 # Using head() to# drop last n rowsdf1 = df.head(-n) # Printing dataframeprint(df1)
Output:
Method 4: Using Dataframe slicing [ ].
Example:
Python3
# Import Required Librariesimport pandas as pd # Create a dictionary for the dataframedict = { 'Name': ['Sukritin', 'Sumit Tyagi', 'Akriti Goel', 'Sanskriti', 'Abhishek Jain'], 'Age': [22, 20, 45, 21, 22], 'Marks': [90, 84, -33, -87, 82]} # Converting Dictionary to# Pandas Dataframedf = pd.DataFrame(dict) # Number of rows to dropn = 3 # Slicing last n rowsdf1 = df[:-n] # Printing dataframeprint(df1)
Output:
surindertarika1234
Picked
Python pandas-basics
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
|
[
{
"code": null,
"e": 26287,
"s": 26259,
"text": "\n29 Jul, 2021"
},
{
"code": null,
"e": 26392,
"s": 26287,
"text": "Let’s see the various methods to Remove last n rows of a Pandas Dataframe.First, let’s make a dataframe:"
},
{
"code": null,
"e": 26400,
"s": 26392,
"text": "Python3"
},
{
"code": "# Import Required Librariesimport pandas as pd # Create a dictionary for the dataframedict = { 'Name': ['Sukritin', 'Sumit Tyagi', 'Akriti Goel', 'Sanskriti', 'Abhishek Jain'], 'Age': [22, 20, 45, 21, 22], 'Marks': [90, 84, -33, -87, 82]} # Converting Dictionary to# Pandas Dataframedf = pd.DataFrame(dict) # Print Dataframeprint(df)",
"e": 26748,
"s": 26400,
"text": null
},
{
"code": null,
"e": 26761,
"s": 26752,
"text": "Output: "
},
{
"code": null,
"e": 27060,
"s": 26765,
"text": "Method 1: Using Dataframe.drop() .We can remove the last n rows using the drop() method. drop() method gets an inplace argument which takes a boolean value. If inplace attribute is set to True then the dataframe gets updated with the new value of dataframe (dataframe with last n rows removed)."
},
{
"code": null,
"e": 27071,
"s": 27062,
"text": "Example:"
},
{
"code": null,
"e": 27081,
"s": 27073,
"text": "Python3"
},
{
"code": "# Import Required Librariesimport pandas as pd # Create a dictionary for the dataframedict = { 'Name': ['Sukritin', 'Sumit Tyagi', 'Akriti Goel', 'Sanskriti', 'Abhishek Jain'], 'Age': [22, 20, 45, 21, 22], 'Marks': [90, 84, -33, -87, 82]} # Converting Dictionary to# Pandas Dataframedf = pd.DataFrame(dict) # Number of rows to dropn = 3 # Dropping last n rows using dropdf.drop(df.tail(n).index, inplace = True) # Printing dataframeprint(df)",
"e": 27544,
"s": 27081,
"text": null
},
{
"code": null,
"e": 27553,
"s": 27544,
"text": "Output: "
},
{
"code": null,
"e": 27590,
"s": 27555,
"text": "Method 2: Using Dataframe.iloc[ ]."
},
{
"code": null,
"e": 27756,
"s": 27590,
"text": "This method is used when the index label of a data frame is something other than numeric series of 0, 1, 2, 3....n or in case the user doesn’t know the index label. "
},
{
"code": null,
"e": 27765,
"s": 27756,
"text": "Example:"
},
{
"code": null,
"e": 27773,
"s": 27765,
"text": "Python3"
},
{
"code": "# Import Required Librariesimport pandas as pd # Create a dictionary for the dataframedict = { 'Name': ['Sukritin', 'Sumit Tyagi', 'Akriti Goel', 'Sanskriti', 'Abhishek Jain'], 'Age': [22, 20, 45, 21, 22], 'Marks': [90, 84, -33, -87, 82]} # Converting Dictionary to# Pandas Dataframedf = pd.DataFrame(dict) # Number of rows to dropn = 3 # Removing last n rowsdf_dropped_last_n = df.iloc[:-n] # Printing dataframeprint(df_dropped_last_n)",
"e": 28224,
"s": 27773,
"text": null
},
{
"code": null,
"e": 28237,
"s": 28228,
"text": "Output: "
},
{
"code": null,
"e": 28279,
"s": 28245,
"text": "Method 3: Using Dataframe.head()."
},
{
"code": null,
"e": 28364,
"s": 28281,
"text": "This method is used to return top n (5 by default) rows of a data frame or series."
},
{
"code": null,
"e": 28375,
"s": 28366,
"text": "Example:"
},
{
"code": null,
"e": 28385,
"s": 28377,
"text": "Python3"
},
{
"code": "# Import Required Librariesimport pandas as pd # Create a dictionary for the dataframedict = { 'Name': ['Sukritin', 'Sumit Tyagi', 'Akriti Goel', 'Sanskriti', 'Abhishek Jain'], 'Age': [22, 20, 45, 21, 22], 'Marks': [90, 84, -33, -87, 82]} # Converting Dictionary to# Pandas Dataframedf = pd.DataFrame(dict) # Number of rows to dropn = 3 # Using head() to# drop last n rowsdf1 = df.head(-n) # Printing dataframeprint(df1)",
"e": 28820,
"s": 28385,
"text": null
},
{
"code": null,
"e": 28829,
"s": 28820,
"text": "Output: "
},
{
"code": null,
"e": 28870,
"s": 28831,
"text": "Method 4: Using Dataframe slicing [ ]."
},
{
"code": null,
"e": 28879,
"s": 28870,
"text": "Example:"
},
{
"code": null,
"e": 28887,
"s": 28879,
"text": "Python3"
},
{
"code": "# Import Required Librariesimport pandas as pd # Create a dictionary for the dataframedict = { 'Name': ['Sukritin', 'Sumit Tyagi', 'Akriti Goel', 'Sanskriti', 'Abhishek Jain'], 'Age': [22, 20, 45, 21, 22], 'Marks': [90, 84, -33, -87, 82]} # Converting Dictionary to# Pandas Dataframedf = pd.DataFrame(dict) # Number of rows to dropn = 3 # Slicing last n rowsdf1 = df[:-n] # Printing dataframeprint(df1)",
"e": 29304,
"s": 28887,
"text": null
},
{
"code": null,
"e": 29318,
"s": 29308,
"text": "Output: "
},
{
"code": null,
"e": 29341,
"s": 29322,
"text": "surindertarika1234"
},
{
"code": null,
"e": 29348,
"s": 29341,
"text": "Picked"
},
{
"code": null,
"e": 29369,
"s": 29348,
"text": "Python pandas-basics"
},
{
"code": null,
"e": 29376,
"s": 29369,
"text": "Python"
},
{
"code": null,
"e": 29474,
"s": 29376,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29492,
"s": 29474,
"text": "Python Dictionary"
},
{
"code": null,
"e": 29527,
"s": 29492,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 29559,
"s": 29527,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29581,
"s": 29559,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 29623,
"s": 29581,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 29653,
"s": 29623,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 29679,
"s": 29653,
"text": "Python String | replace()"
},
{
"code": null,
"e": 29708,
"s": 29679,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 29752,
"s": 29708,
"text": "Reading and Writing to text files in Python"
}
] |
PyQt5 QComboBox - Setting mouse tracking - GeeksforGeeks
|
10 May, 2020
In this article we will see how we can set mouse tracking to the combo box, combo box receive signal about the mouse when any button is pressed but after mouse tracking it will receive all the signals about the mouse even if any button is not pressed. By default this property is False.
In order to turn on the mouse tracking we use setMouseTracking method
Syntax : combo_box.setMouseTracking(bool)
Argument : It takes bool as argument
Return : It returns None
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating a check-able combo box object self.combo_box = QComboBox(self) # setting geometry of combo box self.combo_box.setGeometry(200, 150, 100, 30) # geek list geek_list = ["Sayian", "Super Sayian", "Super Sayian 2", "Super Sayian B"] # adding list of items to combo box self.combo_box.addItems(geek_list) # setting mouse tracking self.combo_box.setMouseTracking(True) # setting stylesheet of the combo box self.combo_box.setStyleSheet("border : 1px solid red;") # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
Python PyQt-SpinBox
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Defaultdict in Python
Enumerate() in Python
sum() function in Python
Python String | replace()
Read a file line by line in Python
How to Install PIP on Windows ?
Deque in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
|
[
{
"code": null,
"e": 26233,
"s": 26205,
"text": "\n10 May, 2020"
},
{
"code": null,
"e": 26520,
"s": 26233,
"text": "In this article we will see how we can set mouse tracking to the combo box, combo box receive signal about the mouse when any button is pressed but after mouse tracking it will receive all the signals about the mouse even if any button is not pressed. By default this property is False."
},
{
"code": null,
"e": 26590,
"s": 26520,
"text": "In order to turn on the mouse tracking we use setMouseTracking method"
},
{
"code": null,
"e": 26632,
"s": 26590,
"text": "Syntax : combo_box.setMouseTracking(bool)"
},
{
"code": null,
"e": 26669,
"s": 26632,
"text": "Argument : It takes bool as argument"
},
{
"code": null,
"e": 26694,
"s": 26669,
"text": "Return : It returns None"
},
{
"code": null,
"e": 26722,
"s": 26694,
"text": "Below is the implementation"
},
{
"code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating a check-able combo box object self.combo_box = QComboBox(self) # setting geometry of combo box self.combo_box.setGeometry(200, 150, 100, 30) # geek list geek_list = [\"Sayian\", \"Super Sayian\", \"Super Sayian 2\", \"Super Sayian B\"] # adding list of items to combo box self.combo_box.addItems(geek_list) # setting mouse tracking self.combo_box.setMouseTracking(True) # setting stylesheet of the combo box self.combo_box.setStyleSheet(\"border : 1px solid red;\") # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 27954,
"s": 26722,
"text": null
},
{
"code": null,
"e": 27963,
"s": 27954,
"text": "Output :"
},
{
"code": null,
"e": 27983,
"s": 27963,
"text": "Python PyQt-SpinBox"
},
{
"code": null,
"e": 27994,
"s": 27983,
"text": "Python-gui"
},
{
"code": null,
"e": 28006,
"s": 27994,
"text": "Python-PyQt"
},
{
"code": null,
"e": 28013,
"s": 28006,
"text": "Python"
},
{
"code": null,
"e": 28111,
"s": 28013,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28129,
"s": 28111,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28151,
"s": 28129,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28173,
"s": 28151,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28198,
"s": 28173,
"text": "sum() function in Python"
},
{
"code": null,
"e": 28224,
"s": 28198,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28259,
"s": 28224,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28291,
"s": 28259,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28307,
"s": 28291,
"text": "Deque in Python"
},
{
"code": null,
"e": 28349,
"s": 28307,
"text": "Different ways to create Pandas Dataframe"
}
] |
How to select ID that starts with certain character using jQuery ? - GeeksforGeeks
|
28 Jun, 2019
Given an HTML document and the task is to select the elements with ID starts with certain characters using jQuery.
Approach: Use jQuery [attribute^=value] Selector to select the element with ID starts with certain characters.
Example 1: This example selects that element whose ID starts with ‘GFG’ and change their background color.
<!DOCTYPE HTML> <html> <head> <title> How to select ID starts with certain character in jQuery ? </title> <style> #GFG_DIV { background: green; height: 100px; width: 200px; margin: 0 auto; color: white; } </style> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 19px; font-weight: bold;"> </p> <div id = "GFG_DIV"> This is Div box. </div> <br> <button onClick = "GFG_Fun()"> click here </button> <p id = "GFG_DOWN" style = "color: green; font-size: 24px; font-weight: bold;"> </p> <script> $('#GFG_UP').text("Click on button to change " + "background-color of element's " + "ID starts with 'GFG'"); function GFG_Fun() { $( "[id^='GFG']" ).css("background-color", "pink"); $('#GFG_DOWN').text("Div hides after 1 second."); } </script> </body> </html>
Output:
Before clicking the button:
After clicking the button:
Example 2: This example selects the elements whose ID starts with ‘GFG’ and set their background color.
<!DOCTYPE HTML> <html> <head> <title> How to select ID starts with certain character in jQuery ? </title> <style> #GFG_DIV { background: green; height: 100px; width: 200px; margin: 0 auto; color: white; } </style> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 19px; font-weight: bold;"> </p> <div id = "GFG_DIV"> This is Div box. </div> <br> <button onClick = "GFG_Fun()"> click here </button> <p id = "GFG_DOWN" style = "color: green; font-size: 24px; font-weight: bold;"> </p> <script> $('#GFG_UP').text("Click on button to change " + "background-color of element's " + "ID starts with 'GFG'"); function GFG_Fun() { var value = "GFG"; $("[id^='" + value + "']" ).css("background-color", "pink"); $('#GFG_DOWN').text("Div hides after 1 second."); } </script> </body> </html>
Output:
Before clicking the button:
After clicking the button:
jQuery-Misc
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
|
[
{
"code": null,
"e": 25929,
"s": 25901,
"text": "\n28 Jun, 2019"
},
{
"code": null,
"e": 26044,
"s": 25929,
"text": "Given an HTML document and the task is to select the elements with ID starts with certain characters using jQuery."
},
{
"code": null,
"e": 26155,
"s": 26044,
"text": "Approach: Use jQuery [attribute^=value] Selector to select the element with ID starts with certain characters."
},
{
"code": null,
"e": 26262,
"s": 26155,
"text": "Example 1: This example selects that element whose ID starts with ‘GFG’ and change their background color."
},
{
"code": "<!DOCTYPE HTML> <html> <head> <title> How to select ID starts with certain character in jQuery ? </title> <style> #GFG_DIV { background: green; height: 100px; width: 200px; margin: 0 auto; color: white; } </style> <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 19px; font-weight: bold;\"> </p> <div id = \"GFG_DIV\"> This is Div box. </div> <br> <button onClick = \"GFG_Fun()\"> click here </button> <p id = \"GFG_DOWN\" style = \"color: green; font-size: 24px; font-weight: bold;\"> </p> <script> $('#GFG_UP').text(\"Click on button to change \" + \"background-color of element's \" + \"ID starts with 'GFG'\"); function GFG_Fun() { $( \"[id^='GFG']\" ).css(\"background-color\", \"pink\"); $('#GFG_DOWN').text(\"Div hides after 1 second.\"); } </script> </body> </html> ",
"e": 27732,
"s": 26262,
"text": null
},
{
"code": null,
"e": 27740,
"s": 27732,
"text": "Output:"
},
{
"code": null,
"e": 27768,
"s": 27740,
"text": "Before clicking the button:"
},
{
"code": null,
"e": 27795,
"s": 27768,
"text": "After clicking the button:"
},
{
"code": null,
"e": 27899,
"s": 27795,
"text": "Example 2: This example selects the elements whose ID starts with ‘GFG’ and set their background color."
},
{
"code": "<!DOCTYPE HTML> <html> <head> <title> How to select ID starts with certain character in jQuery ? </title> <style> #GFG_DIV { background: green; height: 100px; width: 200px; margin: 0 auto; color: white; } </style> <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 19px; font-weight: bold;\"> </p> <div id = \"GFG_DIV\"> This is Div box. </div> <br> <button onClick = \"GFG_Fun()\"> click here </button> <p id = \"GFG_DOWN\" style = \"color: green; font-size: 24px; font-weight: bold;\"> </p> <script> $('#GFG_UP').text(\"Click on button to change \" + \"background-color of element's \" + \"ID starts with 'GFG'\"); function GFG_Fun() { var value = \"GFG\"; $(\"[id^='\" + value + \"']\" ).css(\"background-color\", \"pink\"); $('#GFG_DOWN').text(\"Div hides after 1 second.\"); } </script> </body> </html> ",
"e": 29412,
"s": 27899,
"text": null
},
{
"code": null,
"e": 29420,
"s": 29412,
"text": "Output:"
},
{
"code": null,
"e": 29448,
"s": 29420,
"text": "Before clicking the button:"
},
{
"code": null,
"e": 29475,
"s": 29448,
"text": "After clicking the button:"
},
{
"code": null,
"e": 29487,
"s": 29475,
"text": "jQuery-Misc"
},
{
"code": null,
"e": 29498,
"s": 29487,
"text": "JavaScript"
},
{
"code": null,
"e": 29515,
"s": 29498,
"text": "Web Technologies"
},
{
"code": null,
"e": 29542,
"s": 29515,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 29640,
"s": 29542,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29680,
"s": 29640,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29725,
"s": 29680,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29786,
"s": 29725,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29858,
"s": 29786,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 29910,
"s": 29858,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 29950,
"s": 29910,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29983,
"s": 29950,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 30028,
"s": 29983,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 30071,
"s": 30028,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Matplotlib.pyplot.gca() in Python - GeeksforGeeks
|
01 Jul, 2021
Matplotlib is a library in Python and it is a numerical – mathematical extension for the NumPy library. Pyplot is a state-based interface to a Matplotlib module that provides a MATLAB-like interface.
The gca() function in pyplot module of matplotlib library is used to get the current Axes instance on the current figure matching the given keyword args, or create one.
Syntax: matplotlib.pyplot.gca(\*\*kwargs)Parameters: This method does not accepts any parameter. Returns: This method does not return any value.
Below examples illustrate the matplotlib.pyplot.gca() function in matplotlib.pyplot:
Example #1:
Python3
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npimport matplotlib.gridspec as gridspecfrom mpl_toolkits.axes_grid1 import make_axes_locatable plt.close('all')arr = np.arange(100).reshape((10, 10))fig = plt.figure(figsize =(4, 4))im = plt.imshow(arr, interpolation ="none", cmap ="plasma") divider = make_axes_locatable(plt.gca())cax = divider.append_axes("left", "15 %", pad ="30 %") plt.colorbar(im, cax = cax) fig.suptitle('matplotlib.pyplot.gca() function\Example\n\n', fontweight ="bold")plt.show()
Output:
Example #2:
Python3
# Implementation of matplotlib functionimport matplotlib.pyplot as pltfrom matplotlib.tri import Triangulationfrom matplotlib.patches import Polygonimport numpy as np def update_polygon(tri): if tri == -1: points = [0, 0, 0] else: points = triang.triangles[tri] xs = triang.x[points] ys = triang.y[points] polygon.set_xy(np.column_stack([xs, ys])) def motion_notify(event): if event.inaxes is None: tri = -1 else: tri = trifinder(event.xdata, event.ydata) update_polygon(tri) plt.title('matplotlib.pyplot.gca() function \ Example\n\n Potion number : % i' % tri, fontweight ="bold") event.canvas.draw() ang = 3radi = 8radii = np.linspace(0.25, 0.95, radi)res = np.linspace(0, 4 * np.pi, ang)res = np.repeat(res[..., np.newaxis], radi, axis = 1)res[:, 1::2] += np.pi / ang x = (radii * np.cos(2 * res)).flatten()y = (radii * np.sin(2 * res)).flatten()triang = Triangulation(x, y)triang.set_mask(np.hypot(x[triang.triangles].mean(axis = 1), y[triang.triangles].mean(axis = 1)) < 0.25) trifinder = triang.get_trifinder() plt.subplot(111, aspect ='equal')plt.triplot(triang, 'go-')polygon = Polygon([[0, 0], [0, 0]], facecolor ='r')update_polygon(-1) plt.gca().add_patch(polygon)plt.gcf().canvas.mpl_connect('motion_notify_event', motion_notify) plt.show()
Output:
codingyash
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
|
[
{
"code": null,
"e": 26178,
"s": 26150,
"text": "\n01 Jul, 2021"
},
{
"code": null,
"e": 26380,
"s": 26178,
"text": "Matplotlib is a library in Python and it is a numerical – mathematical extension for the NumPy library. Pyplot is a state-based interface to a Matplotlib module that provides a MATLAB-like interface. "
},
{
"code": null,
"e": 26551,
"s": 26380,
"text": "The gca() function in pyplot module of matplotlib library is used to get the current Axes instance on the current figure matching the given keyword args, or create one. "
},
{
"code": null,
"e": 26698,
"s": 26551,
"text": "Syntax: matplotlib.pyplot.gca(\\*\\*kwargs)Parameters: This method does not accepts any parameter. Returns: This method does not return any value. "
},
{
"code": null,
"e": 26784,
"s": 26698,
"text": "Below examples illustrate the matplotlib.pyplot.gca() function in matplotlib.pyplot: "
},
{
"code": null,
"e": 26797,
"s": 26784,
"text": "Example #1: "
},
{
"code": null,
"e": 26805,
"s": 26797,
"text": "Python3"
},
{
"code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npimport matplotlib.gridspec as gridspecfrom mpl_toolkits.axes_grid1 import make_axes_locatable plt.close('all')arr = np.arange(100).reshape((10, 10))fig = plt.figure(figsize =(4, 4))im = plt.imshow(arr, interpolation =\"none\", cmap =\"plasma\") divider = make_axes_locatable(plt.gca())cax = divider.append_axes(\"left\", \"15 %\", pad =\"30 %\") plt.colorbar(im, cax = cax) fig.suptitle('matplotlib.pyplot.gca() function\\Example\\n\\n', fontweight =\"bold\")plt.show()",
"e": 27429,
"s": 26805,
"text": null
},
{
"code": null,
"e": 27439,
"s": 27429,
"text": "Output: "
},
{
"code": null,
"e": 27452,
"s": 27439,
"text": "Example #2: "
},
{
"code": null,
"e": 27460,
"s": 27452,
"text": "Python3"
},
{
"code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltfrom matplotlib.tri import Triangulationfrom matplotlib.patches import Polygonimport numpy as np def update_polygon(tri): if tri == -1: points = [0, 0, 0] else: points = triang.triangles[tri] xs = triang.x[points] ys = triang.y[points] polygon.set_xy(np.column_stack([xs, ys])) def motion_notify(event): if event.inaxes is None: tri = -1 else: tri = trifinder(event.xdata, event.ydata) update_polygon(tri) plt.title('matplotlib.pyplot.gca() function \\ Example\\n\\n Potion number : % i' % tri, fontweight =\"bold\") event.canvas.draw() ang = 3radi = 8radii = np.linspace(0.25, 0.95, radi)res = np.linspace(0, 4 * np.pi, ang)res = np.repeat(res[..., np.newaxis], radi, axis = 1)res[:, 1::2] += np.pi / ang x = (radii * np.cos(2 * res)).flatten()y = (radii * np.sin(2 * res)).flatten()triang = Triangulation(x, y)triang.set_mask(np.hypot(x[triang.triangles].mean(axis = 1), y[triang.triangles].mean(axis = 1)) < 0.25) trifinder = triang.get_trifinder() plt.subplot(111, aspect ='equal')plt.triplot(triang, 'go-')polygon = Polygon([[0, 0], [0, 0]], facecolor ='r')update_polygon(-1) plt.gca().add_patch(polygon)plt.gcf().canvas.mpl_connect('motion_notify_event', motion_notify) plt.show()",
"e": 28911,
"s": 27460,
"text": null
},
{
"code": null,
"e": 28921,
"s": 28911,
"text": "Output: "
},
{
"code": null,
"e": 28934,
"s": 28923,
"text": "codingyash"
},
{
"code": null,
"e": 28952,
"s": 28934,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 28959,
"s": 28952,
"text": "Python"
},
{
"code": null,
"e": 29057,
"s": 28959,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29075,
"s": 29057,
"text": "Python Dictionary"
},
{
"code": null,
"e": 29110,
"s": 29075,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 29142,
"s": 29110,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29164,
"s": 29142,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 29206,
"s": 29164,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 29236,
"s": 29206,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 29262,
"s": 29236,
"text": "Python String | replace()"
},
{
"code": null,
"e": 29291,
"s": 29262,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 29335,
"s": 29291,
"text": "Reading and Writing to text files in Python"
}
] |
Offset-Fetch in MS SQL Server - GeeksforGeeks
|
29 Jul, 2020
Suppose a table has 30 rows. A user wants to extract list of last 10 rows and skip topmost rows. To make job easier, the offset-fetch clause is used in the query.
Syntax :
order by column_list[ASC|DESC]
Offset offset_row count{ROW|ROWS}
Fetch{FIRST|NEXT} fetch row_count {ROW|ROWS} only
Analysis of Syntax :
Order by clause is mandatory to use alongside offset-fetch clause otherwise it results in an error. ASC arranges rows from ascending to descending order while DESC arranges rows from descending to ascending order.
Offset skips number of rows specified in a table.
Fetch returns number of rows after offset clause is being used. It returns specified number of rows.
FIRST returns number of rows at start of table after offset is while NEXT returns consecutive rows after first set of rows.
Example –
If the user wants to skip first two rows and return rest of them, query is given as –
select name, rollnumber, course
from student
order by rollnumber ASC
offset 2 ROWS
Output –
Offset skips number of rows specified in query while order by ASC arranges rows from ascending to descending order. If a user wants to skip first 6 rows and fetch the next ones, query is given as –
select name, rollnumber, course
from student
order by roll number ASC
offset 6 ROWS
fetch FIRST 2 ROWS ONLY
Output –
Offset clause skips all rows specified in table while Fetch clause returns first two rows after offset clause. In the fetch clause, FIRST and NEXT can be used according to user’s requirements. Offset clause is mandatory to use while fetch is optional for use in queries.
DBMS-SQL
SQL-Server
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL Interview Questions
Introduction of B-Tree
SQL Trigger | Student Database
CTE in SQL
Difference between Clustered and Non-clustered index
How to find Nth highest salary from a table
SQL Interview Questions
SQL | ALTER (RENAME)
SQL Trigger | Student Database
CTE in SQL
|
[
{
"code": null,
"e": 25219,
"s": 25191,
"text": "\n29 Jul, 2020"
},
{
"code": null,
"e": 25382,
"s": 25219,
"text": "Suppose a table has 30 rows. A user wants to extract list of last 10 rows and skip topmost rows. To make job easier, the offset-fetch clause is used in the query."
},
{
"code": null,
"e": 25391,
"s": 25382,
"text": "Syntax :"
},
{
"code": null,
"e": 25507,
"s": 25391,
"text": "order by column_list[ASC|DESC]\nOffset offset_row count{ROW|ROWS}\nFetch{FIRST|NEXT} fetch row_count {ROW|ROWS} only\n"
},
{
"code": null,
"e": 25528,
"s": 25507,
"text": "Analysis of Syntax :"
},
{
"code": null,
"e": 25742,
"s": 25528,
"text": "Order by clause is mandatory to use alongside offset-fetch clause otherwise it results in an error. ASC arranges rows from ascending to descending order while DESC arranges rows from descending to ascending order."
},
{
"code": null,
"e": 25792,
"s": 25742,
"text": "Offset skips number of rows specified in a table."
},
{
"code": null,
"e": 25893,
"s": 25792,
"text": "Fetch returns number of rows after offset clause is being used. It returns specified number of rows."
},
{
"code": null,
"e": 26017,
"s": 25893,
"text": "FIRST returns number of rows at start of table after offset is while NEXT returns consecutive rows after first set of rows."
},
{
"code": null,
"e": 26027,
"s": 26017,
"text": "Example –"
},
{
"code": null,
"e": 26113,
"s": 26027,
"text": "If the user wants to skip first two rows and return rest of them, query is given as –"
},
{
"code": null,
"e": 26197,
"s": 26113,
"text": "select name, rollnumber, course\nfrom student \norder by rollnumber ASC\noffset 2 ROWS"
},
{
"code": null,
"e": 26206,
"s": 26197,
"text": "Output –"
},
{
"code": null,
"e": 26404,
"s": 26206,
"text": "Offset skips number of rows specified in query while order by ASC arranges rows from ascending to descending order. If a user wants to skip first 6 rows and fetch the next ones, query is given as –"
},
{
"code": null,
"e": 26513,
"s": 26404,
"text": "select name, rollnumber, course \nfrom student\norder by roll number ASC\noffset 6 ROWS\nfetch FIRST 2 ROWS ONLY"
},
{
"code": null,
"e": 26522,
"s": 26513,
"text": "Output –"
},
{
"code": null,
"e": 26793,
"s": 26522,
"text": "Offset clause skips all rows specified in table while Fetch clause returns first two rows after offset clause. In the fetch clause, FIRST and NEXT can be used according to user’s requirements. Offset clause is mandatory to use while fetch is optional for use in queries."
},
{
"code": null,
"e": 26802,
"s": 26793,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 26813,
"s": 26802,
"text": "SQL-Server"
},
{
"code": null,
"e": 26818,
"s": 26813,
"text": "DBMS"
},
{
"code": null,
"e": 26822,
"s": 26818,
"text": "SQL"
},
{
"code": null,
"e": 26827,
"s": 26822,
"text": "DBMS"
},
{
"code": null,
"e": 26831,
"s": 26827,
"text": "SQL"
},
{
"code": null,
"e": 26929,
"s": 26831,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26953,
"s": 26929,
"text": "SQL Interview Questions"
},
{
"code": null,
"e": 26976,
"s": 26953,
"text": "Introduction of B-Tree"
},
{
"code": null,
"e": 27007,
"s": 26976,
"text": "SQL Trigger | Student Database"
},
{
"code": null,
"e": 27018,
"s": 27007,
"text": "CTE in SQL"
},
{
"code": null,
"e": 27071,
"s": 27018,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 27115,
"s": 27071,
"text": "How to find Nth highest salary from a table"
},
{
"code": null,
"e": 27139,
"s": 27115,
"text": "SQL Interview Questions"
},
{
"code": null,
"e": 27160,
"s": 27139,
"text": "SQL | ALTER (RENAME)"
},
{
"code": null,
"e": 27191,
"s": 27160,
"text": "SQL Trigger | Student Database"
}
] |
Git - Update Operation
|
Tom performs the clone operation and finds a new file string.c. He wants to know who added this file to the repository and for what purpose, so, he executes the git log command.
[tom@CentOS ~]$ git clone gituser@git.server.com:project.git
The above command will produce the following result −
Initialized empty Git repository in /home/tom/project/.git/
remote: Counting objects: 6, done.
remote: Compressing objects: 100% (4/4), done.
Receiving objects: 100% (6/6), 726 bytes, done.
remote: Total 6 (delta 0), reused 0 (delta 0)
The Clone operation will create a new directory inside the current working directory. He changes the directory to newly created directory and executes the git log command.
[tom@CentOS ~]$ cd project/
[tom@CentOS project]$ git log
The above command will produce the following result −
commit d1e19d316224cddc437e3ed34ec3c931ad803958
Author: Jerry Mouse <jerry@tutorialspoint.com>
Date: Wed Sep 11 08:05:26 2013 +0530
Changed return type of my_strlen to size_t
commit 19ae20683fc460db7d127cf201a1429523b0e319
Author: Tom Cat <tom@tutorialspoint.com>
Date: Wed Sep 11 07:32:56 2013 +0530
Initial commit
After observing the log, he realizes that the file string.c was added by Jerry to implement basic string operations. He is curious about Jerry’s code. So he opens string.c in text editor and immediately finds a bug. In my_strlen function, Jerry is not using a constant pointer. So, he decides to modify Jerry’s code. After modification, the code looks as follows −
[tom@CentOS project]$ git diff
The above command will produce the following result −
diff --git a/string.c b/string.c
index 7da2992..32489eb 100644
--- a/string.c
+++ b/string.c
@@ -1,8 +1,8 @@
#include <stdio.h>
-size_t my_strlen(char *s)
+size_t my_strlen(const char *s)
{
- char *p = s;
+ const char *p = s;
while (*p)
++p;
}
After testing, he commits his change.
[tom@CentOS project]$ git status -s
M string.c
?? string
[tom@CentOS project]$ git add string.c
[tom@CentOS project]$ git commit -m 'Changed char pointer to const char pointer'
[master cea2c00] Changed char pointer to const char pointer
1 files changed, 2 insertions(+), 2 deletions(-)
[tom@CentOS project]$ git log
The above command will produce the following result −
commit cea2c000f53ba99508c5959e3e12fff493b
Author: Tom Cat <tom@tutorialspoint.com>
Date: Wed Sep 11 08:32:07 2013 +0530
Changed char pointer to const char pointer
commit d1e19d316224cddc437e3ed34ec3c931ad803958
Author: Jerry Mouse <jerry@tutorialspoint.com>
Date: Wed Sep 11 08:05:26 2013 +0530
Changed return type of my_strlen to size_t
commit 19ae20683fc460db7d127cf201a1429523b0e319
Author: Tom Cat <tom@tutorialspoint.com>
Date: Wed Sep 11 07:32:56 2013 +0530
Initial commit
Tom uses git push command to push his changes.
[tom@CentOS project]$ git push origin master
The above command will produce the following result −
Counting objects: 5, done.
Compressing objects: 100% (3/3), done.
Writing objects: 100% (3/3), 336 bytes, done.
Total 3 (delta 1), reused 0 (delta 0)
To gituser@git.server.com:project.git
d1e19d3..cea2c00 master −> master
Meanwhile, Jerry decides to implement string compare functionality. So he modifies string.c. After modification, the file looks as follows −
[jerry@CentOS project]$ git diff
The above command will produce the following result −
index 7da2992..bc864ed 100644
--- a/string.c
+++ b/string.c
30Git Tutorials
@@ -9,9 +9,20 @@ size_t my_strlen(char *s)
return (p -s );
}
+char *my_strcpy(char *t, char *s)
+
{
+
char *p = t;
+
+ while (*t++ = *s++)
+ ;
+
+
return p;
+
}
+
int main(void)
{
int i;
+
char p1[32];
char *s[] =
{
"Git tutorials",
"Tutorials Point"
@@ -20,5 +31,7 @@ int main(void)
for (i = 0; i < 2; ++i)
printf("string lenght of %s = %lu\n", s[i], my_strlen(s[i]));
+
printf("%s\n", my_strcpy(p1, "Hello, World !!!"));
+
return 0;
}
}
After testing, he is ready to push his change.
[jerry@CentOS project]$ git status -s
M string.c
?? string
[jerry@CentOS project]$ git add string.c
[jerry@CentOS project]$ git commit -m "Added my_strcpy function"
[master e944e5a] Added my_strcpy function
1 files changed, 13 insertions(+), 0 deletions(-)
Before push operation, he verifies commit by viewing log messages.
[jerry@CentOS project]$ git log
The above command will produce the following result −
commit e944e5aab74b26e7447d3281b225309e4e59efcd
Author: Jerry Mouse <jerry@tutorialspoint.com>
Date: Wed Sep 11 08:41:42 2013 +0530
Added my_strcpy function
commit d1e19d316224cddc437e3ed34ec3c931ad803958
Author: Jerry Mouse <jerry@tutorialspoint.com>
Date: Wed Sep 11 08:05:26 2013 +0530
Changed return type of my_strlen to size_t
commit 19ae20683fc460db7d127cf201a1429523b0e319
Author: Tom Cat <tom@tutorialspoint.com>
Date: Wed Sep 11 07:32:56 2013 +0530
Initial commit
Jerry is happy with the changes and he wants to push his changes.
[jerry@CentOS project]$ git push origin master
The above command will produce the following result −
To gituser@git.server.com:project.git
! [rejected]
master −> master (non-fast-forward)
error: failed to push some refs to 'gituser@git.server.com:project.git'
To prevent you from losing history, non-fast-forward updates were rejected
Merge the remote changes before pushing again. See the 'Note about
fast-forwards' section of 'git push --help' for details.
But Git is not allowing Jerry to push his changes. Because Git identified that remote repository and Jerry’s local repository are not in sync. Because of this, he can lose the history of the project. To avoid this mess, Git failed this operation. Now, Jerry has to first update the local repository and only thereafter, he can push his own changes.
Jerry executes the git pull command to synchronize his local repository with the remote one.
[jerry@CentOS project]$ git pull
The above command will produce the following result −
remote: Counting objects: 5, done.
remote: Compressing objects: 100% (3/3), done.
remote: Total 3 (delta 1), reused 0 (delta 0)
Unpacking objects: 100% (3/3), done.
From git.server.com:project
d1e19d3..cea2c00 master −> origin/master
First, rewinding head to replay your work on top of it...
Applying: Added my_strcpy function
After pull operation, Jerry checks the log messages and finds the details of Tom’s commit with commit ID cea2c000f53ba99508c5959e3e12fff493ba6f69
[jerry@CentOS project]$ git log
The above command will produce the following result −
commit e86f0621c2a3f68190bba633a9fe6c57c94f8e4f
Author: Jerry Mouse <jerry@tutorialspoint.com>
Date: Wed Sep 11 08:41:42 2013 +0530
Added my_strcpy function
commit cea2c000f53ba99508c5959e3e12fff493ba6f69
Author: Tom Cat <tom@tutorialspoint.com>
Date: Wed Sep 11 08:32:07 2013 +0530
Changed char pointer to const char pointer
commit d1e19d316224cddc437e3ed34ec3c931ad803958
Author: Jerry Mouse <jerry@tutorialspoint.com>
Date: Wed Sep 11 08:05:26 2013 +0530
Changed return type of my_strlen to size_t
commit 19ae20683fc460db7d127cf201a1429523b0e319
Author: Tom Cat <tom@tutorialspoint.com>
Date: Wed Sep 11 07:32:56 2013 +0530
Initial commit
Now, Jerry’s local repository is fully synchronized with the remote repository. So he can safely push his changes.
[jerry@CentOS project]$ git push origin master
The above command will produce the following result −
Counting objects: 5, done.
Compressing objects: 100% (3/3), done.
Writing objects: 100% (3/3), 455 bytes, done.
Total 3 (delta 1), reused 0 (delta 0)
To gituser@git.server.com:project.git
cea2c00..e86f062 master −> master
251 Lectures
35.5 hours
Gowthami Swarna
23 Lectures
2 hours
Asif Hussain
15 Lectures
1.5 hours
Abhilash Nelson
125 Lectures
9 hours
John Shea
13 Lectures
2.5 hours
Raghu Pandey
13 Lectures
3 hours
Sebastian Sulinski
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2223,
"s": 2045,
"text": "Tom performs the clone operation and finds a new file string.c. He wants to know who added this file to the repository and for what purpose, so, he executes the git log command."
},
{
"code": null,
"e": 2285,
"s": 2223,
"text": "[tom@CentOS ~]$ git clone gituser@git.server.com:project.git\n"
},
{
"code": null,
"e": 2339,
"s": 2285,
"text": "The above command will produce the following result −"
},
{
"code": null,
"e": 2576,
"s": 2339,
"text": "Initialized empty Git repository in /home/tom/project/.git/\nremote: Counting objects: 6, done.\nremote: Compressing objects: 100% (4/4), done.\nReceiving objects: 100% (6/6), 726 bytes, done.\nremote: Total 6 (delta 0), reused 0 (delta 0)\n"
},
{
"code": null,
"e": 2748,
"s": 2576,
"text": "The Clone operation will create a new directory inside the current working directory. He changes the directory to newly created directory and executes the git log command."
},
{
"code": null,
"e": 2808,
"s": 2748,
"text": "[tom@CentOS ~]$ cd project/\n\n[tom@CentOS project]$ git log\n"
},
{
"code": null,
"e": 2862,
"s": 2808,
"text": "The above command will produce the following result −"
},
{
"code": null,
"e": 3183,
"s": 2862,
"text": "commit d1e19d316224cddc437e3ed34ec3c931ad803958\nAuthor: Jerry Mouse <jerry@tutorialspoint.com>\nDate: Wed Sep 11 08:05:26 2013 +0530\n\nChanged return type of my_strlen to size_t\n\n\ncommit 19ae20683fc460db7d127cf201a1429523b0e319\nAuthor: Tom Cat <tom@tutorialspoint.com>\nDate: Wed Sep 11 07:32:56 2013 +0530\n\nInitial commit\n"
},
{
"code": null,
"e": 3548,
"s": 3183,
"text": "After observing the log, he realizes that the file string.c was added by Jerry to implement basic string operations. He is curious about Jerry’s code. So he opens string.c in text editor and immediately finds a bug. In my_strlen function, Jerry is not using a constant pointer. So, he decides to modify Jerry’s code. After modification, the code looks as follows −"
},
{
"code": null,
"e": 3580,
"s": 3548,
"text": "[tom@CentOS project]$ git diff\n"
},
{
"code": null,
"e": 3634,
"s": 3580,
"text": "The above command will produce the following result −"
},
{
"code": null,
"e": 3891,
"s": 3634,
"text": "diff --git a/string.c b/string.c\nindex 7da2992..32489eb 100644\n--- a/string.c\n+++ b/string.c\n@@ -1,8 +1,8 @@\n#include <stdio.h>\n-size_t my_strlen(char *s)\n+size_t my_strlen(const char *s)\n{\n - char *p = s;\n + const char *p = s;\n while (*p)\n ++p;\n}\n"
},
{
"code": null,
"e": 3929,
"s": 3891,
"text": "After testing, he commits his change."
},
{
"code": null,
"e": 4249,
"s": 3929,
"text": "[tom@CentOS project]$ git status -s\nM string.c\n?? string\n\n[tom@CentOS project]$ git add string.c\n\n[tom@CentOS project]$ git commit -m 'Changed char pointer to const char pointer'\n[master cea2c00] Changed char pointer to const char pointer\n1 files changed, 2 insertions(+), 2 deletions(-)\n\n[tom@CentOS project]$ git log\n"
},
{
"code": null,
"e": 4303,
"s": 4249,
"text": "The above command will produce the following result −"
},
{
"code": null,
"e": 4790,
"s": 4303,
"text": "commit cea2c000f53ba99508c5959e3e12fff493b\nAuthor: Tom Cat <tom@tutorialspoint.com>\nDate: Wed Sep 11 08:32:07 2013 +0530\n\nChanged char pointer to const char pointer\n\n\ncommit d1e19d316224cddc437e3ed34ec3c931ad803958\nAuthor: Jerry Mouse <jerry@tutorialspoint.com>\nDate: Wed Sep 11 08:05:26 2013 +0530\n\nChanged return type of my_strlen to size_t\n\n\ncommit 19ae20683fc460db7d127cf201a1429523b0e319\nAuthor: Tom Cat <tom@tutorialspoint.com>\nDate: Wed Sep 11 07:32:56 2013 +0530\nInitial commit\n"
},
{
"code": null,
"e": 4837,
"s": 4790,
"text": "Tom uses git push command to push his changes."
},
{
"code": null,
"e": 4883,
"s": 4837,
"text": "[tom@CentOS project]$ git push origin master\n"
},
{
"code": null,
"e": 4937,
"s": 4883,
"text": "The above command will produce the following result −"
},
{
"code": null,
"e": 5160,
"s": 4937,
"text": "Counting objects: 5, done.\nCompressing objects: 100% (3/3), done.\nWriting objects: 100% (3/3), 336 bytes, done.\nTotal 3 (delta 1), reused 0 (delta 0)\nTo gituser@git.server.com:project.git\nd1e19d3..cea2c00 master −> master\n"
},
{
"code": null,
"e": 5301,
"s": 5160,
"text": "Meanwhile, Jerry decides to implement string compare functionality. So he modifies string.c. After modification, the file looks as follows −"
},
{
"code": null,
"e": 5335,
"s": 5301,
"text": "[jerry@CentOS project]$ git diff\n"
},
{
"code": null,
"e": 5389,
"s": 5335,
"text": "The above command will produce the following result −"
},
{
"code": null,
"e": 6006,
"s": 5389,
"text": "index 7da2992..bc864ed 100644\n--- a/string.c\n+++ b/string.c\n30Git Tutorials\n@@ -9,9 +9,20 @@ size_t my_strlen(char *s)\nreturn (p -s );\n}\n+char *my_strcpy(char *t, char *s)\n+\n{\n +\n char *p = t;\n +\n + while (*t++ = *s++)\n + ;\n +\n +\n return p;\n +\n}\n+\nint main(void)\n{\n int i; \n +\n char p1[32];\n char *s[] = \n {\n \"Git tutorials\",\n \"Tutorials Point\"\n @@ -20,5 +31,7 @@ int main(void)\n for (i = 0; i < 2; ++i)\n printf(\"string lenght of %s = %lu\\n\", s[i], my_strlen(s[i]));\n +\n printf(\"%s\\n\", my_strcpy(p1, \"Hello, World !!!\"));\n +\n return 0;\n }\n}\n"
},
{
"code": null,
"e": 6053,
"s": 6006,
"text": "After testing, he is ready to push his change."
},
{
"code": null,
"e": 6313,
"s": 6053,
"text": "[jerry@CentOS project]$ git status -s\nM string.c\n?? string\n\n[jerry@CentOS project]$ git add string.c\n\n[jerry@CentOS project]$ git commit -m \"Added my_strcpy function\"\n[master e944e5a] Added my_strcpy function\n1 files changed, 13 insertions(+), 0 deletions(-)\n"
},
{
"code": null,
"e": 6380,
"s": 6313,
"text": "Before push operation, he verifies commit by viewing log messages."
},
{
"code": null,
"e": 6413,
"s": 6380,
"text": "[jerry@CentOS project]$ git log\n"
},
{
"code": null,
"e": 6467,
"s": 6413,
"text": "The above command will produce the following result −"
},
{
"code": null,
"e": 6948,
"s": 6467,
"text": "commit e944e5aab74b26e7447d3281b225309e4e59efcd\nAuthor: Jerry Mouse <jerry@tutorialspoint.com>\nDate: Wed Sep 11 08:41:42 2013 +0530\n\nAdded my_strcpy function\n\n\ncommit d1e19d316224cddc437e3ed34ec3c931ad803958\nAuthor: Jerry Mouse <jerry@tutorialspoint.com>\nDate: Wed Sep 11 08:05:26 2013 +0530\n\nChanged return type of my_strlen to size_t\n\n\ncommit 19ae20683fc460db7d127cf201a1429523b0e319\nAuthor: Tom Cat <tom@tutorialspoint.com>\nDate: Wed Sep 11 07:32:56 2013 +0530\n\nInitial commit\n"
},
{
"code": null,
"e": 7014,
"s": 6948,
"text": "Jerry is happy with the changes and he wants to push his changes."
},
{
"code": null,
"e": 7062,
"s": 7014,
"text": "[jerry@CentOS project]$ git push origin master\n"
},
{
"code": null,
"e": 7116,
"s": 7062,
"text": "The above command will produce the following result −"
},
{
"code": null,
"e": 7475,
"s": 7116,
"text": "To gituser@git.server.com:project.git\n! [rejected]\nmaster −> master (non-fast-forward)\nerror: failed to push some refs to 'gituser@git.server.com:project.git'\nTo prevent you from losing history, non-fast-forward updates were rejected\nMerge the remote changes before pushing again. See the 'Note about\nfast-forwards' section of 'git push --help' for details.\n"
},
{
"code": null,
"e": 7824,
"s": 7475,
"text": "But Git is not allowing Jerry to push his changes. Because Git identified that remote repository and Jerry’s local repository are not in sync. Because of this, he can lose the history of the project. To avoid this mess, Git failed this operation. Now, Jerry has to first update the local repository and only thereafter, he can push his own changes."
},
{
"code": null,
"e": 7918,
"s": 7824,
"text": "Jerry executes the git pull command to synchronize his local repository with the remote one."
},
{
"code": null,
"e": 7952,
"s": 7918,
"text": "[jerry@CentOS project]$ git pull\n"
},
{
"code": null,
"e": 8006,
"s": 7952,
"text": "The above command will produce the following result −"
},
{
"code": null,
"e": 8334,
"s": 8006,
"text": "remote: Counting objects: 5, done.\nremote: Compressing objects: 100% (3/3), done.\nremote: Total 3 (delta 1), reused 0 (delta 0)\nUnpacking objects: 100% (3/3), done.\nFrom git.server.com:project\nd1e19d3..cea2c00 master −> origin/master\nFirst, rewinding head to replay your work on top of it...\nApplying: Added my_strcpy function\n"
},
{
"code": null,
"e": 8480,
"s": 8334,
"text": "After pull operation, Jerry checks the log messages and finds the details of Tom’s commit with commit ID cea2c000f53ba99508c5959e3e12fff493ba6f69"
},
{
"code": null,
"e": 8513,
"s": 8480,
"text": "[jerry@CentOS project]$ git log\n"
},
{
"code": null,
"e": 8567,
"s": 8513,
"text": "The above command will produce the following result −"
},
{
"code": null,
"e": 9219,
"s": 8567,
"text": "commit e86f0621c2a3f68190bba633a9fe6c57c94f8e4f\nAuthor: Jerry Mouse <jerry@tutorialspoint.com>\nDate: Wed Sep 11 08:41:42 2013 +0530\n\nAdded my_strcpy function\n\n\ncommit cea2c000f53ba99508c5959e3e12fff493ba6f69\nAuthor: Tom Cat <tom@tutorialspoint.com>\nDate: Wed Sep 11 08:32:07 2013 +0530\n\nChanged char pointer to const char pointer\n\n\ncommit d1e19d316224cddc437e3ed34ec3c931ad803958\nAuthor: Jerry Mouse <jerry@tutorialspoint.com>\nDate: Wed Sep 11 08:05:26 2013 +0530\n\nChanged return type of my_strlen to size_t\n\n\ncommit 19ae20683fc460db7d127cf201a1429523b0e319\nAuthor: Tom Cat <tom@tutorialspoint.com>\nDate: Wed Sep 11 07:32:56 2013 +0530\nInitial commit\n"
},
{
"code": null,
"e": 9334,
"s": 9219,
"text": "Now, Jerry’s local repository is fully synchronized with the remote repository. So he can safely push his changes."
},
{
"code": null,
"e": 9382,
"s": 9334,
"text": "[jerry@CentOS project]$ git push origin master\n"
},
{
"code": null,
"e": 9436,
"s": 9382,
"text": "The above command will produce the following result −"
},
{
"code": null,
"e": 9659,
"s": 9436,
"text": "Counting objects: 5, done.\nCompressing objects: 100% (3/3), done.\nWriting objects: 100% (3/3), 455 bytes, done.\nTotal 3 (delta 1), reused 0 (delta 0)\nTo gituser@git.server.com:project.git\ncea2c00..e86f062 master −> master\n"
},
{
"code": null,
"e": 9696,
"s": 9659,
"text": "\n 251 Lectures \n 35.5 hours \n"
},
{
"code": null,
"e": 9713,
"s": 9696,
"text": " Gowthami Swarna"
},
{
"code": null,
"e": 9746,
"s": 9713,
"text": "\n 23 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 9760,
"s": 9746,
"text": " Asif Hussain"
},
{
"code": null,
"e": 9795,
"s": 9760,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 9812,
"s": 9795,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 9846,
"s": 9812,
"text": "\n 125 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 9857,
"s": 9846,
"text": " John Shea"
},
{
"code": null,
"e": 9892,
"s": 9857,
"text": "\n 13 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 9906,
"s": 9892,
"text": " Raghu Pandey"
},
{
"code": null,
"e": 9939,
"s": 9906,
"text": "\n 13 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 9959,
"s": 9939,
"text": " Sebastian Sulinski"
},
{
"code": null,
"e": 9966,
"s": 9959,
"text": " Print"
},
{
"code": null,
"e": 9977,
"s": 9966,
"text": " Add Notes"
}
] |
How to multiple a matrix rows in R with a vector?
|
When we multiple a matrix with a vector in R, the multiplication is done by column but if we want to do it with rows then we can use transpose function. We can multiply the transpose of the matrix with the vector and then take the transpose of that multiplication this will result in the multiplication by rows.
Consider the below matrix −
> M1<-matrix(1:25,nrow=5)
> M1
[,1] [,2] [,3] [,4] [,5]
[1,] 1 6 11 16 21
[2,] 2 7 12 17 22
[3,] 3 8 13 18 23
[4,] 4 9 14 19 24
[5,] 5 10 15 20 25
> V1<-1:5
Simple multiplication −
> M1*V1
[,1] [,2] [,3] [,4] [,5]
[1,] 1 6 11 16 21
[2,] 4 14 24 34 44
[3,] 9 24 39 54 69
[4,] 16 36 56 76 96
[5,] 25 50 75 100 125
Row-wise Multiplication −
> t(t(M1)*V1)
[,1] [,2] [,3] [,4] [,5]
[1,] 1 12 33 64 105
[2,] 2 14 36 68 110
[3,] 3 16 39 72 115
[4,] 4 18 42 76 120
[5,] 5 20 45 80 125
Let’s have a look at one more example −
> M2<-matrix(sample(1:100,25),nrow=5)
> M2
[,1] [,2] [,3] [,4] [,5]
[1,] 72 5 36 11 76
[2,] 61 38 17 73 25
[3,] 96 9 62 79 64
[4,] 77 53 80 78 50
[5,] 81 15 21 43 23
> V2<-sample(1:100,5)
> V2
[1] 28 20 1 68 86
> t(t(M2)*V2)
[,1] [,2] [,3] [,4] [,5]
[1,] 2016 100 36 748 6536
[2,] 1708 760 17 4964 2150
[3,] 2688 180 62 5372 5504
[4,] 2156 1060 80 5304 4300
[5,] 2268 300 21 2924 1978
|
[
{
"code": null,
"e": 1374,
"s": 1062,
"text": "When we multiple a matrix with a vector in R, the multiplication is done by column but if we want to do it with rows then we can use transpose function. We can multiply the transpose of the matrix with the vector and then take the transpose of that multiplication this will result in the multiplication by rows."
},
{
"code": null,
"e": 1402,
"s": 1374,
"text": "Consider the below matrix −"
},
{
"code": null,
"e": 1611,
"s": 1402,
"text": "> M1<-matrix(1:25,nrow=5)\n> M1\n [,1] [,2] [,3] [,4] [,5]\n[1,] 1 6 11 16 21\n[2,] 2 7 12 17 22\n[3,] 3 8 13 18 23\n[4,] 4 9 14 19 24\n[5,] 5 10 15 20 25\n> V1<-1:5"
},
{
"code": null,
"e": 1635,
"s": 1611,
"text": "Simple multiplication −"
},
{
"code": null,
"e": 1806,
"s": 1635,
"text": "> M1*V1\n [,1] [,2] [,3] [,4] [,5]\n[1,] 1 6 11 16 21\n[2,] 4 14 24 34 44\n[3,] 9 24 39 54 69\n[4,] 16 36 56 76 96\n[5,] 25 50 75 100 125"
},
{
"code": null,
"e": 1832,
"s": 1806,
"text": "Row-wise Multiplication −"
},
{
"code": null,
"e": 2009,
"s": 1832,
"text": "> t(t(M1)*V1)\n [,1] [,2] [,3] [,4] [,5]\n[1,] 1 12 33 64 105\n[2,] 2 14 36 68 110\n[3,] 3 16 39 72 115\n[4,] 4 18 42 76 120\n[5,] 5 20 45 80 125"
},
{
"code": null,
"e": 2049,
"s": 2009,
"text": "Let’s have a look at one more example −"
},
{
"code": null,
"e": 2492,
"s": 2049,
"text": "> M2<-matrix(sample(1:100,25),nrow=5)\n> M2\n [,1] [,2] [,3] [,4] [,5]\n[1,] 72 5 36 11 76\n[2,] 61 38 17 73 25\n[3,] 96 9 62 79 64\n[4,] 77 53 80 78 50\n[5,] 81 15 21 43 23\n> V2<-sample(1:100,5)\n> V2\n[1] 28 20 1 68 86\n> t(t(M2)*V2)\n[,1] [,2] [,3] [,4] [,5]\n[1,] 2016 100 36 748 6536\n[2,] 1708 760 17 4964 2150\n[3,] 2688 180 62 5372 5504\n[4,] 2156 1060 80 5304 4300\n[5,] 2268 300 21 2924 1978"
}
] |
Hyper-Parameter Tuning and Model Selection, Like a Movie Star | by Caleb Neale | Towards Data Science
|
“Hyper-parameter tuning for random forest classifier optimization” is one of those phrases which would sound just as at ease in a movie scene where hackers are aggressively typing to “gain access to the mainframe” as it does in a Medium article on Towards Data science. The reality of it, however, is that phrases like that are the unfortunate consequence of combining mathematical and computational concepts in one field, and worse, one name. Though the concepts in this article will benefit from a solid understanding of fundamental python modelling using scikit-learn and how some of these models work, I’ll attempt to explain everything from the bottom up so readers of all levels can enjoy and learn these concepts; you too can sound (and code) like a Hollywood hacker.
In this article, I will attempt to address:
What is a hyper-parameter and how does it differ from a parameter?
When should hyper parameters be used?
What do hyper-parameters actually do?
How can hyper-parameters be tuned?
What is grid search?
What is pipelining?
How are individual hyper-parameters defined?
Skip to the end for a summary of all these topics.
The term hyper-parameter came about due to the increasing prevalence of machine learning in programming and big data. Many people who began their journey as data scientists or programmers will know the word parameter to be defined as a value which is passed into a function such that the function performs operations on and/or is informed by these value(s). However, in machine learning and modelling, parameters are not input by the programmer but rather developed by the machine learning model. This is due to the fundamental differences between machine learning and traditional programming; in traditional programming, rules and data are input by the programmer in order to output results, whereas in machine learning, data and results are input in order to output rules (usually called parameters in this context). This Google I/O 2019 talk addresses this flip pretty succinctly in the first few minutes.
If the model itself generates parameters, it would be quite confusing to call what we (programmers, data scientists, whatever) input into the model parameters as well. This is the birth of the term hyper-parameter. Hyper-parameters are input into any machine learning model which generates its own parameters in order to influence the values of said generated parameters in the hope of making the model more accurate. A little bit later in the article, I’ll show specific examples as well as defining what individual hyper-parameters are.
Let’s take a quick peek at scikit-learn’s documentation on Logistic Regression to better understand what this question really means.
LogisticRegression(penalty=’l2’, dual=False, tol=0.0001, C=1.0, fit_intercept=True, intercept_scaling=1, class_weight=None, random_state=None, solver=’warn’, max_iter=100, multi_class=’warn’, verbose=0, warm_start=False, n_jobs=None, l1_ratio=None)
As we can see here, LogisticRegression() takes in 15 different values, which we now know to be called hyper-parameters. However, every single one of those 15 values is defined with a default value, meaning that is it very possible, even common, to create a LogisticRegression() object without specifying any hyper-parameters. This is the case for all models in scikit-learn. As such, I’ll only take the time to define and explain some of the more relevant and commonly modified hyper-parameters for four common modelling methodologies.
Penalty: is used to specify the method of penalization of the coefficients of noncontributing variables.
Lasso (L1) performs feature selection as it shrinks the less important feature’s coefficient to zero.
Ridge (L2) all variables are included in model, though some are shrunk. Less computationally intensive than lasso.
Both penalty values restrict solver choices, as seen here.
C: is the inverse of the regularization term (1/lambda). It tells the model how much large parameters are penalized, smaller values result in larger penalization; must be a positive float.
Common values: [0.001,0.1 ...10..100]
class_weight: allows you to place greater emphasis on a class. For example, if the distribution between class 1 and class 2 is heavily imbalanced, the model can treat the two distributions appropriately.
Default is that all weights = 1. Class weights can be specified in a dictionary.
“Balanced” will create class weights that are inversely proportional to class frequencies, giving more weight to individual occurrences of smaller classes.
Fit intercept: specifies whether the intercept of the model should be calculated or set to zero.
If false, intercept for regression line will be 0.
If true, model will calculate the intercept.
Normalize: specifies whether to normalize the data for the model using the L2 norm.
C: is the inverse of the regularization term (1/lambda). It tells the model how much large parameters are penalized, smaller values result in larger penalization; must be a positive float.
A higher C will cause the model to misclassify less, but is much more likely to cause overfit.
Good range of values : [0.001, 0.01, 10, 100, 1000...]
class_weight: Set the parameter of class i to be class_weight[i] *C.
This allows you to place greater emphasis on a class. For example, if the distribution between class 1 and class 2 is heavily imbalanced, the model can treat the two distributions appropriately.
Default is that all weights = 1. Class weights can be specified in a dictionary.
“Balanced” will create class weights that are inversely proportional to class frequencies, giving more weight to individual occurrences of smaller classes.
n_neighbors: determines the number of neighbors used when calculating the nearest-neighbors algorithm.
Good range of values: [2,4,8,16]
p: power metric when calculating the Minkowski metric, a fairly mathematically complex topic. When evaluating models, simply trying both 1 and two here is usually sufficient.
Use value 1 to calculate Manhattan distance
Use value 2 to calculate Euclidean distance (default)
n_estimators: sets the number of decision trees to be used in the forest.
Default is 100
Good range of values: [100, 120, 300, 500, 800, 1200]
max_depth: Set the max depth of the tree.
If not set then there is no cap. The tree will keep expanding until all leaves are pure.
Limiting the depth is good for pruning trees to prevent over-fitting on noisy data.
Good range of values: [5, 8, 15, 25, 30, None]
min_samples_split: The minimum number of samples needed before a split (differentiation) is made in an internal node
Default is 2
Good range of values: [1,2,5,10,15,100]
min_samples_leaf: The minimum number of samples needed to create a leaf (decision) node.
Default is 1. This means that a split point at any depth will only be allowed if there is at least 1 sample for each path.
Good range of values: [1,2,5,10]
max_features: Set the number of features to consider for the best node split
Default is “auto”, which means that the square root of the number of features is used for every split in the tree.
“None” means that all features are used for each split.
Each decision tree in the random forest will typically use a random subset of features for splitting.
Good range of values: [log2, sqrt, auto, None]
In order to figure out both of these questions, let’s tackle an example using the classic UC Irvine Iris dataset.
First we’ll load the dataset and import some of the packages we’ll use:
# import packagesimport numpy as npfrom sklearn import linear_model, datasetsfrom sklearn.model_selection import GridSearchCVfrom sklearn.linear_model import LogisticRegression from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import GridSearchCV from sklearn.pipeline import Pipeline# Loading datasetiris = datasets.load_iris()features = iris.datatarget = iris.target
Now let’s create a quick model using no additional hyper-parameters and get the score for later evaluation.
logistic.fit(features, target)print(logistic.score(features, target))
Output:
0.96
Now let’s try some methods of hyper-parameter tuning to see if we can improve the accuracy of our model.
Gird search is a method by which we create sets of possible hyper-parameters values for each hyper-parameter, then test them against each other in a “grid.” For example, if I’d like to test a logistic regression with the values [L1, L2] and the values of C as [1,2] the GridSearchCV() method would test L1 with C=1, then L1 with C=2, then L2 with both values of C, creating a 2x2 grid and a total of four combinations. Let’s go though an example with out current dataset. The verbose parameter dictates whetehr the function will print information as it runs, and the cv parameter refers to cross validation folds. Full documentation for GridSearchCV() can be found here.
# Create range of candidate penalty hyperparameter valuespenalty = ['l1', 'l2']# Create range of candidate regularization hyperparameter values C# Choose 10 values, between 0 and 4C = np.logspace(0, 4, 10)# Create dictionary hyperparameter candidateshyperparameters = dict(C=C, penalty=penalty)# Create grid search, and pass in all defined valuesgridsearch = GridSearchCV(logistic, hyperparameters, cv=5, verbose=1) # the verbose parameter above will give output updates as the calculations are complete. # select the best model and create a fitbest_model = gridsearch.fit(features, target)
Now that our model is created based of a larger input space, we can hope that we see improvement. Let’s check:
print('Best Penalty:', best_model.best_estimator_.get_params(['penalty']) print('Best C:', best_model.best_estimator_.get_params()['C'])print("The mean accuracy of the model is:",best_model.score(features, target))
Output:
Best Penalty: l1 Best C: 7.742636826811269The mean accuracy of the model is: 0.98
That’s an accuracy improvement of 0.02, using the same model and adding a small variation in hyper-parameters. Try experimenting with different sets of hyper-parameters and adding them to the hyper-parameter dict and running GridSearchCV() again. Notice how adding many hyper-parameters quickly increases the computation time.
What if we want to test more than one algorithm with more than one hyper-parameter in order to find the best model possible? Pipelining allows us to do this in a code-efficient manner. Let’s go through an example with our Iris dataset to see if we can improve on our logistic regression model.
# Create a pipelinepipe = Pipeline([("classifier", RandomForestClassifier())])# Create dictionary with candidate learning algorithms and their hyperparameterssearch_space = [ {"classifier": [LogisticRegression()], "classifier__penalty": ['l2','l1'], "classifier__C": np.logspace(0, 4, 10) }, {"classifier": [LogisticRegression()], "classifier__penalty": ['l2'], "classifier__C": np.logspace(0, 4, 10), "classifier__solver":['newton-cg','saga','sag','liblinear'] ##This solvers don't allow L1 penalty }, {"classifier": [RandomForestClassifier()], "classifier__n_estimators": [10, 100, 1000], "classifier__max_depth":[5,8,15,25,30,None], "classifier__min_samples_leaf":[1,2,5,10,15,100], "classifier__max_leaf_nodes": [2, 5,10]}]# create a gridsearch of the pipeline, the fit the best modelgridsearch = GridSearchCV(pipe, search_space, cv=5, verbose=0,n_jobs=-1) # Fit grid searchbest_model = gridsearch.fit(features, target)
Notice how long this function takes to run. In another article, I’ll talk about how to reduce run times and pick effective hyper-parameters, as well as combining a RandomizedSearchCV() with a GridSearchCV. After running the method, let’s check the results.
print(best_model.best_estimator_)print("The mean accuracy of the model is:",best_model.score(features, target))
Output:
Pipeline(memory=None, steps=[('classifier', LogisticRegression(C=7.742636826811269, class_weight=None, dual=False, fit_intercept=True,intercept_scaling=1, l1_ratio=None, max_iter=100, multi_class='warn', n_jobs=None, penalty='l1', random_state=None, solver='warn', tol=0.0001, verbose=0, warm_start=False))], verbose=False) The mean accuracy of the model is: 0.98
According to our pipeline search, a LogisticRegression() with the specified hyper-parameters performs better than a RandomForestClassifier() with any of the given hyper-parameters. Interesting!
Okay, so we’ve used a pipeline method to make this all happen, but what does it actually do, and why did we pass in a RandomForestClassifier()?
The pipeline method allows us to pass in preprocessing methods as well an algorithm we’d like to use to create a model with the data. In this simple example we skipped the preprocessing step, but we still input a model. The algorithm we input is simply the algorithm used to instantiate the pipe object, but will be replaced by the contents of our search_space variable which we create to be passed into our GridSearchCV() later on. A simplified post focusing just on pipeline can be found here.
The difference between the accuracies of our original, baseline model, and the model generated with our hyper-parameter tuning shows the effects of hyper-parameter tuning. By guiding the creation of our machine learning models, we can improve their performance and create better and more reliable models.
A hyper-parameter is used in machine learning model to better guide the creation of the the parameters which the models use to generate predictions on data. Hyper-parameters are set by the programmer whereas parameters are generated by the model.
Always! Models usually have built in default hyper-parameters which can serve most purposes. However in many cases, additional performance can be squeezed out of models using hyper-parameter tuning. Knowing the limitations and effects of different hyper-parameters can assist in limiting negative effects like overfit while increasing performance.
Simply, they change the ways in which the model approaches finding parameters for the model. Individual definitions can be found in the article above.
Grid search, random search, and pipelining are common methods. Random search isn’t addressed in this article but you can read more here.
Grid search is an element-wise test of all the hyper-parameters passed into the GridSearchCV() function. Quite computationally expensive on large search spaces, grid search is also exhaustive in its testing.
Pipelining allows the searching of multiple algorithms with many hyper-parameters each. It is a very code efficient way of testing many models in order to select the best possible one. Additionally, it can handle reprocessing methods as well, allowing for further control of the process.
Finally, below are some functions which can perform a few different types of hyper-parameter tuning just by passing in the arguments. A Google Colab notebook containing all of the code use in this article can also be found here. Using these functions, you can efficiently perform hyper-parameter tuning in just one line!
# # # Hyperparameter tuning and model selectionimport numpy as npfrom sklearn import linear_modelfrom sklearn import datasetsfrom sklearn.linear_model import LogisticRegression from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import GridSearchCV from sklearn.pipeline import Pipelinefrom sklearn.model_selection import RandomizedSearchCVfrom sklearn.model_selection import GridSearchCVfrom sklearn.ensemble import RandomForestRegressordef perform_gridsearch_log(features, labels, log_params = {'penalty': ['l1', 'l2'], 'C': np.logspace(0, 4, 10)}, cv=5, verbose = 1): import numpy as np from sklearn import linear_model, datasets from sklearn.model_selection import GridSearchCV global best_model logistic = linear_model.LogisticRegression() penalty = log_params['penalty'] C = log_params['C'] hyperparameters = dict(C=C, penalty=penalty)gridsearch = GridSearchCV(logistic, hyperparameters, cv=cv, verbose=verbose) # Fit grid search best_model = gridsearch.fit(features, target) print(best_model.best_estimator_) print("The mean accuracy of the model is:",best_model.score(features, labels))def rand_forest_rand_grid(features, labels, n_estimators = [int(x) for x in np.linspace(start = 200, stop = 2000, num = 10)], max_features = ['auto', 'sqrt'], max_depth = [int(x) for x in np.linspace(10, 110, num = 11)], min_samples_split = [2, 5, 10], min_samples_leaf = [1, 2, 4], bootstrap = [True, False]): max_depth.append(None) global best_model random_grid = {'n_estimators': n_estimators, 'max_features': max_features, 'max_depth': max_depth, 'min_samples_split': min_samples_split, 'min_samples_leaf': min_samples_leaf, 'bootstrap': bootstrap} rf = RandomForestRegressor() rf_random = RandomizedSearchCV(estimator = rf, param_distributions = random_grid, n_iter = 100, cv = 3, verbose=1, random_state=42, n_jobs = -1) best_model = rf_random.fit(features, labels) print(best_model.best_estimator_) print("The mean accuracy of the model is:",best_model.score(features, labels))def rand_forest_grid_search(features, labels, n_estimators = [int(x) for x in np.linspace(start = 200, stop = 2000, num = 10)], max_features = ['auto', 'sqrt'], max_depth = [int(x) for x in np.linspace(10, 110, num = 11)], min_samples_split = [2, 5, 10], min_samples_leaf = [1, 2, 4], bootstrap = [True, False]): param_grid = {'n_estimators': n_estimators, 'max_features': max_features, 'max_depth': max_depth, 'min_samples_split': min_samples_split, 'min_samples_leaf': min_samples_leaf, 'bootstrap': bootstrap} global best_model rf = RandomForestRegressor() grid_search = GridSearchCV(estimator = rf, param_grid = param_grid, cv = 3, n_jobs = -1, verbose = 1)best_model = grid_search.fit(train_features, train_labels) print(best_model.best_estimator_) print("The mean accuracy of the model is:",best_model.score(features, labels))def execute_pipeline(features,labels, search_space=[ {"classifier": [LogisticRegression()], "classifier__penalty": ['l2','l1'], "classifier__C": np.logspace(0, 4, 10) }, {"classifier": [LogisticRegression()], "classifier__penalty": ['l2'], "classifier__C": np.logspace(0, 4, 10), "classifier__solver":['newton-cg','saga','sag','liblinear'] ##This solvers don't allow L1 penalty }, {"classifier": [RandomForestClassifier()], "classifier__n_estimators": [10, 100, 1000], "classifier__max_depth":[5,8,15,25,30,None], "classifier__min_samples_leaf":[1,2,5,10,15,100], "classifier__max_leaf_nodes": [2, 5,10]}], cv=5, verbose=0, n_jobs=-1):global best_model pipe = Pipeline([("classifier", RandomForestClassifier())]) gridsearch = GridSearchCV(pipe, search_space, cv=cv, verbose=verbose,n_jobs=n_jobs) # Fit grid search best_model = gridsearch.fit(features, labels) print(best_model.best_estimator_) print("The mean accuracy of the model is:",best_model.score(features, labels))
Thanks for reading!
|
[
{
"code": null,
"e": 946,
"s": 171,
"text": "“Hyper-parameter tuning for random forest classifier optimization” is one of those phrases which would sound just as at ease in a movie scene where hackers are aggressively typing to “gain access to the mainframe” as it does in a Medium article on Towards Data science. The reality of it, however, is that phrases like that are the unfortunate consequence of combining mathematical and computational concepts in one field, and worse, one name. Though the concepts in this article will benefit from a solid understanding of fundamental python modelling using scikit-learn and how some of these models work, I’ll attempt to explain everything from the bottom up so readers of all levels can enjoy and learn these concepts; you too can sound (and code) like a Hollywood hacker."
},
{
"code": null,
"e": 990,
"s": 946,
"text": "In this article, I will attempt to address:"
},
{
"code": null,
"e": 1057,
"s": 990,
"text": "What is a hyper-parameter and how does it differ from a parameter?"
},
{
"code": null,
"e": 1095,
"s": 1057,
"text": "When should hyper parameters be used?"
},
{
"code": null,
"e": 1133,
"s": 1095,
"text": "What do hyper-parameters actually do?"
},
{
"code": null,
"e": 1168,
"s": 1133,
"text": "How can hyper-parameters be tuned?"
},
{
"code": null,
"e": 1189,
"s": 1168,
"text": "What is grid search?"
},
{
"code": null,
"e": 1209,
"s": 1189,
"text": "What is pipelining?"
},
{
"code": null,
"e": 1254,
"s": 1209,
"text": "How are individual hyper-parameters defined?"
},
{
"code": null,
"e": 1305,
"s": 1254,
"text": "Skip to the end for a summary of all these topics."
},
{
"code": null,
"e": 2214,
"s": 1305,
"text": "The term hyper-parameter came about due to the increasing prevalence of machine learning in programming and big data. Many people who began their journey as data scientists or programmers will know the word parameter to be defined as a value which is passed into a function such that the function performs operations on and/or is informed by these value(s). However, in machine learning and modelling, parameters are not input by the programmer but rather developed by the machine learning model. This is due to the fundamental differences between machine learning and traditional programming; in traditional programming, rules and data are input by the programmer in order to output results, whereas in machine learning, data and results are input in order to output rules (usually called parameters in this context). This Google I/O 2019 talk addresses this flip pretty succinctly in the first few minutes."
},
{
"code": null,
"e": 2753,
"s": 2214,
"text": "If the model itself generates parameters, it would be quite confusing to call what we (programmers, data scientists, whatever) input into the model parameters as well. This is the birth of the term hyper-parameter. Hyper-parameters are input into any machine learning model which generates its own parameters in order to influence the values of said generated parameters in the hope of making the model more accurate. A little bit later in the article, I’ll show specific examples as well as defining what individual hyper-parameters are."
},
{
"code": null,
"e": 2886,
"s": 2753,
"text": "Let’s take a quick peek at scikit-learn’s documentation on Logistic Regression to better understand what this question really means."
},
{
"code": null,
"e": 3135,
"s": 2886,
"text": "LogisticRegression(penalty=’l2’, dual=False, tol=0.0001, C=1.0, fit_intercept=True, intercept_scaling=1, class_weight=None, random_state=None, solver=’warn’, max_iter=100, multi_class=’warn’, verbose=0, warm_start=False, n_jobs=None, l1_ratio=None)"
},
{
"code": null,
"e": 3671,
"s": 3135,
"text": "As we can see here, LogisticRegression() takes in 15 different values, which we now know to be called hyper-parameters. However, every single one of those 15 values is defined with a default value, meaning that is it very possible, even common, to create a LogisticRegression() object without specifying any hyper-parameters. This is the case for all models in scikit-learn. As such, I’ll only take the time to define and explain some of the more relevant and commonly modified hyper-parameters for four common modelling methodologies."
},
{
"code": null,
"e": 3776,
"s": 3671,
"text": "Penalty: is used to specify the method of penalization of the coefficients of noncontributing variables."
},
{
"code": null,
"e": 3878,
"s": 3776,
"text": "Lasso (L1) performs feature selection as it shrinks the less important feature’s coefficient to zero."
},
{
"code": null,
"e": 3993,
"s": 3878,
"text": "Ridge (L2) all variables are included in model, though some are shrunk. Less computationally intensive than lasso."
},
{
"code": null,
"e": 4052,
"s": 3993,
"text": "Both penalty values restrict solver choices, as seen here."
},
{
"code": null,
"e": 4241,
"s": 4052,
"text": "C: is the inverse of the regularization term (1/lambda). It tells the model how much large parameters are penalized, smaller values result in larger penalization; must be a positive float."
},
{
"code": null,
"e": 4279,
"s": 4241,
"text": "Common values: [0.001,0.1 ...10..100]"
},
{
"code": null,
"e": 4483,
"s": 4279,
"text": "class_weight: allows you to place greater emphasis on a class. For example, if the distribution between class 1 and class 2 is heavily imbalanced, the model can treat the two distributions appropriately."
},
{
"code": null,
"e": 4564,
"s": 4483,
"text": "Default is that all weights = 1. Class weights can be specified in a dictionary."
},
{
"code": null,
"e": 4720,
"s": 4564,
"text": "“Balanced” will create class weights that are inversely proportional to class frequencies, giving more weight to individual occurrences of smaller classes."
},
{
"code": null,
"e": 4817,
"s": 4720,
"text": "Fit intercept: specifies whether the intercept of the model should be calculated or set to zero."
},
{
"code": null,
"e": 4868,
"s": 4817,
"text": "If false, intercept for regression line will be 0."
},
{
"code": null,
"e": 4913,
"s": 4868,
"text": "If true, model will calculate the intercept."
},
{
"code": null,
"e": 4997,
"s": 4913,
"text": "Normalize: specifies whether to normalize the data for the model using the L2 norm."
},
{
"code": null,
"e": 5186,
"s": 4997,
"text": "C: is the inverse of the regularization term (1/lambda). It tells the model how much large parameters are penalized, smaller values result in larger penalization; must be a positive float."
},
{
"code": null,
"e": 5281,
"s": 5186,
"text": "A higher C will cause the model to misclassify less, but is much more likely to cause overfit."
},
{
"code": null,
"e": 5336,
"s": 5281,
"text": "Good range of values : [0.001, 0.01, 10, 100, 1000...]"
},
{
"code": null,
"e": 5405,
"s": 5336,
"text": "class_weight: Set the parameter of class i to be class_weight[i] *C."
},
{
"code": null,
"e": 5600,
"s": 5405,
"text": "This allows you to place greater emphasis on a class. For example, if the distribution between class 1 and class 2 is heavily imbalanced, the model can treat the two distributions appropriately."
},
{
"code": null,
"e": 5681,
"s": 5600,
"text": "Default is that all weights = 1. Class weights can be specified in a dictionary."
},
{
"code": null,
"e": 5837,
"s": 5681,
"text": "“Balanced” will create class weights that are inversely proportional to class frequencies, giving more weight to individual occurrences of smaller classes."
},
{
"code": null,
"e": 5940,
"s": 5837,
"text": "n_neighbors: determines the number of neighbors used when calculating the nearest-neighbors algorithm."
},
{
"code": null,
"e": 5973,
"s": 5940,
"text": "Good range of values: [2,4,8,16]"
},
{
"code": null,
"e": 6148,
"s": 5973,
"text": "p: power metric when calculating the Minkowski metric, a fairly mathematically complex topic. When evaluating models, simply trying both 1 and two here is usually sufficient."
},
{
"code": null,
"e": 6192,
"s": 6148,
"text": "Use value 1 to calculate Manhattan distance"
},
{
"code": null,
"e": 6246,
"s": 6192,
"text": "Use value 2 to calculate Euclidean distance (default)"
},
{
"code": null,
"e": 6320,
"s": 6246,
"text": "n_estimators: sets the number of decision trees to be used in the forest."
},
{
"code": null,
"e": 6335,
"s": 6320,
"text": "Default is 100"
},
{
"code": null,
"e": 6389,
"s": 6335,
"text": "Good range of values: [100, 120, 300, 500, 800, 1200]"
},
{
"code": null,
"e": 6431,
"s": 6389,
"text": "max_depth: Set the max depth of the tree."
},
{
"code": null,
"e": 6520,
"s": 6431,
"text": "If not set then there is no cap. The tree will keep expanding until all leaves are pure."
},
{
"code": null,
"e": 6604,
"s": 6520,
"text": "Limiting the depth is good for pruning trees to prevent over-fitting on noisy data."
},
{
"code": null,
"e": 6651,
"s": 6604,
"text": "Good range of values: [5, 8, 15, 25, 30, None]"
},
{
"code": null,
"e": 6768,
"s": 6651,
"text": "min_samples_split: The minimum number of samples needed before a split (differentiation) is made in an internal node"
},
{
"code": null,
"e": 6781,
"s": 6768,
"text": "Default is 2"
},
{
"code": null,
"e": 6821,
"s": 6781,
"text": "Good range of values: [1,2,5,10,15,100]"
},
{
"code": null,
"e": 6910,
"s": 6821,
"text": "min_samples_leaf: The minimum number of samples needed to create a leaf (decision) node."
},
{
"code": null,
"e": 7033,
"s": 6910,
"text": "Default is 1. This means that a split point at any depth will only be allowed if there is at least 1 sample for each path."
},
{
"code": null,
"e": 7066,
"s": 7033,
"text": "Good range of values: [1,2,5,10]"
},
{
"code": null,
"e": 7143,
"s": 7066,
"text": "max_features: Set the number of features to consider for the best node split"
},
{
"code": null,
"e": 7258,
"s": 7143,
"text": "Default is “auto”, which means that the square root of the number of features is used for every split in the tree."
},
{
"code": null,
"e": 7314,
"s": 7258,
"text": "“None” means that all features are used for each split."
},
{
"code": null,
"e": 7416,
"s": 7314,
"text": "Each decision tree in the random forest will typically use a random subset of features for splitting."
},
{
"code": null,
"e": 7463,
"s": 7416,
"text": "Good range of values: [log2, sqrt, auto, None]"
},
{
"code": null,
"e": 7577,
"s": 7463,
"text": "In order to figure out both of these questions, let’s tackle an example using the classic UC Irvine Iris dataset."
},
{
"code": null,
"e": 7649,
"s": 7577,
"text": "First we’ll load the dataset and import some of the packages we’ll use:"
},
{
"code": null,
"e": 8049,
"s": 7649,
"text": "# import packagesimport numpy as npfrom sklearn import linear_model, datasetsfrom sklearn.model_selection import GridSearchCVfrom sklearn.linear_model import LogisticRegression from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import GridSearchCV from sklearn.pipeline import Pipeline# Loading datasetiris = datasets.load_iris()features = iris.datatarget = iris.target"
},
{
"code": null,
"e": 8157,
"s": 8049,
"text": "Now let’s create a quick model using no additional hyper-parameters and get the score for later evaluation."
},
{
"code": null,
"e": 8227,
"s": 8157,
"text": "logistic.fit(features, target)print(logistic.score(features, target))"
},
{
"code": null,
"e": 8235,
"s": 8227,
"text": "Output:"
},
{
"code": null,
"e": 8240,
"s": 8235,
"text": "0.96"
},
{
"code": null,
"e": 8345,
"s": 8240,
"text": "Now let’s try some methods of hyper-parameter tuning to see if we can improve the accuracy of our model."
},
{
"code": null,
"e": 9016,
"s": 8345,
"text": "Gird search is a method by which we create sets of possible hyper-parameters values for each hyper-parameter, then test them against each other in a “grid.” For example, if I’d like to test a logistic regression with the values [L1, L2] and the values of C as [1,2] the GridSearchCV() method would test L1 with C=1, then L1 with C=2, then L2 with both values of C, creating a 2x2 grid and a total of four combinations. Let’s go though an example with out current dataset. The verbose parameter dictates whetehr the function will print information as it runs, and the cv parameter refers to cross validation folds. Full documentation for GridSearchCV() can be found here."
},
{
"code": null,
"e": 9607,
"s": 9016,
"text": "# Create range of candidate penalty hyperparameter valuespenalty = ['l1', 'l2']# Create range of candidate regularization hyperparameter values C# Choose 10 values, between 0 and 4C = np.logspace(0, 4, 10)# Create dictionary hyperparameter candidateshyperparameters = dict(C=C, penalty=penalty)# Create grid search, and pass in all defined valuesgridsearch = GridSearchCV(logistic, hyperparameters, cv=5, verbose=1) # the verbose parameter above will give output updates as the calculations are complete. # select the best model and create a fitbest_model = gridsearch.fit(features, target)"
},
{
"code": null,
"e": 9718,
"s": 9607,
"text": "Now that our model is created based of a larger input space, we can hope that we see improvement. Let’s check:"
},
{
"code": null,
"e": 9933,
"s": 9718,
"text": "print('Best Penalty:', best_model.best_estimator_.get_params(['penalty']) print('Best C:', best_model.best_estimator_.get_params()['C'])print(\"The mean accuracy of the model is:\",best_model.score(features, target))"
},
{
"code": null,
"e": 9941,
"s": 9933,
"text": "Output:"
},
{
"code": null,
"e": 10023,
"s": 9941,
"text": "Best Penalty: l1 Best C: 7.742636826811269The mean accuracy of the model is: 0.98"
},
{
"code": null,
"e": 10350,
"s": 10023,
"text": "That’s an accuracy improvement of 0.02, using the same model and adding a small variation in hyper-parameters. Try experimenting with different sets of hyper-parameters and adding them to the hyper-parameter dict and running GridSearchCV() again. Notice how adding many hyper-parameters quickly increases the computation time."
},
{
"code": null,
"e": 10644,
"s": 10350,
"text": "What if we want to test more than one algorithm with more than one hyper-parameter in order to find the best model possible? Pipelining allows us to do this in a code-efficient manner. Let’s go through an example with our Iris dataset to see if we can improve on our logistic regression model."
},
{
"code": null,
"e": 11789,
"s": 10644,
"text": "# Create a pipelinepipe = Pipeline([(\"classifier\", RandomForestClassifier())])# Create dictionary with candidate learning algorithms and their hyperparameterssearch_space = [ {\"classifier\": [LogisticRegression()], \"classifier__penalty\": ['l2','l1'], \"classifier__C\": np.logspace(0, 4, 10) }, {\"classifier\": [LogisticRegression()], \"classifier__penalty\": ['l2'], \"classifier__C\": np.logspace(0, 4, 10), \"classifier__solver\":['newton-cg','saga','sag','liblinear'] ##This solvers don't allow L1 penalty }, {\"classifier\": [RandomForestClassifier()], \"classifier__n_estimators\": [10, 100, 1000], \"classifier__max_depth\":[5,8,15,25,30,None], \"classifier__min_samples_leaf\":[1,2,5,10,15,100], \"classifier__max_leaf_nodes\": [2, 5,10]}]# create a gridsearch of the pipeline, the fit the best modelgridsearch = GridSearchCV(pipe, search_space, cv=5, verbose=0,n_jobs=-1) # Fit grid searchbest_model = gridsearch.fit(features, target)"
},
{
"code": null,
"e": 12046,
"s": 11789,
"text": "Notice how long this function takes to run. In another article, I’ll talk about how to reduce run times and pick effective hyper-parameters, as well as combining a RandomizedSearchCV() with a GridSearchCV. After running the method, let’s check the results."
},
{
"code": null,
"e": 12158,
"s": 12046,
"text": "print(best_model.best_estimator_)print(\"The mean accuracy of the model is:\",best_model.score(features, target))"
},
{
"code": null,
"e": 12166,
"s": 12158,
"text": "Output:"
},
{
"code": null,
"e": 12602,
"s": 12166,
"text": "Pipeline(memory=None, steps=[('classifier', LogisticRegression(C=7.742636826811269, class_weight=None, dual=False, fit_intercept=True,intercept_scaling=1, l1_ratio=None, max_iter=100, multi_class='warn', n_jobs=None, penalty='l1', random_state=None, solver='warn', tol=0.0001, verbose=0, warm_start=False))], verbose=False) The mean accuracy of the model is: 0.98"
},
{
"code": null,
"e": 12796,
"s": 12602,
"text": "According to our pipeline search, a LogisticRegression() with the specified hyper-parameters performs better than a RandomForestClassifier() with any of the given hyper-parameters. Interesting!"
},
{
"code": null,
"e": 12940,
"s": 12796,
"text": "Okay, so we’ve used a pipeline method to make this all happen, but what does it actually do, and why did we pass in a RandomForestClassifier()?"
},
{
"code": null,
"e": 13436,
"s": 12940,
"text": "The pipeline method allows us to pass in preprocessing methods as well an algorithm we’d like to use to create a model with the data. In this simple example we skipped the preprocessing step, but we still input a model. The algorithm we input is simply the algorithm used to instantiate the pipe object, but will be replaced by the contents of our search_space variable which we create to be passed into our GridSearchCV() later on. A simplified post focusing just on pipeline can be found here."
},
{
"code": null,
"e": 13741,
"s": 13436,
"text": "The difference between the accuracies of our original, baseline model, and the model generated with our hyper-parameter tuning shows the effects of hyper-parameter tuning. By guiding the creation of our machine learning models, we can improve their performance and create better and more reliable models."
},
{
"code": null,
"e": 13988,
"s": 13741,
"text": "A hyper-parameter is used in machine learning model to better guide the creation of the the parameters which the models use to generate predictions on data. Hyper-parameters are set by the programmer whereas parameters are generated by the model."
},
{
"code": null,
"e": 14336,
"s": 13988,
"text": "Always! Models usually have built in default hyper-parameters which can serve most purposes. However in many cases, additional performance can be squeezed out of models using hyper-parameter tuning. Knowing the limitations and effects of different hyper-parameters can assist in limiting negative effects like overfit while increasing performance."
},
{
"code": null,
"e": 14487,
"s": 14336,
"text": "Simply, they change the ways in which the model approaches finding parameters for the model. Individual definitions can be found in the article above."
},
{
"code": null,
"e": 14624,
"s": 14487,
"text": "Grid search, random search, and pipelining are common methods. Random search isn’t addressed in this article but you can read more here."
},
{
"code": null,
"e": 14832,
"s": 14624,
"text": "Grid search is an element-wise test of all the hyper-parameters passed into the GridSearchCV() function. Quite computationally expensive on large search spaces, grid search is also exhaustive in its testing."
},
{
"code": null,
"e": 15120,
"s": 14832,
"text": "Pipelining allows the searching of multiple algorithms with many hyper-parameters each. It is a very code efficient way of testing many models in order to select the best possible one. Additionally, it can handle reprocessing methods as well, allowing for further control of the process."
},
{
"code": null,
"e": 15441,
"s": 15120,
"text": "Finally, below are some functions which can perform a few different types of hyper-parameter tuning just by passing in the arguments. A Google Colab notebook containing all of the code use in this article can also be found here. Using these functions, you can efficiently perform hyper-parameter tuning in just one line!"
},
{
"code": null,
"e": 20092,
"s": 15441,
"text": "# # # Hyperparameter tuning and model selectionimport numpy as npfrom sklearn import linear_modelfrom sklearn import datasetsfrom sklearn.linear_model import LogisticRegression from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import GridSearchCV from sklearn.pipeline import Pipelinefrom sklearn.model_selection import RandomizedSearchCVfrom sklearn.model_selection import GridSearchCVfrom sklearn.ensemble import RandomForestRegressordef perform_gridsearch_log(features, labels, log_params = {'penalty': ['l1', 'l2'], 'C': np.logspace(0, 4, 10)}, cv=5, verbose = 1): import numpy as np from sklearn import linear_model, datasets from sklearn.model_selection import GridSearchCV global best_model logistic = linear_model.LogisticRegression() penalty = log_params['penalty'] C = log_params['C'] hyperparameters = dict(C=C, penalty=penalty)gridsearch = GridSearchCV(logistic, hyperparameters, cv=cv, verbose=verbose) # Fit grid search best_model = gridsearch.fit(features, target) print(best_model.best_estimator_) print(\"The mean accuracy of the model is:\",best_model.score(features, labels))def rand_forest_rand_grid(features, labels, n_estimators = [int(x) for x in np.linspace(start = 200, stop = 2000, num = 10)], max_features = ['auto', 'sqrt'], max_depth = [int(x) for x in np.linspace(10, 110, num = 11)], min_samples_split = [2, 5, 10], min_samples_leaf = [1, 2, 4], bootstrap = [True, False]): max_depth.append(None) global best_model random_grid = {'n_estimators': n_estimators, 'max_features': max_features, 'max_depth': max_depth, 'min_samples_split': min_samples_split, 'min_samples_leaf': min_samples_leaf, 'bootstrap': bootstrap} rf = RandomForestRegressor() rf_random = RandomizedSearchCV(estimator = rf, param_distributions = random_grid, n_iter = 100, cv = 3, verbose=1, random_state=42, n_jobs = -1) best_model = rf_random.fit(features, labels) print(best_model.best_estimator_) print(\"The mean accuracy of the model is:\",best_model.score(features, labels))def rand_forest_grid_search(features, labels, n_estimators = [int(x) for x in np.linspace(start = 200, stop = 2000, num = 10)], max_features = ['auto', 'sqrt'], max_depth = [int(x) for x in np.linspace(10, 110, num = 11)], min_samples_split = [2, 5, 10], min_samples_leaf = [1, 2, 4], bootstrap = [True, False]): param_grid = {'n_estimators': n_estimators, 'max_features': max_features, 'max_depth': max_depth, 'min_samples_split': min_samples_split, 'min_samples_leaf': min_samples_leaf, 'bootstrap': bootstrap} global best_model rf = RandomForestRegressor() grid_search = GridSearchCV(estimator = rf, param_grid = param_grid, cv = 3, n_jobs = -1, verbose = 1)best_model = grid_search.fit(train_features, train_labels) print(best_model.best_estimator_) print(\"The mean accuracy of the model is:\",best_model.score(features, labels))def execute_pipeline(features,labels, search_space=[ {\"classifier\": [LogisticRegression()], \"classifier__penalty\": ['l2','l1'], \"classifier__C\": np.logspace(0, 4, 10) }, {\"classifier\": [LogisticRegression()], \"classifier__penalty\": ['l2'], \"classifier__C\": np.logspace(0, 4, 10), \"classifier__solver\":['newton-cg','saga','sag','liblinear'] ##This solvers don't allow L1 penalty }, {\"classifier\": [RandomForestClassifier()], \"classifier__n_estimators\": [10, 100, 1000], \"classifier__max_depth\":[5,8,15,25,30,None], \"classifier__min_samples_leaf\":[1,2,5,10,15,100], \"classifier__max_leaf_nodes\": [2, 5,10]}], cv=5, verbose=0, n_jobs=-1):global best_model pipe = Pipeline([(\"classifier\", RandomForestClassifier())]) gridsearch = GridSearchCV(pipe, search_space, cv=cv, verbose=verbose,n_jobs=n_jobs) # Fit grid search best_model = gridsearch.fit(features, labels) print(best_model.best_estimator_) print(\"The mean accuracy of the model is:\",best_model.score(features, labels))"
}
] |
How to push new items to an array inside of an object in MongoDB?
|
You can use $elemMatch operator for this. Let us first create a collection with documents −
> db.pushNewItemsDemo.insertOne(
{
"_id" :1,
"StudentScore" : 56,
"StudentOtherDetails" : [
{
"StudentName" : "John",
"StudentFriendName" : [
"Bob",
"Carol"
]
},
{
"StudentName" : "David",
"StudentFriendName" : [
"Mike",
"Sam"
]
}
]
}
);
{ "acknowledged" : true, "insertedId" : 1 }
Following is the query to display all documents from a collection with the help of find() method −
> db.pushNewItemsDemo.find();
This will produce the following output −
{ "_id" : 1, "StudentScore" : 56, "StudentOtherDetails" : [ { "StudentName" : "John", "StudentFriendName" : [ "Bob", "Carol" ] }, { "StudentName" : "David", "StudentFriendName" : [ "Mike", "Sam" ] } ] }
Following is the query to push new items to an array inside of an object −
>db.pushNewItemsDemo.update({"_id":1,"StudentOtherDetails":{"$elemMatch":{"StudentName":"David"}}},
{"$push":{"StudentOtherDetails.$.StudentFriendName":"James"}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Let us check the documents once again −
> db.pushNewItemsDemo.find();
This will produce the following output −
{ "_id" : 1, "StudentScore" : 56, "StudentOtherDetails" : [ { "StudentName" : "John", "StudentFriendName" : [ "Bob", "Carol" ] }, { "StudentName" : "David", "StudentFriendName" : [ "Mike", "Sam", "James" ] } ] }
|
[
{
"code": null,
"e": 1154,
"s": 1062,
"text": "You can use $elemMatch operator for this. Let us first create a collection with documents −"
},
{
"code": null,
"e": 1640,
"s": 1154,
"text": "> db.pushNewItemsDemo.insertOne(\n {\n \"_id\" :1,\n \"StudentScore\" : 56,\n \"StudentOtherDetails\" : [\n {\n \"StudentName\" : \"John\",\n \"StudentFriendName\" : [\n \"Bob\",\n \"Carol\"\n ]\n },\n {\n \"StudentName\" : \"David\",\n \"StudentFriendName\" : [\n \"Mike\",\n \"Sam\"\n ] \n }\n ]\n }\n);\n{ \"acknowledged\" : true, \"insertedId\" : 1 }"
},
{
"code": null,
"e": 1739,
"s": 1640,
"text": "Following is the query to display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 1769,
"s": 1739,
"text": "> db.pushNewItemsDemo.find();"
},
{
"code": null,
"e": 1810,
"s": 1769,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2013,
"s": 1810,
"text": "{ \"_id\" : 1, \"StudentScore\" : 56, \"StudentOtherDetails\" : [ { \"StudentName\" : \"John\", \"StudentFriendName\" : [ \"Bob\", \"Carol\" ] }, { \"StudentName\" : \"David\", \"StudentFriendName\" : [ \"Mike\", \"Sam\" ] } ] }"
},
{
"code": null,
"e": 2088,
"s": 2013,
"text": "Following is the query to push new items to an array inside of an object −"
},
{
"code": null,
"e": 2321,
"s": 2088,
"text": ">db.pushNewItemsDemo.update({\"_id\":1,\"StudentOtherDetails\":{\"$elemMatch\":{\"StudentName\":\"David\"}}},\n {\"$push\":{\"StudentOtherDetails.$.StudentFriendName\":\"James\"}});\nWriteResult({ \"nMatched\" : 1, \"nUpserted\" : 0, \"nModified\" : 1 })"
},
{
"code": null,
"e": 2361,
"s": 2321,
"text": "Let us check the documents once again −"
},
{
"code": null,
"e": 2391,
"s": 2361,
"text": "> db.pushNewItemsDemo.find();"
},
{
"code": null,
"e": 2432,
"s": 2391,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2644,
"s": 2432,
"text": "{ \"_id\" : 1, \"StudentScore\" : 56, \"StudentOtherDetails\" : [ { \"StudentName\" : \"John\", \"StudentFriendName\" : [ \"Bob\", \"Carol\" ] }, { \"StudentName\" : \"David\", \"StudentFriendName\" : [ \"Mike\", \"Sam\", \"James\" ] } ] }"
}
] |
VB.Net - PrintDialog Control
|
The PrintDialog control lets the user to print documents by selecting a printer and choosing which sections of the document to print from a Windows Forms application.
There are various other controls related to printing of documents. Let us have a brief look at these controls and their purpose. These other controls are −
The PrintDocument control − it provides support for actual events and operations of printing in Visual Basic and sets the properties for printing.
The PrintDocument control − it provides support for actual events and operations of printing in Visual Basic and sets the properties for printing.
The PrinterSettings control − it is used to configure how a document is printed by specifying the printer.
The PrinterSettings control − it is used to configure how a document is printed by specifying the printer.
The PageSetUpDialog control − it allows the user to specify page-related print settings including page orientation, paper size and margin size.
The PageSetUpDialog control − it allows the user to specify page-related print settings including page orientation, paper size and margin size.
The PrintPreviewControl control − it represents the raw preview part of print previewing from a Windows Forms application, without any dialog boxes or buttons.
The PrintPreviewControl control − it represents the raw preview part of print previewing from a Windows Forms application, without any dialog boxes or buttons.
The PrintPreviewDialog control − it represents a dialog box form that contains a PrintPreviewControl for printing from a Windows Forms application.
The PrintPreviewDialog control − it represents a dialog box form that contains a PrintPreviewControl for printing from a Windows Forms application.
Following is the Print dialog box −
The following are some of the commonly used properties of the PrintDialog control −
AllowCurrentPage
Gets or sets a value indicating whether the Current Page option button is displayed.
AllowPrintToFile
Gets or sets a value indicating whether the Print to file check box is enabled.
AllowSelection
Gets or sets a value indicating whether the Selection option button is enabled.
AllowSomePages
Gets or sets a value indicating whether the Pages option button is enabled.
Document
Gets or sets a value indicating the PrintDocument used to obtain PrinterSettings.
PrinterSettings
Gets or sets the printer settings the dialog box modifies.
PrintToFile
Gets or sets a value indicating whether the Print to file check box is selected.
ShowHelp
Gets or sets a value indicating whether the Help button is displayed.
ShowNetwork
Gets or sets a value indicating whether the Network button is displayed.
The following are some of the commonly used methods of the PrintDialog control −
Reset
Resets all options to their default values.
RunDialog
When overridden in a derived class, specifies a common dialog box.
ShowDialog
Runs a common dialog box with a default owner.
In this example, let us see how to show a Print dialog box in a form. Take the following steps −
Add a PrintDocument control, a PrintDialog control and a Button control on the form. The PrintDocument and the PrintDialog controls are found on the Print category of the controls toolbox.
Add a PrintDocument control, a PrintDialog control and a Button control on the form. The PrintDocument and the PrintDialog controls are found on the Print category of the controls toolbox.
Change the text of the button to 'Print'.
Change the text of the button to 'Print'.
Double-click the Print button and modify the code of the Click event as shown −
Double-click the Print button and modify the code of the Click event as shown −
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
PrintDialog1.Document = PrintDocument1
PrintDialog1.PrinterSettings = PrintDocument1.PrinterSettings
PrintDialog1.AllowSomePages = True
If PrintDialog1.ShowDialog = DialogResult.OK Then
PrintDocument1.PrinterSettings = PrintDialog1.PrinterSettings
PrintDocument1.Print()
End If
End Sub
When the application is compiled and run using Start button available at the Microsoft Visual Studio tool bar, it will show the following window −
Click the Print button to make the Print dialog box appear.
63 Lectures
4 hours
Frahaan Hussain
103 Lectures
12 hours
Arnold Higuit
60 Lectures
9.5 hours
Arnold Higuit
97 Lectures
9 hours
Arnold Higuit
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2467,
"s": 2300,
"text": "The PrintDialog control lets the user to print documents by selecting a printer and choosing which sections of the document to print from a Windows Forms application."
},
{
"code": null,
"e": 2623,
"s": 2467,
"text": "There are various other controls related to printing of documents. Let us have a brief look at these controls and their purpose. These other controls are −"
},
{
"code": null,
"e": 2770,
"s": 2623,
"text": "The PrintDocument control − it provides support for actual events and operations of printing in Visual Basic and sets the properties for printing."
},
{
"code": null,
"e": 2917,
"s": 2770,
"text": "The PrintDocument control − it provides support for actual events and operations of printing in Visual Basic and sets the properties for printing."
},
{
"code": null,
"e": 3024,
"s": 2917,
"text": "The PrinterSettings control − it is used to configure how a document is printed by specifying the printer."
},
{
"code": null,
"e": 3131,
"s": 3024,
"text": "The PrinterSettings control − it is used to configure how a document is printed by specifying the printer."
},
{
"code": null,
"e": 3275,
"s": 3131,
"text": "The PageSetUpDialog control − it allows the user to specify page-related print settings including page orientation, paper size and margin size."
},
{
"code": null,
"e": 3419,
"s": 3275,
"text": "The PageSetUpDialog control − it allows the user to specify page-related print settings including page orientation, paper size and margin size."
},
{
"code": null,
"e": 3579,
"s": 3419,
"text": "The PrintPreviewControl control − it represents the raw preview part of print previewing from a Windows Forms application, without any dialog boxes or buttons."
},
{
"code": null,
"e": 3739,
"s": 3579,
"text": "The PrintPreviewControl control − it represents the raw preview part of print previewing from a Windows Forms application, without any dialog boxes or buttons."
},
{
"code": null,
"e": 3887,
"s": 3739,
"text": "The PrintPreviewDialog control − it represents a dialog box form that contains a PrintPreviewControl for printing from a Windows Forms application."
},
{
"code": null,
"e": 4035,
"s": 3887,
"text": "The PrintPreviewDialog control − it represents a dialog box form that contains a PrintPreviewControl for printing from a Windows Forms application."
},
{
"code": null,
"e": 4071,
"s": 4035,
"text": "Following is the Print dialog box −"
},
{
"code": null,
"e": 4155,
"s": 4071,
"text": "The following are some of the commonly used properties of the PrintDialog control −"
},
{
"code": null,
"e": 4172,
"s": 4155,
"text": "AllowCurrentPage"
},
{
"code": null,
"e": 4258,
"s": 4172,
"text": "Gets or sets a value indicating whether the Current Page option button is displayed. "
},
{
"code": null,
"e": 4275,
"s": 4258,
"text": "AllowPrintToFile"
},
{
"code": null,
"e": 4355,
"s": 4275,
"text": "Gets or sets a value indicating whether the Print to file check box is enabled."
},
{
"code": null,
"e": 4370,
"s": 4355,
"text": "AllowSelection"
},
{
"code": null,
"e": 4450,
"s": 4370,
"text": "Gets or sets a value indicating whether the Selection option button is enabled."
},
{
"code": null,
"e": 4465,
"s": 4450,
"text": "AllowSomePages"
},
{
"code": null,
"e": 4541,
"s": 4465,
"text": "Gets or sets a value indicating whether the Pages option button is enabled."
},
{
"code": null,
"e": 4550,
"s": 4541,
"text": "Document"
},
{
"code": null,
"e": 4632,
"s": 4550,
"text": "Gets or sets a value indicating the PrintDocument used to obtain PrinterSettings."
},
{
"code": null,
"e": 4648,
"s": 4632,
"text": "PrinterSettings"
},
{
"code": null,
"e": 4707,
"s": 4648,
"text": "Gets or sets the printer settings the dialog box modifies."
},
{
"code": null,
"e": 4719,
"s": 4707,
"text": "PrintToFile"
},
{
"code": null,
"e": 4800,
"s": 4719,
"text": "Gets or sets a value indicating whether the Print to file check box is selected."
},
{
"code": null,
"e": 4809,
"s": 4800,
"text": "ShowHelp"
},
{
"code": null,
"e": 4879,
"s": 4809,
"text": "Gets or sets a value indicating whether the Help button is displayed."
},
{
"code": null,
"e": 4891,
"s": 4879,
"text": "ShowNetwork"
},
{
"code": null,
"e": 4964,
"s": 4891,
"text": "Gets or sets a value indicating whether the Network button is displayed."
},
{
"code": null,
"e": 5045,
"s": 4964,
"text": "The following are some of the commonly used methods of the PrintDialog control −"
},
{
"code": null,
"e": 5051,
"s": 5045,
"text": "Reset"
},
{
"code": null,
"e": 5095,
"s": 5051,
"text": "Resets all options to their default values."
},
{
"code": null,
"e": 5105,
"s": 5095,
"text": "RunDialog"
},
{
"code": null,
"e": 5172,
"s": 5105,
"text": "When overridden in a derived class, specifies a common dialog box."
},
{
"code": null,
"e": 5183,
"s": 5172,
"text": "ShowDialog"
},
{
"code": null,
"e": 5230,
"s": 5183,
"text": "Runs a common dialog box with a default owner."
},
{
"code": null,
"e": 5327,
"s": 5230,
"text": "In this example, let us see how to show a Print dialog box in a form. Take the following steps −"
},
{
"code": null,
"e": 5517,
"s": 5327,
"text": "Add a PrintDocument control, a PrintDialog control and a Button control on the form. The PrintDocument and the PrintDialog controls are found on the Print category of the controls toolbox. "
},
{
"code": null,
"e": 5707,
"s": 5517,
"text": "Add a PrintDocument control, a PrintDialog control and a Button control on the form. The PrintDocument and the PrintDialog controls are found on the Print category of the controls toolbox. "
},
{
"code": null,
"e": 5749,
"s": 5707,
"text": "Change the text of the button to 'Print'."
},
{
"code": null,
"e": 5791,
"s": 5749,
"text": "Change the text of the button to 'Print'."
},
{
"code": null,
"e": 5872,
"s": 5791,
"text": "Double-click the Print button and modify the code of the Click event as shown −\n"
},
{
"code": null,
"e": 5952,
"s": 5872,
"text": "Double-click the Print button and modify the code of the Click event as shown −"
},
{
"code": null,
"e": 6351,
"s": 5952,
"text": "Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click\n PrintDialog1.Document = PrintDocument1\n PrintDialog1.PrinterSettings = PrintDocument1.PrinterSettings\n PrintDialog1.AllowSomePages = True\n \n If PrintDialog1.ShowDialog = DialogResult.OK Then\n PrintDocument1.PrinterSettings = PrintDialog1.PrinterSettings\n PrintDocument1.Print()\n End If\nEnd Sub"
},
{
"code": null,
"e": 6498,
"s": 6351,
"text": "When the application is compiled and run using Start button available at the Microsoft Visual Studio tool bar, it will show the following window −"
},
{
"code": null,
"e": 6558,
"s": 6498,
"text": "Click the Print button to make the Print dialog box appear."
},
{
"code": null,
"e": 6591,
"s": 6558,
"text": "\n 63 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 6608,
"s": 6591,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 6643,
"s": 6608,
"text": "\n 103 Lectures \n 12 hours \n"
},
{
"code": null,
"e": 6658,
"s": 6643,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 6693,
"s": 6658,
"text": "\n 60 Lectures \n 9.5 hours \n"
},
{
"code": null,
"e": 6708,
"s": 6693,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 6741,
"s": 6708,
"text": "\n 97 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 6756,
"s": 6741,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 6763,
"s": 6756,
"text": " Print"
},
{
"code": null,
"e": 6774,
"s": 6763,
"text": " Add Notes"
}
] |
Extract only characters from given string in Python
|
A piece of data may contain letters, numbers as well as special characters. If we are interested in extracting only the letters form this string of data, then we can use various options available in python.
The isalpha function will check if the given character is an alphabet or not. We will use this inside a for loop which will fetch each character from the given string and check if it is an alphabet. The join method will capture only the valid characters into the result.
Live Demo
stringA = "Qwer34^&t%y"
# Given string
print("Given string : ", stringA)
# Find characters
res = ""
for i in stringA:
if i.isalpha():
res = "".join([res, i])
# Result
print("Result: ", res)
Running the above code gives us the following result −
Given string : Qwer34^&t%y
Result: Qwerty
We can leverage the regular expression module and use the function findall giving the parameter value which represents only the characters.
Live Demo
import re
stringA = "Qwer34^&t%y"
# Given string
print("Given string : ", stringA)
# Find characters
res = "".join(re.findall("[a-zA-Z]+", stringA))
# Result
print("Result: ", res)
Running the above code gives us the following result −
Given string : Qwer34^&t%y
Result: Qwerty
|
[
{
"code": null,
"e": 1269,
"s": 1062,
"text": "A piece of data may contain letters, numbers as well as special characters. If we are interested in extracting only the letters form this string of data, then we can use various options available in python."
},
{
"code": null,
"e": 1540,
"s": 1269,
"text": "The isalpha function will check if the given character is an alphabet or not. We will use this inside a for loop which will fetch each character from the given string and check if it is an alphabet. The join method will capture only the valid characters into the result."
},
{
"code": null,
"e": 1551,
"s": 1540,
"text": " Live Demo"
},
{
"code": null,
"e": 1744,
"s": 1551,
"text": "stringA = \"Qwer34^&t%y\"\n\n# Given string\nprint(\"Given string : \", stringA)\n\n# Find characters\nres = \"\"\nfor i in stringA:\nif i.isalpha():\nres = \"\".join([res, i])\n\n# Result\nprint(\"Result: \", res)"
},
{
"code": null,
"e": 1799,
"s": 1744,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 1841,
"s": 1799,
"text": "Given string : Qwer34^&t%y\nResult: Qwerty"
},
{
"code": null,
"e": 1981,
"s": 1841,
"text": "We can leverage the regular expression module and use the function findall giving the parameter value which represents only the characters."
},
{
"code": null,
"e": 1992,
"s": 1981,
"text": " Live Demo"
},
{
"code": null,
"e": 2176,
"s": 1992,
"text": "import re\nstringA = \"Qwer34^&t%y\"\n\n# Given string\nprint(\"Given string : \", stringA)\n\n# Find characters\nres = \"\".join(re.findall(\"[a-zA-Z]+\", stringA))\n\n# Result\nprint(\"Result: \", res)"
},
{
"code": null,
"e": 2231,
"s": 2176,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2273,
"s": 2231,
"text": "Given string : Qwer34^&t%y\nResult: Qwerty"
}
] |
Use of bool in C - GeeksforGeeks
|
14 Oct, 2020
Prerequisite: Bool Data Type in C++The C99 standard for C language supports bool variables. Unlike C++, where no header file is needed to use bool, a header file “stdbool.h” must be included to use bool in C. If we save the below program as .c, it will not compile, but if we save it as .cpp, it will work fine.
C
int main(){ bool arr[2] = {true, false}; return 0;}
If we include the header file “stdbool.h” in the above program, it will work fine as a C program.
C
#include <stdbool.h>int main(){ bool arr[2] = { true, false }; return 0;}
There is one more way to do it using enum function in C language. You can create a bool using enum. One enum will be created as bool, then put the elements of enum as True and False respectively. The false will be at the first position, so it will hold 0, and true will be at the second position, so it will get value 1.
Below is the implementation of the above idea:
C
// C implementation of the above idea#include <stdio.h> // Declaration of enumtypedef enum { F, T } boolean; int main(){ boolean bool1, bool2; bool1 = F; if (bool1 == F) { printf("bool1 is false\n"); } else { printf("bool1 is true\n"); } bool2 = 2; if (bool2 == F) { printf("bool2 is false\n"); } else { printf("bool2 is true\n"); }}
bool1 is false
bool2 is true
pulkitagarwal03pulkit
C-Data Types
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
rand() and srand() in C/C++
Left Shift and Right Shift Operators in C/C++
Core Dump (Segmentation fault) in C/C++
fork() in C
Command line arguments in C/C++
Function Pointer in C
Substring in C++
Structures in C
Different methods to reverse a string in C/C++
TCP Server-Client implementation in C
|
[
{
"code": null,
"e": 24444,
"s": 24416,
"text": "\n14 Oct, 2020"
},
{
"code": null,
"e": 24758,
"s": 24444,
"text": "Prerequisite: Bool Data Type in C++The C99 standard for C language supports bool variables. Unlike C++, where no header file is needed to use bool, a header file “stdbool.h” must be included to use bool in C. If we save the below program as .c, it will not compile, but if we save it as .cpp, it will work fine. "
},
{
"code": null,
"e": 24760,
"s": 24758,
"text": "C"
},
{
"code": "int main(){ bool arr[2] = {true, false}; return 0;}",
"e": 24814,
"s": 24760,
"text": null
},
{
"code": null,
"e": 24913,
"s": 24814,
"text": "If we include the header file “stdbool.h” in the above program, it will work fine as a C program. "
},
{
"code": null,
"e": 24915,
"s": 24913,
"text": "C"
},
{
"code": "#include <stdbool.h>int main(){ bool arr[2] = { true, false }; return 0;}",
"e": 24995,
"s": 24915,
"text": null
},
{
"code": null,
"e": 25316,
"s": 24995,
"text": "There is one more way to do it using enum function in C language. You can create a bool using enum. One enum will be created as bool, then put the elements of enum as True and False respectively. The false will be at the first position, so it will hold 0, and true will be at the second position, so it will get value 1."
},
{
"code": null,
"e": 25363,
"s": 25316,
"text": "Below is the implementation of the above idea:"
},
{
"code": null,
"e": 25365,
"s": 25363,
"text": "C"
},
{
"code": "// C implementation of the above idea#include <stdio.h> // Declaration of enumtypedef enum { F, T } boolean; int main(){ boolean bool1, bool2; bool1 = F; if (bool1 == F) { printf(\"bool1 is false\\n\"); } else { printf(\"bool1 is true\\n\"); } bool2 = 2; if (bool2 == F) { printf(\"bool2 is false\\n\"); } else { printf(\"bool2 is true\\n\"); }}",
"e": 25764,
"s": 25365,
"text": null
},
{
"code": null,
"e": 25794,
"s": 25764,
"text": "bool1 is false\nbool2 is true\n"
},
{
"code": null,
"e": 25816,
"s": 25794,
"text": "pulkitagarwal03pulkit"
},
{
"code": null,
"e": 25829,
"s": 25816,
"text": "C-Data Types"
},
{
"code": null,
"e": 25840,
"s": 25829,
"text": "C Language"
},
{
"code": null,
"e": 25938,
"s": 25840,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25966,
"s": 25938,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 26012,
"s": 25966,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 26052,
"s": 26012,
"text": "Core Dump (Segmentation fault) in C/C++"
},
{
"code": null,
"e": 26064,
"s": 26052,
"text": "fork() in C"
},
{
"code": null,
"e": 26096,
"s": 26064,
"text": "Command line arguments in C/C++"
},
{
"code": null,
"e": 26118,
"s": 26096,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 26135,
"s": 26118,
"text": "Substring in C++"
},
{
"code": null,
"e": 26151,
"s": 26135,
"text": "Structures in C"
},
{
"code": null,
"e": 26198,
"s": 26151,
"text": "Different methods to reverse a string in C/C++"
}
] |
AI with Python â Analyzing Time Series Data
|
Predicting the next in a given input sequence is another important concept in machine learning. This chapter gives you a detailed explanation about analyzing time series data.
Time series data means the data that is in a series of particular time intervals. If we want to build sequence prediction in machine learning, then we have to deal with sequential data and time. Series data is an abstract of sequential data. Ordering of data is an important feature of sequential data.
Sequence analysis or time series analysis is to predict the next in a given input sequence based on the previously observed. The prediction can be of anything that may come next: a symbol, a number, next day weather, next term in speech etc. Sequence analysis can be very handy in applications such as stock market analysis, weather forecasting, and product recommendations.
Example
Consider the following example to understand sequence prediction. Here A,B,C,D are the given values and you have to predict the value E using a Sequence Prediction Model.
For time series data analysis using Python, we need to install the following packages −
Pandas is an open source BSD-licensed library which provides high-performance, ease of data structure usage and data analysis tools for Python. You can install Pandas with the help of the following command −
pip install pandas
If you are using Anaconda and want to install by using the conda package manager, then you can use the following command −
conda install -c anaconda pandas
It is an open source BSD-licensed library which consists of simple algorithms and models to learn Hidden Markov Models(HMM) in Python. You can install it with the help of the following command −
pip install hmmlearn
If you are using Anaconda and want to install by using the conda package manager, then you can use the following command −
conda install -c omnia hmmlearn
It is a structured learning and prediction library. Learning algorithms implemented in PyStruct have names such as conditional random fields(CRF), Maximum-Margin Markov Random Networks (M3N) or structural support vector machines. You can install it with the help of the following command −
pip install pystruct
It is used for convex optimization based on Python programming language. It is also a free software package. You can install it with the help of following command −
pip install cvxopt
If you are using Anaconda and want to install by using the conda package manager, then you can use the following command −
conda install -c anaconda cvdoxt
Pandas is a very useful tool if you have to work with time series data. With the help of Pandas, you can perform the following −
Create a range of dates by using the pd.date_range package
Create a range of dates by using the pd.date_range package
Index pandas with dates by using the pd.Series package
Index pandas with dates by using the pd.Series package
Perform re-sampling by using the ts.resample package
Perform re-sampling by using the ts.resample package
Change the frequency
Change the frequency
The following example shows you handling and slicing the time series data by using Pandas. Note that here we are using the Monthly Arctic Oscillation data, which can be downloaded from monthly.ao.index.b50.current.ascii and can be converted to text format for our use.
For handling time series data, you will have to perform the following steps −
The first step involves importing the following packages −
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
Next, define a function which will read the data from the input file, as shown in the code given below −
def read_data(input_file):
input_data = np.loadtxt(input_file, delimiter = None)
Now, convert this data to time series. For this, create the range of dates of our time series. In this example, we keep one month as frequency of data. Our file is having the data which starts from January 1950.
dates = pd.date_range('1950-01', periods = input_data.shape[0], freq = 'M')
In this step, we create the time series data with the help of Pandas Series, as shown below −
output = pd.Series(input_data[:, index], index = dates)
return output
if __name__=='__main__':
Enter the path of the input file as shown here −
input_file = "/Users/admin/AO.txt"
Now, convert the column to timeseries format, as shown here −
timeseries = read_data(input_file)
Finally, plot and visualize the data, using the commands shown −
plt.figure()
timeseries.plot()
plt.show()
You will observe the plots as shown in the following images −
Slicing involves retrieving only some part of the time series data. As a part of the example, we are slicing the data only from 1980 to 1990. Observe the following code that performs this task −
timeseries['1980':'1990'].plot()
<matplotlib.axes._subplots.AxesSubplot at 0xa0e4b00>
plt.show()
When you run the code for slicing the time series data, you can observe the following graph as shown in the image here −
You will have to extract some statistics from a given data, in cases where you need to draw some important conclusion. Mean, variance, correlation, maximum value, and minimum value are some of such statistics. You can use the following code if you want to extract such statistics from a given time series data −
You can use the mean() function, for finding the mean, as shown here −
timeseries.mean()
Then the output that you will observe for the example discussed is −
-0.11143128165238671
You can use the max() function, for finding maximum, as shown here −
timeseries.max()
Then the output that you will observe for the example discussed is −
3.4952999999999999
You can use the min() function, for finding minimum, as shown here −
timeseries.min()
Then the output that you will observe for the example discussed is −
-4.2656999999999998
If you want to calculate all statistics at a time, you can use the describe() function as shown here −
timeseries.describe()
Then the output that you will observe for the example discussed is −
count 817.000000
mean -0.111431
std 1.003151
min -4.265700
25% -0.649430
50% -0.042744
75% 0.475720
max 3.495300
dtype: float64
You can resample the data to a different time frequency. The two parameters for performing re-sampling are −
Time period
Method
You can use the following code to resample the data with the mean()method, which is the default method −
timeseries_mm = timeseries.resample("A").mean()
timeseries_mm.plot(style = 'g--')
plt.show()
Then, you can observe the following graph as the output of resampling using mean() −
You can use the following code to resample the data using the median()method −
timeseries_mm = timeseries.resample("A").median()
timeseries_mm.plot()
plt.show()
Then, you can observe the following graph as the output of re-sampling with median() −
You can use the following code to calculate the rolling (moving) mean −
timeseries.rolling(window = 12, center = False).mean().plot(style = '-g')
plt.show()
Then, you can observe the following graph as the output of the rolling (moving) mean −
HMM is a statistic model which is widely used for data having continuation and extensibility such as time series stock market analysis, health checkup, and speech recognition. This section deals in detail with analyzing sequential data using Hidden Markov Model (HMM).
HMM is a stochastic model which is built upon the concept of Markov chain based on the assumption that probability of future stats depends only on the current process state rather any state that preceded it. For example, when tossing a coin, we cannot say that the result of the fifth toss will be a head. This is because a coin does not have any memory and the next result does not depend on the previous result.
Mathematically, HMM consists of the following variables −
It is a set of hidden or latent states present in a HMM. It is denoted by S.
It is a set of possible output symbols present in a HMM. It is denoted by O.
It is the probability of making transition from one state to each of the other states. It is denoted by A.
It is the probability of emitting/observing a symbol at a particular state. It is denoted by B.
It is the probability of starting at a particular state from various states of the system. It is denoted by Π.
Hence, a HMM may be defined as λ = (S,O,A,B,π),
where,
S = {s1,s2,...,sN} is a set of N possible states,
O = {o1,o2,...,oM} is a set of M possible observation symbols,
A is an NxN state Transition Probability Matrix (TPM),
B is an NxM observation or Emission Probability Matrix (EPM),
π is an N dimensional initial state probability distribution vector.
In this example, we are going to analyze the data of stock market, step by step, to get an idea about how the HMM works with sequential or time series data. Please note that we are implementing this example in Python.
Import the necessary packages as shown below −
import datetime
import warnings
Now, use the stock market data from the matpotlib.finance package, as shown here −
import numpy as np
from matplotlib import cm, pyplot as plt
from matplotlib.dates import YearLocator, MonthLocator
try:
from matplotlib.finance import quotes_historical_yahoo_och1
except ImportError:
from matplotlib.finance import (
quotes_historical_yahoo as quotes_historical_yahoo_och1)
from hmmlearn.hmm import GaussianHMM
Load the data from a start date and end date, i.e., between two specific dates as shown here −
start_date = datetime.date(1995, 10, 10)
end_date = datetime.date(2015, 4, 25)
quotes = quotes_historical_yahoo_och1('INTC', start_date, end_date)
In this step, we will extract the closing quotes every day. For this, use the following command −
closing_quotes = np.array([quote[2] for quote in quotes])
Now, we will extract the volume of shares traded every day. For this, use the following command −
volumes = np.array([quote[5] for quote in quotes])[1:]
Here, take the percentage difference of closing stock prices, using the code shown below −
diff_percentages = 100.0 * np.diff(closing_quotes) / closing_quotes[:-]
dates = np.array([quote[0] for quote in quotes], dtype = np.int)[1:]
training_data = np.column_stack([diff_percentages, volumes])
In this step, create and train the Gaussian HMM. For this, use the following code −
hmm = GaussianHMM(n_components = 7, covariance_type = 'diag', n_iter = 1000)
with warnings.catch_warnings():
warnings.simplefilter('ignore')
hmm.fit(training_data)
Now, generate data using the HMM model, using the commands shown −
num_samples = 300
samples, _ = hmm.sample(num_samples)
Finally, in this step, we plot and visualize the difference percentage and volume of shares traded as output in the form of graph.
Use the following code to plot and visualize the difference percentages −
plt.figure()
plt.title('Difference percentages')
plt.plot(np.arange(num_samples), samples[:, 0], c = 'black')
Use the following code to plot and visualize the volume of shares traded −
plt.figure()
plt.title('Volume of shares')
plt.plot(np.arange(num_samples), samples[:, 1], c = 'black')
plt.ylim(ymin = 0)
plt.show()
78 Lectures
7 hours
Arnab Chakraborty
87 Lectures
9.5 hours
DigiFisk (Programming Is Fun)
10 Lectures
1 hours
Nikoloz Sanakoevi
15 Lectures
54 mins
Mukund Kumar Mishra
11 Lectures
1 hours
Gilad James, PhD
20 Lectures
2 hours
Gilad James, PhD
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2381,
"s": 2205,
"text": "Predicting the next in a given input sequence is another important concept in machine learning. This chapter gives you a detailed explanation about analyzing time series data."
},
{
"code": null,
"e": 2684,
"s": 2381,
"text": "Time series data means the data that is in a series of particular time intervals. If we want to build sequence prediction in machine learning, then we have to deal with sequential data and time. Series data is an abstract of sequential data. Ordering of data is an important feature of sequential data."
},
{
"code": null,
"e": 3059,
"s": 2684,
"text": "Sequence analysis or time series analysis is to predict the next in a given input sequence based on the previously observed. The prediction can be of anything that may come next: a symbol, a number, next day weather, next term in speech etc. Sequence analysis can be very handy in applications such as stock market analysis, weather forecasting, and product recommendations."
},
{
"code": null,
"e": 3067,
"s": 3059,
"text": "Example"
},
{
"code": null,
"e": 3238,
"s": 3067,
"text": "Consider the following example to understand sequence prediction. Here A,B,C,D are the given values and you have to predict the value E using a Sequence Prediction Model."
},
{
"code": null,
"e": 3326,
"s": 3238,
"text": "For time series data analysis using Python, we need to install the following packages −"
},
{
"code": null,
"e": 3534,
"s": 3326,
"text": "Pandas is an open source BSD-licensed library which provides high-performance, ease of data structure usage and data analysis tools for Python. You can install Pandas with the help of the following command −"
},
{
"code": null,
"e": 3554,
"s": 3534,
"text": "pip install pandas\n"
},
{
"code": null,
"e": 3677,
"s": 3554,
"text": "If you are using Anaconda and want to install by using the conda package manager, then you can use the following command −"
},
{
"code": null,
"e": 3711,
"s": 3677,
"text": "conda install -c anaconda pandas\n"
},
{
"code": null,
"e": 3906,
"s": 3711,
"text": "It is an open source BSD-licensed library which consists of simple algorithms and models to learn Hidden Markov Models(HMM) in Python. You can install it with the help of the following command −"
},
{
"code": null,
"e": 3928,
"s": 3906,
"text": "pip install hmmlearn\n"
},
{
"code": null,
"e": 4051,
"s": 3928,
"text": "If you are using Anaconda and want to install by using the conda package manager, then you can use the following command −"
},
{
"code": null,
"e": 4084,
"s": 4051,
"text": "conda install -c omnia hmmlearn\n"
},
{
"code": null,
"e": 4374,
"s": 4084,
"text": "It is a structured learning and prediction library. Learning algorithms implemented in PyStruct have names such as conditional random fields(CRF), Maximum-Margin Markov Random Networks (M3N) or structural support vector machines. You can install it with the help of the following command −"
},
{
"code": null,
"e": 4396,
"s": 4374,
"text": "pip install pystruct\n"
},
{
"code": null,
"e": 4561,
"s": 4396,
"text": "It is used for convex optimization based on Python programming language. It is also a free software package. You can install it with the help of following command −"
},
{
"code": null,
"e": 4581,
"s": 4561,
"text": "pip install cvxopt\n"
},
{
"code": null,
"e": 4704,
"s": 4581,
"text": "If you are using Anaconda and want to install by using the conda package manager, then you can use the following command −"
},
{
"code": null,
"e": 4738,
"s": 4704,
"text": "conda install -c anaconda cvdoxt\n"
},
{
"code": null,
"e": 4867,
"s": 4738,
"text": "Pandas is a very useful tool if you have to work with time series data. With the help of Pandas, you can perform the following −"
},
{
"code": null,
"e": 4926,
"s": 4867,
"text": "Create a range of dates by using the pd.date_range package"
},
{
"code": null,
"e": 4985,
"s": 4926,
"text": "Create a range of dates by using the pd.date_range package"
},
{
"code": null,
"e": 5040,
"s": 4985,
"text": "Index pandas with dates by using the pd.Series package"
},
{
"code": null,
"e": 5095,
"s": 5040,
"text": "Index pandas with dates by using the pd.Series package"
},
{
"code": null,
"e": 5148,
"s": 5095,
"text": "Perform re-sampling by using the ts.resample package"
},
{
"code": null,
"e": 5201,
"s": 5148,
"text": "Perform re-sampling by using the ts.resample package"
},
{
"code": null,
"e": 5222,
"s": 5201,
"text": "Change the frequency"
},
{
"code": null,
"e": 5243,
"s": 5222,
"text": "Change the frequency"
},
{
"code": null,
"e": 5512,
"s": 5243,
"text": "The following example shows you handling and slicing the time series data by using Pandas. Note that here we are using the Monthly Arctic Oscillation data, which can be downloaded from monthly.ao.index.b50.current.ascii and can be converted to text format for our use."
},
{
"code": null,
"e": 5590,
"s": 5512,
"text": "For handling time series data, you will have to perform the following steps −"
},
{
"code": null,
"e": 5649,
"s": 5590,
"text": "The first step involves importing the following packages −"
},
{
"code": null,
"e": 5720,
"s": 5649,
"text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd"
},
{
"code": null,
"e": 5825,
"s": 5720,
"text": "Next, define a function which will read the data from the input file, as shown in the code given below −"
},
{
"code": null,
"e": 5909,
"s": 5825,
"text": "def read_data(input_file):\n input_data = np.loadtxt(input_file, delimiter = None)"
},
{
"code": null,
"e": 6121,
"s": 5909,
"text": "Now, convert this data to time series. For this, create the range of dates of our time series. In this example, we keep one month as frequency of data. Our file is having the data which starts from January 1950."
},
{
"code": null,
"e": 6197,
"s": 6121,
"text": "dates = pd.date_range('1950-01', periods = input_data.shape[0], freq = 'M')"
},
{
"code": null,
"e": 6291,
"s": 6197,
"text": "In this step, we create the time series data with the help of Pandas Series, as shown below −"
},
{
"code": null,
"e": 6389,
"s": 6291,
"text": "output = pd.Series(input_data[:, index], index = dates)\t\nreturn output\n\t\nif __name__=='__main__':"
},
{
"code": null,
"e": 6438,
"s": 6389,
"text": "Enter the path of the input file as shown here −"
},
{
"code": null,
"e": 6473,
"s": 6438,
"text": "input_file = \"/Users/admin/AO.txt\""
},
{
"code": null,
"e": 6535,
"s": 6473,
"text": "Now, convert the column to timeseries format, as shown here −"
},
{
"code": null,
"e": 6570,
"s": 6535,
"text": "timeseries = read_data(input_file)"
},
{
"code": null,
"e": 6635,
"s": 6570,
"text": "Finally, plot and visualize the data, using the commands shown −"
},
{
"code": null,
"e": 6677,
"s": 6635,
"text": "plt.figure()\ntimeseries.plot()\nplt.show()"
},
{
"code": null,
"e": 6739,
"s": 6677,
"text": "You will observe the plots as shown in the following images −"
},
{
"code": null,
"e": 6934,
"s": 6739,
"text": "Slicing involves retrieving only some part of the time series data. As a part of the example, we are slicing the data only from 1980 to 1990. Observe the following code that performs this task −"
},
{
"code": null,
"e": 7035,
"s": 6934,
"text": "timeseries['1980':'1990'].plot()\n <matplotlib.axes._subplots.AxesSubplot at 0xa0e4b00>\n\nplt.show()"
},
{
"code": null,
"e": 7156,
"s": 7035,
"text": "When you run the code for slicing the time series data, you can observe the following graph as shown in the image here −"
},
{
"code": null,
"e": 7468,
"s": 7156,
"text": "You will have to extract some statistics from a given data, in cases where you need to draw some important conclusion. Mean, variance, correlation, maximum value, and minimum value are some of such statistics. You can use the following code if you want to extract such statistics from a given time series data −"
},
{
"code": null,
"e": 7539,
"s": 7468,
"text": "You can use the mean() function, for finding the mean, as shown here −"
},
{
"code": null,
"e": 7557,
"s": 7539,
"text": "timeseries.mean()"
},
{
"code": null,
"e": 7626,
"s": 7557,
"text": "Then the output that you will observe for the example discussed is −"
},
{
"code": null,
"e": 7648,
"s": 7626,
"text": "-0.11143128165238671\n"
},
{
"code": null,
"e": 7717,
"s": 7648,
"text": "You can use the max() function, for finding maximum, as shown here −"
},
{
"code": null,
"e": 7734,
"s": 7717,
"text": "timeseries.max()"
},
{
"code": null,
"e": 7803,
"s": 7734,
"text": "Then the output that you will observe for the example discussed is −"
},
{
"code": null,
"e": 7823,
"s": 7803,
"text": "3.4952999999999999\n"
},
{
"code": null,
"e": 7892,
"s": 7823,
"text": "You can use the min() function, for finding minimum, as shown here −"
},
{
"code": null,
"e": 7909,
"s": 7892,
"text": "timeseries.min()"
},
{
"code": null,
"e": 7978,
"s": 7909,
"text": "Then the output that you will observe for the example discussed is −"
},
{
"code": null,
"e": 7999,
"s": 7978,
"text": "-4.2656999999999998\n"
},
{
"code": null,
"e": 8102,
"s": 7999,
"text": "If you want to calculate all statistics at a time, you can use the describe() function as shown here −"
},
{
"code": null,
"e": 8124,
"s": 8102,
"text": "timeseries.describe()"
},
{
"code": null,
"e": 8193,
"s": 8124,
"text": "Then the output that you will observe for the example discussed is −"
},
{
"code": null,
"e": 8361,
"s": 8193,
"text": "count 817.000000\nmean -0.111431\nstd 1.003151\nmin -4.265700\n25% -0.649430\n50% -0.042744\n75% 0.475720\nmax 3.495300\ndtype: float64\n"
},
{
"code": null,
"e": 8470,
"s": 8361,
"text": "You can resample the data to a different time frequency. The two parameters for performing re-sampling are −"
},
{
"code": null,
"e": 8482,
"s": 8470,
"text": "Time period"
},
{
"code": null,
"e": 8489,
"s": 8482,
"text": "Method"
},
{
"code": null,
"e": 8594,
"s": 8489,
"text": "You can use the following code to resample the data with the mean()method, which is the default method −"
},
{
"code": null,
"e": 8687,
"s": 8594,
"text": "timeseries_mm = timeseries.resample(\"A\").mean()\ntimeseries_mm.plot(style = 'g--')\nplt.show()"
},
{
"code": null,
"e": 8772,
"s": 8687,
"text": "Then, you can observe the following graph as the output of resampling using mean() −"
},
{
"code": null,
"e": 8851,
"s": 8772,
"text": "You can use the following code to resample the data using the median()method −"
},
{
"code": null,
"e": 8934,
"s": 8851,
"text": "timeseries_mm = timeseries.resample(\"A\").median()\ntimeseries_mm.plot()\nplt.show()\n"
},
{
"code": null,
"e": 9021,
"s": 8934,
"text": "Then, you can observe the following graph as the output of re-sampling with median() −"
},
{
"code": null,
"e": 9093,
"s": 9021,
"text": "You can use the following code to calculate the rolling (moving) mean −"
},
{
"code": null,
"e": 9178,
"s": 9093,
"text": "timeseries.rolling(window = 12, center = False).mean().plot(style = '-g')\nplt.show()"
},
{
"code": null,
"e": 9265,
"s": 9178,
"text": "Then, you can observe the following graph as the output of the rolling (moving) mean −"
},
{
"code": null,
"e": 9534,
"s": 9265,
"text": "HMM is a statistic model which is widely used for data having continuation and extensibility such as time series stock market analysis, health checkup, and speech recognition. This section deals in detail with analyzing sequential data using Hidden Markov Model (HMM)."
},
{
"code": null,
"e": 9948,
"s": 9534,
"text": "HMM is a stochastic model which is built upon the concept of Markov chain based on the assumption that probability of future stats depends only on the current process state rather any state that preceded it. For example, when tossing a coin, we cannot say that the result of the fifth toss will be a head. This is because a coin does not have any memory and the next result does not depend on the previous result."
},
{
"code": null,
"e": 10006,
"s": 9948,
"text": "Mathematically, HMM consists of the following variables −"
},
{
"code": null,
"e": 10083,
"s": 10006,
"text": "It is a set of hidden or latent states present in a HMM. It is denoted by S."
},
{
"code": null,
"e": 10160,
"s": 10083,
"text": "It is a set of possible output symbols present in a HMM. It is denoted by O."
},
{
"code": null,
"e": 10267,
"s": 10160,
"text": "It is the probability of making transition from one state to each of the other states. It is denoted by A."
},
{
"code": null,
"e": 10363,
"s": 10267,
"text": "It is the probability of emitting/observing a symbol at a particular state. It is denoted by B."
},
{
"code": null,
"e": 10474,
"s": 10363,
"text": "It is the probability of starting at a particular state from various states of the system. It is denoted by Π."
},
{
"code": null,
"e": 10522,
"s": 10474,
"text": "Hence, a HMM may be defined as λ = (S,O,A,B,π),"
},
{
"code": null,
"e": 10529,
"s": 10522,
"text": "where,"
},
{
"code": null,
"e": 10579,
"s": 10529,
"text": "S = {s1,s2,...,sN} is a set of N possible states,"
},
{
"code": null,
"e": 10642,
"s": 10579,
"text": "O = {o1,o2,...,oM} is a set of M possible observation symbols,"
},
{
"code": null,
"e": 10697,
"s": 10642,
"text": "A is an NxN state Transition Probability Matrix (TPM),"
},
{
"code": null,
"e": 10759,
"s": 10697,
"text": "B is an NxM observation or Emission Probability Matrix (EPM),"
},
{
"code": null,
"e": 10828,
"s": 10759,
"text": "π is an N dimensional initial state probability distribution vector."
},
{
"code": null,
"e": 11046,
"s": 10828,
"text": "In this example, we are going to analyze the data of stock market, step by step, to get an idea about how the HMM works with sequential or time series data. Please note that we are implementing this example in Python."
},
{
"code": null,
"e": 11093,
"s": 11046,
"text": "Import the necessary packages as shown below −"
},
{
"code": null,
"e": 11125,
"s": 11093,
"text": "import datetime\nimport warnings"
},
{
"code": null,
"e": 11208,
"s": 11125,
"text": "Now, use the stock market data from the matpotlib.finance package, as shown here −"
},
{
"code": null,
"e": 11548,
"s": 11208,
"text": "import numpy as np\nfrom matplotlib import cm, pyplot as plt\nfrom matplotlib.dates import YearLocator, MonthLocator\ntry:\n from matplotlib.finance import quotes_historical_yahoo_och1\nexcept ImportError:\n from matplotlib.finance import (\n quotes_historical_yahoo as quotes_historical_yahoo_och1)\n\nfrom hmmlearn.hmm import GaussianHMM"
},
{
"code": null,
"e": 11643,
"s": 11548,
"text": "Load the data from a start date and end date, i.e., between two specific dates as shown here −"
},
{
"code": null,
"e": 11790,
"s": 11643,
"text": "start_date = datetime.date(1995, 10, 10)\nend_date = datetime.date(2015, 4, 25)\nquotes = quotes_historical_yahoo_och1('INTC', start_date, end_date)"
},
{
"code": null,
"e": 11888,
"s": 11790,
"text": "In this step, we will extract the closing quotes every day. For this, use the following command −"
},
{
"code": null,
"e": 11947,
"s": 11888,
"text": "closing_quotes = np.array([quote[2] for quote in quotes])\n"
},
{
"code": null,
"e": 12045,
"s": 11947,
"text": "Now, we will extract the volume of shares traded every day. For this, use the following command −"
},
{
"code": null,
"e": 12101,
"s": 12045,
"text": "volumes = np.array([quote[5] for quote in quotes])[1:]\n"
},
{
"code": null,
"e": 12192,
"s": 12101,
"text": "Here, take the percentage difference of closing stock prices, using the code shown below −"
},
{
"code": null,
"e": 12394,
"s": 12192,
"text": "diff_percentages = 100.0 * np.diff(closing_quotes) / closing_quotes[:-]\ndates = np.array([quote[0] for quote in quotes], dtype = np.int)[1:]\ntraining_data = np.column_stack([diff_percentages, volumes])"
},
{
"code": null,
"e": 12478,
"s": 12394,
"text": "In this step, create and train the Gaussian HMM. For this, use the following code −"
},
{
"code": null,
"e": 12648,
"s": 12478,
"text": "hmm = GaussianHMM(n_components = 7, covariance_type = 'diag', n_iter = 1000)\nwith warnings.catch_warnings():\n warnings.simplefilter('ignore')\n hmm.fit(training_data)"
},
{
"code": null,
"e": 12715,
"s": 12648,
"text": "Now, generate data using the HMM model, using the commands shown −"
},
{
"code": null,
"e": 12771,
"s": 12715,
"text": "num_samples = 300\nsamples, _ = hmm.sample(num_samples)\n"
},
{
"code": null,
"e": 12902,
"s": 12771,
"text": "Finally, in this step, we plot and visualize the difference percentage and volume of shares traded as output in the form of graph."
},
{
"code": null,
"e": 12976,
"s": 12902,
"text": "Use the following code to plot and visualize the difference percentages −"
},
{
"code": null,
"e": 13086,
"s": 12976,
"text": "plt.figure()\nplt.title('Difference percentages')\nplt.plot(np.arange(num_samples), samples[:, 0], c = 'black')"
},
{
"code": null,
"e": 13161,
"s": 13086,
"text": "Use the following code to plot and visualize the volume of shares traded −"
},
{
"code": null,
"e": 13295,
"s": 13161,
"text": "plt.figure()\nplt.title('Volume of shares')\nplt.plot(np.arange(num_samples), samples[:, 1], c = 'black')\nplt.ylim(ymin = 0)\nplt.show()"
},
{
"code": null,
"e": 13328,
"s": 13295,
"text": "\n 78 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 13347,
"s": 13328,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 13382,
"s": 13347,
"text": "\n 87 Lectures \n 9.5 hours \n"
},
{
"code": null,
"e": 13413,
"s": 13382,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 13446,
"s": 13413,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 13465,
"s": 13446,
"text": " Nikoloz Sanakoevi"
},
{
"code": null,
"e": 13497,
"s": 13465,
"text": "\n 15 Lectures \n 54 mins\n"
},
{
"code": null,
"e": 13518,
"s": 13497,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 13551,
"s": 13518,
"text": "\n 11 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 13569,
"s": 13551,
"text": " Gilad James, PhD"
},
{
"code": null,
"e": 13602,
"s": 13569,
"text": "\n 20 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 13620,
"s": 13602,
"text": " Gilad James, PhD"
},
{
"code": null,
"e": 13627,
"s": 13620,
"text": " Print"
},
{
"code": null,
"e": 13638,
"s": 13627,
"text": " Add Notes"
}
] |
How to use regular expressions in xpath in Selenium with python?
|
We can identify elements by matching its attributes partially with the help of regular expressions. In xpath, there are multiple methods to achieve this. They are listed below −
Using the contains() method. This means the string contains our given text.
Using the contains() method. This means the string contains our given text.
Syntax −
driver.find_element_by_xpath("//input[contains(@name,'sel')]")
It will search the input tag which contains the 'name' attribute containing 'sel' text.
Using the starts-with() method. This means the string starts with our given text.
Using the starts-with() method. This means the string starts with our given text.
Syntax −
driver.find_element_by_xpath("//input[starts-with (@name,'Tut')]")
It will search the input tag which contains the 'name' attribute starting with 'Tut' text.
Using the ends-with() method. This means the string ends with our given text.
Using the ends-with() method. This means the string ends with our given text.
Syntax
driver.find_element_by_xpath("//input[ends-with (@name,'nium')]")
It will search the input tag which contains the 'name' attribute ending with 'nium' text.
Code Implementation with contains()
from selenium import webdriver
#browser exposes an executable file
#Through Selenium test we will invoke the executable file which will then #invoke actual browser
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://www.tutorialspoint.com/index.htm")
#to refresh the browser
driver.refresh()
# identifying the edit box with the help of contains() in xpath
driver.find_element_by_xpath("//input[contains(@id,'sc-i')]").
send_keys("Selenium")
#to close the browser
driver.close()
Code Implementation with starts-with()
from selenium import webdriver
#browser exposes an executable file
#Through Selenium test we will invoke the executable file which will then #invoke actual browser
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://www.tutorialspoint.com/index.htm")
#to refresh the browser
driver.refresh()
# identifying the edit box with the help of starts-with() in xpath
driver.find_element_by_xpath("//input[starts-with(@id,'gsc')]").
send_keys("Selenium")
#to close the browser
driver.close()
Code Implementation with ends-with()
from selenium import webdriver
#browser exposes an executable file
#Through Selenium test we will invoke the executable file which will then #invoke actual browser
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://www.tutorialspoint.com/index.htm")
#to refresh the browser
driver.refresh()
# identifying the edit box with the help of ends-with() in xpath
driver.find_element_by_xpath("//input[ends-with(@id,'id1')]").
send_keys("Selenium")
#to close the browser
driver.close()
|
[
{
"code": null,
"e": 1240,
"s": 1062,
"text": "We can identify elements by matching its attributes partially with the help of regular expressions. In xpath, there are multiple methods to achieve this. They are listed below −"
},
{
"code": null,
"e": 1316,
"s": 1240,
"text": "Using the contains() method. This means the string contains our given text."
},
{
"code": null,
"e": 1392,
"s": 1316,
"text": "Using the contains() method. This means the string contains our given text."
},
{
"code": null,
"e": 1401,
"s": 1392,
"text": "Syntax −"
},
{
"code": null,
"e": 1464,
"s": 1401,
"text": "driver.find_element_by_xpath(\"//input[contains(@name,'sel')]\")"
},
{
"code": null,
"e": 1552,
"s": 1464,
"text": "It will search the input tag which contains the 'name' attribute containing 'sel' text."
},
{
"code": null,
"e": 1634,
"s": 1552,
"text": "Using the starts-with() method. This means the string starts with our given text."
},
{
"code": null,
"e": 1716,
"s": 1634,
"text": "Using the starts-with() method. This means the string starts with our given text."
},
{
"code": null,
"e": 1725,
"s": 1716,
"text": "Syntax −"
},
{
"code": null,
"e": 1792,
"s": 1725,
"text": "driver.find_element_by_xpath(\"//input[starts-with (@name,'Tut')]\")"
},
{
"code": null,
"e": 1883,
"s": 1792,
"text": "It will search the input tag which contains the 'name' attribute starting with 'Tut' text."
},
{
"code": null,
"e": 1961,
"s": 1883,
"text": "Using the ends-with() method. This means the string ends with our given text."
},
{
"code": null,
"e": 2039,
"s": 1961,
"text": "Using the ends-with() method. This means the string ends with our given text."
},
{
"code": null,
"e": 2046,
"s": 2039,
"text": "Syntax"
},
{
"code": null,
"e": 2112,
"s": 2046,
"text": "driver.find_element_by_xpath(\"//input[ends-with (@name,'nium')]\")"
},
{
"code": null,
"e": 2202,
"s": 2112,
"text": "It will search the input tag which contains the 'name' attribute ending with 'nium' text."
},
{
"code": null,
"e": 2238,
"s": 2202,
"text": "Code Implementation with contains()"
},
{
"code": null,
"e": 2838,
"s": 2238,
"text": "from selenium import webdriver\n#browser exposes an executable file\n#Through Selenium test we will invoke the executable file which will then #invoke actual browser\ndriver = webdriver.Chrome(executable_path=\"C:\\\\chromedriver.exe\")\n# to maximize the browser window\ndriver.maximize_window()\n#get method to launch the URL\ndriver.get(\"https://www.tutorialspoint.com/index.htm\")\n#to refresh the browser\ndriver.refresh()\n# identifying the edit box with the help of contains() in xpath\ndriver.find_element_by_xpath(\"//input[contains(@id,'sc-i')]\").\nsend_keys(\"Selenium\")\n#to close the browser\ndriver.close()"
},
{
"code": null,
"e": 2877,
"s": 2838,
"text": "Code Implementation with starts-with()"
},
{
"code": null,
"e": 3482,
"s": 2877,
"text": "from selenium import webdriver\n#browser exposes an executable file\n#Through Selenium test we will invoke the executable file which will then #invoke actual browser\ndriver = webdriver.Chrome(executable_path=\"C:\\\\chromedriver.exe\")\n# to maximize the browser window\ndriver.maximize_window()\n#get method to launch the URL\ndriver.get(\"https://www.tutorialspoint.com/index.htm\")\n#to refresh the browser\ndriver.refresh()\n# identifying the edit box with the help of starts-with() in xpath\ndriver.find_element_by_xpath(\"//input[starts-with(@id,'gsc')]\").\nsend_keys(\"Selenium\")\n#to close the browser\ndriver.close()"
},
{
"code": null,
"e": 3519,
"s": 3482,
"text": "Code Implementation with ends-with()"
},
{
"code": null,
"e": 4120,
"s": 3519,
"text": "from selenium import webdriver\n#browser exposes an executable file\n#Through Selenium test we will invoke the executable file which will then #invoke actual browser\ndriver = webdriver.Chrome(executable_path=\"C:\\\\chromedriver.exe\")\n# to maximize the browser window\ndriver.maximize_window()\n#get method to launch the URL\ndriver.get(\"https://www.tutorialspoint.com/index.htm\")\n#to refresh the browser\ndriver.refresh()\n# identifying the edit box with the help of ends-with() in xpath\ndriver.find_element_by_xpath(\"//input[ends-with(@id,'id1')]\").\nsend_keys(\"Selenium\")\n#to close the browser\ndriver.close()"
}
] |
How can we read a JSON 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 read and 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 JSONReadFromTheFileTest {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("/Users/User/Desktop/course.json"));
JSONObject jsonObject = (JSONObject)obj;
String name = (String)jsonObject.get("Name");
String course = (String)jsonObject.get("Course");
JSONArray subjects = (JSONArray)jsonObject.get("Subjects");
System.out.println("Name: " + name);
System.out.println("Course: " + course);
System.out.println("Subjects:");
Iterator iterator = subjects.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
} catch(Exception e) {
e.printStackTrace();
}
}
}
Name: Raja
Course: MCA
Subjects:
subject1: MIS
subject2: DBMS
subject3: UML
|
[
{
"code": null,
"e": 1608,
"s": 1187,
"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 read and 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": 2524,
"s": 1608,
"text": "import java.io.*;\nimport java.util.*;\nimport org.json.simple.*;\nimport org.json.simple.parser.*;\npublic class JSONReadFromTheFileTest {\n public static void main(String[] args) {\n JSONParser parser = new JSONParser();\n try {\n Object obj = parser.parse(new FileReader(\"/Users/User/Desktop/course.json\"));\n JSONObject jsonObject = (JSONObject)obj;\n String name = (String)jsonObject.get(\"Name\");\n String course = (String)jsonObject.get(\"Course\");\n JSONArray subjects = (JSONArray)jsonObject.get(\"Subjects\");\n System.out.println(\"Name: \" + name);\n System.out.println(\"Course: \" + course);\n System.out.println(\"Subjects:\");\n Iterator iterator = subjects.iterator();\n while (iterator.hasNext()) {\n System.out.println(iterator.next());\n }\n } catch(Exception e) {\n e.printStackTrace();\n }\n }\n}"
},
{
"code": null,
"e": 2600,
"s": 2524,
"text": "Name: Raja\nCourse: MCA\nSubjects:\nsubject1: MIS\nsubject2: DBMS\nsubject3: UML"
}
] |
Matplotlib.axes.Axes.set_visible() in Python
|
30 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.set_visible() function in axes module of matplotlib library is used to set the artist’s visibility.
Syntax: Axes.set_visible(self, b)
Parameters: This method accepts only one parameters.
b: This parameter is the boolean value.
Returns: This method does not return any value.
Below examples illustrate the matplotlib.axes.Axes.set_visible() function in matplotlib.axes:
Example 1:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltfrom mpl_toolkits.axisartist.axislines import Subplot fig = plt.figure() ax = Subplot(fig, 111)fig.add_subplot(ax) ax.axis["left"].set_visible(False)ax.axis["top"].set_visible(False) fig.suptitle('matplotlib.axes.Axes.set_visible()\ function Example\n', fontweight ="bold") plt.show()
Output:
Example-2:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np X = np.arange(-20, 20, 0.5)Y = np.arange(-20, 20, 0.5)U, V = np.meshgrid(X, Y) fig, ax = plt.subplots()ax.quiver(X, Y, U, V)w = ax.get_xaxis()w.set_visible(False) fig.suptitle('matplotlib.axes.Axes.set_visible() \function Example\n', fontweight ="bold") plt.show()
Output:
Matplotlib axes-class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Apr, 2020"
},
{
"code": null,
"e": 328,
"s": 28,
"text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute."
},
{
"code": null,
"e": 437,
"s": 328,
"text": "The Axes.set_visible() function in axes module of matplotlib library is used to set the artist’s visibility."
},
{
"code": null,
"e": 471,
"s": 437,
"text": "Syntax: Axes.set_visible(self, b)"
},
{
"code": null,
"e": 524,
"s": 471,
"text": "Parameters: This method accepts only one parameters."
},
{
"code": null,
"e": 564,
"s": 524,
"text": "b: This parameter is the boolean value."
},
{
"code": null,
"e": 612,
"s": 564,
"text": "Returns: This method does not return any value."
},
{
"code": null,
"e": 706,
"s": 612,
"text": "Below examples illustrate the matplotlib.axes.Axes.set_visible() function in matplotlib.axes:"
},
{
"code": null,
"e": 717,
"s": 706,
"text": "Example 1:"
},
{
"code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltfrom mpl_toolkits.axisartist.axislines import Subplot fig = plt.figure() ax = Subplot(fig, 111)fig.add_subplot(ax) ax.axis[\"left\"].set_visible(False)ax.axis[\"top\"].set_visible(False) fig.suptitle('matplotlib.axes.Axes.set_visible()\\ function Example\\n', fontweight =\"bold\") plt.show()",
"e": 1081,
"s": 717,
"text": null
},
{
"code": null,
"e": 1089,
"s": 1081,
"text": "Output:"
},
{
"code": null,
"e": 1100,
"s": 1089,
"text": "Example-2:"
},
{
"code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np X = np.arange(-20, 20, 0.5)Y = np.arange(-20, 20, 0.5)U, V = np.meshgrid(X, Y) fig, ax = plt.subplots()ax.quiver(X, Y, U, V)w = ax.get_xaxis()w.set_visible(False) fig.suptitle('matplotlib.axes.Axes.set_visible() \\function Example\\n', fontweight =\"bold\") plt.show()",
"e": 1467,
"s": 1100,
"text": null
},
{
"code": null,
"e": 1475,
"s": 1467,
"text": "Output:"
},
{
"code": null,
"e": 1497,
"s": 1475,
"text": "Matplotlib axes-class"
},
{
"code": null,
"e": 1515,
"s": 1497,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 1522,
"s": 1515,
"text": "Python"
}
] |
Reverse a stack using recursion
|
25 Jun, 2022
Write a program to reverse a stack using recursion. You are not allowed to use loop constructs like while, for..etc, and you can only use the following ADT functions on Stack S: isEmpty(S) push(S) pop(S)
The idea of the solution is to hold all values in Function Call Stack until the stack becomes empty. When the stack becomes empty, insert all held items one by one at the bottom of the stack. For example, let the input stack be
1 <-- top
2
3
4
First 4 is inserted at the bottom.
4 <-- top
Then 3 is inserted at the bottom
4 <-- top
3
Then 2 is inserted at the bottom
4 <-- top
3
2
Then 1 is inserted at the bottom
4 <-- top
3
2
1
So we need a function that inserts at the bottom of a stack using the above given basic stack function.
void insertAtBottom((): First pops all stack items and stores the popped item in function call stack using recursion. And when stack becomes empty, pushes new item and all items stored in call stack.
void reverse(): This function mainly uses insertAtBottom() to pop all items one by one and insert the popped items at the bottom.
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.
C++
C
Java
Python3
C#
Javascript
// C++ code to reverse a // stack using recursion#include<bits/stdc++.h>using namespace std; // using std::stack for // stack implementationstack<char> st; // initializing a string to store// result of reversed stackstring ns; // Below is a recursive function // that inserts an element// at the bottom of a stack.void insert_at_bottom(char x){ if(st.size() == 0) st.push(x); else { // All items are held in Function Call // Stack until we reach end of the stack // When the stack becomes empty, the // st.size() becomes 0, the above if // part is executed and the item is // inserted at the bottom char a = st.top(); st.pop(); insert_at_bottom(x); // push allthe items held in // Function Call Stack // once the item is inserted // at the bottom st.push(a); }} // Below is the function that// reverses the given stack using// insert_at_bottom()void reverse(){ if(st.size()>0) { // Hold all items in Function // Call Stack until we // reach end of the stack char x = st.top(); st.pop(); reverse(); // Insert all the items held // in Function Call Stack // one by one from the bottom // to top. Every item is // inserted at the bottom insert_at_bottom(x); }} // Driver Codeint main(){ // push elements into // the stack st.push('1'); st.push('2'); st.push('3'); st.push('4'); cout<<"Original Stack"<<endl; // print the elements // of original stack cout<<"1"<<" "<<"2"<<" " <<"3"<<" "<<"4" <<endl; // function to reverse // the stack reverse(); cout<<"Reversed Stack" <<endl; // storing values of reversed // stack into a string for display while(!st.empty()) { char p=st.top(); st.pop(); ns+=p; } //display of reversed stack cout<<ns[3]<<" "<<ns[2]<<" " <<ns[1]<<" "<<ns[0]<<endl; return 0;} // This code is contributed by Gautam Singh
// C program to reverse a // stack using recursion#include<stdio.h>#include<stdlib.h>#define bool int // structure of a stack node struct sNode{ char data; struct sNode *next;}; // Function Prototypes void push(struct sNode** top_ref, int new_data);int pop(struct sNode** top_ref);bool isEmpty(struct sNode* top);void print(struct sNode* top); // Below is a recursive function// that inserts an element// at the bottom of a stack.void insertAtBottom(struct sNode** top_ref, int item){ if (isEmpty(*top_ref)) push(top_ref, item); else { // Hold all items in Function Call // Stack until we reach end of the // stack. When the stack becomes // empty, the isEmpty(*top_ref)becomes // true, the above if part is executed // and the item is inserted at the bottom int temp = pop(top_ref); insertAtBottom(top_ref, item); // Once the item is inserted // at the bottom, push all // the items held in Function // Call Stack push(top_ref, temp); }} // Below is the function that // reverses the given stack using// insertAtBottom()void reverse(struct sNode** top_ref){ if (!isEmpty(*top_ref)) { // Hold all items in Function // Call Stack until we // reach end of the stack int temp = pop(top_ref); reverse(top_ref); // Insert all the items (held in // Function Call Stack) // one by one from the bottom // to top. Every item is // inserted at the bottom insertAtBottom(top_ref, temp); }} // Driver Codeint main(){ struct sNode *s = NULL; push(&s, 4); push(&s, 3); push(&s, 2); push(&s, 1); printf("\n Original Stack "); print(s); reverse(&s); printf("\n Reversed Stack "); print(s); return 0;} // Function to check if// the stack is empty bool isEmpty(struct sNode* top){ return (top == NULL)? 1 : 0;} // Function to push an item to stackvoid push(struct sNode** top_ref, int new_data){ // allocate node struct sNode* new_node = (struct sNode*) malloc(sizeof(struct sNode)); if (new_node == NULL) { printf("Stack overflow \n"); exit(0); } // put in the data new_node->data = new_data; // link the old list // off the new node new_node->next = (*top_ref); // move the head to // point to the new node (*top_ref) = new_node;} // Function to pop an item from stackint pop(struct sNode** top_ref){ char res; struct sNode *top; // If stack is empty then error if (*top_ref == NULL) { printf("Stack overflow \n"); exit(0); } else { top = *top_ref; res = top->data; *top_ref = top->next; free(top); return res; }} // Function to print a// linked list void print(struct sNode* top){ printf("\n"); while (top != NULL) { printf(" %d ", top->data); top = top->next; }}
// Java code to reverse a // stack using recursionimport java.util.Stack; class Test { // using Stack class for // stack implementation static Stack<Character> st = new Stack<>(); // Below is a recursive function // that inserts an element // at the bottom of a stack. static void insert_at_bottom(char x) { if(st.isEmpty()) st.push(x); else { // All items are held in Function // Call Stack until we reach end // of the stack. When the stack becomes // empty, the st.size() becomes 0, the // above if part is executed and // the item is inserted at the bottom char a = st.peek(); st.pop(); insert_at_bottom(x); // push allthe items held // in Function Call Stack // once the item is inserted // at the bottom st.push(a); } } // Below is the function that // reverses the given stack using // insert_at_bottom() static void reverse() { if(st.size() > 0) { // Hold all items in Function // Call Stack until we // reach end of the stack char x = st.peek(); st.pop(); reverse(); // Insert all the items held // in Function Call Stack // one by one from the bottom // to top. Every item is // inserted at the bottom insert_at_bottom(x); } } // Driver Code public static void main(String[] args) { // push elements into // the stack st.push('1'); st.push('2'); st.push('3'); st.push('4'); System.out.println("Original Stack"); System.out.println(st); // function to reverse // the stack reverse(); System.out.println("Reversed Stack"); System.out.println(st); }}
# Python program to reverse a # stack using recursion # Below is a recursive function # that inserts an element# at the bottom of a stack.def insertAtBottom(stack, item): if isEmpty(stack): push(stack, item) else: temp = pop(stack) insertAtBottom(stack, item) push(stack, temp) # Below is the function that # reverses the given stack# using insertAtBottom()def reverse(stack): if not isEmpty(stack): temp = pop(stack) reverse(stack) insertAtBottom(stack, temp) # Below is a complete running # program for testing above# functions. # Function to create a stack. # It initializes size of stack# as 0def createStack(): stack = [] return stack # Function to check if # the stack is emptydef isEmpty( stack ): return len(stack) == 0 # Function to push an # item to stackdef push( stack, item ): stack.append( item ) # Function to pop an # item from stackdef pop( stack ): # If stack is empty # then error if(isEmpty( stack )): print("Stack Underflow ") exit(1) return stack.pop() # Function to print the stackdef prints(stack): for i in range(len(stack)-1, -1, -1): print(stack[i], end = ' ') print() # Driver Code stack = createStack()push( stack, str(4) )push( stack, str(3) )push( stack, str(2) )push( stack, str(1) )print("Original Stack ")prints(stack) reverse(stack) print("Reversed Stack ")prints(stack) # This code is contributed by Sunny Karira
// C# code to reverse a // stack using recursionusing System;using System.Collections; public class GFG { // using Stack class for // stack implementation static Stack st = new Stack(); // Below is a recursive function // that inserts an element // at the bottom of a stack. static void insert_at_bottom(char x) { if(st.Count==0) st.Push(x); else { // All items are held in Function // Call Stack until we reach end // of the stack. When the stack becomes // empty, the st.size() becomes 0, the // above if part is executed and // the item is inserted at the bottom char a = (char)st.Peek(); st.Pop(); insert_at_bottom(x); // push all the items held // in Function Call Stack // once the item is inserted // at the bottom st.Push(a); } } // Below is the function that // reverses the given stack using // insert_at_bottom() static void reverse() { if(st.Count > 0) { // Hold all items in Function // Call Stack until we // reach end of the stack char x = (char)st.Peek(); st.Pop(); reverse(); // Insert all the items held // in Function Call Stack // one by one from the bottom // to top. Every item is // inserted at the bottom insert_at_bottom(x); } } // Driver Code public static void Main(String []args) { // push elements into // the stack st.Push('1'); st.Push('2'); st.Push('3'); st.Push('4'); Console.WriteLine("Original Stack"); foreach (char i in st) { Console.WriteLine(i); } // function to reverse // the stack reverse(); Console.WriteLine("Reversed Stack"); foreach (char i in st) { Console.WriteLine(i); } } } // This code is Contributed by Arnab Kundu
<script> // JavaScript code to reverse a// stack using recursion // using Stack class for// stack implementationlet st = []; // Below is a recursive function// that inserts an element// at the bottom of a stack.function insert_at_bottom(x){ if(st.length==0) st.push(x); else { // All items are held in Function // Call Stack until we reach end // of the stack. When the stack becomes // empty, the st.size() becomes 0, the // above if part is executed and // the item is inserted at the bottom let a = st.pop(); insert_at_bottom(x); // push allthe items held // in Function Call Stack // once the item is inserted // at the bottom st.push(a); } } // Below is the function that // reverses the given stack using // insert_at_bottom()function reverse(){ if(st.length > 0) { // Hold all items in Function // Call Stack until we // reach end of the stack let x = st.pop(); reverse(); // Insert all the items held // in Function Call Stack // one by one from the bottom // to top. Every item is // inserted at the bottom insert_at_bottom(x); }} // Driver Code // push elements into// the stackst.push('1');st.push('2');st.push('3');st.push('4'); document.write("Original Stack<br>"); document.write(st.join(" ")+"<br>"); // function to reverse// the stackreverse(); document.write("Reversed Stack<br>"); document.write(st.join(" ")); // This code is contributed by avanitrachhadiya2155 </script>
Output:
Original Stack
1 2 3 4
Reversed Stack
4 3 2 1
Time Complexity: This approach takes the worst time complexity of O(n^2),
Auxiliary Space: O(n) since using call stack
Please write comments if you find any bug in above code/algorithm, or find other ways to solve the same problem.
SBanzal
andrew1234
pavanareti02
simranarora5sos
avanitrachhadiya2155
surinderdawra388
samartajshaikh
technophpfij
Reverse
Recursion
Stack
Recursion
Stack
Reverse
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n25 Jun, 2022"
},
{
"code": null,
"e": 258,
"s": 54,
"text": "Write a program to reverse a stack using recursion. You are not allowed to use loop constructs like while, for..etc, and you can only use the following ADT functions on Stack S: isEmpty(S) push(S) pop(S)"
},
{
"code": null,
"e": 488,
"s": 258,
"text": "The idea of the solution is to hold all values in Function Call Stack until the stack becomes empty. When the stack becomes empty, insert all held items one by one at the bottom of the stack. For example, let the input stack be "
},
{
"code": null,
"e": 525,
"s": 488,
"text": " 1 <-- top\n 2\n 3\n 4 "
},
{
"code": null,
"e": 773,
"s": 525,
"text": "First 4 is inserted at the bottom.\n 4 <-- top\n\nThen 3 is inserted at the bottom\n 4 <-- top \n 3\n\nThen 2 is inserted at the bottom\n 4 <-- top \n 3 \n 2\n \nThen 1 is inserted at the bottom\n 4 <-- top \n 3 \n 2\n 1"
},
{
"code": null,
"e": 877,
"s": 773,
"text": "So we need a function that inserts at the bottom of a stack using the above given basic stack function."
},
{
"code": null,
"e": 1077,
"s": 877,
"text": "void insertAtBottom((): First pops all stack items and stores the popped item in function call stack using recursion. And when stack becomes empty, pushes new item and all items stored in call stack."
},
{
"code": null,
"e": 1209,
"s": 1077,
"text": "void reverse(): This function mainly uses insertAtBottom() to pop all items one by one and insert the popped items at the bottom. "
},
{
"code": null,
"e": 1218,
"s": 1209,
"text": "Chapters"
},
{
"code": null,
"e": 1245,
"s": 1218,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 1295,
"s": 1245,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 1318,
"s": 1295,
"text": "captions off, selected"
},
{
"code": null,
"e": 1326,
"s": 1318,
"text": "English"
},
{
"code": null,
"e": 1350,
"s": 1326,
"text": "This is a modal window."
},
{
"code": null,
"e": 1419,
"s": 1350,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 1441,
"s": 1419,
"text": "End of dialog window."
},
{
"code": null,
"e": 1445,
"s": 1441,
"text": "C++"
},
{
"code": null,
"e": 1447,
"s": 1445,
"text": "C"
},
{
"code": null,
"e": 1452,
"s": 1447,
"text": "Java"
},
{
"code": null,
"e": 1460,
"s": 1452,
"text": "Python3"
},
{
"code": null,
"e": 1463,
"s": 1460,
"text": "C#"
},
{
"code": null,
"e": 1474,
"s": 1463,
"text": "Javascript"
},
{
"code": "// C++ code to reverse a // stack using recursion#include<bits/stdc++.h>using namespace std; // using std::stack for // stack implementationstack<char> st; // initializing a string to store// result of reversed stackstring ns; // Below is a recursive function // that inserts an element// at the bottom of a stack.void insert_at_bottom(char x){ if(st.size() == 0) st.push(x); else { // All items are held in Function Call // Stack until we reach end of the stack // When the stack becomes empty, the // st.size() becomes 0, the above if // part is executed and the item is // inserted at the bottom char a = st.top(); st.pop(); insert_at_bottom(x); // push allthe items held in // Function Call Stack // once the item is inserted // at the bottom st.push(a); }} // Below is the function that// reverses the given stack using// insert_at_bottom()void reverse(){ if(st.size()>0) { // Hold all items in Function // Call Stack until we // reach end of the stack char x = st.top(); st.pop(); reverse(); // Insert all the items held // in Function Call Stack // one by one from the bottom // to top. Every item is // inserted at the bottom insert_at_bottom(x); }} // Driver Codeint main(){ // push elements into // the stack st.push('1'); st.push('2'); st.push('3'); st.push('4'); cout<<\"Original Stack\"<<endl; // print the elements // of original stack cout<<\"1\"<<\" \"<<\"2\"<<\" \" <<\"3\"<<\" \"<<\"4\" <<endl; // function to reverse // the stack reverse(); cout<<\"Reversed Stack\" <<endl; // storing values of reversed // stack into a string for display while(!st.empty()) { char p=st.top(); st.pop(); ns+=p; } //display of reversed stack cout<<ns[3]<<\" \"<<ns[2]<<\" \" <<ns[1]<<\" \"<<ns[0]<<endl; return 0;} // This code is contributed by Gautam Singh",
"e": 3634,
"s": 1474,
"text": null
},
{
"code": "// C program to reverse a // stack using recursion#include<stdio.h>#include<stdlib.h>#define bool int // structure of a stack node struct sNode{ char data; struct sNode *next;}; // Function Prototypes void push(struct sNode** top_ref, int new_data);int pop(struct sNode** top_ref);bool isEmpty(struct sNode* top);void print(struct sNode* top); // Below is a recursive function// that inserts an element// at the bottom of a stack.void insertAtBottom(struct sNode** top_ref, int item){ if (isEmpty(*top_ref)) push(top_ref, item); else { // Hold all items in Function Call // Stack until we reach end of the // stack. When the stack becomes // empty, the isEmpty(*top_ref)becomes // true, the above if part is executed // and the item is inserted at the bottom int temp = pop(top_ref); insertAtBottom(top_ref, item); // Once the item is inserted // at the bottom, push all // the items held in Function // Call Stack push(top_ref, temp); }} // Below is the function that // reverses the given stack using// insertAtBottom()void reverse(struct sNode** top_ref){ if (!isEmpty(*top_ref)) { // Hold all items in Function // Call Stack until we // reach end of the stack int temp = pop(top_ref); reverse(top_ref); // Insert all the items (held in // Function Call Stack) // one by one from the bottom // to top. Every item is // inserted at the bottom insertAtBottom(top_ref, temp); }} // Driver Codeint main(){ struct sNode *s = NULL; push(&s, 4); push(&s, 3); push(&s, 2); push(&s, 1); printf(\"\\n Original Stack \"); print(s); reverse(&s); printf(\"\\n Reversed Stack \"); print(s); return 0;} // Function to check if// the stack is empty bool isEmpty(struct sNode* top){ return (top == NULL)? 1 : 0;} // Function to push an item to stackvoid push(struct sNode** top_ref, int new_data){ // allocate node struct sNode* new_node = (struct sNode*) malloc(sizeof(struct sNode)); if (new_node == NULL) { printf(\"Stack overflow \\n\"); exit(0); } // put in the data new_node->data = new_data; // link the old list // off the new node new_node->next = (*top_ref); // move the head to // point to the new node (*top_ref) = new_node;} // Function to pop an item from stackint pop(struct sNode** top_ref){ char res; struct sNode *top; // If stack is empty then error if (*top_ref == NULL) { printf(\"Stack overflow \\n\"); exit(0); } else { top = *top_ref; res = top->data; *top_ref = top->next; free(top); return res; }} // Function to print a// linked list void print(struct sNode* top){ printf(\"\\n\"); while (top != NULL) { printf(\" %d \", top->data); top = top->next; }}",
"e": 6702,
"s": 3634,
"text": null
},
{
"code": "// Java code to reverse a // stack using recursionimport java.util.Stack; class Test { // using Stack class for // stack implementation static Stack<Character> st = new Stack<>(); // Below is a recursive function // that inserts an element // at the bottom of a stack. static void insert_at_bottom(char x) { if(st.isEmpty()) st.push(x); else { // All items are held in Function // Call Stack until we reach end // of the stack. When the stack becomes // empty, the st.size() becomes 0, the // above if part is executed and // the item is inserted at the bottom char a = st.peek(); st.pop(); insert_at_bottom(x); // push allthe items held // in Function Call Stack // once the item is inserted // at the bottom st.push(a); } } // Below is the function that // reverses the given stack using // insert_at_bottom() static void reverse() { if(st.size() > 0) { // Hold all items in Function // Call Stack until we // reach end of the stack char x = st.peek(); st.pop(); reverse(); // Insert all the items held // in Function Call Stack // one by one from the bottom // to top. Every item is // inserted at the bottom insert_at_bottom(x); } } // Driver Code public static void main(String[] args) { // push elements into // the stack st.push('1'); st.push('2'); st.push('3'); st.push('4'); System.out.println(\"Original Stack\"); System.out.println(st); // function to reverse // the stack reverse(); System.out.println(\"Reversed Stack\"); System.out.println(st); }}",
"e": 8797,
"s": 6702,
"text": null
},
{
"code": "# Python program to reverse a # stack using recursion # Below is a recursive function # that inserts an element# at the bottom of a stack.def insertAtBottom(stack, item): if isEmpty(stack): push(stack, item) else: temp = pop(stack) insertAtBottom(stack, item) push(stack, temp) # Below is the function that # reverses the given stack# using insertAtBottom()def reverse(stack): if not isEmpty(stack): temp = pop(stack) reverse(stack) insertAtBottom(stack, temp) # Below is a complete running # program for testing above# functions. # Function to create a stack. # It initializes size of stack# as 0def createStack(): stack = [] return stack # Function to check if # the stack is emptydef isEmpty( stack ): return len(stack) == 0 # Function to push an # item to stackdef push( stack, item ): stack.append( item ) # Function to pop an # item from stackdef pop( stack ): # If stack is empty # then error if(isEmpty( stack )): print(\"Stack Underflow \") exit(1) return stack.pop() # Function to print the stackdef prints(stack): for i in range(len(stack)-1, -1, -1): print(stack[i], end = ' ') print() # Driver Code stack = createStack()push( stack, str(4) )push( stack, str(3) )push( stack, str(2) )push( stack, str(1) )print(\"Original Stack \")prints(stack) reverse(stack) print(\"Reversed Stack \")prints(stack) # This code is contributed by Sunny Karira",
"e": 10272,
"s": 8797,
"text": null
},
{
"code": "// C# code to reverse a // stack using recursionusing System;using System.Collections; public class GFG { // using Stack class for // stack implementation static Stack st = new Stack(); // Below is a recursive function // that inserts an element // at the bottom of a stack. static void insert_at_bottom(char x) { if(st.Count==0) st.Push(x); else { // All items are held in Function // Call Stack until we reach end // of the stack. When the stack becomes // empty, the st.size() becomes 0, the // above if part is executed and // the item is inserted at the bottom char a = (char)st.Peek(); st.Pop(); insert_at_bottom(x); // push all the items held // in Function Call Stack // once the item is inserted // at the bottom st.Push(a); } } // Below is the function that // reverses the given stack using // insert_at_bottom() static void reverse() { if(st.Count > 0) { // Hold all items in Function // Call Stack until we // reach end of the stack char x = (char)st.Peek(); st.Pop(); reverse(); // Insert all the items held // in Function Call Stack // one by one from the bottom // to top. Every item is // inserted at the bottom insert_at_bottom(x); } } // Driver Code public static void Main(String []args) { // push elements into // the stack st.Push('1'); st.Push('2'); st.Push('3'); st.Push('4'); Console.WriteLine(\"Original Stack\"); foreach (char i in st) { Console.WriteLine(i); } // function to reverse // the stack reverse(); Console.WriteLine(\"Reversed Stack\"); foreach (char i in st) { Console.WriteLine(i); } } } // This code is Contributed by Arnab Kundu",
"e": 12569,
"s": 10272,
"text": null
},
{
"code": "<script> // JavaScript code to reverse a// stack using recursion // using Stack class for// stack implementationlet st = []; // Below is a recursive function// that inserts an element// at the bottom of a stack.function insert_at_bottom(x){ if(st.length==0) st.push(x); else { // All items are held in Function // Call Stack until we reach end // of the stack. When the stack becomes // empty, the st.size() becomes 0, the // above if part is executed and // the item is inserted at the bottom let a = st.pop(); insert_at_bottom(x); // push allthe items held // in Function Call Stack // once the item is inserted // at the bottom st.push(a); } } // Below is the function that // reverses the given stack using // insert_at_bottom()function reverse(){ if(st.length > 0) { // Hold all items in Function // Call Stack until we // reach end of the stack let x = st.pop(); reverse(); // Insert all the items held // in Function Call Stack // one by one from the bottom // to top. Every item is // inserted at the bottom insert_at_bottom(x); }} // Driver Code // push elements into// the stackst.push('1');st.push('2');st.push('3');st.push('4'); document.write(\"Original Stack<br>\"); document.write(st.join(\" \")+\"<br>\"); // function to reverse// the stackreverse(); document.write(\"Reversed Stack<br>\"); document.write(st.join(\" \")); // This code is contributed by avanitrachhadiya2155 </script>",
"e": 14321,
"s": 12569,
"text": null
},
{
"code": null,
"e": 14330,
"s": 14321,
"text": "Output: "
},
{
"code": null,
"e": 14390,
"s": 14330,
"text": " Original Stack \n 1 2 3 4 \n Reversed Stack \n 4 3 2 1 "
},
{
"code": null,
"e": 14465,
"s": 14390,
"text": "Time Complexity: This approach takes the worst time complexity of O(n^2), "
},
{
"code": null,
"e": 14510,
"s": 14465,
"text": "Auxiliary Space: O(n) since using call stack"
},
{
"code": null,
"e": 14624,
"s": 14510,
"text": "Please write comments if you find any bug in above code/algorithm, or find other ways to solve the same problem. "
},
{
"code": null,
"e": 14634,
"s": 14626,
"text": "SBanzal"
},
{
"code": null,
"e": 14645,
"s": 14634,
"text": "andrew1234"
},
{
"code": null,
"e": 14658,
"s": 14645,
"text": "pavanareti02"
},
{
"code": null,
"e": 14674,
"s": 14658,
"text": "simranarora5sos"
},
{
"code": null,
"e": 14695,
"s": 14674,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 14712,
"s": 14695,
"text": "surinderdawra388"
},
{
"code": null,
"e": 14727,
"s": 14712,
"text": "samartajshaikh"
},
{
"code": null,
"e": 14740,
"s": 14727,
"text": "technophpfij"
},
{
"code": null,
"e": 14748,
"s": 14740,
"text": "Reverse"
},
{
"code": null,
"e": 14758,
"s": 14748,
"text": "Recursion"
},
{
"code": null,
"e": 14764,
"s": 14758,
"text": "Stack"
},
{
"code": null,
"e": 14774,
"s": 14764,
"text": "Recursion"
},
{
"code": null,
"e": 14780,
"s": 14774,
"text": "Stack"
},
{
"code": null,
"e": 14788,
"s": 14780,
"text": "Reverse"
}
] |
How to create refs in ReactJS?
|
25 Jan, 2021
Creating refs in ReactJS is very simple. Refs are generally used for the following purposes:
Managing focus, text selection, or media playback.
Triggering imperative animations.
Integrating with third-party DOM libraries.
Note: You should avoid using refs for anything that can be done declaratively.
The following examples are based on only Functional-Components but you are free to use Class-Components as well.
Method 1: Using React.createRef(). It was introduced in React 16.3.
Create a ref variable using React.createRef()
Use the element’s ref attribute to attach the ref variable
Filename: App.js
Javascript
// Importing everything as Reactimport * as React from "react"; const App = () => { // Creating textInputRef variable const textInputRef = React.createRef(); // This method will be used to focus textInput const textInputFocusHandler = () => { // Focusing input element textInputRef.current.focus(); }; return ( <div> {/** Attaching ref variable using element's ref attribute */} <input ref={textInputRef} type="text" placeholder="Enter something" /> {/** Attaching textInputFocusHandler method to button click */} <button onClick={textInputFocusHandler}> Click me to focus input </button> </div> );}; export default App;
Method 2: Using useRef() hook.
Create a ref variable using React.useRef()
Use the element’s ref attribute to attach the ref variable
The benefit of using useRef() over createRef() is that it’s handy for keeping any mutable value around similar to how you’d use instance fields in classes.
useRef() also takes an initial value.
Filename: App.js
Javascript
// Importing everything as Reactimport * as React from "react"; const App = () => { // Creating textInputRef variable with initialValue "null" const textInputRef = React.useRef(null); // This method will be used to focus textInput const textInputFocusHandler = () => { // Focusing input element textInputRef.current.focus(); }; return ( <div> {/** Attaching ref variable using element's ref attribute */} <input ref={textInputRef} type="text" placeholder="Enter something" /> {/** Attaching textInputFocusHandler method to button click */} <button onClick={textInputFocusHandler}> Click me to focus input </button> </div> );}; export default App;
Method 3: Using callback ref. This method was used prior to React 16.3. So if you are using React < 16.3 use this method.
Creating ref using this method is a bit different than the other two methods. Instead of passing a ref attribute created using createRef() or useRef() we pass a function. The function receives the React element or HTML DOM element as an argument, which can be used.
Filename: App.js
Javascript
// Importing everything as Reactimport * as React from "react"; const App = () => { // Creating and initializing textInputRef variable as null let textInputRef = null; // Callback function that will set ref for input field // Note: It can be used to set ref for any element const setTextInputRef = (element) => { textInputRef = element; }; // This method will be used to focus textInput const textInputFocusHandler = () => { // If textInputRef is not null // otherwise it will throw an error if (textInputRef) { // Focusing input element textInputRef.focus(); } }; return ( <div style={{ padding: 16 }}> {/** Using setTextInputRef function so that * textInputRef can be set as ref for this input field * */} <input style={{ display: "block" }} ref={setTextInputRef} type="text" placeholder="Enter something" /> {/** Attaching textInputFocusHandler method to button click */} <button onClick={textInputFocusHandler}> Click me to focus input </button> </div> );}; export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output:
Picked
Technical Scripter 2020
JavaScript
ReactJS
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 Jan, 2021"
},
{
"code": null,
"e": 121,
"s": 28,
"text": "Creating refs in ReactJS is very simple. Refs are generally used for the following purposes:"
},
{
"code": null,
"e": 172,
"s": 121,
"text": "Managing focus, text selection, or media playback."
},
{
"code": null,
"e": 206,
"s": 172,
"text": "Triggering imperative animations."
},
{
"code": null,
"e": 250,
"s": 206,
"text": "Integrating with third-party DOM libraries."
},
{
"code": null,
"e": 329,
"s": 250,
"text": "Note: You should avoid using refs for anything that can be done declaratively."
},
{
"code": null,
"e": 442,
"s": 329,
"text": "The following examples are based on only Functional-Components but you are free to use Class-Components as well."
},
{
"code": null,
"e": 510,
"s": 442,
"text": "Method 1: Using React.createRef(). It was introduced in React 16.3."
},
{
"code": null,
"e": 556,
"s": 510,
"text": "Create a ref variable using React.createRef()"
},
{
"code": null,
"e": 615,
"s": 556,
"text": "Use the element’s ref attribute to attach the ref variable"
},
{
"code": null,
"e": 632,
"s": 615,
"text": "Filename: App.js"
},
{
"code": null,
"e": 643,
"s": 632,
"text": "Javascript"
},
{
"code": "// Importing everything as Reactimport * as React from \"react\"; const App = () => { // Creating textInputRef variable const textInputRef = React.createRef(); // This method will be used to focus textInput const textInputFocusHandler = () => { // Focusing input element textInputRef.current.focus(); }; return ( <div> {/** Attaching ref variable using element's ref attribute */} <input ref={textInputRef} type=\"text\" placeholder=\"Enter something\" /> {/** Attaching textInputFocusHandler method to button click */} <button onClick={textInputFocusHandler}> Click me to focus input </button> </div> );}; export default App;",
"e": 1349,
"s": 643,
"text": null
},
{
"code": null,
"e": 1380,
"s": 1349,
"text": "Method 2: Using useRef() hook."
},
{
"code": null,
"e": 1423,
"s": 1380,
"text": "Create a ref variable using React.useRef()"
},
{
"code": null,
"e": 1482,
"s": 1423,
"text": "Use the element’s ref attribute to attach the ref variable"
},
{
"code": null,
"e": 1638,
"s": 1482,
"text": "The benefit of using useRef() over createRef() is that it’s handy for keeping any mutable value around similar to how you’d use instance fields in classes."
},
{
"code": null,
"e": 1676,
"s": 1638,
"text": "useRef() also takes an initial value."
},
{
"code": null,
"e": 1693,
"s": 1676,
"text": "Filename: App.js"
},
{
"code": null,
"e": 1704,
"s": 1693,
"text": "Javascript"
},
{
"code": "// Importing everything as Reactimport * as React from \"react\"; const App = () => { // Creating textInputRef variable with initialValue \"null\" const textInputRef = React.useRef(null); // This method will be used to focus textInput const textInputFocusHandler = () => { // Focusing input element textInputRef.current.focus(); }; return ( <div> {/** Attaching ref variable using element's ref attribute */} <input ref={textInputRef} type=\"text\" placeholder=\"Enter something\" /> {/** Attaching textInputFocusHandler method to button click */} <button onClick={textInputFocusHandler}> Click me to focus input </button> </div> );}; export default App;",
"e": 2437,
"s": 1704,
"text": null
},
{
"code": null,
"e": 2559,
"s": 2437,
"text": "Method 3: Using callback ref. This method was used prior to React 16.3. So if you are using React < 16.3 use this method."
},
{
"code": null,
"e": 2825,
"s": 2559,
"text": "Creating ref using this method is a bit different than the other two methods. Instead of passing a ref attribute created using createRef() or useRef() we pass a function. The function receives the React element or HTML DOM element as an argument, which can be used."
},
{
"code": null,
"e": 2842,
"s": 2825,
"text": "Filename: App.js"
},
{
"code": null,
"e": 2853,
"s": 2842,
"text": "Javascript"
},
{
"code": "// Importing everything as Reactimport * as React from \"react\"; const App = () => { // Creating and initializing textInputRef variable as null let textInputRef = null; // Callback function that will set ref for input field // Note: It can be used to set ref for any element const setTextInputRef = (element) => { textInputRef = element; }; // This method will be used to focus textInput const textInputFocusHandler = () => { // If textInputRef is not null // otherwise it will throw an error if (textInputRef) { // Focusing input element textInputRef.focus(); } }; return ( <div style={{ padding: 16 }}> {/** Using setTextInputRef function so that * textInputRef can be set as ref for this input field * */} <input style={{ display: \"block\" }} ref={setTextInputRef} type=\"text\" placeholder=\"Enter something\" /> {/** Attaching textInputFocusHandler method to button click */} <button onClick={textInputFocusHandler}> Click me to focus input </button> </div> );}; export default App;",
"e": 3990,
"s": 2853,
"text": null
},
{
"code": null,
"e": 4103,
"s": 3990,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 4113,
"s": 4103,
"text": "npm start"
},
{
"code": null,
"e": 4121,
"s": 4113,
"text": "Output:"
},
{
"code": null,
"e": 4128,
"s": 4121,
"text": "Picked"
},
{
"code": null,
"e": 4152,
"s": 4128,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 4163,
"s": 4152,
"text": "JavaScript"
},
{
"code": null,
"e": 4171,
"s": 4163,
"text": "ReactJS"
},
{
"code": null,
"e": 4190,
"s": 4171,
"text": "Technical Scripter"
}
] |
Last Minute Notes – Discrete Mathematics
|
28 Jun, 2021
See Last Minute Notes on all subjects here.
Implication( →): For any two propositions p and q, the statement “if p then q” is called an implication and it is denoted by p → q.if and only if(↔): For any two propositions p and q, the statement “p if and only if(iff) q” is called a biconditional and it is denoted by p ↔ q.De Morgan’s Law : Special Conditional Statements1.Implication : 2.Converse : The converse of the proposition is 3.Contrapositive : The contrapositive of the proposition is 4.Inverse : The inverse of the proposition is Types of propositions based on Truth values1.Tautology – A proposition which is always true, is called a tautology.2.Contradiction – A proposition which is always false, is called a contradiction.3.Contingency – A proposition that is neither a tautology nor a contradiction is called a contingency.There are two very important equivalences involving quantifiers1.
2.
Rules of inferenceCombinatricsPermutation: A permutation of a set of distinct objects is an ordered arrangement of these objects. Combination: A combination of a set of distinct objects is just a count of the number of ways a specific number of elements can be selected from a set of a certain size. The order of elements does not matter in a combination.which gives us- Binomial Coefficients: The -combinations from a set of elements if denoted by . This number is also called a binomial coefficient since it occurs as a coefficient in the expansion of powers of binomial expressions.Let and be variables and be a non-negative integer. Then The binomial expansion using Combinatorial symbolsSet TheoryA Set is an unordered collection of objects, known as elements or members of the set.An element ‘a’ belong to a set A can be written as ‘a ∈ A’, ‘a ∉ A’ denotes that a is not an element of the set A.Equal setsTwo sets are said to be equal if both have same elements. For example A = {1, 3, 9, 7} and B = {3, 1, 7, 9} are equal sets.NOTE: Order of elements of a set doesn’t matter.SubsetA set A is said to be subset of another set B if and only if every element of set A is also a part of other set B.Denoted by ‘⊆‘.‘A ⊆ B ‘ denotes A is a subset of B.To prove A is the subset of B, we need to simply show that if x belongs to A then x also belongs to B.To prove A is not a subset of B, we need to find out one element which is part of set A but not belong to set B.‘U’ denotes the universal set. Above Venn Diagram shows that A is a subset of B.Size of a SetSize of a set can be finite or infinite.For exampleFinite set: Set of natural numbers less than 100.
Infinite set: Set of real numbers.Size of the set S is known as Cardinality number, denoted as |S|.Note: Cardinality of a null set is 0.Power SetsThe power set is the set all possible subset of the set S. Denoted by P(S).Example: What is the power set of {0, 1, 2}?Solution: All possible subsets{∅}, {0}, {1}, {2}, {0, 1}, {0, 2}, {1, 2}, {0, 1, 2}.Note: Empty set and set itself is also the member of this set of subsets.Cardinality of power set is , where n is the number of elements in a set.Cartesian ProductsLet A and B be two sets. Cartesian product of A and B is denoted by A × B, is the set of all ordered pairs (a, b), where a belong to A and b belong to B.A × B = {(a, b) | a ∈ A ∧ b ∈ B}.The cardinality of A × B is N*M, where N is the Cardinality of A and M is the cardinality of B.Note: A × B is not the same as B × A.UnionUnion of the sets A and B, denoted by A ∪ B, is the set of distinct element belongs to set A or set B, or both.IntersectionThe intersection of the sets A and B, denoted by A ∩ B, is the set of elements belongs to both A and B i.e. set of the common element in A and B.DisjointTwo sets are said to be disjoint if their intersection is the empty set .i.e sets have no common elements.Set DifferenceDifference between sets is denoted by ‘A – B’, is the set containing elements of set A but not in B. i.e all elements of A except the element of B.ComplementThe complement of a set A, denoted by , is the set of all the elements except A. Complement of the set A is U – A.Formula:GroupA non-empty set G, (G, *) is called a group if it follows the following axiom:Closure:(a*b) belongs to G for all a, b ∈ G.Associativity: a*(b*c) = (a*b)*c ∀ a, b, c belongs to G.Identity Element:There exists e ∈ G such that a*e = e*a = a ∀ a ∈ GInverses:∀ a ∈ G there exists a-1 ∈ G such that a*a-1 = a-1*a = eRelations And Functions|A| = m and |B| = n, then1. No. of functions from A to B = nm2. No. of one to one function = (n, P, m)3. No. of onto function =nm – (n, C, 1)*(n-1)m + (n, C, 2)*(n-2)m .... +(-1)m*(n, C, n-1), if m >= n; 0 otherwise4. Necessary condition for bijective function |A| = |B|5. The no. of bijection function =n!6. No. of relations =2mn7. No. of reflexive relations =2n(n-1)8. No. of symmetric relations = 2n(n+1)/29. No. of Anti Symmetric Relations = 2n*3n(n-1)/210. No. of asymmetric relations = 3n(n-1)/211. No. of irreflexive relations = 2n(n-1)12. A relation is a partial order if 1) Reflexive
2) Antisymmetric
3) Transitive
13. Meet Semi Lattice : For all a, b belongs to L a∧b exists 14. Join Semi Lattice For all a, b belongs to L a∨b exists 15. A poset is called Lattice if it is both meet and join semi-lattice16. Complemented Lattice : Every element has complement17. Distributive Lattice : Every Element has zero or 1 complement .18. Boolean Lattice: It should be both complemented and distributive. Every element has exactly one complement.19. A relation is an equivalence if 1) Reflexive
2) symmetric
3) Transitive
Graph Theory1. No. of edges in a complete graph = n(n-1)/22. Bipartite Graph : There is no edges between any two vertices of same partition . In complete bipartite graph no. of edges =m*n3. Sum of degree of all vertices is equal to twice the number of edges.4. Maximum no. of connected components in graph with n vertices = n5. Minimum number of connected components =0 (null graph)
1 (not null graph)
6. Minimum no. of edges to have connected graph with n vertices = n-17. To guarantee that a graph with n vertices is connected, minimum no. of edges required = {(n-1)*(n-2)/2 } + 18. A graph is euler graph if it there exists atmost 2 vertices of odd – degree9. Tree -> Has exactly one path btw any two vertices
-> not contain cycle
-> connected
-> no. of edges = n -1
10. For complete graph the no . of spanning tree possible = nn-211. For simple connected planar graphA graph is planar if and only if it does not contain a subdivision of K5 and K3, 3 as a subgraph.Let G be a connected planar graph, and let n, m and f denote, respectively, the numbers of vertices, edges, and faces in a plane drawing of G. Then n – m + f = 2.Let G be a connected planar simple graph with n vertices and m edges, and no triangles. Then m ≤ 2n – 4.Let G be a connected planar simple graph with n vertices, where n ? 3 and m edges. Then m ≤ 3n – 6.12.) Every bipartite graph is 2 colourable and vice versa13.) The no. of perfect matchings for a complete graph (2n)/(2nn!)14.) The no. of complete matchings for Kn.n = n!My Personal Notes
arrow_drop_upSave
Implication( →): For any two propositions p and q, the statement “if p then q” is called an implication and it is denoted by p → q.
if and only if(↔): For any two propositions p and q, the statement “p if and only if(iff) q” is called a biconditional and it is denoted by p ↔ q.
De Morgan’s Law :
Special Conditional Statements
1.Implication : 2.Converse : The converse of the proposition is 3.Contrapositive : The contrapositive of the proposition is 4.Inverse : The inverse of the proposition is
Types of propositions based on Truth values1.Tautology – A proposition which is always true, is called a tautology.2.Contradiction – A proposition which is always false, is called a contradiction.3.Contingency – A proposition that is neither a tautology nor a contradiction is called a contingency.
There are two very important equivalences involving quantifiers
1.
2.
Rules of inference
Permutation: A permutation of a set of distinct objects is an ordered arrangement of these objects.
Combination: A combination of a set of distinct objects is just a count of the number of ways a specific number of elements can be selected from a set of a certain size. The order of elements does not matter in a combination.which gives us-
Binomial Coefficients: The -combinations from a set of elements if denoted by . This number is also called a binomial coefficient since it occurs as a coefficient in the expansion of powers of binomial expressions.Let and be variables and be a non-negative integer. Then
The binomial expansion using Combinatorial symbols
A Set is an unordered collection of objects, known as elements or members of the set.An element ‘a’ belong to a set A can be written as ‘a ∈ A’, ‘a ∉ A’ denotes that a is not an element of the set A.
Equal setsTwo sets are said to be equal if both have same elements. For example A = {1, 3, 9, 7} and B = {3, 1, 7, 9} are equal sets.
NOTE: Order of elements of a set doesn’t matter.
Subset
A set A is said to be subset of another set B if and only if every element of set A is also a part of other set B.Denoted by ‘⊆‘.‘A ⊆ B ‘ denotes A is a subset of B.
To prove A is the subset of B, we need to simply show that if x belongs to A then x also belongs to B.To prove A is not a subset of B, we need to find out one element which is part of set A but not belong to set B.
‘U’ denotes the universal set. Above Venn Diagram shows that A is a subset of B.
Size of a SetSize of a set can be finite or infinite.
For example
Finite set: Set of natural numbers less than 100.
Infinite set: Set of real numbers.
Size of the set S is known as Cardinality number, denoted as |S|.
Note: Cardinality of a null set is 0.
Power SetsThe power set is the set all possible subset of the set S. Denoted by P(S).Example: What is the power set of {0, 1, 2}?Solution: All possible subsets{∅}, {0}, {1}, {2}, {0, 1}, {0, 2}, {1, 2}, {0, 1, 2}.Note: Empty set and set itself is also the member of this set of subsets.
Cardinality of power set is , where n is the number of elements in a set.
Cartesian ProductsLet A and B be two sets. Cartesian product of A and B is denoted by A × B, is the set of all ordered pairs (a, b), where a belong to A and b belong to B.
A × B = {(a, b) | a ∈ A ∧ b ∈ B}.
The cardinality of A × B is N*M, where N is the Cardinality of A and M is the cardinality of B.
Note: A × B is not the same as B × A.
UnionUnion of the sets A and B, denoted by A ∪ B, is the set of distinct element belongs to set A or set B, or both.
IntersectionThe intersection of the sets A and B, denoted by A ∩ B, is the set of elements belongs to both A and B i.e. set of the common element in A and B.
DisjointTwo sets are said to be disjoint if their intersection is the empty set .i.e sets have no common elements.
Set DifferenceDifference between sets is denoted by ‘A – B’, is the set containing elements of set A but not in B. i.e all elements of A except the element of B.ComplementThe complement of a set A, denoted by , is the set of all the elements except A. Complement of the set A is U – A.
Formula:
GroupA non-empty set G, (G, *) is called a group if it follows the following axiom:
Closure:(a*b) belongs to G for all a, b ∈ G.
Associativity: a*(b*c) = (a*b)*c ∀ a, b, c belongs to G.
Identity Element:There exists e ∈ G such that a*e = e*a = a ∀ a ∈ G
Inverses:∀ a ∈ G there exists a-1 ∈ G such that a*a-1 = a-1*a = e
|A| = m and |B| = n, then1. No. of functions from A to B = nm2. No. of one to one function = (n, P, m)3. No. of onto function =nm – (n, C, 1)*(n-1)m + (n, C, 2)*(n-2)m .... +(-1)m*(n, C, n-1), if m >= n; 0 otherwise4. Necessary condition for bijective function |A| = |B|5. The no. of bijection function =n!6. No. of relations =2mn7. No. of reflexive relations =2n(n-1)8. No. of symmetric relations = 2n(n+1)/29. No. of Anti Symmetric Relations = 2n*3n(n-1)/210. No. of asymmetric relations = 3n(n-1)/211. No. of irreflexive relations = 2n(n-1)
12. A relation is a partial order if
1) Reflexive
2) Antisymmetric
3) Transitive
13. Meet Semi Lattice :
For all a, b belongs to L a∧b exists
14. Join Semi Lattice
For all a, b belongs to L a∨b exists
15. A poset is called Lattice if it is both meet and join semi-lattice16. Complemented Lattice : Every element has complement17. Distributive Lattice : Every Element has zero or 1 complement .18. Boolean Lattice: It should be both complemented and distributive. Every element has exactly one complement.19. A relation is an equivalence if
1) Reflexive
2) symmetric
3) Transitive
1. No. of edges in a complete graph = n(n-1)/22. Bipartite Graph : There is no edges between any two vertices of same partition . In complete bipartite graph no. of edges =m*n3. Sum of degree of all vertices is equal to twice the number of edges.4. Maximum no. of connected components in graph with n vertices = n5. Minimum number of connected components =
0 (null graph)
1 (not null graph)
6. Minimum no. of edges to have connected graph with n vertices = n-17. To guarantee that a graph with n vertices is connected, minimum no. of edges required = {(n-1)*(n-2)/2 } + 18. A graph is euler graph if it there exists atmost 2 vertices of odd – degree9. Tree
-> Has exactly one path btw any two vertices
-> not contain cycle
-> connected
-> no. of edges = n -1
10. For complete graph the no . of spanning tree possible = nn-2
A graph is planar if and only if it does not contain a subdivision of K5 and K3, 3 as a subgraph.
Let G be a connected planar graph, and let n, m and f denote, respectively, the numbers of vertices, edges, and faces in a plane drawing of G. Then n – m + f = 2.
Let G be a connected planar simple graph with n vertices and m edges, and no triangles. Then m ≤ 2n – 4.
Let G be a connected planar simple graph with n vertices, where n ? 3 and m edges. Then m ≤ 3n – 6.
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Normal Forms in DBMS
Page Replacement Algorithms in Operating Systems
Introduction of Operating System - Set 1
Inter Process Communication (IPC)
Differences between TCP and UDP
Cache Memory in Computer Organization
Semaphores in Process Synchronization
Types of Network Topology
LRU Cache Implementation
Difference between Process and Thread
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 96,
"s": 52,
"text": "See Last Minute Notes on all subjects here."
},
{
"code": null,
"e": 7198,
"s": 96,
"text": "Implication( →): For any two propositions p and q, the statement “if p then q” is called an implication and it is denoted by p → q.if and only if(↔): For any two propositions p and q, the statement “p if and only if(iff) q” is called a biconditional and it is denoted by p ↔ q.De Morgan’s Law : Special Conditional Statements1.Implication : 2.Converse : The converse of the proposition is 3.Contrapositive : The contrapositive of the proposition is 4.Inverse : The inverse of the proposition is Types of propositions based on Truth values1.Tautology – A proposition which is always true, is called a tautology.2.Contradiction – A proposition which is always false, is called a contradiction.3.Contingency – A proposition that is neither a tautology nor a contradiction is called a contingency.There are two very important equivalences involving quantifiers1. \n\n2. \nRules of inferenceCombinatricsPermutation: A permutation of a set of distinct objects is an ordered arrangement of these objects. Combination: A combination of a set of distinct objects is just a count of the number of ways a specific number of elements can be selected from a set of a certain size. The order of elements does not matter in a combination.which gives us- Binomial Coefficients: The -combinations from a set of elements if denoted by . This number is also called a binomial coefficient since it occurs as a coefficient in the expansion of powers of binomial expressions.Let and be variables and be a non-negative integer. Then The binomial expansion using Combinatorial symbolsSet TheoryA Set is an unordered collection of objects, known as elements or members of the set.An element ‘a’ belong to a set A can be written as ‘a ∈ A’, ‘a ∉ A’ denotes that a is not an element of the set A.Equal setsTwo sets are said to be equal if both have same elements. For example A = {1, 3, 9, 7} and B = {3, 1, 7, 9} are equal sets.NOTE: Order of elements of a set doesn’t matter.SubsetA set A is said to be subset of another set B if and only if every element of set A is also a part of other set B.Denoted by ‘⊆‘.‘A ⊆ B ‘ denotes A is a subset of B.To prove A is the subset of B, we need to simply show that if x belongs to A then x also belongs to B.To prove A is not a subset of B, we need to find out one element which is part of set A but not belong to set B.‘U’ denotes the universal set. Above Venn Diagram shows that A is a subset of B.Size of a SetSize of a set can be finite or infinite.For exampleFinite set: Set of natural numbers less than 100.\nInfinite set: Set of real numbers.Size of the set S is known as Cardinality number, denoted as |S|.Note: Cardinality of a null set is 0.Power SetsThe power set is the set all possible subset of the set S. Denoted by P(S).Example: What is the power set of {0, 1, 2}?Solution: All possible subsets{∅}, {0}, {1}, {2}, {0, 1}, {0, 2}, {1, 2}, {0, 1, 2}.Note: Empty set and set itself is also the member of this set of subsets.Cardinality of power set is , where n is the number of elements in a set.Cartesian ProductsLet A and B be two sets. Cartesian product of A and B is denoted by A × B, is the set of all ordered pairs (a, b), where a belong to A and b belong to B.A × B = {(a, b) | a ∈ A ∧ b ∈ B}.The cardinality of A × B is N*M, where N is the Cardinality of A and M is the cardinality of B.Note: A × B is not the same as B × A.UnionUnion of the sets A and B, denoted by A ∪ B, is the set of distinct element belongs to set A or set B, or both.IntersectionThe intersection of the sets A and B, denoted by A ∩ B, is the set of elements belongs to both A and B i.e. set of the common element in A and B.DisjointTwo sets are said to be disjoint if their intersection is the empty set .i.e sets have no common elements.Set DifferenceDifference between sets is denoted by ‘A – B’, is the set containing elements of set A but not in B. i.e all elements of A except the element of B.ComplementThe complement of a set A, denoted by , is the set of all the elements except A. Complement of the set A is U – A.Formula:GroupA non-empty set G, (G, *) is called a group if it follows the following axiom:Closure:(a*b) belongs to G for all a, b ∈ G.Associativity: a*(b*c) = (a*b)*c ∀ a, b, c belongs to G.Identity Element:There exists e ∈ G such that a*e = e*a = a ∀ a ∈ GInverses:∀ a ∈ G there exists a-1 ∈ G such that a*a-1 = a-1*a = eRelations And Functions|A| = m and |B| = n, then1. No. of functions from A to B = nm2. No. of one to one function = (n, P, m)3. No. of onto function =nm – (n, C, 1)*(n-1)m + (n, C, 2)*(n-2)m .... +(-1)m*(n, C, n-1), if m >= n; 0 otherwise4. Necessary condition for bijective function |A| = |B|5. The no. of bijection function =n!6. No. of relations =2mn7. No. of reflexive relations =2n(n-1)8. No. of symmetric relations = 2n(n+1)/29. No. of Anti Symmetric Relations = 2n*3n(n-1)/210. No. of asymmetric relations = 3n(n-1)/211. No. of irreflexive relations = 2n(n-1)12. A relation is a partial order if 1) Reflexive\n 2) Antisymmetric\n 3) Transitive\n13. Meet Semi Lattice : For all a, b belongs to L a∧b exists 14. Join Semi Lattice For all a, b belongs to L a∨b exists 15. A poset is called Lattice if it is both meet and join semi-lattice16. Complemented Lattice : Every element has complement17. Distributive Lattice : Every Element has zero or 1 complement .18. Boolean Lattice: It should be both complemented and distributive. Every element has exactly one complement.19. A relation is an equivalence if 1) Reflexive\n 2) symmetric\n 3) Transitive\nGraph Theory1. No. of edges in a complete graph = n(n-1)/22. Bipartite Graph : There is no edges between any two vertices of same partition . In complete bipartite graph no. of edges =m*n3. Sum of degree of all vertices is equal to twice the number of edges.4. Maximum no. of connected components in graph with n vertices = n5. Minimum number of connected components =0 (null graph)\n1 (not null graph) \n6. Minimum no. of edges to have connected graph with n vertices = n-17. To guarantee that a graph with n vertices is connected, minimum no. of edges required = {(n-1)*(n-2)/2 } + 18. A graph is euler graph if it there exists atmost 2 vertices of odd – degree9. Tree -> Has exactly one path btw any two vertices\n -> not contain cycle\n -> connected\n -> no. of edges = n -1\n10. For complete graph the no . of spanning tree possible = nn-211. For simple connected planar graphA graph is planar if and only if it does not contain a subdivision of K5 and K3, 3 as a subgraph.Let G be a connected planar graph, and let n, m and f denote, respectively, the numbers of vertices, edges, and faces in a plane drawing of G. Then n – m + f = 2.Let G be a connected planar simple graph with n vertices and m edges, and no triangles. Then m ≤ 2n – 4.Let G be a connected planar simple graph with n vertices, where n ? 3 and m edges. Then m ≤ 3n – 6.12.) Every bipartite graph is 2 colourable and vice versa13.) The no. of perfect matchings for a complete graph (2n)/(2nn!)14.) The no. of complete matchings for Kn.n = n!My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 7330,
"s": 7198,
"text": "Implication( →): For any two propositions p and q, the statement “if p then q” is called an implication and it is denoted by p → q."
},
{
"code": null,
"e": 7477,
"s": 7330,
"text": "if and only if(↔): For any two propositions p and q, the statement “p if and only if(iff) q” is called a biconditional and it is denoted by p ↔ q."
},
{
"code": null,
"e": 7495,
"s": 7477,
"text": "De Morgan’s Law :"
},
{
"code": null,
"e": 7527,
"s": 7495,
"text": " Special Conditional Statements"
},
{
"code": null,
"e": 7701,
"s": 7527,
"text": "1.Implication : 2.Converse : The converse of the proposition is 3.Contrapositive : The contrapositive of the proposition is 4.Inverse : The inverse of the proposition is "
},
{
"code": null,
"e": 8000,
"s": 7701,
"text": "Types of propositions based on Truth values1.Tautology – A proposition which is always true, is called a tautology.2.Contradiction – A proposition which is always false, is called a contradiction.3.Contingency – A proposition that is neither a tautology nor a contradiction is called a contingency."
},
{
"code": null,
"e": 8064,
"s": 8000,
"text": "There are two very important equivalences involving quantifiers"
},
{
"code": null,
"e": 8077,
"s": 8064,
"text": "1. \n\n2. \n"
},
{
"code": null,
"e": 8096,
"s": 8077,
"text": "Rules of inference"
},
{
"code": null,
"e": 8196,
"s": 8096,
"text": "Permutation: A permutation of a set of distinct objects is an ordered arrangement of these objects."
},
{
"code": null,
"e": 8442,
"s": 8201,
"text": "Combination: A combination of a set of distinct objects is just a count of the number of ways a specific number of elements can be selected from a set of a certain size. The order of elements does not matter in a combination.which gives us-"
},
{
"code": null,
"e": 8722,
"s": 8447,
"text": "Binomial Coefficients: The -combinations from a set of elements if denoted by . This number is also called a binomial coefficient since it occurs as a coefficient in the expansion of powers of binomial expressions.Let and be variables and be a non-negative integer. Then"
},
{
"code": null,
"e": 8778,
"s": 8727,
"text": "The binomial expansion using Combinatorial symbols"
},
{
"code": null,
"e": 8979,
"s": 8778,
"text": "A Set is an unordered collection of objects, known as elements or members of the set.An element ‘a’ belong to a set A can be written as ‘a ∈ A’, ‘a ∉ A’ denotes that a is not an element of the set A."
},
{
"code": null,
"e": 9113,
"s": 8979,
"text": "Equal setsTwo sets are said to be equal if both have same elements. For example A = {1, 3, 9, 7} and B = {3, 1, 7, 9} are equal sets."
},
{
"code": null,
"e": 9162,
"s": 9113,
"text": "NOTE: Order of elements of a set doesn’t matter."
},
{
"code": null,
"e": 9169,
"s": 9162,
"text": "Subset"
},
{
"code": null,
"e": 9335,
"s": 9169,
"text": "A set A is said to be subset of another set B if and only if every element of set A is also a part of other set B.Denoted by ‘⊆‘.‘A ⊆ B ‘ denotes A is a subset of B."
},
{
"code": null,
"e": 9550,
"s": 9335,
"text": "To prove A is the subset of B, we need to simply show that if x belongs to A then x also belongs to B.To prove A is not a subset of B, we need to find out one element which is part of set A but not belong to set B."
},
{
"code": null,
"e": 9631,
"s": 9550,
"text": "‘U’ denotes the universal set. Above Venn Diagram shows that A is a subset of B."
},
{
"code": null,
"e": 9685,
"s": 9631,
"text": "Size of a SetSize of a set can be finite or infinite."
},
{
"code": null,
"e": 9697,
"s": 9685,
"text": "For example"
},
{
"code": null,
"e": 9782,
"s": 9697,
"text": "Finite set: Set of natural numbers less than 100.\nInfinite set: Set of real numbers."
},
{
"code": null,
"e": 9848,
"s": 9782,
"text": "Size of the set S is known as Cardinality number, denoted as |S|."
},
{
"code": null,
"e": 9886,
"s": 9848,
"text": "Note: Cardinality of a null set is 0."
},
{
"code": null,
"e": 10173,
"s": 9886,
"text": "Power SetsThe power set is the set all possible subset of the set S. Denoted by P(S).Example: What is the power set of {0, 1, 2}?Solution: All possible subsets{∅}, {0}, {1}, {2}, {0, 1}, {0, 2}, {1, 2}, {0, 1, 2}.Note: Empty set and set itself is also the member of this set of subsets."
},
{
"code": null,
"e": 10247,
"s": 10173,
"text": "Cardinality of power set is , where n is the number of elements in a set."
},
{
"code": null,
"e": 10419,
"s": 10247,
"text": "Cartesian ProductsLet A and B be two sets. Cartesian product of A and B is denoted by A × B, is the set of all ordered pairs (a, b), where a belong to A and b belong to B."
},
{
"code": null,
"e": 10453,
"s": 10419,
"text": "A × B = {(a, b) | a ∈ A ∧ b ∈ B}."
},
{
"code": null,
"e": 10549,
"s": 10453,
"text": "The cardinality of A × B is N*M, where N is the Cardinality of A and M is the cardinality of B."
},
{
"code": null,
"e": 10587,
"s": 10549,
"text": "Note: A × B is not the same as B × A."
},
{
"code": null,
"e": 10704,
"s": 10587,
"text": "UnionUnion of the sets A and B, denoted by A ∪ B, is the set of distinct element belongs to set A or set B, or both."
},
{
"code": null,
"e": 10862,
"s": 10704,
"text": "IntersectionThe intersection of the sets A and B, denoted by A ∩ B, is the set of elements belongs to both A and B i.e. set of the common element in A and B."
},
{
"code": null,
"e": 10977,
"s": 10862,
"text": "DisjointTwo sets are said to be disjoint if their intersection is the empty set .i.e sets have no common elements."
},
{
"code": null,
"e": 11263,
"s": 10977,
"text": "Set DifferenceDifference between sets is denoted by ‘A – B’, is the set containing elements of set A but not in B. i.e all elements of A except the element of B.ComplementThe complement of a set A, denoted by , is the set of all the elements except A. Complement of the set A is U – A."
},
{
"code": null,
"e": 11272,
"s": 11263,
"text": "Formula:"
},
{
"code": null,
"e": 11356,
"s": 11272,
"text": "GroupA non-empty set G, (G, *) is called a group if it follows the following axiom:"
},
{
"code": null,
"e": 11401,
"s": 11356,
"text": "Closure:(a*b) belongs to G for all a, b ∈ G."
},
{
"code": null,
"e": 11458,
"s": 11401,
"text": "Associativity: a*(b*c) = (a*b)*c ∀ a, b, c belongs to G."
},
{
"code": null,
"e": 11526,
"s": 11458,
"text": "Identity Element:There exists e ∈ G such that a*e = e*a = a ∀ a ∈ G"
},
{
"code": null,
"e": 11592,
"s": 11526,
"text": "Inverses:∀ a ∈ G there exists a-1 ∈ G such that a*a-1 = a-1*a = e"
},
{
"code": null,
"e": 12136,
"s": 11592,
"text": "|A| = m and |B| = n, then1. No. of functions from A to B = nm2. No. of one to one function = (n, P, m)3. No. of onto function =nm – (n, C, 1)*(n-1)m + (n, C, 2)*(n-2)m .... +(-1)m*(n, C, n-1), if m >= n; 0 otherwise4. Necessary condition for bijective function |A| = |B|5. The no. of bijection function =n!6. No. of relations =2mn7. No. of reflexive relations =2n(n-1)8. No. of symmetric relations = 2n(n+1)/29. No. of Anti Symmetric Relations = 2n*3n(n-1)/210. No. of asymmetric relations = 3n(n-1)/211. No. of irreflexive relations = 2n(n-1)"
},
{
"code": null,
"e": 12173,
"s": 12136,
"text": "12. A relation is a partial order if"
},
{
"code": null,
"e": 12230,
"s": 12173,
"text": " 1) Reflexive\n 2) Antisymmetric\n 3) Transitive\n"
},
{
"code": null,
"e": 12254,
"s": 12230,
"text": "13. Meet Semi Lattice :"
},
{
"code": null,
"e": 12296,
"s": 12254,
"text": " For all a, b belongs to L a∧b exists "
},
{
"code": null,
"e": 12318,
"s": 12296,
"text": "14. Join Semi Lattice"
},
{
"code": null,
"e": 12360,
"s": 12318,
"text": " For all a, b belongs to L a∨b exists "
},
{
"code": null,
"e": 12699,
"s": 12360,
"text": "15. A poset is called Lattice if it is both meet and join semi-lattice16. Complemented Lattice : Every element has complement17. Distributive Lattice : Every Element has zero or 1 complement .18. Boolean Lattice: It should be both complemented and distributive. Every element has exactly one complement.19. A relation is an equivalence if"
},
{
"code": null,
"e": 12752,
"s": 12699,
"text": " 1) Reflexive\n 2) symmetric\n 3) Transitive\n"
},
{
"code": null,
"e": 13109,
"s": 12752,
"text": "1. No. of edges in a complete graph = n(n-1)/22. Bipartite Graph : There is no edges between any two vertices of same partition . In complete bipartite graph no. of edges =m*n3. Sum of degree of all vertices is equal to twice the number of edges.4. Maximum no. of connected components in graph with n vertices = n5. Minimum number of connected components ="
},
{
"code": null,
"e": 13145,
"s": 13109,
"text": "0 (null graph)\n1 (not null graph) \n"
},
{
"code": null,
"e": 13411,
"s": 13145,
"text": "6. Minimum no. of edges to have connected graph with n vertices = n-17. To guarantee that a graph with n vertices is connected, minimum no. of edges required = {(n-1)*(n-2)/2 } + 18. A graph is euler graph if it there exists atmost 2 vertices of odd – degree9. Tree"
},
{
"code": null,
"e": 13530,
"s": 13411,
"text": " -> Has exactly one path btw any two vertices\n -> not contain cycle\n -> connected\n -> no. of edges = n -1\n"
},
{
"code": null,
"e": 13595,
"s": 13530,
"text": "10. For complete graph the no . of spanning tree possible = nn-2"
},
{
"code": null,
"e": 13693,
"s": 13595,
"text": "A graph is planar if and only if it does not contain a subdivision of K5 and K3, 3 as a subgraph."
},
{
"code": null,
"e": 13856,
"s": 13693,
"text": "Let G be a connected planar graph, and let n, m and f denote, respectively, the numbers of vertices, edges, and faces in a plane drawing of G. Then n – m + f = 2."
},
{
"code": null,
"e": 13961,
"s": 13856,
"text": "Let G be a connected planar simple graph with n vertices and m edges, and no triangles. Then m ≤ 2n – 4."
},
{
"code": null,
"e": 14061,
"s": 13961,
"text": "Let G be a connected planar simple graph with n vertices, where n ? 3 and m edges. Then m ≤ 3n – 6."
},
{
"code": null,
"e": 14069,
"s": 14061,
"text": "GATE CS"
},
{
"code": null,
"e": 14167,
"s": 14069,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 14188,
"s": 14167,
"text": "Normal Forms in DBMS"
},
{
"code": null,
"e": 14237,
"s": 14188,
"text": "Page Replacement Algorithms in Operating Systems"
},
{
"code": null,
"e": 14278,
"s": 14237,
"text": "Introduction of Operating System - Set 1"
},
{
"code": null,
"e": 14312,
"s": 14278,
"text": "Inter Process Communication (IPC)"
},
{
"code": null,
"e": 14344,
"s": 14312,
"text": "Differences between TCP and UDP"
},
{
"code": null,
"e": 14382,
"s": 14344,
"text": "Cache Memory in Computer Organization"
},
{
"code": null,
"e": 14420,
"s": 14382,
"text": "Semaphores in Process Synchronization"
},
{
"code": null,
"e": 14446,
"s": 14420,
"text": "Types of Network Topology"
},
{
"code": null,
"e": 14471,
"s": 14446,
"text": "LRU Cache Implementation"
}
] |
How to create a Venn Diagram in R ?
|
17 Jun, 2021
Venn diagram is the graphical representation of sets used for showing the relationship between them. Through the use of Venn diagram one can highlight the differences as well as similarities between elements of sets. Venn diagram is also known as Logic diagram or set diagram. We use circles to represent sets that can be intersecting or overlapping or non-intersecting, based on relationship between them. There are a number of operations we can perform using Venn diagram, but the major among them are: Union, Intersection, and Complement.
Union: Union of sets refers to the combined elements of all sets.
Intersection: Intersection of sets is the set of elements containing the common element of both sets. When there is no common element, the intersection will give a null value.
Complement: The complement of a set is the set of all elements in the universal set other than the set itself. The complement of an empty set is the universal set.
In this article, we are going to implement Venn diagram using R programming language.
We need to install and load the package first:
Syntax:
install.packages(“VennDiagram”)
library(“VennDiagram”)
For creating a Venn diagram for pair sets or for triple sets or for any number of sets, there is only a slight difference in the syntax. For example, we use keyword “pairwise” for creating a Venn diagram with two sets, and for three sets we use “triple” keyword.
For two sets:
Syntax:
grid.newpage()
draw.pairwise.venn(area1,area2,cross.area,col,fill)
For three sets:
Syntax:
grid.newpage()
draw.triple.venn(area1,area2, area3,n12,n23,n13, n123,category)
Parameters:
area1: The size of first set
area2: The size of second set
area3: The size of third set
cross.area: The size of the intersection between the sets
n12: The size of intersection between the first and second set
n23: The size of intersection between the third and second set
n13: The size of intersection between the first and third set
n123: The size of intersection between all the three sets
col: A vector giving the colours of the circle’s circumference
fill: A vector giving the colours to circle’s area
category: A vector of strings giving the category names of the sets
In order to create a Venn diagram using this package install and load the package in the editor. Add a new plotting page using grid.newpage( ). Then, insert the data for Venn diagram using the above syntax. For one set use draw.single, two sets use draw.pairwise, three sets use draw.triple, four sets use draw.quad and five sets use quintuple.
Example 1:
R
# load Venn diagram packagelibrary("VennDiagram") # move to new plotting pagegrid.newpage() # create pairwise Venn diagramdraw.pairwise.venn(area1=20, area2=45,cross.area=10, category=c("Mango","Banana"),fill=c("Red","Yellow"))
Output:
Example 2:
R
# load Venn diagram packagelibrary("VennDiagram") # move to new plotting pagegrid.newpage() # create Venn diagram with three setsdraw.triple.venn(area1=40, area2=15, area3=10, n12=5, n23=12, n13=4, n123=2, category=c("Science","Economics","English"), col="Red",fill=c("Green","Yellow","Blue"))
Output:
Example 3:
R
# load Venn diagram packagelibrary("VennDiagram") # move to new plotting pagegrid.newpage() # create Venn diagram with four setsdraw.quad.venn(area1=72, area2=86, area3=50, area4 =52, n12=44, n23=38, n13=27, n14= 32,n24=32, n34=20, n123=18, n124=17, n234=13, n134=11, n1234=6, category=c("Cricket","Football","Badminton","Table Tennis"), col="Green",fill=c("Red","Pink","Blue","Orange"),lty="dashed")
Output:
First, we need to install this package and load it in order to make it usable.
install.packages(“ggvenn”)
library(“ggvenn”)
ggvenn plots venn diagram as an independent function. It supports both data frame and list as input.
Syntax:
ggvenn (data, show_elements, show_percentage, fill_color, stroke_color, stroke_linetype)
Parameters:
data: A data frame or list as input data
show_elements: Shows set elements instead of count
show_percentage: Show percentage for each set
fill_color: Fill colours in circles
stroke_color: Stroke colour for drawing circles
stroke_linetype: Line type for drawing circles
This approach is simple and only data to be plotted, needs to be passed.
Example 1:
R
# load ggvenn packagelibrary("ggvenn") # use list as inputA <-list('India'=c(1,3,5,7),'USA'=c(1,6,5)) # create venn diagram and display all the setsggvenn(A)
Output:
Example 2:
R
# load ggvenn packagelibrary("ggvenn") # use data frame as inputM <-tibble(value=c(1,3,2,7,5),'TEA'=c(TRUE,FALSE,TRUE,FALSE,FALSE), 'COFFEE'=c(TRUE,TRUE,FALSE,FALSE,TRUE), 'JUICE'=c(TRUE,FALSE,FALSE,TRUE,TRUE)) # create Venn diagram and display all setsggvenn(M)
Output:
Example 3:
R
# load ggvenn packagelibrary("ggvenn") # use list as inputD <-list('Autumn'=c(2,3,1),'Winter'=c(4,7,9,1), 'Summer'=c(3,7,2,5),'Spring'=c(2,5,9,1)) # creating venn diagram for four sets# and displaying only two setsggvenn(D,c("Autumn","Spring"),show_percentage=FALSE, fill_color=c("red","orange"))
Output:
Example 4:
R
# load ggvenn packagelibrary("ggvenn") # use list as input H <-list('Bus'=c(6,7,3),'Truck'=c(4,3,9), 'Cycle'=c(10,3,2,8),'Car'=c(7,5,4,3)) # create customised venn diagramggvenn(H,show_elements=TRUE,stroke_color="Red", stroke_linetype="solid")
Output:
The gplots package provides Venn diagrams for up to five sets. The venn( ) function accepts either a list of sets as an argument, or it takes a binary matrix, one column per set, indicating for every element, one per row, the membership with every set. The main page of venn( ) lists options to change the appearance of the plots, e.g., the names of the sets may be omitted and sizes changed. However, there is ample opportunity to extend the functionality of this package.
As usual, the first step is to install and load the package:
install.packages(“gplots”)
library(“gplots”)
We simply pass the input as a parameter in venn( ) function.
Example 1:
R
# load gplots packagelibrary("gplots") # use list as inputx <-list('Plants'=c(6,7,8),'Animals'=c(7,8,3,4)) # create Venn diagram with two setsvenn(x)
Output:
Example 2:
R
# load gplots packagelibrary("gplots") # creating venn diagram by passing # list as direct parametervenn(list(YouTube=1:6,Netflix=3:8,Instagram=c(5,8:12)))
Output:
‘ggVennDiagram’ returns structured data that can be used to plot Venn. The first step to make use of this package is to install and load it.
install.packages(“ggVennDiagram”)
library(“ggVennDiagram”)
Here also we will simply pass the parameter in ggVennDiagram( ) function.
Syntax:
ggVennDiagram(data, label_alpha, category.names, show_intersect, set_color)
Parameters:
data: Input in form of list
label_alpha: Remove the background of region labels
category.names: Give names to sets.
show_intersect: If true, text can be visualized
set_color: Color of set labels
For this to work for, first install and load ggVennDiagram Package and give input as list. Then, use the above syntax for creating Venn Diagram and for customizing Venn diagram use other parameters.
Example 1:
R
# load ggVennDiagram Packagelibrary("ggVennDiagram") # use list as an inputx <-list('C++'=c(9,3,5,2),'Java'=c(7,8,4,3), 'Python'=c(11,2,4,5,8),'Ruby'=c(3,8)) # creating Venn diagram and displaying # all setsggVennDiagram(x)
Output:
Example 2:
R
# load ggVennDiagram Packagelibrary("ggVennDiagram") # use list as inputM <-list('Rose'=c(2,6),'Lily'=c(5,3,9,2), 'Sunflower'=c(3,10,2),'Lotus'=c(5,7,8)) # creating Venn diagram with four sets# but displaying only first twoggVennDiagram(M[1:2],set_color="Red",label_alpha=0, show_intersect=FALSE)
Output:
Example 3:
R
# load ggVennDiagram Packagelibrary("ggVennDiagram") # use list as inputD<-list(A=c(5,6,8),B=c(1,9,8,2),C=c(8,9,4,7,11)) # creating Venn diagram with three sets# but displaying only last twoggVennDiagram(D[2:3],category.names=c("BREAKFAST","LUNCH"))
Output:
Data Visualization
Picked
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
R - if statement
How to filter R DataFrame by values in a column?
Logistic Regression in R Programming
Replace Specific Characters in String in R
How to import an Excel File into R ?
Joining of Dataframes in R Programming
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Jun, 2021"
},
{
"code": null,
"e": 570,
"s": 28,
"text": "Venn diagram is the graphical representation of sets used for showing the relationship between them. Through the use of Venn diagram one can highlight the differences as well as similarities between elements of sets. Venn diagram is also known as Logic diagram or set diagram. We use circles to represent sets that can be intersecting or overlapping or non-intersecting, based on relationship between them. There are a number of operations we can perform using Venn diagram, but the major among them are: Union, Intersection, and Complement."
},
{
"code": null,
"e": 636,
"s": 570,
"text": "Union: Union of sets refers to the combined elements of all sets."
},
{
"code": null,
"e": 812,
"s": 636,
"text": "Intersection: Intersection of sets is the set of elements containing the common element of both sets. When there is no common element, the intersection will give a null value."
},
{
"code": null,
"e": 976,
"s": 812,
"text": "Complement: The complement of a set is the set of all elements in the universal set other than the set itself. The complement of an empty set is the universal set."
},
{
"code": null,
"e": 1063,
"s": 976,
"text": "In this article, we are going to implement Venn diagram using R programming language. "
},
{
"code": null,
"e": 1113,
"s": 1063,
"text": "We need to install and load the package first: "
},
{
"code": null,
"e": 1121,
"s": 1113,
"text": "Syntax:"
},
{
"code": null,
"e": 1168,
"s": 1121,
"text": "install.packages(“VennDiagram”) "
},
{
"code": null,
"e": 1215,
"s": 1168,
"text": "library(“VennDiagram”) "
},
{
"code": null,
"e": 1479,
"s": 1215,
"text": "For creating a Venn diagram for pair sets or for triple sets or for any number of sets, there is only a slight difference in the syntax. For example, we use keyword “pairwise” for creating a Venn diagram with two sets, and for three sets we use “triple” keyword. "
},
{
"code": null,
"e": 1493,
"s": 1479,
"text": "For two sets:"
},
{
"code": null,
"e": 1501,
"s": 1493,
"text": "Syntax:"
},
{
"code": null,
"e": 1560,
"s": 1501,
"text": " grid.newpage() "
},
{
"code": null,
"e": 1616,
"s": 1560,
"text": " draw.pairwise.venn(area1,area2,cross.area,col,fill)"
},
{
"code": null,
"e": 1632,
"s": 1616,
"text": "For three sets:"
},
{
"code": null,
"e": 1640,
"s": 1632,
"text": "Syntax:"
},
{
"code": null,
"e": 1699,
"s": 1640,
"text": " grid.newpage() "
},
{
"code": null,
"e": 1767,
"s": 1699,
"text": " draw.triple.venn(area1,area2, area3,n12,n23,n13, n123,category)"
},
{
"code": null,
"e": 1779,
"s": 1767,
"text": "Parameters:"
},
{
"code": null,
"e": 1808,
"s": 1779,
"text": "area1: The size of first set"
},
{
"code": null,
"e": 1838,
"s": 1808,
"text": "area2: The size of second set"
},
{
"code": null,
"e": 1867,
"s": 1838,
"text": "area3: The size of third set"
},
{
"code": null,
"e": 1925,
"s": 1867,
"text": "cross.area: The size of the intersection between the sets"
},
{
"code": null,
"e": 1988,
"s": 1925,
"text": "n12: The size of intersection between the first and second set"
},
{
"code": null,
"e": 2051,
"s": 1988,
"text": "n23: The size of intersection between the third and second set"
},
{
"code": null,
"e": 2113,
"s": 2051,
"text": "n13: The size of intersection between the first and third set"
},
{
"code": null,
"e": 2171,
"s": 2113,
"text": "n123: The size of intersection between all the three sets"
},
{
"code": null,
"e": 2234,
"s": 2171,
"text": "col: A vector giving the colours of the circle’s circumference"
},
{
"code": null,
"e": 2285,
"s": 2234,
"text": "fill: A vector giving the colours to circle’s area"
},
{
"code": null,
"e": 2353,
"s": 2285,
"text": "category: A vector of strings giving the category names of the sets"
},
{
"code": null,
"e": 2700,
"s": 2353,
"text": "In order to create a Venn diagram using this package install and load the package in the editor. Add a new plotting page using grid.newpage( ). Then, insert the data for Venn diagram using the above syntax. For one set use draw.single, two sets use draw.pairwise, three sets use draw.triple, four sets use draw.quad and five sets use quintuple. "
},
{
"code": null,
"e": 2711,
"s": 2700,
"text": "Example 1:"
},
{
"code": null,
"e": 2713,
"s": 2711,
"text": "R"
},
{
"code": "# load Venn diagram packagelibrary(\"VennDiagram\") # move to new plotting pagegrid.newpage() # create pairwise Venn diagramdraw.pairwise.venn(area1=20, area2=45,cross.area=10, category=c(\"Mango\",\"Banana\"),fill=c(\"Red\",\"Yellow\"))",
"e": 2961,
"s": 2713,
"text": null
},
{
"code": null,
"e": 2970,
"s": 2961,
"text": " Output:"
},
{
"code": null,
"e": 2981,
"s": 2970,
"text": "Example 2:"
},
{
"code": null,
"e": 2983,
"s": 2981,
"text": "R"
},
{
"code": "# load Venn diagram packagelibrary(\"VennDiagram\") # move to new plotting pagegrid.newpage() # create Venn diagram with three setsdraw.triple.venn(area1=40, area2=15, area3=10, n12=5, n23=12, n13=4, n123=2, category=c(\"Science\",\"Economics\",\"English\"), col=\"Red\",fill=c(\"Green\",\"Yellow\",\"Blue\"))",
"e": 3329,
"s": 2983,
"text": null
},
{
"code": null,
"e": 3337,
"s": 3329,
"text": "Output:"
},
{
"code": null,
"e": 3348,
"s": 3337,
"text": "Example 3:"
},
{
"code": null,
"e": 3350,
"s": 3348,
"text": "R"
},
{
"code": "# load Venn diagram packagelibrary(\"VennDiagram\") # move to new plotting pagegrid.newpage() # create Venn diagram with four setsdraw.quad.venn(area1=72, area2=86, area3=50, area4 =52, n12=44, n23=38, n13=27, n14= 32,n24=32, n34=20, n123=18, n124=17, n234=13, n134=11, n1234=6, category=c(\"Cricket\",\"Football\",\"Badminton\",\"Table Tennis\"), col=\"Green\",fill=c(\"Red\",\"Pink\",\"Blue\",\"Orange\"),lty=\"dashed\")",
"e": 3827,
"s": 3350,
"text": null
},
{
"code": null,
"e": 3835,
"s": 3827,
"text": "Output:"
},
{
"code": null,
"e": 3914,
"s": 3835,
"text": "First, we need to install this package and load it in order to make it usable."
},
{
"code": null,
"e": 3955,
"s": 3914,
"text": "install.packages(“ggvenn”) "
},
{
"code": null,
"e": 3996,
"s": 3955,
"text": "library(“ggvenn”) "
},
{
"code": null,
"e": 4097,
"s": 3996,
"text": "ggvenn plots venn diagram as an independent function. It supports both data frame and list as input."
},
{
"code": null,
"e": 4105,
"s": 4097,
"text": "Syntax:"
},
{
"code": null,
"e": 4194,
"s": 4105,
"text": "ggvenn (data, show_elements, show_percentage, fill_color, stroke_color, stroke_linetype)"
},
{
"code": null,
"e": 4206,
"s": 4194,
"text": "Parameters:"
},
{
"code": null,
"e": 4247,
"s": 4206,
"text": "data: A data frame or list as input data"
},
{
"code": null,
"e": 4298,
"s": 4247,
"text": "show_elements: Shows set elements instead of count"
},
{
"code": null,
"e": 4344,
"s": 4298,
"text": "show_percentage: Show percentage for each set"
},
{
"code": null,
"e": 4380,
"s": 4344,
"text": "fill_color: Fill colours in circles"
},
{
"code": null,
"e": 4428,
"s": 4380,
"text": "stroke_color: Stroke colour for drawing circles"
},
{
"code": null,
"e": 4475,
"s": 4428,
"text": "stroke_linetype: Line type for drawing circles"
},
{
"code": null,
"e": 4548,
"s": 4475,
"text": "This approach is simple and only data to be plotted, needs to be passed."
},
{
"code": null,
"e": 4559,
"s": 4548,
"text": "Example 1:"
},
{
"code": null,
"e": 4561,
"s": 4559,
"text": "R"
},
{
"code": "# load ggvenn packagelibrary(\"ggvenn\") # use list as inputA <-list('India'=c(1,3,5,7),'USA'=c(1,6,5)) # create venn diagram and display all the setsggvenn(A)",
"e": 4721,
"s": 4561,
"text": null
},
{
"code": null,
"e": 4729,
"s": 4721,
"text": "Output:"
},
{
"code": null,
"e": 4740,
"s": 4729,
"text": "Example 2:"
},
{
"code": null,
"e": 4742,
"s": 4740,
"text": "R"
},
{
"code": "# load ggvenn packagelibrary(\"ggvenn\") # use data frame as inputM <-tibble(value=c(1,3,2,7,5),'TEA'=c(TRUE,FALSE,TRUE,FALSE,FALSE), 'COFFEE'=c(TRUE,TRUE,FALSE,FALSE,TRUE), 'JUICE'=c(TRUE,FALSE,FALSE,TRUE,TRUE)) # create Venn diagram and display all setsggvenn(M)",
"e": 5029,
"s": 4742,
"text": null
},
{
"code": null,
"e": 5038,
"s": 5029,
"text": "Output: "
},
{
"code": null,
"e": 5049,
"s": 5038,
"text": "Example 3:"
},
{
"code": null,
"e": 5051,
"s": 5049,
"text": "R"
},
{
"code": "# load ggvenn packagelibrary(\"ggvenn\") # use list as inputD <-list('Autumn'=c(2,3,1),'Winter'=c(4,7,9,1), 'Summer'=c(3,7,2,5),'Spring'=c(2,5,9,1)) # creating venn diagram for four sets# and displaying only two setsggvenn(D,c(\"Autumn\",\"Spring\"),show_percentage=FALSE, fill_color=c(\"red\",\"orange\"))",
"e": 5364,
"s": 5051,
"text": null
},
{
"code": null,
"e": 5372,
"s": 5364,
"text": "Output:"
},
{
"code": null,
"e": 5383,
"s": 5372,
"text": "Example 4:"
},
{
"code": null,
"e": 5385,
"s": 5383,
"text": "R"
},
{
"code": "# load ggvenn packagelibrary(\"ggvenn\") # use list as input H <-list('Bus'=c(6,7,3),'Truck'=c(4,3,9), 'Cycle'=c(10,3,2,8),'Car'=c(7,5,4,3)) # create customised venn diagramggvenn(H,show_elements=TRUE,stroke_color=\"Red\", stroke_linetype=\"solid\")",
"e": 5645,
"s": 5385,
"text": null
},
{
"code": null,
"e": 5654,
"s": 5645,
"text": " Output:"
},
{
"code": null,
"e": 6129,
"s": 5654,
"text": "The gplots package provides Venn diagrams for up to five sets. The venn( ) function accepts either a list of sets as an argument, or it takes a binary matrix, one column per set, indicating for every element, one per row, the membership with every set. The main page of venn( ) lists options to change the appearance of the plots, e.g., the names of the sets may be omitted and sizes changed. However, there is ample opportunity to extend the functionality of this package. "
},
{
"code": null,
"e": 6190,
"s": 6129,
"text": "As usual, the first step is to install and load the package:"
},
{
"code": null,
"e": 6237,
"s": 6190,
"text": "install.packages(“gplots”) "
},
{
"code": null,
"e": 6284,
"s": 6237,
"text": "library(“gplots”) "
},
{
"code": null,
"e": 6345,
"s": 6284,
"text": "We simply pass the input as a parameter in venn( ) function."
},
{
"code": null,
"e": 6356,
"s": 6345,
"text": "Example 1:"
},
{
"code": null,
"e": 6358,
"s": 6356,
"text": "R"
},
{
"code": "# load gplots packagelibrary(\"gplots\") # use list as inputx <-list('Plants'=c(6,7,8),'Animals'=c(7,8,3,4)) # create Venn diagram with two setsvenn(x)",
"e": 6510,
"s": 6358,
"text": null
},
{
"code": null,
"e": 6518,
"s": 6510,
"text": "Output:"
},
{
"code": null,
"e": 6529,
"s": 6518,
"text": "Example 2:"
},
{
"code": null,
"e": 6531,
"s": 6529,
"text": "R"
},
{
"code": "# load gplots packagelibrary(\"gplots\") # creating venn diagram by passing # list as direct parametervenn(list(YouTube=1:6,Netflix=3:8,Instagram=c(5,8:12)))",
"e": 6688,
"s": 6531,
"text": null
},
{
"code": null,
"e": 6696,
"s": 6688,
"text": "Output:"
},
{
"code": null,
"e": 6837,
"s": 6696,
"text": "‘ggVennDiagram’ returns structured data that can be used to plot Venn. The first step to make use of this package is to install and load it."
},
{
"code": null,
"e": 6906,
"s": 6837,
"text": "install.packages(“ggVennDiagram”) "
},
{
"code": null,
"e": 6966,
"s": 6906,
"text": "library(“ggVennDiagram”) "
},
{
"code": null,
"e": 7040,
"s": 6966,
"text": "Here also we will simply pass the parameter in ggVennDiagram( ) function."
},
{
"code": null,
"e": 7048,
"s": 7040,
"text": "Syntax:"
},
{
"code": null,
"e": 7124,
"s": 7048,
"text": "ggVennDiagram(data, label_alpha, category.names, show_intersect, set_color)"
},
{
"code": null,
"e": 7136,
"s": 7124,
"text": "Parameters:"
},
{
"code": null,
"e": 7164,
"s": 7136,
"text": "data: Input in form of list"
},
{
"code": null,
"e": 7216,
"s": 7164,
"text": "label_alpha: Remove the background of region labels"
},
{
"code": null,
"e": 7252,
"s": 7216,
"text": "category.names: Give names to sets."
},
{
"code": null,
"e": 7300,
"s": 7252,
"text": "show_intersect: If true, text can be visualized"
},
{
"code": null,
"e": 7331,
"s": 7300,
"text": "set_color: Color of set labels"
},
{
"code": null,
"e": 7530,
"s": 7331,
"text": "For this to work for, first install and load ggVennDiagram Package and give input as list. Then, use the above syntax for creating Venn Diagram and for customizing Venn diagram use other parameters."
},
{
"code": null,
"e": 7541,
"s": 7530,
"text": "Example 1:"
},
{
"code": null,
"e": 7543,
"s": 7541,
"text": "R"
},
{
"code": "# load ggVennDiagram Packagelibrary(\"ggVennDiagram\") # use list as an inputx <-list('C++'=c(9,3,5,2),'Java'=c(7,8,4,3), 'Python'=c(11,2,4,5,8),'Ruby'=c(3,8)) # creating Venn diagram and displaying # all setsggVennDiagram(x)",
"e": 7777,
"s": 7543,
"text": null
},
{
"code": null,
"e": 7785,
"s": 7777,
"text": "Output:"
},
{
"code": null,
"e": 7796,
"s": 7785,
"text": "Example 2:"
},
{
"code": null,
"e": 7798,
"s": 7796,
"text": "R"
},
{
"code": "# load ggVennDiagram Packagelibrary(\"ggVennDiagram\") # use list as inputM <-list('Rose'=c(2,6),'Lily'=c(5,3,9,2), 'Sunflower'=c(3,10,2),'Lotus'=c(5,7,8)) # creating Venn diagram with four sets# but displaying only first twoggVennDiagram(M[1:2],set_color=\"Red\",label_alpha=0, show_intersect=FALSE)",
"e": 8118,
"s": 7798,
"text": null
},
{
"code": null,
"e": 8126,
"s": 8118,
"text": "Output:"
},
{
"code": null,
"e": 8137,
"s": 8126,
"text": "Example 3:"
},
{
"code": null,
"e": 8139,
"s": 8137,
"text": "R"
},
{
"code": "# load ggVennDiagram Packagelibrary(\"ggVennDiagram\") # use list as inputD<-list(A=c(5,6,8),B=c(1,9,8,2),C=c(8,9,4,7,11)) # creating Venn diagram with three sets# but displaying only last twoggVennDiagram(D[2:3],category.names=c(\"BREAKFAST\",\"LUNCH\"))",
"e": 8391,
"s": 8139,
"text": null
},
{
"code": null,
"e": 8399,
"s": 8391,
"text": "Output:"
},
{
"code": null,
"e": 8418,
"s": 8399,
"text": "Data Visualization"
},
{
"code": null,
"e": 8425,
"s": 8418,
"text": "Picked"
},
{
"code": null,
"e": 8436,
"s": 8425,
"text": "R Language"
},
{
"code": null,
"e": 8534,
"s": 8436,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8586,
"s": 8534,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 8644,
"s": 8586,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 8679,
"s": 8644,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 8717,
"s": 8679,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 8734,
"s": 8717,
"text": "R - if statement"
},
{
"code": null,
"e": 8783,
"s": 8734,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 8820,
"s": 8783,
"text": "Logistic Regression in R Programming"
},
{
"code": null,
"e": 8863,
"s": 8820,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 8900,
"s": 8863,
"text": "How to import an Excel File into R ?"
}
] |
C program to reverse the content of the file and print it
|
17 Feb, 2022
Given a text file in a directory, the task is to print the file content backward i.e., the last line should get printed first, 2nd last line should be printed second, and so on.Examples:
Input: file1.txt has: Welcome to GeeksforGeeks Output: GeeksforGeeks to WelcomeGeeksforGeeks Input: file1.txt has: This is line one This is line two This is line three This is line four This is line five Output: This is line five This is line four This is line three This is line two This is line one
Approach:
Initialise previous length of the text as 0.Find the length of the current line and add it to the previous length. This given the next starting index of the new line.Repeat the above steps till the end of the file.Initialise the array of length of the given message in the given file.Now rewind your file pointer and place the last pointer of the text to arr[K – 1] where K is the length of the array using fseek().Print the length of the last line and decrease K by 1 for printing the next last line of the file.Repeat the above steps until K is equals to 0.
Initialise previous length of the text as 0.
Find the length of the current line and add it to the previous length. This given the next starting index of the new line.
Repeat the above steps till the end of the file.
Initialise the array of length of the given message in the given file.
Now rewind your file pointer and place the last pointer of the text to arr[K – 1] where K is the length of the array using fseek().
Print the length of the last line and decrease K by 1 for printing the next last line of the file.
Repeat the above steps until K is equals to 0.
Below is the implementation of the above approach:
C
// C program for the above approach#include <stdio.h>#include <string.h>#define MAX 100 // Function to reverse the file contentvoid reverseContent(char* x){ // Opening the path entered by user FILE* fp = fopen(x, "a+"); // If file is not found then return if (fp == NULL) { printf("Unable to open file\n"); return; } // To store the content char buf[100]; int a[MAX], s = 0, c = 0, l; // Explicitly inserting a newline // at the end, so that o/p doesn't // get effected. fprintf(fp, " \n"); rewind(fp); // Adding current length so far + // previous length of a line in // array such that we have starting // indices of upcoming lines while (!feof(fp)) { fgets(buf, sizeof(buf), fp); l = strlen(buf); a = s += l; } // Move the pointer back to 0th index rewind(fp); c -= 1; // Print the contents while (c >= 0) { fseek(fp, a, 0); fgets(buf, sizeof(buf), fp); printf("%s", buf); c--; } return ;} // Driver Codeint main(){ // File name in the directory char x[] = "file1.txt"; // Function Call to reverse the // File Content reverseContent(x); return 0;}
Input File:
Output File:
nikhatkhan11
File Handling
Arrays
C Programs
Placements
Arrays
File Handling
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Window Sliding Technique
Search, insert and delete in an unsorted array
Chocolate Distribution Problem
What is Data Structure: Types, Classifications and Applications
Strings in C
Arrow operator -> in C/C++ with Examples
Basics of File Handling in C
UDP Server-Client implementation in C
Header files in C/C++ and its uses
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n17 Feb, 2022"
},
{
"code": null,
"e": 241,
"s": 52,
"text": "Given a text file in a directory, the task is to print the file content backward i.e., the last line should get printed first, 2nd last line should be printed second, and so on.Examples: "
},
{
"code": null,
"e": 544,
"s": 241,
"text": "Input: file1.txt has: Welcome to GeeksforGeeks Output: GeeksforGeeks to WelcomeGeeksforGeeks Input: file1.txt has: This is line one This is line two This is line three This is line four This is line five Output: This is line five This is line four This is line three This is line two This is line one "
},
{
"code": null,
"e": 558,
"s": 546,
"text": "Approach: "
},
{
"code": null,
"e": 1118,
"s": 558,
"text": "Initialise previous length of the text as 0.Find the length of the current line and add it to the previous length. This given the next starting index of the new line.Repeat the above steps till the end of the file.Initialise the array of length of the given message in the given file.Now rewind your file pointer and place the last pointer of the text to arr[K – 1] where K is the length of the array using fseek().Print the length of the last line and decrease K by 1 for printing the next last line of the file.Repeat the above steps until K is equals to 0."
},
{
"code": null,
"e": 1163,
"s": 1118,
"text": "Initialise previous length of the text as 0."
},
{
"code": null,
"e": 1286,
"s": 1163,
"text": "Find the length of the current line and add it to the previous length. This given the next starting index of the new line."
},
{
"code": null,
"e": 1335,
"s": 1286,
"text": "Repeat the above steps till the end of the file."
},
{
"code": null,
"e": 1406,
"s": 1335,
"text": "Initialise the array of length of the given message in the given file."
},
{
"code": null,
"e": 1538,
"s": 1406,
"text": "Now rewind your file pointer and place the last pointer of the text to arr[K – 1] where K is the length of the array using fseek()."
},
{
"code": null,
"e": 1637,
"s": 1538,
"text": "Print the length of the last line and decrease K by 1 for printing the next last line of the file."
},
{
"code": null,
"e": 1684,
"s": 1637,
"text": "Repeat the above steps until K is equals to 0."
},
{
"code": null,
"e": 1736,
"s": 1684,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1738,
"s": 1736,
"text": "C"
},
{
"code": "// C program for the above approach#include <stdio.h>#include <string.h>#define MAX 100 // Function to reverse the file contentvoid reverseContent(char* x){ // Opening the path entered by user FILE* fp = fopen(x, \"a+\"); // If file is not found then return if (fp == NULL) { printf(\"Unable to open file\\n\"); return; } // To store the content char buf[100]; int a[MAX], s = 0, c = 0, l; // Explicitly inserting a newline // at the end, so that o/p doesn't // get effected. fprintf(fp, \" \\n\"); rewind(fp); // Adding current length so far + // previous length of a line in // array such that we have starting // indices of upcoming lines while (!feof(fp)) { fgets(buf, sizeof(buf), fp); l = strlen(buf); a = s += l; } // Move the pointer back to 0th index rewind(fp); c -= 1; // Print the contents while (c >= 0) { fseek(fp, a, 0); fgets(buf, sizeof(buf), fp); printf(\"%s\", buf); c--; } return ;} // Driver Codeint main(){ // File name in the directory char x[] = \"file1.txt\"; // Function Call to reverse the // File Content reverseContent(x); return 0;}",
"e": 2957,
"s": 1738,
"text": null
},
{
"code": null,
"e": 2971,
"s": 2957,
"text": "Input File: "
},
{
"code": null,
"e": 2986,
"s": 2971,
"text": "Output File: "
},
{
"code": null,
"e": 3001,
"s": 2988,
"text": "nikhatkhan11"
},
{
"code": null,
"e": 3015,
"s": 3001,
"text": "File Handling"
},
{
"code": null,
"e": 3022,
"s": 3015,
"text": "Arrays"
},
{
"code": null,
"e": 3033,
"s": 3022,
"text": "C Programs"
},
{
"code": null,
"e": 3044,
"s": 3033,
"text": "Placements"
},
{
"code": null,
"e": 3051,
"s": 3044,
"text": "Arrays"
},
{
"code": null,
"e": 3065,
"s": 3051,
"text": "File Handling"
},
{
"code": null,
"e": 3163,
"s": 3065,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3195,
"s": 3163,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 3220,
"s": 3195,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 3267,
"s": 3220,
"text": "Search, insert and delete in an unsorted array"
},
{
"code": null,
"e": 3298,
"s": 3267,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 3362,
"s": 3298,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 3375,
"s": 3362,
"text": "Strings in C"
},
{
"code": null,
"e": 3416,
"s": 3375,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 3445,
"s": 3416,
"text": "Basics of File Handling in C"
},
{
"code": null,
"e": 3483,
"s": 3445,
"text": "UDP Server-Client implementation in C"
}
] |
How to get decimal portion of a number using JavaScript ?
|
12 May, 2021
Given a float number, The task is to separate the number into the integer and decimal part using JavaScript. For example, a value of 15.6 would be split into two numbers, i.e. 15 and 0.6 Here are few methods discussed.
Method 1: Using split() method. This method is used to split a string into an array of substrings, and returns the new array. Syntax:
string.split(separator, limit)
Parameters:
separator: This parameter is optional. It specifies the character, or the regular expression, to use for splitting the string. If not used, the whole string will be returned (an array with only one item)
limit: This parameter is optional. It specifies the integer that specifies the number of splits, items beyond the split limit will be excluded from the array.
Return value:Returns a new Array, having the splitted items.
Example 1: This example first converts the number to string then remove the portion before the decimal using split() method.
HTML
<!DOCTYPE HTML><html> <head> <title> JavaScript | Get decimal portion of a number. </title></head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"> </p> <button onclick="GFG_Fun()"> click here </button> <p id="GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </p> <script> var up = document.getElementById('GFG_UP'); var n = -2.50999974435; up.innerHTML = n; var down = document.getElementById('GFG_DOWN'); function GFG_Fun() { down.innerHTML = (n + "").split(".")[1]; } </script></body> </html>
Output:
Before clicking on the button:
After clicking on the button:
Method 2: Using Math.abs( ) and Math.floor( ).
Math.abs( ): The Math.abs() function in JavaScript is used to return the absolute value of a number. It takes a number as its parameter and returns its absolute value.
Math.floor( ): The Math.floor() function in JavaScript is used to round off the number passed as parameter to its nearest integer in Downward direction of rounding i.g towards the lesser value.
Example 2: This example subtracts the floor of the number by original number to get the decimal portion. But in this case, we’ll get the exact portion after decimal. We’ll get the approximate result.
HTML
<!DOCTYPE HTML><html> <head> <title> JavaScript | Get decimal portion of a number. </title></head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"> </p> <button onclick="GFG_Fun()"> click here </button> <p id="GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </p> <script> var up = document.getElementById('GFG_UP'); var n = 2.57; up.innerHTML = n; var down = document.getElementById('GFG_DOWN'); function GFG_Fun() { n = Math.abs(n) down.innerHTML = n - Math.floor(n); } </script></body> </html>
Output:
Before clicking on the button:
After clicking on the button:
anikakapoor
JavaScript-Misc
JavaScript
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": "\n12 May, 2021"
},
{
"code": null,
"e": 248,
"s": 28,
"text": "Given a float number, The task is to separate the number into the integer and decimal part using JavaScript. For example, a value of 15.6 would be split into two numbers, i.e. 15 and 0.6 Here are few methods discussed. "
},
{
"code": null,
"e": 383,
"s": 248,
"text": "Method 1: Using split() method. This method is used to split a string into an array of substrings, and returns the new array. Syntax: "
},
{
"code": null,
"e": 414,
"s": 383,
"text": "string.split(separator, limit)"
},
{
"code": null,
"e": 426,
"s": 414,
"text": "Parameters:"
},
{
"code": null,
"e": 631,
"s": 426,
"text": "separator: This parameter is optional. It specifies the character, or the regular expression, to use for splitting the string. If not used, the whole string will be returned (an array with only one item) "
},
{
"code": null,
"e": 791,
"s": 631,
"text": "limit: This parameter is optional. It specifies the integer that specifies the number of splits, items beyond the split limit will be excluded from the array. "
},
{
"code": null,
"e": 852,
"s": 791,
"text": "Return value:Returns a new Array, having the splitted items."
},
{
"code": null,
"e": 978,
"s": 852,
"text": "Example 1: This example first converts the number to string then remove the portion before the decimal using split() method. "
},
{
"code": null,
"e": 983,
"s": 978,
"text": "HTML"
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> JavaScript | Get decimal portion of a number. </title></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 15px; font-weight: bold;\"> </p> <button onclick=\"GFG_Fun()\"> click here </button> <p id=\"GFG_DOWN\" style=\"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var up = document.getElementById('GFG_UP'); var n = -2.50999974435; up.innerHTML = n; var down = document.getElementById('GFG_DOWN'); function GFG_Fun() { down.innerHTML = (n + \"\").split(\".\")[1]; } </script></body> </html>",
"e": 1790,
"s": 983,
"text": null
},
{
"code": null,
"e": 1799,
"s": 1790,
"text": "Output: "
},
{
"code": null,
"e": 1831,
"s": 1799,
"text": "Before clicking on the button: "
},
{
"code": null,
"e": 1863,
"s": 1831,
"text": "After clicking on the button: "
},
{
"code": null,
"e": 1912,
"s": 1863,
"text": "Method 2: Using Math.abs( ) and Math.floor( ). "
},
{
"code": null,
"e": 2080,
"s": 1912,
"text": "Math.abs( ): The Math.abs() function in JavaScript is used to return the absolute value of a number. It takes a number as its parameter and returns its absolute value."
},
{
"code": null,
"e": 2274,
"s": 2080,
"text": "Math.floor( ): The Math.floor() function in JavaScript is used to round off the number passed as parameter to its nearest integer in Downward direction of rounding i.g towards the lesser value."
},
{
"code": null,
"e": 2474,
"s": 2274,
"text": "Example 2: This example subtracts the floor of the number by original number to get the decimal portion. But in this case, we’ll get the exact portion after decimal. We’ll get the approximate result."
},
{
"code": null,
"e": 2479,
"s": 2474,
"text": "HTML"
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> JavaScript | Get decimal portion of a number. </title></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 15px; font-weight: bold;\"> </p> <button onclick=\"GFG_Fun()\"> click here </button> <p id=\"GFG_DOWN\" style=\"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var up = document.getElementById('GFG_UP'); var n = 2.57; up.innerHTML = n; var down = document.getElementById('GFG_DOWN'); function GFG_Fun() { n = Math.abs(n) down.innerHTML = n - Math.floor(n); } </script></body> </html>",
"e": 3286,
"s": 2479,
"text": null
},
{
"code": null,
"e": 3295,
"s": 3286,
"text": "Output: "
},
{
"code": null,
"e": 3328,
"s": 3295,
"text": "Before clicking on the button: "
},
{
"code": null,
"e": 3360,
"s": 3328,
"text": "After clicking on the button: "
},
{
"code": null,
"e": 3376,
"s": 3364,
"text": "anikakapoor"
},
{
"code": null,
"e": 3392,
"s": 3376,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 3403,
"s": 3392,
"text": "JavaScript"
},
{
"code": null,
"e": 3420,
"s": 3403,
"text": "Web Technologies"
}
] |
Perl | defined() Function
|
21 Feb, 2019
Defined() in Perl returns true if the provided variable ‘VAR’ has a value other than the undef value, or it checks the value of $_ if VAR is not specified. This can be used with many functions to detect for the failure of operation since they return undef if there was a problem.
If VAR is a function or reference of a function, then it returns true if the function has been defined else it will return false if the function doesn’t exist. If a hash element is specified, it returns true if the corresponding value has been defined, but it doesn’t check for the existence of the key in the hash
Syntax: defined(VAR)
Parameters:VAR which is to be checked
Returns:Returns 0 if VAR is undef and 1 if VAR contains a value
Example 1:
#!/usr/bin/perl # Defining a variable$X = "X is defined"; # Checking for existence of $X # with defined() functionif(defined($X)) { print "$X\n";} # Checking for existence of $Y # with defined() functionif(defined($Y)) { print "Y is also defined\n";} else{ print "Y is not defined\n";}
Output:
X is defined
Y is not defined
Example 2:
#!/usr/bin/perl # Defining a functionsub X{ # Defining a variable $VAR = 20;} # Checking for existence of $X # with defined() functionif(defined(X)) { print "Function Exists\n";} # Checking for existence of $Y # with defined() functionif(defined($Y)) { print "Y is also defined\n";} else{ print "Y is not defined\n";}
Output:
Function Exists
Y is not defined
Perl-function
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Perl | Arrays (push, pop, shift, unshift)
Perl | Arrays
Perl Tutorial - Learn Perl With Examples
Perl | length() Function
Perl | Boolean Values
Perl | Subroutines or Functions
Use of print() and say() in Perl
Perl | Basic Syntax of a Perl Program
Hello World Program in Perl
Introduction to Perl
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Feb, 2019"
},
{
"code": null,
"e": 308,
"s": 28,
"text": "Defined() in Perl returns true if the provided variable ‘VAR’ has a value other than the undef value, or it checks the value of $_ if VAR is not specified. This can be used with many functions to detect for the failure of operation since they return undef if there was a problem."
},
{
"code": null,
"e": 623,
"s": 308,
"text": "If VAR is a function or reference of a function, then it returns true if the function has been defined else it will return false if the function doesn’t exist. If a hash element is specified, it returns true if the corresponding value has been defined, but it doesn’t check for the existence of the key in the hash"
},
{
"code": null,
"e": 644,
"s": 623,
"text": "Syntax: defined(VAR)"
},
{
"code": null,
"e": 682,
"s": 644,
"text": "Parameters:VAR which is to be checked"
},
{
"code": null,
"e": 746,
"s": 682,
"text": "Returns:Returns 0 if VAR is undef and 1 if VAR contains a value"
},
{
"code": null,
"e": 757,
"s": 746,
"text": "Example 1:"
},
{
"code": "#!/usr/bin/perl # Defining a variable$X = \"X is defined\"; # Checking for existence of $X # with defined() functionif(defined($X)) { print \"$X\\n\";} # Checking for existence of $Y # with defined() functionif(defined($Y)) { print \"Y is also defined\\n\";} else{ print \"Y is not defined\\n\";}",
"e": 1055,
"s": 757,
"text": null
},
{
"code": null,
"e": 1063,
"s": 1055,
"text": "Output:"
},
{
"code": null,
"e": 1093,
"s": 1063,
"text": "X is defined\nY is not defined"
},
{
"code": null,
"e": 1105,
"s": 1093,
"text": " Example 2:"
},
{
"code": "#!/usr/bin/perl # Defining a functionsub X{ # Defining a variable $VAR = 20;} # Checking for existence of $X # with defined() functionif(defined(X)) { print \"Function Exists\\n\";} # Checking for existence of $Y # with defined() functionif(defined($Y)) { print \"Y is also defined\\n\";} else{ print \"Y is not defined\\n\";}",
"e": 1447,
"s": 1105,
"text": null
},
{
"code": null,
"e": 1455,
"s": 1447,
"text": "Output:"
},
{
"code": null,
"e": 1489,
"s": 1455,
"text": "Function Exists\nY is not defined\n"
},
{
"code": null,
"e": 1503,
"s": 1489,
"text": "Perl-function"
},
{
"code": null,
"e": 1508,
"s": 1503,
"text": "Perl"
},
{
"code": null,
"e": 1513,
"s": 1508,
"text": "Perl"
},
{
"code": null,
"e": 1611,
"s": 1513,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1653,
"s": 1611,
"text": "Perl | Arrays (push, pop, shift, unshift)"
},
{
"code": null,
"e": 1667,
"s": 1653,
"text": "Perl | Arrays"
},
{
"code": null,
"e": 1708,
"s": 1667,
"text": "Perl Tutorial - Learn Perl With Examples"
},
{
"code": null,
"e": 1733,
"s": 1708,
"text": "Perl | length() Function"
},
{
"code": null,
"e": 1755,
"s": 1733,
"text": "Perl | Boolean Values"
},
{
"code": null,
"e": 1787,
"s": 1755,
"text": "Perl | Subroutines or Functions"
},
{
"code": null,
"e": 1820,
"s": 1787,
"text": "Use of print() and say() in Perl"
},
{
"code": null,
"e": 1858,
"s": 1820,
"text": "Perl | Basic Syntax of a Perl Program"
},
{
"code": null,
"e": 1886,
"s": 1858,
"text": "Hello World Program in Perl"
}
] |
How to get all the methods of an object using JavaScript ?
|
23 Dec, 2019
An HTML document contains some methods and the task is to get all methods of the object. There are two methods to solve this problem which are discussed below:
Approach 1:
Create a function which takes object as input.
Use typeof operator, which checks if the type of object is function or not.
If the type of object is function then it returns the object.
Example: This example implements the above approach.
<!DOCTYPE HTML><html> <head> <title> Ways to print all methods of an object. </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script></head> <body style="text-align:center;"> <h1 style="color: green"> GeeksForGeeks </h1> <p id="GFG_UP" style= "font-size: 15px;font-weight: bold;"> </p> <button onclick="gfg_Run()"> Click Here </button> <p id="GFG_DOWN" style="color:green; font-size: 30px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); el_up.innerHTML = "Click on the button to get " + "the all methods of any Object."; function Obj() { this.m1 = function M1() { return "From M1"; } this.m2 = function M2() { return "From M2"; } } function getAllMethods(obj = this) { return Object.keys(obj) .filter((key) => typeof obj[key] === 'function') .map((key) => obj[key]); } function gfg_Run() { el_down.innerHTML = getAllMethods(new Obj()); } </script></body> </html>
Output:
Before clicking on the button:
After clicking on the button:
Approach 2:
Create a function which takes object as input.
Use typeof operator, which checks if the type of object is function or not. This example also checks if any error occurred or not and if occurred then handle it properly.
If the typeof Object is function then return it.
Example 2: This example implements the above approach.
<!DOCTYPE HTML><html> <head> <title> Ways to print all methods of an object. </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script></head> <body style="text-align:center;" id="body"> <h1 id="h1" style="color: green"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"> </p> <button onclick="gfg_Run()"> Click Here </button> <p id="GFG_DOWN" style="color:green; font-size: 30px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); el_up.innerHTML = "Click on the button to get the all methods of any Object."; function Obj() { this.m1 = function M1() { return "From M1"; } this.m2 = function M2() { return "From M2"; } } function getAllMethods(obj) { var result = []; for (var id in obj) { try { if (typeof(obj[id]) == "function") { result.push(id + ": " + obj[id].toString()); } } catch (err) { result.push(id + ": Not accessible"); } } return result; } function gfg_Run() { el_down.innerHTML = getAllMethods(new Obj()).join("\n"); } </script></body> </html>
Output:
Before clicking on the button:
After clicking on the button:
JavaScript-Misc
javascript-object
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Hide or show elements in HTML using display property
Difference Between PUT and PATCH Request
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Dec, 2019"
},
{
"code": null,
"e": 188,
"s": 28,
"text": "An HTML document contains some methods and the task is to get all methods of the object. There are two methods to solve this problem which are discussed below:"
},
{
"code": null,
"e": 200,
"s": 188,
"text": "Approach 1:"
},
{
"code": null,
"e": 247,
"s": 200,
"text": "Create a function which takes object as input."
},
{
"code": null,
"e": 323,
"s": 247,
"text": "Use typeof operator, which checks if the type of object is function or not."
},
{
"code": null,
"e": 385,
"s": 323,
"text": "If the type of object is function then it returns the object."
},
{
"code": null,
"e": 438,
"s": 385,
"text": "Example: This example implements the above approach."
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> Ways to print all methods of an object. </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script></head> <body style=\"text-align:center;\"> <h1 style=\"color: green\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style= \"font-size: 15px;font-weight: bold;\"> </p> <button onclick=\"gfg_Run()\"> Click Here </button> <p id=\"GFG_DOWN\" style=\"color:green; font-size: 30px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); el_up.innerHTML = \"Click on the button to get \" + \"the all methods of any Object.\"; function Obj() { this.m1 = function M1() { return \"From M1\"; } this.m2 = function M2() { return \"From M2\"; } } function getAllMethods(obj = this) { return Object.keys(obj) .filter((key) => typeof obj[key] === 'function') .map((key) => obj[key]); } function gfg_Run() { el_down.innerHTML = getAllMethods(new Obj()); } </script></body> </html>",
"e": 1782,
"s": 438,
"text": null
},
{
"code": null,
"e": 1790,
"s": 1782,
"text": "Output:"
},
{
"code": null,
"e": 1821,
"s": 1790,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 1851,
"s": 1821,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 1863,
"s": 1851,
"text": "Approach 2:"
},
{
"code": null,
"e": 1910,
"s": 1863,
"text": "Create a function which takes object as input."
},
{
"code": null,
"e": 2081,
"s": 1910,
"text": "Use typeof operator, which checks if the type of object is function or not. This example also checks if any error occurred or not and if occurred then handle it properly."
},
{
"code": null,
"e": 2130,
"s": 2081,
"text": "If the typeof Object is function then return it."
},
{
"code": null,
"e": 2185,
"s": 2130,
"text": "Example 2: This example implements the above approach."
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> Ways to print all methods of an object. </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script></head> <body style=\"text-align:center;\" id=\"body\"> <h1 id=\"h1\" style=\"color: green\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 15px; font-weight: bold;\"> </p> <button onclick=\"gfg_Run()\"> Click Here </button> <p id=\"GFG_DOWN\" style=\"color:green; font-size: 30px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); el_up.innerHTML = \"Click on the button to get the all methods of any Object.\"; function Obj() { this.m1 = function M1() { return \"From M1\"; } this.m2 = function M2() { return \"From M2\"; } } function getAllMethods(obj) { var result = []; for (var id in obj) { try { if (typeof(obj[id]) == \"function\") { result.push(id + \": \" + obj[id].toString()); } } catch (err) { result.push(id + \": Not accessible\"); } } return result; } function gfg_Run() { el_down.innerHTML = getAllMethods(new Obj()).join(\"\\n\"); } </script></body> </html>",
"e": 3787,
"s": 2185,
"text": null
},
{
"code": null,
"e": 3795,
"s": 3787,
"text": "Output:"
},
{
"code": null,
"e": 3826,
"s": 3795,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 3856,
"s": 3826,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 3872,
"s": 3856,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 3890,
"s": 3872,
"text": "javascript-object"
},
{
"code": null,
"e": 3901,
"s": 3890,
"text": "JavaScript"
},
{
"code": null,
"e": 3918,
"s": 3901,
"text": "Web Technologies"
},
{
"code": null,
"e": 3945,
"s": 3918,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 4043,
"s": 3945,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4104,
"s": 4043,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4176,
"s": 4104,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 4216,
"s": 4176,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 4269,
"s": 4216,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 4310,
"s": 4269,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 4372,
"s": 4310,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 4405,
"s": 4372,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 4466,
"s": 4405,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4516,
"s": 4466,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
How to create Threads in C#
|
24 Jan, 2019
In C#, a multi-threading system is built upon the Thread class, which encapsulates the execution of threads. This class contains several methods and properties which helps in managing and creating threads and this class is defined under System.Threading namespace. The System.Threading namespace provides classes and interfaces that are used in multi-thread programming.
Some commonly used classes in this namespace are :
Steps to create a thread in a C# Program:
First of all import System.Threading namespace, it plays an important role in creating a thread in your program as you have no need to write the fully qualified name of class everytime.Using System;
Using System.Threading
Now, create and initialize the thread object in your main method.public static void main()
{
Thread thr = new Thread(job1);
}
OrYou can also use ThreadStart constructor for initializing a new instance.public static void main()
{
Thread thr = new Thread(new ThreadStart(job1));
}
Now you can call your thread object.public static void main()
{
Thread thr = new Thread(job1);
thr.Start();
}
First of all import System.Threading namespace, it plays an important role in creating a thread in your program as you have no need to write the fully qualified name of class everytime.Using System;
Using System.Threading
Using System;
Using System.Threading
Now, create and initialize the thread object in your main method.public static void main()
{
Thread thr = new Thread(job1);
}
OrYou can also use ThreadStart constructor for initializing a new instance.public static void main()
{
Thread thr = new Thread(new ThreadStart(job1));
}
public static void main()
{
Thread thr = new Thread(job1);
}
Or
You can also use ThreadStart constructor for initializing a new instance.
public static void main()
{
Thread thr = new Thread(new ThreadStart(job1));
}
Now you can call your thread object.public static void main()
{
Thread thr = new Thread(job1);
thr.Start();
}
public static void main()
{
Thread thr = new Thread(job1);
thr.Start();
}
Below programs illustrate the practical implementations of above steps:
Example 1:
// C# program to illustrate the// creation of thread using// non-static methodusing System;using System.Threading; public class ExThread { // Non-static method public void mythread1() { for (int z = 0; z < 3; z++) { Console.WriteLine("First Thread"); } }} // Driver Classpublic class GFG { // Main Method public static void Main() { // Creating object of ExThread class ExThread obj = new ExThread(); // Creating thread // Using thread class Thread thr = new Thread(new ThreadStart(obj.mythread1)); thr.Start(); }}
Output:
First Thread
First Thread
First Thread
Explanation: In the above example, we have a class named as ExThread that contain a non-static method named as mythread1(). So we create an instance, i.e. obj of ExThread class and refer it in the constructor of ThreadStart class as given in this statement Thread a = new Thread(new ThreadStart(obj.mythread1));. Using Thread a = new Thread(new ThreadStart(obj.mythread1)); statement we will create a thread named as thr and initialize the work of this thread. By using thr.Start(); statement.
Example 2:
// C# program to illustrate the creation// of thread using static methodusing System;using System.Threading; public class ExThread { // Static method for thread a public static void thread1() { for (int z = 0; z < 5; z++) { Console.WriteLine(z); } } // static method for thread b public static void thread2() { for (int z = 0; z < 5; z++) { Console.WriteLine(z); } }} // Driver Classpublic class GFG { // Main method public static void Main() { // Creating and initializing threads Thread a = new Thread(ExThread.thread1); Thread b = new Thread(ExThread.thread2); a.Start(); b.Start(); }}
Output :
0
1
2
3
4
0
1
2
3
4
Explanation: In the above example, we have a class named as ExThread and contain two static methods named as thread1() and thread2(). So we do not need to create an instance of ExThread class. Here we call these methods using a class name, like ExThread.thread1, ExThread.thread2. By using Thread a = new Thread(ExThread.thread1); statement we create and initialize the work of thread a, similarly for thread b. By using a.Start(); and b.Start(); statements, a and b threads scheduled for execution.
Note: The output of these programs may vary due to context switching.
CSharp Multithreading
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
Introduction to .NET Framework
C# | Delegates
C# | Multiple inheritance using interfaces
Differences Between .NET Core and .NET Framework
C# | Method Overriding
C# | Data Types
C# | Constructors
C# | String.IndexOf( ) Method | Set - 1
C# | Class and Object
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n24 Jan, 2019"
},
{
"code": null,
"e": 424,
"s": 53,
"text": "In C#, a multi-threading system is built upon the Thread class, which encapsulates the execution of threads. This class contains several methods and properties which helps in managing and creating threads and this class is defined under System.Threading namespace. The System.Threading namespace provides classes and interfaces that are used in multi-thread programming."
},
{
"code": null,
"e": 475,
"s": 424,
"text": "Some commonly used classes in this namespace are :"
},
{
"code": null,
"e": 517,
"s": 475,
"text": "Steps to create a thread in a C# Program:"
},
{
"code": null,
"e": 1146,
"s": 517,
"text": "First of all import System.Threading namespace, it plays an important role in creating a thread in your program as you have no need to write the fully qualified name of class everytime.Using System;\nUsing System.Threading\nNow, create and initialize the thread object in your main method.public static void main()\n{\n Thread thr = new Thread(job1);\n}\nOrYou can also use ThreadStart constructor for initializing a new instance.public static void main()\n{\n Thread thr = new Thread(new ThreadStart(job1));\n}\nNow you can call your thread object.public static void main()\n{\n Thread thr = new Thread(job1);\n thr.Start();\n}\n"
},
{
"code": null,
"e": 1369,
"s": 1146,
"text": "First of all import System.Threading namespace, it plays an important role in creating a thread in your program as you have no need to write the fully qualified name of class everytime.Using System;\nUsing System.Threading\n"
},
{
"code": null,
"e": 1407,
"s": 1369,
"text": "Using System;\nUsing System.Threading\n"
},
{
"code": null,
"e": 1696,
"s": 1407,
"text": "Now, create and initialize the thread object in your main method.public static void main()\n{\n Thread thr = new Thread(job1);\n}\nOrYou can also use ThreadStart constructor for initializing a new instance.public static void main()\n{\n Thread thr = new Thread(new ThreadStart(job1));\n}\n"
},
{
"code": null,
"e": 1762,
"s": 1696,
"text": "public static void main()\n{\n Thread thr = new Thread(job1);\n}\n"
},
{
"code": null,
"e": 1765,
"s": 1762,
"text": "Or"
},
{
"code": null,
"e": 1839,
"s": 1765,
"text": "You can also use ThreadStart constructor for initializing a new instance."
},
{
"code": null,
"e": 1923,
"s": 1839,
"text": "public static void main()\n{\n Thread thr = new Thread(new ThreadStart(job1));\n}\n"
},
{
"code": null,
"e": 2042,
"s": 1923,
"text": "Now you can call your thread object.public static void main()\n{\n Thread thr = new Thread(job1);\n thr.Start();\n}\n"
},
{
"code": null,
"e": 2125,
"s": 2042,
"text": "public static void main()\n{\n Thread thr = new Thread(job1);\n thr.Start();\n}\n"
},
{
"code": null,
"e": 2197,
"s": 2125,
"text": "Below programs illustrate the practical implementations of above steps:"
},
{
"code": null,
"e": 2208,
"s": 2197,
"text": "Example 1:"
},
{
"code": "// C# program to illustrate the// creation of thread using// non-static methodusing System;using System.Threading; public class ExThread { // Non-static method public void mythread1() { for (int z = 0; z < 3; z++) { Console.WriteLine(\"First Thread\"); } }} // Driver Classpublic class GFG { // Main Method public static void Main() { // Creating object of ExThread class ExThread obj = new ExThread(); // Creating thread // Using thread class Thread thr = new Thread(new ThreadStart(obj.mythread1)); thr.Start(); }}",
"e": 2822,
"s": 2208,
"text": null
},
{
"code": null,
"e": 2830,
"s": 2822,
"text": "Output:"
},
{
"code": null,
"e": 2870,
"s": 2830,
"text": "First Thread\nFirst Thread\nFirst Thread\n"
},
{
"code": null,
"e": 3364,
"s": 2870,
"text": "Explanation: In the above example, we have a class named as ExThread that contain a non-static method named as mythread1(). So we create an instance, i.e. obj of ExThread class and refer it in the constructor of ThreadStart class as given in this statement Thread a = new Thread(new ThreadStart(obj.mythread1));. Using Thread a = new Thread(new ThreadStart(obj.mythread1)); statement we will create a thread named as thr and initialize the work of this thread. By using thr.Start(); statement."
},
{
"code": null,
"e": 3375,
"s": 3364,
"text": "Example 2:"
},
{
"code": "// C# program to illustrate the creation// of thread using static methodusing System;using System.Threading; public class ExThread { // Static method for thread a public static void thread1() { for (int z = 0; z < 5; z++) { Console.WriteLine(z); } } // static method for thread b public static void thread2() { for (int z = 0; z < 5; z++) { Console.WriteLine(z); } }} // Driver Classpublic class GFG { // Main method public static void Main() { // Creating and initializing threads Thread a = new Thread(ExThread.thread1); Thread b = new Thread(ExThread.thread2); a.Start(); b.Start(); }}",
"e": 4093,
"s": 3375,
"text": null
},
{
"code": null,
"e": 4102,
"s": 4093,
"text": "Output :"
},
{
"code": null,
"e": 4123,
"s": 4102,
"text": "0\n1\n2\n3\n4\n0\n1\n2\n3\n4\n"
},
{
"code": null,
"e": 4623,
"s": 4123,
"text": "Explanation: In the above example, we have a class named as ExThread and contain two static methods named as thread1() and thread2(). So we do not need to create an instance of ExThread class. Here we call these methods using a class name, like ExThread.thread1, ExThread.thread2. By using Thread a = new Thread(ExThread.thread1); statement we create and initialize the work of thread a, similarly for thread b. By using a.Start(); and b.Start(); statements, a and b threads scheduled for execution."
},
{
"code": null,
"e": 4693,
"s": 4623,
"text": "Note: The output of these programs may vary due to context switching."
},
{
"code": null,
"e": 4715,
"s": 4693,
"text": "CSharp Multithreading"
},
{
"code": null,
"e": 4718,
"s": 4715,
"text": "C#"
},
{
"code": null,
"e": 4816,
"s": 4718,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4844,
"s": 4816,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 4875,
"s": 4844,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 4890,
"s": 4875,
"text": "C# | Delegates"
},
{
"code": null,
"e": 4933,
"s": 4890,
"text": "C# | Multiple inheritance using interfaces"
},
{
"code": null,
"e": 4982,
"s": 4933,
"text": "Differences Between .NET Core and .NET Framework"
},
{
"code": null,
"e": 5005,
"s": 4982,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 5021,
"s": 5005,
"text": "C# | Data Types"
},
{
"code": null,
"e": 5039,
"s": 5021,
"text": "C# | Constructors"
},
{
"code": null,
"e": 5079,
"s": 5039,
"text": "C# | String.IndexOf( ) Method | Set - 1"
}
] |
Get length of a string in Julia – length() Method
|
26 Mar, 2020
The length() is an inbuilt function in julia which is used to return the length of the specified string with desired starting and end position.
Syntax:length(S::AbstractString)orlength(S::AbstractString, i::Integer, j::Integer)
Parameters:
S::AbstractString: Specified string
i::Integer: Inclusive starting position.
i::Integer: Inclusive ending position.
Returns: It returns the length of the specified string with desired starting and end position.
Example 1:
# Julia program to illustrate # the use of String length() method # Finding the length of the string# "Geeks"println(length("Geeks")) # Finding the length of the string# "Geeks" from 2nd to 4th positionprintln(length("Geeks", 2, 4)) # Finding the length of the string# "Geeks" from 2nd to 5th positionprintln(length("Geeks", 2, 5)) # Finding the length of the string# "GeeksforGeeks" println(length("GeeksforGeeks")) # Finding the length of the string# "GeeksforGeeks" from 2nd to 2nd positionprintln(length("GeeksforGeeks", 2, 2)) # Finding the length of the string# "GeeksforGeeks" from 4th to 10th positionprintln(length("GeeksforGeeks", 4, 10))
Output:Example 2:
# Julia program to illustrate # the use of String length() method # Finding the length of the string# "12345"println(length("12345")) # Finding the length of the string# "12345" from 2nd to 4th positionprintln(length("12345", 2, 4)) # Finding the length of the string# "2468" from 1st to 3rd positionprintln(length("2468", 2, 3))
Output:
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Mar, 2020"
},
{
"code": null,
"e": 172,
"s": 28,
"text": "The length() is an inbuilt function in julia which is used to return the length of the specified string with desired starting and end position."
},
{
"code": null,
"e": 256,
"s": 172,
"text": "Syntax:length(S::AbstractString)orlength(S::AbstractString, i::Integer, j::Integer)"
},
{
"code": null,
"e": 268,
"s": 256,
"text": "Parameters:"
},
{
"code": null,
"e": 304,
"s": 268,
"text": "S::AbstractString: Specified string"
},
{
"code": null,
"e": 345,
"s": 304,
"text": "i::Integer: Inclusive starting position."
},
{
"code": null,
"e": 384,
"s": 345,
"text": "i::Integer: Inclusive ending position."
},
{
"code": null,
"e": 479,
"s": 384,
"text": "Returns: It returns the length of the specified string with desired starting and end position."
},
{
"code": null,
"e": 490,
"s": 479,
"text": "Example 1:"
},
{
"code": "# Julia program to illustrate # the use of String length() method # Finding the length of the string# \"Geeks\"println(length(\"Geeks\")) # Finding the length of the string# \"Geeks\" from 2nd to 4th positionprintln(length(\"Geeks\", 2, 4)) # Finding the length of the string# \"Geeks\" from 2nd to 5th positionprintln(length(\"Geeks\", 2, 5)) # Finding the length of the string# \"GeeksforGeeks\" println(length(\"GeeksforGeeks\")) # Finding the length of the string# \"GeeksforGeeks\" from 2nd to 2nd positionprintln(length(\"GeeksforGeeks\", 2, 2)) # Finding the length of the string# \"GeeksforGeeks\" from 4th to 10th positionprintln(length(\"GeeksforGeeks\", 4, 10))",
"e": 1145,
"s": 490,
"text": null
},
{
"code": null,
"e": 1163,
"s": 1145,
"text": "Output:Example 2:"
},
{
"code": "# Julia program to illustrate # the use of String length() method # Finding the length of the string# \"12345\"println(length(\"12345\")) # Finding the length of the string# \"12345\" from 2nd to 4th positionprintln(length(\"12345\", 2, 4)) # Finding the length of the string# \"2468\" from 1st to 3rd positionprintln(length(\"2468\", 2, 3))",
"e": 1499,
"s": 1163,
"text": null
},
{
"code": null,
"e": 1507,
"s": 1499,
"text": "Output:"
},
{
"code": null,
"e": 1513,
"s": 1507,
"text": "Julia"
}
] |
How to use the foreach loop parallelly in PowerShell?
|
There are two ways to use the foreach loop parallelly in PowerShell.
Using Foreach-Object -Parallel command (Supports in PowerShell 7.0 or above)
Using Foreach-Object -Parallel command (Supports in PowerShell 7.0 or above)
Using Foreach -Parallel in Workflow (Supports PowerShell 5.1 or below)
Using Foreach -Parallel in Workflow (Supports PowerShell 5.1 or below)
Suppose we have Servers.txt and which contains 10 Servers. When we use the Parallel for loop, it isn’t guaranteed which server loop will pick first as shown below with two examples.
Using Foreach-Object-Parallel command. (not Foreach -Parallel)
Using Foreach-Object-Parallel command. (not Foreach -Parallel)
This Foreach-Object -Parallel command feature is newly added to the PowerShell version 7.0 or above.
$servers = Get-Content C:\Temp\Servers.txt
$servers | foreach-Object -parallel{
Write-output "Working on $_"
}
PS C:\> C:\Temp\Test1.ps1
Working on IndiaServer003
Working on IndiaServer002
Working on IndiaServer001
Working on USServer001
Working on IndiaServer005
Working on USServer002
Working on IndiaServer006
Working on NZServer001
Working on NZServer002
If you have more servers, you can also set the -Throttlelimit parameter but need to make sure that the system should not get exhausted due to the throttle limit because it will create more runspaces.
Using PowerShell Workflow.
Using PowerShell Workflow.
If you are working with PowerShell 5.1, we can use Workflow feature Foreach -Parallel to run the loop parallelly. For example,
Workflow TestParallel{
Foreach -parallel($server in (Get-Content C:\Temp\Servers.txt)){
Write-Output "Working on $Server"
}
}
TestParallel
PS C:\WINDOWS\system32> C:\Temp\Test1.ps1
Working on NZServer002
Working on NZServer001
Working on USServer002
Working on USServer001
Working on IndiaServer006
Working on IndiaServer005
Working on IndiaServer003
Working on IndiaServer002
Working on IndiaServer001
|
[
{
"code": null,
"e": 1131,
"s": 1062,
"text": "There are two ways to use the foreach loop parallelly in PowerShell."
},
{
"code": null,
"e": 1208,
"s": 1131,
"text": "Using Foreach-Object -Parallel command (Supports in PowerShell 7.0 or above)"
},
{
"code": null,
"e": 1285,
"s": 1208,
"text": "Using Foreach-Object -Parallel command (Supports in PowerShell 7.0 or above)"
},
{
"code": null,
"e": 1356,
"s": 1285,
"text": "Using Foreach -Parallel in Workflow (Supports PowerShell 5.1 or below)"
},
{
"code": null,
"e": 1427,
"s": 1356,
"text": "Using Foreach -Parallel in Workflow (Supports PowerShell 5.1 or below)"
},
{
"code": null,
"e": 1609,
"s": 1427,
"text": "Suppose we have Servers.txt and which contains 10 Servers. When we use the Parallel for loop, it isn’t guaranteed which server loop will pick first as shown below with two examples."
},
{
"code": null,
"e": 1672,
"s": 1609,
"text": "Using Foreach-Object-Parallel command. (not Foreach -Parallel)"
},
{
"code": null,
"e": 1735,
"s": 1672,
"text": "Using Foreach-Object-Parallel command. (not Foreach -Parallel)"
},
{
"code": null,
"e": 1836,
"s": 1735,
"text": "This Foreach-Object -Parallel command feature is newly added to the PowerShell version 7.0 or above."
},
{
"code": null,
"e": 1951,
"s": 1836,
"text": "$servers = Get-Content C:\\Temp\\Servers.txt\n\n$servers | foreach-Object -parallel{\n Write-output \"Working on $_\"\n}"
},
{
"code": null,
"e": 2199,
"s": 1951,
"text": "PS C:\\> C:\\Temp\\Test1.ps1\nWorking on IndiaServer003\nWorking on IndiaServer002\nWorking on IndiaServer001\nWorking on USServer001\nWorking on IndiaServer005\nWorking on USServer002\nWorking on IndiaServer006\nWorking on NZServer001\nWorking on NZServer002"
},
{
"code": null,
"e": 2399,
"s": 2199,
"text": "If you have more servers, you can also set the -Throttlelimit parameter but need to make sure that the system should not get exhausted due to the throttle limit because it will create more runspaces."
},
{
"code": null,
"e": 2426,
"s": 2399,
"text": "Using PowerShell Workflow."
},
{
"code": null,
"e": 2453,
"s": 2426,
"text": "Using PowerShell Workflow."
},
{
"code": null,
"e": 2580,
"s": 2453,
"text": "If you are working with PowerShell 5.1, we can use Workflow feature Foreach -Parallel to run the loop parallelly. For example,"
},
{
"code": null,
"e": 2732,
"s": 2580,
"text": "Workflow TestParallel{\n Foreach -parallel($server in (Get-Content C:\\Temp\\Servers.txt)){\n Write-Output \"Working on $Server\"\n }\n}\n\nTestParallel"
},
{
"code": null,
"e": 2996,
"s": 2732,
"text": "PS C:\\WINDOWS\\system32> C:\\Temp\\Test1.ps1\nWorking on NZServer002\nWorking on NZServer001\nWorking on USServer002\nWorking on USServer001\nWorking on IndiaServer006\nWorking on IndiaServer005\nWorking on IndiaServer003\nWorking on IndiaServer002\nWorking on IndiaServer001"
}
] |
Dynamic Button in Kotlin - GeeksforGeeks
|
11 Sep, 2021
In Android, a button represent something that can be clicked by the user to perform some action.Firstly, we need to create a project in Android Studio. To do follow these steps:
Click on File, then New, and then New Project, and give name whatever you like:
Click on File, then New, and then New Project, and give name whatever you like
Then, select Kotlin language Support and click next button.
Select minimum SDK, whatever you need.
Select Empty activity and then click finish.
After doing this you will see some directories on the left hand side after your project/gradle is finished loading. It should look like this:
Second step is to design our layout page. Go to app > res > layout and paste the following code:
XML
<?xml version="1.0" encoding="utf-8"?><android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <LinearLayout android:id="@+id/layout" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical"> </LinearLayout> </android.support.constraint.ConstraintLayout>
After setting up the design our final step is to code our progress bar. Open app/src/main/java/yourPackageName/MainActivity.kt
First of all, we define the button and set its attributes.
val button = Button(this)
// setting layout_width and layout_height using layout parameters
button.layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT)
then, add the button in the layout using addView()
val layout = findViewById(R.id.layout) as LinearLayout
// add Button to LinearLayout
layout.addView(button)
Java
package com.geeksforgeeks.myfirstkotlinapp import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.view.ViewGroupimport android.widget.Buttonimport android.widget.LinearLayoutimport android.widget.Toast class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val layout = findViewById(R.id.layout) as LinearLayout // creating the button val button = Button(this) // setting layout_width and layout_height using layout parameters button.layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) button.text = "WELCOME TO GFG" button.setOnClickListener { Toast.makeText(this@MainActivity, "Hello GEEK", Toast.LENGTH_LONG).show() } // add Button to LinearLayout layout.addView(button) }}
XML
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="i.apps.button"> <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>
saurabh1990aror
anikakapoor
Picked
Kotlin
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Broadcast Receiver in Android With Example
Content Providers in Android with Example
Android RecyclerView in Kotlin
Android UI Layouts
Retrofit with Kotlin Coroutine in Android
Android Menus
MVP (Model View Presenter) Architecture Pattern in Android with Example
Kotlin Setters and Getters
MVC (Model View Controller) Architecture Pattern in Android with Example
Kotlin Coroutines on Android
|
[
{
"code": null,
"e": 23954,
"s": 23926,
"text": "\n11 Sep, 2021"
},
{
"code": null,
"e": 24132,
"s": 23954,
"text": "In Android, a button represent something that can be clicked by the user to perform some action.Firstly, we need to create a project in Android Studio. To do follow these steps:"
},
{
"code": null,
"e": 24213,
"s": 24132,
"text": "Click on File, then New, and then New Project, and give name whatever you like: "
},
{
"code": null,
"e": 24292,
"s": 24213,
"text": "Click on File, then New, and then New Project, and give name whatever you like"
},
{
"code": null,
"e": 24352,
"s": 24292,
"text": "Then, select Kotlin language Support and click next button."
},
{
"code": null,
"e": 24391,
"s": 24352,
"text": "Select minimum SDK, whatever you need."
},
{
"code": null,
"e": 24436,
"s": 24391,
"text": "Select Empty activity and then click finish."
},
{
"code": null,
"e": 24579,
"s": 24436,
"text": "After doing this you will see some directories on the left hand side after your project/gradle is finished loading. It should look like this: "
},
{
"code": null,
"e": 24676,
"s": 24579,
"text": "Second step is to design our layout page. Go to app > res > layout and paste the following code:"
},
{
"code": null,
"e": 24680,
"s": 24676,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><android.support.constraint.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <LinearLayout android:id=\"@+id/layout\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:gravity=\"center\" android:orientation=\"vertical\"> </LinearLayout> </android.support.constraint.ConstraintLayout>",
"e": 25361,
"s": 24680,
"text": null
},
{
"code": null,
"e": 25489,
"s": 25361,
"text": "After setting up the design our final step is to code our progress bar. Open app/src/main/java/yourPackageName/MainActivity.kt "
},
{
"code": null,
"e": 25550,
"s": 25489,
"text": "First of all, we define the button and set its attributes. "
},
{
"code": null,
"e": 25786,
"s": 25550,
"text": "val button = Button(this)\n // setting layout_width and layout_height using layout parameters\n button.layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,\n ViewGroup.LayoutParams.WRAP_CONTENT)\n "
},
{
"code": null,
"e": 25838,
"s": 25786,
"text": "then, add the button in the layout using addView() "
},
{
"code": null,
"e": 25964,
"s": 25838,
"text": " \n val layout = findViewById(R.id.layout) as LinearLayout\n // add Button to LinearLayout\n layout.addView(button)"
},
{
"code": null,
"e": 25969,
"s": 25964,
"text": "Java"
},
{
"code": "package com.geeksforgeeks.myfirstkotlinapp import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.view.ViewGroupimport android.widget.Buttonimport android.widget.LinearLayoutimport android.widget.Toast class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val layout = findViewById(R.id.layout) as LinearLayout // creating the button val button = Button(this) // setting layout_width and layout_height using layout parameters button.layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) button.text = \"WELCOME TO GFG\" button.setOnClickListener { Toast.makeText(this@MainActivity, \"Hello GEEK\", Toast.LENGTH_LONG).show() } // add Button to LinearLayout layout.addView(button) }}",
"e": 26952,
"s": 25969,
"text": null
},
{
"code": null,
"e": 26956,
"s": 26952,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"i.apps.button\"> <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>",
"e": 27678,
"s": 26956,
"text": null
},
{
"code": null,
"e": 27694,
"s": 27678,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 27706,
"s": 27694,
"text": "anikakapoor"
},
{
"code": null,
"e": 27713,
"s": 27706,
"text": "Picked"
},
{
"code": null,
"e": 27720,
"s": 27713,
"text": "Kotlin"
},
{
"code": null,
"e": 27818,
"s": 27720,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27827,
"s": 27818,
"text": "Comments"
},
{
"code": null,
"e": 27840,
"s": 27827,
"text": "Old Comments"
},
{
"code": null,
"e": 27883,
"s": 27840,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 27925,
"s": 27883,
"text": "Content Providers in Android with Example"
},
{
"code": null,
"e": 27956,
"s": 27925,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 27975,
"s": 27956,
"text": "Android UI Layouts"
},
{
"code": null,
"e": 28017,
"s": 27975,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 28031,
"s": 28017,
"text": "Android Menus"
},
{
"code": null,
"e": 28103,
"s": 28031,
"text": "MVP (Model View Presenter) Architecture Pattern in Android with Example"
},
{
"code": null,
"e": 28130,
"s": 28103,
"text": "Kotlin Setters and Getters"
},
{
"code": null,
"e": 28203,
"s": 28130,
"text": "MVC (Model View Controller) Architecture Pattern in Android with Example"
}
] |
Which library should I use for my Python dashboard? | by Antoine Hue | Towards Data Science
|
When it comes to data visualization there are many possible tools Matplotlib, Plotly, Bokeh... Which one is fitting my short term goals, within a notebook, and is a good choice for longer-term, in production? What does production mean?
Now that you have a nice machine learning model, or you have completed some data mining or analysis, you need to present and promote this amazing work. You may initially reuse some notebooks to produce a few charts... but soon colleagues or clients are requesting access to the data or are asking for other views or parameters. What should you do? Which tools and libraries should you use? Is there a one fits all solution for all stages of my work?
Data-visualization has a very wide scope, ranging from presenting data with simple charts to be included in a report, to complex interactive dashboards. The first is reachable to anybody that knows about Excel whereas the later is more a software product that may require the full software development cycle and methodology.
In between these two extreme cases, data scientists face many choices that are not trivial. This post is providing some questions that will come along this process, and some tips and answers to these. The chosen starting point is Python within a Jupiter notebook, the target is a Web dashboard in production.
Getting the right chart type is always the first issue we are thinking about.
You have a great new idea for the data visualization, your boss is in love with Sunburst graphs, but is this doable with the charting libraries you are using?
Mainstream open-source charting libraries in Python Matplotlib with Seaborn, Plotly, Bokeh, support more or less the same set of chart types. They also support pixel matrices that allow for extensions like displaying word clouds.
Here is a sample of drawing a word cloud from the Word Cloud Python library documentation1:
import numpy as npimport matplotlib.pyplot as pltfrom wordcloud import WordCloudtext = "square"x, y = np.ogrid[:300, :300]mask = (x - 150) ** 2 + (y - 150) ** 2 > 130 ** 2mask = 255 * mask.astype(int)wc = WordCloud(background_color="white", repeat=True, mask=mask)wc.generate(text)plt.axis("off")plt.imshow(wc, interpolation="bilinear")plt.show()
Network graphs are a specific category that is not natively handled by the above-listed libraries. The main Python library for networks is NetworkX. By default, NetworkX is using Matplotlib as a backend for drawing2. Graphviz (Pygraphviz) is the de facto standard graph drawing libraries and can be coupled with NetworkX3. With quite a few lines of code, you may also use Plotly to draw the graph4. The integration between NetworkX and Bokeh is also documented5.
Geographically located information and maps is also a specific subfield of data-visualization. Plotting maps bears many challenges, among them:
Handling large and complex contours (e.g. country borders)
Showing more or less information depending on the zoom, this is also known as the level of detail. The impact is at the same time on the readability of the plot, and on the complexity that turns into latency to load and memory footprint
Handling of geographical coordinates, that is single or multiple projections from non-euclidean spaces to the 2D euclidian space (e.g. latitude-longitude to UTM with a given UTM zone)
Availability of information in multiple file formats, even if there are de facto standards like GeoJSON and Shape-file
Depending on the chosen plotting library, you may have to do little or a lot of pre-processing. The common open-source library to deal with geographical coordinate is Proj, and GDAL to deal with file formats and translation from formats or coordinates to other contexts.
Matplotlib has no direct support for plotting maps, it relies on pixel matrics (a raster image) as explained in the gallery6. But this is a pis-aller, you do not want to do that, but if your only target is a static image.
Plotly is demonstrating map plots7 based on Mapbox. Many features are available but at least one is missing, the management of the level of detail in scatter plots.
Bokeh has some support for maps including the integration of Google maps8, but it seems quite crude.
Folium is a Python library wrapping the Leaflet Javascript library. Leaflet is used in many collaborative and commercial websites, for example Open Street Map. Folium is very effective to draw maps on Open data.
The open-source reference for geographic data manipulation is QGIS from OSGeo. It is a desktop application but it includes a Python console and it is also possible to directly use the Pyqgis API9.
Pandas and its Dataframe are must use for data science in Python. What is the impact on chart creation and dashboard?
On the one hand, Pandas Dataframes and Series have a plot API. By default, it is relying on Matplotlib as the backend. However, Plotly as the graphical backend for Pandas is available10. Support for Bokeh is also available through a Github project11.
On the other hand, the plots of Pandas might not fit with your requirements and you are wondering how to use dataframes in plots besides using columns and series as vectors. Plotly Express has this capability with support for column-oriented data12.
If none of these libraries and their extensions are dealing with the chart you are looking for, then you may switch to d3.js which is the base charting library for browsers. It means that you would leave the Python world and enter Javascript’s domain. Possibilities and customization are vast as shown in the example gallery13. However, you will need to handle many aspects of the graph that are granted in other libraries: axes, legend, interactivity...
In the design of a dataviz, the layout or composition of charts come along with the requirement for multiple charts to display several features. You probably already enjoyed the pluses and minuses of Matplotlib’s subplots, starting with the quirky imperative commands like “`plt.subplot(1, 2, 1)`” or even weirder equivalent “`plt.subplot(121)`”. If this is enough to reach your goal, I would anyway suggest using the alternate and cleaner “plt.subplots()” API that returns a figure and an array of axes. You might anyway feel limited not only by the interactivity, this is dealt with in the next section, but also limited in layout capabilities.
Matplotlib allows for uneven widths and heights using calls to Figure.add_subplots method like “fig.add_subplot(3, 1, (1, 2))" making a subplot that spans the upper 2/3 of the figure14. Seaborn is introducing one enhancement which is the Scatter matrix15.
Plotly allows for similar capabilities including the uneven sub-plots. However, I find the API rather limited. For example, it is not possible to set the font size of sub-plots title or to share a legend. Bokeh has similar capabilities16.
Plotly, Express API, goes further with marginal probability plots as histograms or rug17, and also a synchronized overview-detail chart that is called “range slider18”. This is leading us to the interactivity of graphs that is detailed in the next section.
But what if these layout helpers are not enough for my purpose? Possible answers are many, ranging from the Plotly Dash solution to full HTML layout or SVG custom design with d3.js.
Plotly Dash is proposing an intermediate solution in which you stick to Python but can generate some more complex and more interactive dashboards than the plotting libraries. Still, it requires that you have some basic HTML knowledge and sooner or later will dive into the cascading stylesheets (CSS).
You are very pleased with the chart but it feels so static, there is not even a zoom!
Interactivity is so many different things. It starts with common operations like zoom and pan. The next step is synchronized graphs: zoom and pan are applied simultaneously on several charts that share an axis. You might also be interested in synchronous selection on two graphs, also called brushing (example in Bokeh19). Matplolib has such interactivity for all render engines but within a notebook20. There is however a solution based on Matplotlib, mpld3 is handling this and might provide all you need. However, the trend is to use newer libraries like Plotly or Bokeh that have zoom and pan in notebooks “out of the box”.
Then come dynamic annotations. They span from hover information when the mouse is located on a marker to line plot highlights. Regarding hover, whatever the used library (Matplotlib with Mpld3 and plugins, Plotly, Bokeh) it means attaching an HTML document div to each marker, and probably also some CSS.
More complex interactions are related to filtering or querying the data. It can be close to the zoom function when the filter is modifying a range (e.g.: daily / weekly / monthly selector for a time series), or a selector on the series of facets, or even more complex associations. Selectors are available in Plotly as Custom Controls21 and in Bokeh as widgets22.
The common plotting libraries provide basic capabilities for interactivity up to the creation of some widget, but, as for advanced layouts, I would suggest to directly switch to Plotly Dash which is more versatile.
The more complex the dashboard or the larger the data, the longer it takes to process, thus the longer to render. It may be ok to wait for a few seconds to get a view of a static plot. It is no longer ok to wait more than 1 second when the graph is interactive with widgets and controls.
If fluidity is gone, you have four main solutions, with increasing complexity:
Simplify the dashboard with fewer plots, fewer controls. That may be ok but then you should think why such complexity was needed first?
Simplify the data, that shows less data or with less granularity. That may provide a good tradeoff between features and accuracy. It is leading to the next solution...
Offline pre-processing of data to pre-assemble the data shown in the dashboard. That probably means storing new series or new tables, leading eventually to other issues linked to data management. In the end, you will do a lot more data engineering and will probably reach a dead-end with two much data, too many tables. The solution to the dead-end is even more data engineering with...
Online processing in dedicated servers and the design of an API.
A server with an API is not the first thing you were thinking but you end up dealing with this software project sooner than you think. It is also better to anticipate it than delay until there is no other solution and project deadlines are coming fast.
Defining an API involves often several teams and skills: data scientists to define the why, data engineers to define the what, and infrastructure engineers to define the how, including performance, security, persistence, and integrity.
Plotly Dash allows for an initial API since it is based on the Flask framework. See the Dash documentation on integration with a Flask app which is defining a custom Flask route, that could serve data, i.e. an API23. There is still no proper API access management, including authentication. On that latter aspect, Dash is very limited24.
How much effort will it take you to develop and publish?
Some tools are effective, they deliver the expected result, but are not efficient, getting to the result takes a large amount of time. For example, d3.js is known as a very powerful and complete data-visualization and charting library but at the same time, it requires dealing with many things that are by default available in libraries with higher abstraction.
Productivity is coming not only with using the right level of abstraction, but also an API that is easy to use and well documented. I would say that none of the surveyed Python charting libraries are easy to master.
Matplotlib’s API is quite complex when dealing with axes, formats (of labels), it is not always consistent and quite redundant. As an example, see the above comment on “`plt.subplot()`”. That’s not the only example, for example, there is a sub-routine “`plt.xlabel()`” that is equivalent to the method “`ax.set_xlabel()`” on the Axes object.
Plotly’s API is not better, first, you must choose between two API sets: the Express set that is quite simple but limited and mostly targeted at dataframes, and the Graphical Object set that is more complete and complementing the Express set, but does not have some nice high-level features that are in Express. Then you will have to deal with the Plotly documentation that is, to me, really difficult to get through. Searching with either the Plotly website internal or a Web search engine seldom leads you to the API you are looking for. And you may have to deal with the documentation of the underneath data model in JSON.
Bokeh API is probably leaner and better documented but has some weird things like two separate instructions to plot a line chart and associated markers.
Your dashboard is successful and will be deployed as a product internally to your organization, available to clients, or even directly exposed on the Internet.
As a data scientist, you are missing skills to handle that and get the help of software specialists. However, you are asked what is the effort or scope of this development. This highly depends on the path to production, which framework is used there, and on the framework that you have been using until now.
Plotly standalone graphics can be exported as static HTML. Bokeh provides some schemes to embed it25. Matplotlib with Mpld3 has an HTML output27. However, this solution is targeting illustrations rather than dashboards.
Plotly Dash may in some cases go up to production as the main Web app or an embedded widget23. As said earlier in such setup you will need to inspect the security of your system before jumping to online production. Regarding security, as a data designer, you mainly need to check that you are exposing only the wanted data and not more.
Today, most of the Web applications we use are based on a pattern called single page application (SPA): the application is loaded once in the Web browser and then interacts with the server through some asynchronous API without reloading the Web page. This is what all of us now expect from a nice Web application.
SPA has two separate components: the browser side application in Javascript with a framework like Angular or React.js, and the server-side application or service that may get written on many frameworks and language: Java, C#, PHP, Javascript..., and even Python.
Dash is already doing part of it. In fact, Dash is using one of the leading browser-side framework, React.js, and on the server-side is based on Flask and Python. But as said above you may reach some limits of Dash.
Besides the transition through Dash, Plotly and Bokeh have another advantage: they are also available in Javascript as Plotly JS (and a React.js wrapper wrapper26), Bokeh JS. In fact, the Python version of Plotly is a wrapper around the Javascript. This implies that given some plots or dashboards in Python based on Plotly or Dash or Bokeh, most of the concepts and chart properties can be reused in the equivalent Javascript implementation.
In this post, we have brushed the path for a data-visualization dashboard from experiments within notebooks, up to production. We have seen that the traditional plotting library, Matplotlib, still has strong features and is usually the default backend for specialized libraries like NetworkX and the Pandas Dataframe. But Matplolib is also lagging on some aspects like integration and interactivity. Learning another framework may be a good investment and will help you going forward up to production.
Two alternative frameworks are presented: Plotly and Bokeh. Both bring value as they are more modern than Matplotlib. Both of them have a leading advantage when it comes to bringing the dashboard to production: they are based on Javascript plotting frameworks and most of the plots Python code can be translated directly in the Javascript equivalent.
Plotly has another advantage on the go-to production path: it is integrated with Dash, a framework to develop a simple dashboard as single-page applications while sticking to Python. Required Javascript, including React components, and server API is generated smoothly by Dash.
We have also seen that, as a data scientist or data-visualization designer, you should anticipate requirements like interactivity, and their implications that may lead to the development of an API to serve data.
In “Plotly Dash or React.js + Plotly.js”, a side by side comparison is showing what is required to port a Dash application to a Javascript application in React.js with Plotly.js for the dataviz, and served by a Web API in Python.
References
[1] Word clouds with Matplotlib and word_cloud library, https://amueller.github.io/word_cloud/auto_examples/single_word.html
[2] NetworkX graph plot, https://networkx.github.io/documentation/stable/auto_examples/index.html#basic
[3] NetworkX with GraphViz, https://networkx.github.io/documentation/stable/auto_examples/pygraphviz/plot_pygraphviz_draw.html
[4] Plotly with NetworkX, https://plotly.com/python/network-graphs/
[5] Bokeh and NetworkX, https://docs.bokeh.org/en/latest/docs/user_guide/graph.html#networkx-integration
[6] Matplotlib to draw maps, https://matplotlib.org/basemap/users/examples.html
[7] Plotly and maps https://plotly.com/python/maps/
[8] Bokeh and maps, https://docs.bokeh.org/en/latest/docs/user_guide/geo.html
[9] Pyqgis API, https://docs.qgis.org/3.10/fr/docs/pyqgis_developer_cookbook/
[10] Plotly as Pandas backend, https://plotly.com/python/pandas-backend/
[11] Bokeh as Pandas backend, https://github.com/PatrikHlobil/Pandas-Bokeh
[12] Plotly Express support for column-oriented data https://plotly.com/python/wide-form/
[13] D3.js gallery https://observablehq.com/@d3/gallery
[14] Maplitlib documentation on figure layouts, https://matplotlib.org/api/_as_gen/matplotlib.figure.Figure.html#matplotlib.figure.Figure
[15] Seaborn scatter matrix, https://seaborn.pydata.org/examples/scatterplot_matrix.html
[16] Bokeh layouts, https://docs.bokeh.org/en/latest/docs/user_guide/layout.html
[17] Plotly marginal plots, https://plotly.com/python/marginal-plots/
[18] Plotly’s range slider, https://plotly.com/python/time-series/#time-series-with-range-slider
[19] Bokeh brushing, https://docs.bokeh.org/en/latest/docs/user_guide/quickstart.html#linked-panning-and-brushing
[20] Matplotlib interactivity, https://matplotlib.org/users/interactive_guide.html)
[21] Plotly controls, https://plotly.com/python/#controls
[22] Bokeh widgets, https://docs.bokeh.org/en/latest/docs/user_guide/interaction/widgets.html
[23] Plotly Dash integration, https://dash.plotly.com/integrating-dash
[24] Plotly Dash authentication, see https://dash.plotly.com/authentication
[25] Bokeh integration, https://docs.bokeh.org/en/latest/docs/user_guide/embed.html#userguide-embed
[26] Plotly JS React wrapper, https://plotly.com/javascript/react/
[27] Mpl3D QuickStart, https://mpld3.github.io/quickstart.html
|
[
{
"code": null,
"e": 408,
"s": 172,
"text": "When it comes to data visualization there are many possible tools Matplotlib, Plotly, Bokeh... Which one is fitting my short term goals, within a notebook, and is a good choice for longer-term, in production? What does production mean?"
},
{
"code": null,
"e": 858,
"s": 408,
"text": "Now that you have a nice machine learning model, or you have completed some data mining or analysis, you need to present and promote this amazing work. You may initially reuse some notebooks to produce a few charts... but soon colleagues or clients are requesting access to the data or are asking for other views or parameters. What should you do? Which tools and libraries should you use? Is there a one fits all solution for all stages of my work?"
},
{
"code": null,
"e": 1183,
"s": 858,
"text": "Data-visualization has a very wide scope, ranging from presenting data with simple charts to be included in a report, to complex interactive dashboards. The first is reachable to anybody that knows about Excel whereas the later is more a software product that may require the full software development cycle and methodology."
},
{
"code": null,
"e": 1492,
"s": 1183,
"text": "In between these two extreme cases, data scientists face many choices that are not trivial. This post is providing some questions that will come along this process, and some tips and answers to these. The chosen starting point is Python within a Jupiter notebook, the target is a Web dashboard in production."
},
{
"code": null,
"e": 1570,
"s": 1492,
"text": "Getting the right chart type is always the first issue we are thinking about."
},
{
"code": null,
"e": 1729,
"s": 1570,
"text": "You have a great new idea for the data visualization, your boss is in love with Sunburst graphs, but is this doable with the charting libraries you are using?"
},
{
"code": null,
"e": 1959,
"s": 1729,
"text": "Mainstream open-source charting libraries in Python Matplotlib with Seaborn, Plotly, Bokeh, support more or less the same set of chart types. They also support pixel matrices that allow for extensions like displaying word clouds."
},
{
"code": null,
"e": 2051,
"s": 1959,
"text": "Here is a sample of drawing a word cloud from the Word Cloud Python library documentation1:"
},
{
"code": null,
"e": 2402,
"s": 2051,
"text": "import numpy as npimport matplotlib.pyplot as pltfrom wordcloud import WordCloudtext = \"square\"x, y = np.ogrid[:300, :300]mask = (x - 150) ** 2 + (y - 150) ** 2 > 130 ** 2mask = 255 * mask.astype(int)wc = WordCloud(background_color=\"white\", repeat=True, mask=mask)wc.generate(text)plt.axis(\"off\")plt.imshow(wc, interpolation=\"bilinear\")plt.show()"
},
{
"code": null,
"e": 2865,
"s": 2402,
"text": "Network graphs are a specific category that is not natively handled by the above-listed libraries. The main Python library for networks is NetworkX. By default, NetworkX is using Matplotlib as a backend for drawing2. Graphviz (Pygraphviz) is the de facto standard graph drawing libraries and can be coupled with NetworkX3. With quite a few lines of code, you may also use Plotly to draw the graph4. The integration between NetworkX and Bokeh is also documented5."
},
{
"code": null,
"e": 3009,
"s": 2865,
"text": "Geographically located information and maps is also a specific subfield of data-visualization. Plotting maps bears many challenges, among them:"
},
{
"code": null,
"e": 3068,
"s": 3009,
"text": "Handling large and complex contours (e.g. country borders)"
},
{
"code": null,
"e": 3305,
"s": 3068,
"text": "Showing more or less information depending on the zoom, this is also known as the level of detail. The impact is at the same time on the readability of the plot, and on the complexity that turns into latency to load and memory footprint"
},
{
"code": null,
"e": 3489,
"s": 3305,
"text": "Handling of geographical coordinates, that is single or multiple projections from non-euclidean spaces to the 2D euclidian space (e.g. latitude-longitude to UTM with a given UTM zone)"
},
{
"code": null,
"e": 3608,
"s": 3489,
"text": "Availability of information in multiple file formats, even if there are de facto standards like GeoJSON and Shape-file"
},
{
"code": null,
"e": 3879,
"s": 3608,
"text": "Depending on the chosen plotting library, you may have to do little or a lot of pre-processing. The common open-source library to deal with geographical coordinate is Proj, and GDAL to deal with file formats and translation from formats or coordinates to other contexts."
},
{
"code": null,
"e": 4101,
"s": 3879,
"text": "Matplotlib has no direct support for plotting maps, it relies on pixel matrics (a raster image) as explained in the gallery6. But this is a pis-aller, you do not want to do that, but if your only target is a static image."
},
{
"code": null,
"e": 4266,
"s": 4101,
"text": "Plotly is demonstrating map plots7 based on Mapbox. Many features are available but at least one is missing, the management of the level of detail in scatter plots."
},
{
"code": null,
"e": 4367,
"s": 4266,
"text": "Bokeh has some support for maps including the integration of Google maps8, but it seems quite crude."
},
{
"code": null,
"e": 4579,
"s": 4367,
"text": "Folium is a Python library wrapping the Leaflet Javascript library. Leaflet is used in many collaborative and commercial websites, for example Open Street Map. Folium is very effective to draw maps on Open data."
},
{
"code": null,
"e": 4776,
"s": 4579,
"text": "The open-source reference for geographic data manipulation is QGIS from OSGeo. It is a desktop application but it includes a Python console and it is also possible to directly use the Pyqgis API9."
},
{
"code": null,
"e": 4894,
"s": 4776,
"text": "Pandas and its Dataframe are must use for data science in Python. What is the impact on chart creation and dashboard?"
},
{
"code": null,
"e": 5145,
"s": 4894,
"text": "On the one hand, Pandas Dataframes and Series have a plot API. By default, it is relying on Matplotlib as the backend. However, Plotly as the graphical backend for Pandas is available10. Support for Bokeh is also available through a Github project11."
},
{
"code": null,
"e": 5395,
"s": 5145,
"text": "On the other hand, the plots of Pandas might not fit with your requirements and you are wondering how to use dataframes in plots besides using columns and series as vectors. Plotly Express has this capability with support for column-oriented data12."
},
{
"code": null,
"e": 5850,
"s": 5395,
"text": "If none of these libraries and their extensions are dealing with the chart you are looking for, then you may switch to d3.js which is the base charting library for browsers. It means that you would leave the Python world and enter Javascript’s domain. Possibilities and customization are vast as shown in the example gallery13. However, you will need to handle many aspects of the graph that are granted in other libraries: axes, legend, interactivity..."
},
{
"code": null,
"e": 6497,
"s": 5850,
"text": "In the design of a dataviz, the layout or composition of charts come along with the requirement for multiple charts to display several features. You probably already enjoyed the pluses and minuses of Matplotlib’s subplots, starting with the quirky imperative commands like “`plt.subplot(1, 2, 1)`” or even weirder equivalent “`plt.subplot(121)`”. If this is enough to reach your goal, I would anyway suggest using the alternate and cleaner “plt.subplots()” API that returns a figure and an array of axes. You might anyway feel limited not only by the interactivity, this is dealt with in the next section, but also limited in layout capabilities."
},
{
"code": null,
"e": 6753,
"s": 6497,
"text": "Matplotlib allows for uneven widths and heights using calls to Figure.add_subplots method like “fig.add_subplot(3, 1, (1, 2))\" making a subplot that spans the upper 2/3 of the figure14. Seaborn is introducing one enhancement which is the Scatter matrix15."
},
{
"code": null,
"e": 6992,
"s": 6753,
"text": "Plotly allows for similar capabilities including the uneven sub-plots. However, I find the API rather limited. For example, it is not possible to set the font size of sub-plots title or to share a legend. Bokeh has similar capabilities16."
},
{
"code": null,
"e": 7249,
"s": 6992,
"text": "Plotly, Express API, goes further with marginal probability plots as histograms or rug17, and also a synchronized overview-detail chart that is called “range slider18”. This is leading us to the interactivity of graphs that is detailed in the next section."
},
{
"code": null,
"e": 7431,
"s": 7249,
"text": "But what if these layout helpers are not enough for my purpose? Possible answers are many, ranging from the Plotly Dash solution to full HTML layout or SVG custom design with d3.js."
},
{
"code": null,
"e": 7733,
"s": 7431,
"text": "Plotly Dash is proposing an intermediate solution in which you stick to Python but can generate some more complex and more interactive dashboards than the plotting libraries. Still, it requires that you have some basic HTML knowledge and sooner or later will dive into the cascading stylesheets (CSS)."
},
{
"code": null,
"e": 7819,
"s": 7733,
"text": "You are very pleased with the chart but it feels so static, there is not even a zoom!"
},
{
"code": null,
"e": 8447,
"s": 7819,
"text": "Interactivity is so many different things. It starts with common operations like zoom and pan. The next step is synchronized graphs: zoom and pan are applied simultaneously on several charts that share an axis. You might also be interested in synchronous selection on two graphs, also called brushing (example in Bokeh19). Matplolib has such interactivity for all render engines but within a notebook20. There is however a solution based on Matplotlib, mpld3 is handling this and might provide all you need. However, the trend is to use newer libraries like Plotly or Bokeh that have zoom and pan in notebooks “out of the box”."
},
{
"code": null,
"e": 8752,
"s": 8447,
"text": "Then come dynamic annotations. They span from hover information when the mouse is located on a marker to line plot highlights. Regarding hover, whatever the used library (Matplotlib with Mpld3 and plugins, Plotly, Bokeh) it means attaching an HTML document div to each marker, and probably also some CSS."
},
{
"code": null,
"e": 9116,
"s": 8752,
"text": "More complex interactions are related to filtering or querying the data. It can be close to the zoom function when the filter is modifying a range (e.g.: daily / weekly / monthly selector for a time series), or a selector on the series of facets, or even more complex associations. Selectors are available in Plotly as Custom Controls21 and in Bokeh as widgets22."
},
{
"code": null,
"e": 9331,
"s": 9116,
"text": "The common plotting libraries provide basic capabilities for interactivity up to the creation of some widget, but, as for advanced layouts, I would suggest to directly switch to Plotly Dash which is more versatile."
},
{
"code": null,
"e": 9619,
"s": 9331,
"text": "The more complex the dashboard or the larger the data, the longer it takes to process, thus the longer to render. It may be ok to wait for a few seconds to get a view of a static plot. It is no longer ok to wait more than 1 second when the graph is interactive with widgets and controls."
},
{
"code": null,
"e": 9698,
"s": 9619,
"text": "If fluidity is gone, you have four main solutions, with increasing complexity:"
},
{
"code": null,
"e": 9834,
"s": 9698,
"text": "Simplify the dashboard with fewer plots, fewer controls. That may be ok but then you should think why such complexity was needed first?"
},
{
"code": null,
"e": 10002,
"s": 9834,
"text": "Simplify the data, that shows less data or with less granularity. That may provide a good tradeoff between features and accuracy. It is leading to the next solution..."
},
{
"code": null,
"e": 10389,
"s": 10002,
"text": "Offline pre-processing of data to pre-assemble the data shown in the dashboard. That probably means storing new series or new tables, leading eventually to other issues linked to data management. In the end, you will do a lot more data engineering and will probably reach a dead-end with two much data, too many tables. The solution to the dead-end is even more data engineering with..."
},
{
"code": null,
"e": 10454,
"s": 10389,
"text": "Online processing in dedicated servers and the design of an API."
},
{
"code": null,
"e": 10707,
"s": 10454,
"text": "A server with an API is not the first thing you were thinking but you end up dealing with this software project sooner than you think. It is also better to anticipate it than delay until there is no other solution and project deadlines are coming fast."
},
{
"code": null,
"e": 10943,
"s": 10707,
"text": "Defining an API involves often several teams and skills: data scientists to define the why, data engineers to define the what, and infrastructure engineers to define the how, including performance, security, persistence, and integrity."
},
{
"code": null,
"e": 11281,
"s": 10943,
"text": "Plotly Dash allows for an initial API since it is based on the Flask framework. See the Dash documentation on integration with a Flask app which is defining a custom Flask route, that could serve data, i.e. an API23. There is still no proper API access management, including authentication. On that latter aspect, Dash is very limited24."
},
{
"code": null,
"e": 11338,
"s": 11281,
"text": "How much effort will it take you to develop and publish?"
},
{
"code": null,
"e": 11700,
"s": 11338,
"text": "Some tools are effective, they deliver the expected result, but are not efficient, getting to the result takes a large amount of time. For example, d3.js is known as a very powerful and complete data-visualization and charting library but at the same time, it requires dealing with many things that are by default available in libraries with higher abstraction."
},
{
"code": null,
"e": 11916,
"s": 11700,
"text": "Productivity is coming not only with using the right level of abstraction, but also an API that is easy to use and well documented. I would say that none of the surveyed Python charting libraries are easy to master."
},
{
"code": null,
"e": 12258,
"s": 11916,
"text": "Matplotlib’s API is quite complex when dealing with axes, formats (of labels), it is not always consistent and quite redundant. As an example, see the above comment on “`plt.subplot()`”. That’s not the only example, for example, there is a sub-routine “`plt.xlabel()`” that is equivalent to the method “`ax.set_xlabel()`” on the Axes object."
},
{
"code": null,
"e": 12884,
"s": 12258,
"text": "Plotly’s API is not better, first, you must choose between two API sets: the Express set that is quite simple but limited and mostly targeted at dataframes, and the Graphical Object set that is more complete and complementing the Express set, but does not have some nice high-level features that are in Express. Then you will have to deal with the Plotly documentation that is, to me, really difficult to get through. Searching with either the Plotly website internal or a Web search engine seldom leads you to the API you are looking for. And you may have to deal with the documentation of the underneath data model in JSON."
},
{
"code": null,
"e": 13037,
"s": 12884,
"text": "Bokeh API is probably leaner and better documented but has some weird things like two separate instructions to plot a line chart and associated markers."
},
{
"code": null,
"e": 13197,
"s": 13037,
"text": "Your dashboard is successful and will be deployed as a product internally to your organization, available to clients, or even directly exposed on the Internet."
},
{
"code": null,
"e": 13505,
"s": 13197,
"text": "As a data scientist, you are missing skills to handle that and get the help of software specialists. However, you are asked what is the effort or scope of this development. This highly depends on the path to production, which framework is used there, and on the framework that you have been using until now."
},
{
"code": null,
"e": 13725,
"s": 13505,
"text": "Plotly standalone graphics can be exported as static HTML. Bokeh provides some schemes to embed it25. Matplotlib with Mpld3 has an HTML output27. However, this solution is targeting illustrations rather than dashboards."
},
{
"code": null,
"e": 14062,
"s": 13725,
"text": "Plotly Dash may in some cases go up to production as the main Web app or an embedded widget23. As said earlier in such setup you will need to inspect the security of your system before jumping to online production. Regarding security, as a data designer, you mainly need to check that you are exposing only the wanted data and not more."
},
{
"code": null,
"e": 14376,
"s": 14062,
"text": "Today, most of the Web applications we use are based on a pattern called single page application (SPA): the application is loaded once in the Web browser and then interacts with the server through some asynchronous API without reloading the Web page. This is what all of us now expect from a nice Web application."
},
{
"code": null,
"e": 14639,
"s": 14376,
"text": "SPA has two separate components: the browser side application in Javascript with a framework like Angular or React.js, and the server-side application or service that may get written on many frameworks and language: Java, C#, PHP, Javascript..., and even Python."
},
{
"code": null,
"e": 14855,
"s": 14639,
"text": "Dash is already doing part of it. In fact, Dash is using one of the leading browser-side framework, React.js, and on the server-side is based on Flask and Python. But as said above you may reach some limits of Dash."
},
{
"code": null,
"e": 15298,
"s": 14855,
"text": "Besides the transition through Dash, Plotly and Bokeh have another advantage: they are also available in Javascript as Plotly JS (and a React.js wrapper wrapper26), Bokeh JS. In fact, the Python version of Plotly is a wrapper around the Javascript. This implies that given some plots or dashboards in Python based on Plotly or Dash or Bokeh, most of the concepts and chart properties can be reused in the equivalent Javascript implementation."
},
{
"code": null,
"e": 15800,
"s": 15298,
"text": "In this post, we have brushed the path for a data-visualization dashboard from experiments within notebooks, up to production. We have seen that the traditional plotting library, Matplotlib, still has strong features and is usually the default backend for specialized libraries like NetworkX and the Pandas Dataframe. But Matplolib is also lagging on some aspects like integration and interactivity. Learning another framework may be a good investment and will help you going forward up to production."
},
{
"code": null,
"e": 16151,
"s": 15800,
"text": "Two alternative frameworks are presented: Plotly and Bokeh. Both bring value as they are more modern than Matplotlib. Both of them have a leading advantage when it comes to bringing the dashboard to production: they are based on Javascript plotting frameworks and most of the plots Python code can be translated directly in the Javascript equivalent."
},
{
"code": null,
"e": 16429,
"s": 16151,
"text": "Plotly has another advantage on the go-to production path: it is integrated with Dash, a framework to develop a simple dashboard as single-page applications while sticking to Python. Required Javascript, including React components, and server API is generated smoothly by Dash."
},
{
"code": null,
"e": 16641,
"s": 16429,
"text": "We have also seen that, as a data scientist or data-visualization designer, you should anticipate requirements like interactivity, and their implications that may lead to the development of an API to serve data."
},
{
"code": null,
"e": 16871,
"s": 16641,
"text": "In “Plotly Dash or React.js + Plotly.js”, a side by side comparison is showing what is required to port a Dash application to a Javascript application in React.js with Plotly.js for the dataviz, and served by a Web API in Python."
},
{
"code": null,
"e": 16882,
"s": 16871,
"text": "References"
},
{
"code": null,
"e": 17007,
"s": 16882,
"text": "[1] Word clouds with Matplotlib and word_cloud library, https://amueller.github.io/word_cloud/auto_examples/single_word.html"
},
{
"code": null,
"e": 17111,
"s": 17007,
"text": "[2] NetworkX graph plot, https://networkx.github.io/documentation/stable/auto_examples/index.html#basic"
},
{
"code": null,
"e": 17238,
"s": 17111,
"text": "[3] NetworkX with GraphViz, https://networkx.github.io/documentation/stable/auto_examples/pygraphviz/plot_pygraphviz_draw.html"
},
{
"code": null,
"e": 17306,
"s": 17238,
"text": "[4] Plotly with NetworkX, https://plotly.com/python/network-graphs/"
},
{
"code": null,
"e": 17411,
"s": 17306,
"text": "[5] Bokeh and NetworkX, https://docs.bokeh.org/en/latest/docs/user_guide/graph.html#networkx-integration"
},
{
"code": null,
"e": 17491,
"s": 17411,
"text": "[6] Matplotlib to draw maps, https://matplotlib.org/basemap/users/examples.html"
},
{
"code": null,
"e": 17543,
"s": 17491,
"text": "[7] Plotly and maps https://plotly.com/python/maps/"
},
{
"code": null,
"e": 17621,
"s": 17543,
"text": "[8] Bokeh and maps, https://docs.bokeh.org/en/latest/docs/user_guide/geo.html"
},
{
"code": null,
"e": 17699,
"s": 17621,
"text": "[9] Pyqgis API, https://docs.qgis.org/3.10/fr/docs/pyqgis_developer_cookbook/"
},
{
"code": null,
"e": 17772,
"s": 17699,
"text": "[10] Plotly as Pandas backend, https://plotly.com/python/pandas-backend/"
},
{
"code": null,
"e": 17847,
"s": 17772,
"text": "[11] Bokeh as Pandas backend, https://github.com/PatrikHlobil/Pandas-Bokeh"
},
{
"code": null,
"e": 17937,
"s": 17847,
"text": "[12] Plotly Express support for column-oriented data https://plotly.com/python/wide-form/"
},
{
"code": null,
"e": 17993,
"s": 17937,
"text": "[13] D3.js gallery https://observablehq.com/@d3/gallery"
},
{
"code": null,
"e": 18131,
"s": 17993,
"text": "[14] Maplitlib documentation on figure layouts, https://matplotlib.org/api/_as_gen/matplotlib.figure.Figure.html#matplotlib.figure.Figure"
},
{
"code": null,
"e": 18220,
"s": 18131,
"text": "[15] Seaborn scatter matrix, https://seaborn.pydata.org/examples/scatterplot_matrix.html"
},
{
"code": null,
"e": 18301,
"s": 18220,
"text": "[16] Bokeh layouts, https://docs.bokeh.org/en/latest/docs/user_guide/layout.html"
},
{
"code": null,
"e": 18371,
"s": 18301,
"text": "[17] Plotly marginal plots, https://plotly.com/python/marginal-plots/"
},
{
"code": null,
"e": 18468,
"s": 18371,
"text": "[18] Plotly’s range slider, https://plotly.com/python/time-series/#time-series-with-range-slider"
},
{
"code": null,
"e": 18582,
"s": 18468,
"text": "[19] Bokeh brushing, https://docs.bokeh.org/en/latest/docs/user_guide/quickstart.html#linked-panning-and-brushing"
},
{
"code": null,
"e": 18666,
"s": 18582,
"text": "[20] Matplotlib interactivity, https://matplotlib.org/users/interactive_guide.html)"
},
{
"code": null,
"e": 18724,
"s": 18666,
"text": "[21] Plotly controls, https://plotly.com/python/#controls"
},
{
"code": null,
"e": 18818,
"s": 18724,
"text": "[22] Bokeh widgets, https://docs.bokeh.org/en/latest/docs/user_guide/interaction/widgets.html"
},
{
"code": null,
"e": 18889,
"s": 18818,
"text": "[23] Plotly Dash integration, https://dash.plotly.com/integrating-dash"
},
{
"code": null,
"e": 18965,
"s": 18889,
"text": "[24] Plotly Dash authentication, see https://dash.plotly.com/authentication"
},
{
"code": null,
"e": 19065,
"s": 18965,
"text": "[25] Bokeh integration, https://docs.bokeh.org/en/latest/docs/user_guide/embed.html#userguide-embed"
},
{
"code": null,
"e": 19132,
"s": 19065,
"text": "[26] Plotly JS React wrapper, https://plotly.com/javascript/react/"
}
] |
How to align multiple plots in a grid using GridSpec Class in Matplotlib
|
Aligning the multiple plots in a grid can be very messy and it can create multiple issues like higher width and height or minimal width to align all the plots. In order to align all the plots in a grid, we use GridSpec class.
Let us suppose that we have a bar graph plot and we want to align the symmetry of the plot in this sample.
First Import all the necessary libraries and plot some graphs in two grids. Then, we will plot a constant error bar and a symmetric and asymmetric error bar on the first grid. In the second grid, we will plot the sample error bar.
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
#Define the figure size and layout
fig = plt.figure(figsize=(8,8))
plt.style.use('seaborn-deep')
#Define the function to plot the graph
def plot_errorbar(axs, x, y, xerr=None, yerr=None, errevery=1,
title=None, xlabel=None, ylabel=None, fmt=None):
ax = fig.add_subplot(axs)
ax.errorbar(x, y, xerr=xerr, yerr=yerr, errorevery=errevery, fmt=fmt)
ax.set(title=title, xlabel=xlabel, ylabel=ylabel)
#First grid with size (3,1)
gs1 = GridSpec(3, 1)
#Data for exponential curve
x = np.arange(0.1, 5, 0.5)
y = np.exp(-x)
#Plot the errorbar with constant axis x and y
plot_errorbar(gs1[0], x, y, xerr=0.8, yerr=0.3, title='Constant
Errors', xlabel='X', ylabel='Y', fmt='-o')
#Define the varying error with as a function of x
error = 0.1 + 0.25 * x
plot_errorbar(gs1[1], x, y, yerr=error, title='Variable Symmetric
Error', xlabel='X', ylabel='Y', fmt='-o')
#Define the bounded and unbounded error
lower_error = 0.5 * error
upper_error = error
asymmetric_error = [lower_error, upper_error]
plot_errorbar(gs1[2], x, y, xerr=asymmetric_error, title='Variable
Asymmetric Error', xlabel='X', ylabel='Y', fmt='o')
#Plot the Grid 2 with the same step as in Grid 1
gs1.tight_layout(fig, rect=[0, 0, 0.5, 1])
#Define the data with a smaller interval for exponential curve
x = np.arange(0.1, 5, 0.1)
y = np.exp(-x)
gs2 = GridSpec(2, 1)
'yerr = 0.1 + 0.1 * np.sqrt(x)
plot_errorbar(gs2[0], x, y, yerr=yerr, title='All Errorbars', xlabel='X', ylabel='Y', fmt='-')
plot_errorbar(gs2[1], x, y, yerr=yerr, errevery=5, title='5th errorbar', xlabel='X', ylabel='Y', fmt='-')
gs2.tight_layout(fig, rect=[0.5, 0, 1, 1], h_pad=0.5)
top = min(gs1.top, gs2.top)
bottom = max(gs1.bottom, gs2.bottom)
gs1.update(top=top, bottom=bottom)
gs2.update(top=top, bottom=bottom)
#Display the plot
plt.show()
|
[
{
"code": null,
"e": 1288,
"s": 1062,
"text": "Aligning the multiple plots in a grid can be very messy and it can create multiple issues like higher width and height or minimal width to align all the plots. In order to align all the plots in a grid, we use GridSpec class."
},
{
"code": null,
"e": 1395,
"s": 1288,
"text": "Let us suppose that we have a bar graph plot and we want to align the symmetry of the plot in this sample."
},
{
"code": null,
"e": 1626,
"s": 1395,
"text": "First Import all the necessary libraries and plot some graphs in two grids. Then, we will plot a constant error bar and a symmetric and asymmetric error bar on the first grid. In the second grid, we will plot the sample error bar."
},
{
"code": null,
"e": 3492,
"s": 1626,
"text": "import matplotlib.pyplot as plt\nfrom matplotlib.gridspec import GridSpec\n\n#Define the figure size and layout\nfig = plt.figure(figsize=(8,8))\nplt.style.use('seaborn-deep')\n\n#Define the function to plot the graph\ndef plot_errorbar(axs, x, y, xerr=None, yerr=None, errevery=1,\n title=None, xlabel=None, ylabel=None, fmt=None):\n ax = fig.add_subplot(axs)\nax.errorbar(x, y, xerr=xerr, yerr=yerr, errorevery=errevery, fmt=fmt)\nax.set(title=title, xlabel=xlabel, ylabel=ylabel)\n\n#First grid with size (3,1)\ngs1 = GridSpec(3, 1)\n\n#Data for exponential curve\nx = np.arange(0.1, 5, 0.5)\ny = np.exp(-x)\n\n#Plot the errorbar with constant axis x and y\nplot_errorbar(gs1[0], x, y, xerr=0.8, yerr=0.3, title='Constant\n Errors', xlabel='X', ylabel='Y', fmt='-o')\n#Define the varying error with as a function of x\nerror = 0.1 + 0.25 * x\nplot_errorbar(gs1[1], x, y, yerr=error, title='Variable Symmetric\n Error', xlabel='X', ylabel='Y', fmt='-o')\n\n#Define the bounded and unbounded error\nlower_error = 0.5 * error\nupper_error = error\nasymmetric_error = [lower_error, upper_error]\nplot_errorbar(gs1[2], x, y, xerr=asymmetric_error, title='Variable\n Asymmetric Error', xlabel='X', ylabel='Y', fmt='o')\n\n#Plot the Grid 2 with the same step as in Grid 1\ngs1.tight_layout(fig, rect=[0, 0, 0.5, 1])\n\n#Define the data with a smaller interval for exponential curve\nx = np.arange(0.1, 5, 0.1)\ny = np.exp(-x)\ngs2 = GridSpec(2, 1)\n'yerr = 0.1 + 0.1 * np.sqrt(x)\nplot_errorbar(gs2[0], x, y, yerr=yerr, title='All Errorbars', xlabel='X', ylabel='Y', fmt='-')\nplot_errorbar(gs2[1], x, y, yerr=yerr, errevery=5, title='5th errorbar', xlabel='X', ylabel='Y', fmt='-')\ngs2.tight_layout(fig, rect=[0.5, 0, 1, 1], h_pad=0.5)\ntop = min(gs1.top, gs2.top)\nbottom = max(gs1.bottom, gs2.bottom)\ngs1.update(top=top, bottom=bottom)\ngs2.update(top=top, bottom=bottom)\n\n#Display the plot\nplt.show()"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.