title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Find the lexicographically smallest sequence which can be formed by re-arranging elements of second array - GeeksforGeeks | 17 Jun, 2021
Given two arrays A and B of N integers. Reorder the elements of B in itself in such a way that the sequence formed by (A[i] + B[i]) % N after re-ordering is the smallest lexicographically. The task is to print the lexicographically smallest sequence possible. Note: The array elements are in range [0, n).Examples:
Input: a[] = {0, 1, 2, 1}, b[] = {3, 2, 1, 1} Output: 1 0 0 2 Reorder B to {1, 3, 2, 1} to get the smallest sequence possible. Input: a[] = {2, 0, 0}, b[] = {1, 0, 2} Output: 0 0 2
Approach: The problem can be solved greedily. Initially keep a count of all the numbers of array B using hashing, and store them in the set in C++, so that lower_bound() [ To check for an element ] and erase() [ To erase an element ] operations can be done in logarithmic time. For every element in the array, check for a number equal or greater than n-a[i] using lower_bound function. If there are no such elements then take the smallest element in the set. Decrease the value by 1 in the hash table for the number used, if the hash table’s value is 0, then erase the element from the set also.However there is an exception if the array element is 0, then check for 0 at the first then for N, if both of them are not there, then take the smallest element. Below is the implementation of the above approach:
CPP
// C++ implementation of the// above approach #include <bits/stdc++.h>using namespace std; // Function to get the smallest// sequence possiblevoid solve(int a[], int b[], int n){ // Hash-table to count the // number of occurrences of b[i] unordered_map<int, int> mpp; // Store the element in sorted order // for using binary search set<int> st; // Iterate in the B array // and count the occurrences and // store in the set for (int i = 0; i < n; i++) { mpp[b[i]]++; st.insert(b[i]); } vector<int> sequence; // Iterate for N elements for (int i = 0; i < n; i++) { // If the element is 0 if (a[i] == 0) { // Find the nearest number to 0 auto it = st.lower_bound(0); int el = *it; sequence.push_back(el % n); // Decrease the count mpp[el]--; // Erase if no more are there if (!mpp[el]) st.erase(el); } // If the element is other than 0 else { // Find the difference int x = n - a[i]; // Find the nearest number which can give us // 0 on modulo auto it = st.lower_bound(x); // If no such number occurs then // find the number closest to 0 if (it == st.end()) it = st.lower_bound(0); // Get the number int el = *it; // store the number sequence.push_back((a[i] + el) % n); // Decrease the count mpp[el]--; // If no more appears, then erase it from set if (!mpp[el]) st.erase(el); } } for (auto it : sequence) cout << it << " ";} // Driver Codeint main(){ int a[] = { 0, 1, 2, 1 }; int b[] = { 3, 2, 1, 1 }; int n = sizeof(a) / sizeof(a[0]); solve(a, b, n); return 0;}
1 0 0 2
Akanksha_Rai
sumitgumber28
Binary Search
cpp-set
lexicographic-ordering
Arrays
Hash
Mathematical
Arrays
Hash
Mathematical
Binary Search
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Chocolate Distribution Problem
Count pairs with given sum
Window Sliding Technique
Reversal algorithm for array rotation
Next Greater Element
Internal Working of HashMap in Java
Count pairs with given sum
Hashing | Set 1 (Introduction)
Hashing | Set 3 (Open Addressing)
Hashing | Set 2 (Separate Chaining) | [
{
"code": null,
"e": 26041,
"s": 26013,
"text": "\n17 Jun, 2021"
},
{
"code": null,
"e": 26358,
"s": 26041,
"text": "Given two arrays A and B of N integers. Reorder the elements of B in itself in such a way that the sequence formed by (A[i] + B[i]) % N after re-ordering is the smallest lexicographically. The task is to print the lexicographically smallest sequence possible. Note: The array elements are in range [0, n).Examples: "
},
{
"code": null,
"e": 26541,
"s": 26358,
"text": "Input: a[] = {0, 1, 2, 1}, b[] = {3, 2, 1, 1} Output: 1 0 0 2 Reorder B to {1, 3, 2, 1} to get the smallest sequence possible. Input: a[] = {2, 0, 0}, b[] = {1, 0, 2} Output: 0 0 2 "
},
{
"code": null,
"e": 27353,
"s": 26543,
"text": "Approach: The problem can be solved greedily. Initially keep a count of all the numbers of array B using hashing, and store them in the set in C++, so that lower_bound() [ To check for an element ] and erase() [ To erase an element ] operations can be done in logarithmic time. For every element in the array, check for a number equal or greater than n-a[i] using lower_bound function. If there are no such elements then take the smallest element in the set. Decrease the value by 1 in the hash table for the number used, if the hash table’s value is 0, then erase the element from the set also.However there is an exception if the array element is 0, then check for 0 at the first then for N, if both of them are not there, then take the smallest element. Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27357,
"s": 27353,
"text": "CPP"
},
{
"code": "// C++ implementation of the// above approach #include <bits/stdc++.h>using namespace std; // Function to get the smallest// sequence possiblevoid solve(int a[], int b[], int n){ // Hash-table to count the // number of occurrences of b[i] unordered_map<int, int> mpp; // Store the element in sorted order // for using binary search set<int> st; // Iterate in the B array // and count the occurrences and // store in the set for (int i = 0; i < n; i++) { mpp[b[i]]++; st.insert(b[i]); } vector<int> sequence; // Iterate for N elements for (int i = 0; i < n; i++) { // If the element is 0 if (a[i] == 0) { // Find the nearest number to 0 auto it = st.lower_bound(0); int el = *it; sequence.push_back(el % n); // Decrease the count mpp[el]--; // Erase if no more are there if (!mpp[el]) st.erase(el); } // If the element is other than 0 else { // Find the difference int x = n - a[i]; // Find the nearest number which can give us // 0 on modulo auto it = st.lower_bound(x); // If no such number occurs then // find the number closest to 0 if (it == st.end()) it = st.lower_bound(0); // Get the number int el = *it; // store the number sequence.push_back((a[i] + el) % n); // Decrease the count mpp[el]--; // If no more appears, then erase it from set if (!mpp[el]) st.erase(el); } } for (auto it : sequence) cout << it << \" \";} // Driver Codeint main(){ int a[] = { 0, 1, 2, 1 }; int b[] = { 3, 2, 1, 1 }; int n = sizeof(a) / sizeof(a[0]); solve(a, b, n); return 0;}",
"e": 29274,
"s": 27357,
"text": null
},
{
"code": null,
"e": 29282,
"s": 29274,
"text": "1 0 0 2"
},
{
"code": null,
"e": 29297,
"s": 29284,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 29311,
"s": 29297,
"text": "sumitgumber28"
},
{
"code": null,
"e": 29325,
"s": 29311,
"text": "Binary Search"
},
{
"code": null,
"e": 29333,
"s": 29325,
"text": "cpp-set"
},
{
"code": null,
"e": 29356,
"s": 29333,
"text": "lexicographic-ordering"
},
{
"code": null,
"e": 29363,
"s": 29356,
"text": "Arrays"
},
{
"code": null,
"e": 29368,
"s": 29363,
"text": "Hash"
},
{
"code": null,
"e": 29381,
"s": 29368,
"text": "Mathematical"
},
{
"code": null,
"e": 29388,
"s": 29381,
"text": "Arrays"
},
{
"code": null,
"e": 29393,
"s": 29388,
"text": "Hash"
},
{
"code": null,
"e": 29406,
"s": 29393,
"text": "Mathematical"
},
{
"code": null,
"e": 29420,
"s": 29406,
"text": "Binary Search"
},
{
"code": null,
"e": 29518,
"s": 29420,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29549,
"s": 29518,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 29576,
"s": 29549,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 29601,
"s": 29576,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 29639,
"s": 29601,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 29660,
"s": 29639,
"text": "Next Greater Element"
},
{
"code": null,
"e": 29696,
"s": 29660,
"text": "Internal Working of HashMap in Java"
},
{
"code": null,
"e": 29723,
"s": 29696,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 29754,
"s": 29723,
"text": "Hashing | Set 1 (Introduction)"
},
{
"code": null,
"e": 29788,
"s": 29754,
"text": "Hashing | Set 3 (Open Addressing)"
}
]
|
ReactJS Evergreen Combobox Component - GeeksforGeeks | 05 Jun, 2021
React Evergreen is a popular front-end library with a set of React components for building beautiful products as this library is flexible, sensible defaults, and User friendly. Combobox Component allows the user to select an option from a predefined list of options. We can use the following approach in ReactJS to use the Combobox Button Component.
Combobox Props:
item: It is used to denote the options to show in the menu.
selectedItem: It is used to denote the selected item when controlled.
onChange: It is a function that is called when value changes.
openOnFocus: It is used to open the autocomplete on focus when this is set to true.
initialSelectedItem: It is used to denote the default selected item when uncontrolled.
placeholder: It is used to denote the placeholder text.
itemToString: It is a function that is used on each item to return the string that will be shown on the filter in case the array of items is not an array of strings.
inputProps: It is used to denote the properties forwarded to the input.
buttonProps: It is used to denote the properties forwarded to the button.
autocompleteProps: It is used to denote the properties forwarded to the autocomplete component.
disabled: It is used to make the input element disabled.
isLoading: It is used to show a loading spinner when this is set to true.
size: It is used to denote the size of the component.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:npx create-react-app foldername
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Step 3: After creating the ReactJS application, Install the required module using the following command:npm install evergreen-ui
Step 3: After creating the ReactJS application, Install the required module using the following command:
npm install evergreen-ui
Project Structure: It will look like the following.
Project Structure
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React from 'react'import { Combobox } from 'evergreen-ui' export default function App() { return ( <div style={{ display: 'block', width: 700, paddingLeft: 30 }}> <h4>ReactJS Evergreen Combobox Component</h4> <Combobox placeholder="Select Week Days" items={['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']} autocompleteProps={{ title: 'Weekdays' }} /> </div> );}
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Reference: https://evergreen.segment.com/components/combobox
ReactJS-Evergreen
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ReactJS useNavigate() Hook
How to set background images in ReactJS ?
Axios in React: A Guide for Beginners
How to create a table in ReactJS ?
How to navigate on path by button click in react router ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 26071,
"s": 26043,
"text": "\n05 Jun, 2021"
},
{
"code": null,
"e": 26421,
"s": 26071,
"text": "React Evergreen is a popular front-end library with a set of React components for building beautiful products as this library is flexible, sensible defaults, and User friendly. Combobox Component allows the user to select an option from a predefined list of options. We can use the following approach in ReactJS to use the Combobox Button Component."
},
{
"code": null,
"e": 26437,
"s": 26421,
"text": "Combobox Props:"
},
{
"code": null,
"e": 26497,
"s": 26437,
"text": "item: It is used to denote the options to show in the menu."
},
{
"code": null,
"e": 26567,
"s": 26497,
"text": "selectedItem: It is used to denote the selected item when controlled."
},
{
"code": null,
"e": 26629,
"s": 26567,
"text": "onChange: It is a function that is called when value changes."
},
{
"code": null,
"e": 26713,
"s": 26629,
"text": "openOnFocus: It is used to open the autocomplete on focus when this is set to true."
},
{
"code": null,
"e": 26800,
"s": 26713,
"text": "initialSelectedItem: It is used to denote the default selected item when uncontrolled."
},
{
"code": null,
"e": 26856,
"s": 26800,
"text": "placeholder: It is used to denote the placeholder text."
},
{
"code": null,
"e": 27022,
"s": 26856,
"text": "itemToString: It is a function that is used on each item to return the string that will be shown on the filter in case the array of items is not an array of strings."
},
{
"code": null,
"e": 27094,
"s": 27022,
"text": "inputProps: It is used to denote the properties forwarded to the input."
},
{
"code": null,
"e": 27168,
"s": 27094,
"text": "buttonProps: It is used to denote the properties forwarded to the button."
},
{
"code": null,
"e": 27264,
"s": 27168,
"text": "autocompleteProps: It is used to denote the properties forwarded to the autocomplete component."
},
{
"code": null,
"e": 27321,
"s": 27264,
"text": "disabled: It is used to make the input element disabled."
},
{
"code": null,
"e": 27395,
"s": 27321,
"text": "isLoading: It is used to show a loading spinner when this is set to true."
},
{
"code": null,
"e": 27449,
"s": 27395,
"text": "size: It is used to denote the size of the component."
},
{
"code": null,
"e": 27499,
"s": 27449,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 27595,
"s": 27499,
"text": "Step 1: Create a React application using the following command:npx create-react-app foldername "
},
{
"code": null,
"e": 27659,
"s": 27595,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 27691,
"s": 27659,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 27806,
"s": 27693,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername"
},
{
"code": null,
"e": 27906,
"s": 27806,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:"
},
{
"code": null,
"e": 27920,
"s": 27906,
"text": "cd foldername"
},
{
"code": null,
"e": 28049,
"s": 27920,
"text": "Step 3: After creating the ReactJS application, Install the required module using the following command:npm install evergreen-ui"
},
{
"code": null,
"e": 28154,
"s": 28049,
"text": "Step 3: After creating the ReactJS application, Install the required module using the following command:"
},
{
"code": null,
"e": 28179,
"s": 28154,
"text": "npm install evergreen-ui"
},
{
"code": null,
"e": 28231,
"s": 28179,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 28249,
"s": 28231,
"text": "Project Structure"
},
{
"code": null,
"e": 28379,
"s": 28249,
"text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code."
},
{
"code": null,
"e": 28386,
"s": 28379,
"text": "App.js"
},
{
"code": "import React from 'react'import { Combobox } from 'evergreen-ui' export default function App() { return ( <div style={{ display: 'block', width: 700, paddingLeft: 30 }}> <h4>ReactJS Evergreen Combobox Component</h4> <Combobox placeholder=\"Select Week Days\" items={['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']} autocompleteProps={{ title: 'Weekdays' }} /> </div> );}",
"e": 28863,
"s": 28386,
"text": null
},
{
"code": null,
"e": 28976,
"s": 28863,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 28986,
"s": 28976,
"text": "npm start"
},
{
"code": null,
"e": 29085,
"s": 28986,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:"
},
{
"code": null,
"e": 29146,
"s": 29085,
"text": "Reference: https://evergreen.segment.com/components/combobox"
},
{
"code": null,
"e": 29164,
"s": 29146,
"text": "ReactJS-Evergreen"
},
{
"code": null,
"e": 29172,
"s": 29164,
"text": "ReactJS"
},
{
"code": null,
"e": 29189,
"s": 29172,
"text": "Web Technologies"
},
{
"code": null,
"e": 29287,
"s": 29189,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29314,
"s": 29287,
"text": "ReactJS useNavigate() Hook"
},
{
"code": null,
"e": 29356,
"s": 29314,
"text": "How to set background images in ReactJS ?"
},
{
"code": null,
"e": 29394,
"s": 29356,
"text": "Axios in React: A Guide for Beginners"
},
{
"code": null,
"e": 29429,
"s": 29394,
"text": "How to create a table in ReactJS ?"
},
{
"code": null,
"e": 29487,
"s": 29429,
"text": "How to navigate on path by button click in react router ?"
},
{
"code": null,
"e": 29527,
"s": 29487,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29560,
"s": 29527,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29605,
"s": 29560,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29667,
"s": 29605,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
]
|
Convert integer to string in Python - GeeksforGeeks | 12 May, 2022
In Python an integer can be converted into a string using the built-in str() function. The str() function takes in any python data type and converts it into a string. But use of the str() is not the only way to do so. This type of conversion can also be done using the “%s” keyword, the .format function or using f-string function.
Below is the list of possible ways to convert an integer to string in python:
1. Using str() function
Syntax: str(integer_value)
Example:
Python3
num = 10 # check and print type of num variableprint(type(num)) # convert the num into stringconverted_num = str(num) # check and print type converted_num variableprint(type(converted_num))
2. Using “%s” keyword
Syntax: “%s” % integer
Example:
Python3
num = 10 # check and print type of num variableprint(type(num)) # convert the num into string and printconverted_num = "% s" % numprint(type(converted_num))
3. Using .format() function
Syntax: ‘{}’.format(integer)
Example:
Python3
num = 10 # check and print type of num variableprint(type(num)) # convert the num into string and printconverted_num = "{}".format(num)print(type(converted_num))
4. Using f-string
Syntax: f'{integer}’
Example:
Python3
num = 10 # check and print type of num variableprint(type(num)) # convert the num into string converted_num = f'{num}' # print type of converted_numprint(type(converted_num))
rahulas1505
python-basics
Python-Data Type
Python-datatype
python-string
Python
Write From Home
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
How to set input type date in dd-mm-yyyy format using HTML ?
Python infinity
Matplotlib.pyplot.title() in Python
Factory method design pattern in Java
Similarities and Difference between Java and C++ | [
{
"code": null,
"e": 25914,
"s": 25886,
"text": "\n12 May, 2022"
},
{
"code": null,
"e": 26246,
"s": 25914,
"text": "In Python an integer can be converted into a string using the built-in str() function. The str() function takes in any python data type and converts it into a string. But use of the str() is not the only way to do so. This type of conversion can also be done using the “%s” keyword, the .format function or using f-string function."
},
{
"code": null,
"e": 26324,
"s": 26246,
"text": "Below is the list of possible ways to convert an integer to string in python:"
},
{
"code": null,
"e": 26349,
"s": 26324,
"text": "1. Using str() function "
},
{
"code": null,
"e": 26376,
"s": 26349,
"text": "Syntax: str(integer_value)"
},
{
"code": null,
"e": 26387,
"s": 26376,
"text": "Example: "
},
{
"code": null,
"e": 26395,
"s": 26387,
"text": "Python3"
},
{
"code": "num = 10 # check and print type of num variableprint(type(num)) # convert the num into stringconverted_num = str(num) # check and print type converted_num variableprint(type(converted_num))",
"e": 26591,
"s": 26395,
"text": null
},
{
"code": null,
"e": 26613,
"s": 26591,
"text": "2. Using “%s” keyword"
},
{
"code": null,
"e": 26636,
"s": 26613,
"text": "Syntax: “%s” % integer"
},
{
"code": null,
"e": 26646,
"s": 26636,
"text": "Example: "
},
{
"code": null,
"e": 26654,
"s": 26646,
"text": "Python3"
},
{
"code": "num = 10 # check and print type of num variableprint(type(num)) # convert the num into string and printconverted_num = \"% s\" % numprint(type(converted_num))",
"e": 26815,
"s": 26654,
"text": null
},
{
"code": null,
"e": 26843,
"s": 26815,
"text": "3. Using .format() function"
},
{
"code": null,
"e": 26872,
"s": 26843,
"text": "Syntax: ‘{}’.format(integer)"
},
{
"code": null,
"e": 26882,
"s": 26872,
"text": "Example: "
},
{
"code": null,
"e": 26890,
"s": 26882,
"text": "Python3"
},
{
"code": "num = 10 # check and print type of num variableprint(type(num)) # convert the num into string and printconverted_num = \"{}\".format(num)print(type(converted_num))",
"e": 27056,
"s": 26890,
"text": null
},
{
"code": null,
"e": 27074,
"s": 27056,
"text": "4. Using f-string"
},
{
"code": null,
"e": 27095,
"s": 27074,
"text": "Syntax: f'{integer}’"
},
{
"code": null,
"e": 27105,
"s": 27095,
"text": "Example: "
},
{
"code": null,
"e": 27113,
"s": 27105,
"text": "Python3"
},
{
"code": "num = 10 # check and print type of num variableprint(type(num)) # convert the num into string converted_num = f'{num}' # print type of converted_numprint(type(converted_num))",
"e": 27293,
"s": 27113,
"text": null
},
{
"code": null,
"e": 27305,
"s": 27293,
"text": "rahulas1505"
},
{
"code": null,
"e": 27319,
"s": 27305,
"text": "python-basics"
},
{
"code": null,
"e": 27336,
"s": 27319,
"text": "Python-Data Type"
},
{
"code": null,
"e": 27352,
"s": 27336,
"text": "Python-datatype"
},
{
"code": null,
"e": 27366,
"s": 27352,
"text": "python-string"
},
{
"code": null,
"e": 27373,
"s": 27366,
"text": "Python"
},
{
"code": null,
"e": 27389,
"s": 27373,
"text": "Write From Home"
},
{
"code": null,
"e": 27487,
"s": 27389,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27505,
"s": 27487,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27540,
"s": 27505,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27572,
"s": 27540,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27594,
"s": 27572,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27636,
"s": 27594,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27697,
"s": 27636,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 27713,
"s": 27697,
"text": "Python infinity"
},
{
"code": null,
"e": 27749,
"s": 27713,
"text": "Matplotlib.pyplot.title() in Python"
},
{
"code": null,
"e": 27787,
"s": 27749,
"text": "Factory method design pattern in Java"
}
]
|
Python - Change type of key in Dictionary list - GeeksforGeeks | 10 May, 2020
Sometimes, while working with data, we can have a problem in which we require to change the type of particular keys’ value in list of dictionary. This kind of problem can have application in data domains. Lets discuss certain ways in which this task can be performed.
Input : test_list = [{‘gfg’: 9, ‘best’: (7, 2), ‘is’: ‘4’}, {‘is’: ‘2’}]Output : [{‘gfg’: 9, ‘best’: (7, 2), ‘is’: 4}, {‘is’: 2}]
Input : test_list = [{‘is’ : ‘98393’}]Output : [{‘is’ : 98393}]
Method #1 : Using loopThis is brute force way to approach this problem. In this, we iterate for all list elements and dictionary keys and convert the desired dictionary key’s value to required type.
# Python3 code to demonstrate working of # Change type of key in Dictionary list# Using loop # initializing listtest_list = [{'gfg' : 1, 'is' : '56', 'best' : (1, 2)}, {'gfg' : 5, 'is' : '12', 'best' : (6, 2)}, {'gfg' : 3, 'is' : '789', 'best' : (7, 2)}] # printing original listprint("The original list is : " + str(test_list)) # initializing change key chnge_key = 'is' # Change type of key in Dictionary list# Using loopfor sub in test_list: sub[chnge_key] = int(sub[chnge_key]) # printing result print("The converted Dictionary list : " + str(test_list))
The original list is : [{‘is’: ’56’, ‘gfg’: 1, ‘best’: (1, 2)}, {‘is’: ’12’, ‘gfg’: 5, ‘best’: (6, 2)}, {‘is’: ‘789’, ‘gfg’: 3, ‘best’: (7, 2)}]The converted Dictionary list : [{‘is’: 56, ‘gfg’: 1, ‘best’: (1, 2)}, {‘is’: 12, ‘gfg’: 5, ‘best’: (6, 2)}, {‘is’: 789, ‘gfg’: 3, ‘best’: (7, 2)}]
Method #2 : Using list comprehensionThis task can also be performed using list comprehension as a shorthand. In this, we iterate for list in shorter way as above with same approach.
# Python3 code to demonstrate working of # Change type of key in Dictionary list# Using list comprehension # initializing listtest_list = [{'gfg' : 1, 'is' : '56', 'best' : (1, 2)}, {'gfg' : 5, 'is' : '12', 'best' : (6, 2)}, {'gfg' : 3, 'is' : '789', 'best' : (7, 2)}] # printing original listprint("The original list is : " + str(test_list)) # initializing change key chnge_key = 'is' # Change type of key in Dictionary list# Using list comprehensionres = [{key : (int(val) if key == chnge_key else val) for key, val in sub.items()} for sub in test_list] # printing result print("The converted Dictionary list : " + str(res))
The original list is : [{‘is’: ’56’, ‘gfg’: 1, ‘best’: (1, 2)}, {‘is’: ’12’, ‘gfg’: 5, ‘best’: (6, 2)}, {‘is’: ‘789’, ‘gfg’: 3, ‘best’: (7, 2)}]The converted Dictionary list : [{‘is’: 56, ‘gfg’: 1, ‘best’: (1, 2)}, {‘is’: 12, ‘gfg’: 5, ‘best’: (6, 2)}, {‘is’: 789, ‘gfg’: 3, ‘best’: (7, 2)}]
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python? | [
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n10 May, 2020"
},
{
"code": null,
"e": 25805,
"s": 25537,
"text": "Sometimes, while working with data, we can have a problem in which we require to change the type of particular keys’ value in list of dictionary. This kind of problem can have application in data domains. Lets discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 25935,
"s": 25805,
"text": "Input : test_list = [{‘gfg’: 9, ‘best’: (7, 2), ‘is’: ‘4’}, {‘is’: ‘2’}]Output : [{‘gfg’: 9, ‘best’: (7, 2), ‘is’: 4}, {‘is’: 2}]"
},
{
"code": null,
"e": 25999,
"s": 25935,
"text": "Input : test_list = [{‘is’ : ‘98393’}]Output : [{‘is’ : 98393}]"
},
{
"code": null,
"e": 26198,
"s": 25999,
"text": "Method #1 : Using loopThis is brute force way to approach this problem. In this, we iterate for all list elements and dictionary keys and convert the desired dictionary key’s value to required type."
},
{
"code": "# Python3 code to demonstrate working of # Change type of key in Dictionary list# Using loop # initializing listtest_list = [{'gfg' : 1, 'is' : '56', 'best' : (1, 2)}, {'gfg' : 5, 'is' : '12', 'best' : (6, 2)}, {'gfg' : 3, 'is' : '789', 'best' : (7, 2)}] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing change key chnge_key = 'is' # Change type of key in Dictionary list# Using loopfor sub in test_list: sub[chnge_key] = int(sub[chnge_key]) # printing result print(\"The converted Dictionary list : \" + str(test_list)) ",
"e": 26793,
"s": 26198,
"text": null
},
{
"code": null,
"e": 27085,
"s": 26793,
"text": "The original list is : [{‘is’: ’56’, ‘gfg’: 1, ‘best’: (1, 2)}, {‘is’: ’12’, ‘gfg’: 5, ‘best’: (6, 2)}, {‘is’: ‘789’, ‘gfg’: 3, ‘best’: (7, 2)}]The converted Dictionary list : [{‘is’: 56, ‘gfg’: 1, ‘best’: (1, 2)}, {‘is’: 12, ‘gfg’: 5, ‘best’: (6, 2)}, {‘is’: 789, ‘gfg’: 3, ‘best’: (7, 2)}]"
},
{
"code": null,
"e": 27269,
"s": 27087,
"text": "Method #2 : Using list comprehensionThis task can also be performed using list comprehension as a shorthand. In this, we iterate for list in shorter way as above with same approach."
},
{
"code": "# Python3 code to demonstrate working of # Change type of key in Dictionary list# Using list comprehension # initializing listtest_list = [{'gfg' : 1, 'is' : '56', 'best' : (1, 2)}, {'gfg' : 5, 'is' : '12', 'best' : (6, 2)}, {'gfg' : 3, 'is' : '789', 'best' : (7, 2)}] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing change key chnge_key = 'is' # Change type of key in Dictionary list# Using list comprehensionres = [{key : (int(val) if key == chnge_key else val) for key, val in sub.items()} for sub in test_list] # printing result print(\"The converted Dictionary list : \" + str(res)) ",
"e": 27971,
"s": 27269,
"text": null
},
{
"code": null,
"e": 28263,
"s": 27971,
"text": "The original list is : [{‘is’: ’56’, ‘gfg’: 1, ‘best’: (1, 2)}, {‘is’: ’12’, ‘gfg’: 5, ‘best’: (6, 2)}, {‘is’: ‘789’, ‘gfg’: 3, ‘best’: (7, 2)}]The converted Dictionary list : [{‘is’: 56, ‘gfg’: 1, ‘best’: (1, 2)}, {‘is’: 12, ‘gfg’: 5, ‘best’: (6, 2)}, {‘is’: 789, ‘gfg’: 3, ‘best’: (7, 2)}]"
},
{
"code": null,
"e": 28284,
"s": 28263,
"text": "Python list-programs"
},
{
"code": null,
"e": 28291,
"s": 28284,
"text": "Python"
},
{
"code": null,
"e": 28307,
"s": 28291,
"text": "Python Programs"
},
{
"code": null,
"e": 28405,
"s": 28307,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28437,
"s": 28405,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28479,
"s": 28437,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28521,
"s": 28479,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28548,
"s": 28521,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28604,
"s": 28548,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28626,
"s": 28604,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28665,
"s": 28626,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 28711,
"s": 28665,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 28749,
"s": 28711,
"text": "Python | Convert a list to dictionary"
}
]
|
Shortest distance between a Line and a Point in a 3-D plane - GeeksforGeeks | 08 Feb, 2021
Given a line passing through two points A and B and an arbitrary point C in a 3-D plane, the task is to find the shortest distance between the point C and the line passing through the points A and B.Examples:
Input: A = (5, 2, 1), B = (3, 1, -1), C = (0, 2, 3)
Output: Shortest Distance is 5
Input: A = (4, 2, 1), B = (3, 2, 1), C = (0, 2, 0)
Output: Shortest Distance is 1
Consider a point C and a line that passes through A and B as shown in the below figure.
Now Consider the vectors, AB and AC and the shortest distance as CD. The Shortest Distance is always the perpendicular distance. The point D is taken on AB such that CD is perpendicular to AB.
Construct BP and CP as shown in the figure to form a Parallelogram. Now C is a vertex of parallelogram ABPC and CD is perpendicular to Side AB. Hence CD is the height of the parallelogram.
Note: In the case when D does not fall on line segment AB there will be a point D’ such that PD’ is perpendicular to AB and D’ lies on line segment AB with CD = PD’.The magnitude of cross product AB and AC gives the Area of the parallelogram. Also, the area of a parallelogram is Base * Height = AB * CD. So,
CD = |ABxAC| / |AB|
Below is the CPP program to find the shortest distance:
CPP
// C++ program to find the Shortest// Distance Between A line and a// Given point.#include<bits/stdc++.h>using namespace std; class Vector {private: int x, y, z; // 3D Coordinates of the Vector public: Vector(int x, int y, int z) { // Constructor this->x = x; this->y = y; this->z = z; } Vector operator+(Vector v); // ADD 2 Vectors Vector operator-(Vector v); // Subtraction int operator^(Vector v); // Dot Product Vector operator*(Vector v); // Cross Product float magnitude() { return sqrt(pow(x, 2) + pow(y, 2) + pow(z, 2)); } friend ostream& operator<<(ostream& out, const Vector& v); // To output the Vector}; // ADD 2 VectorsVector Vector::operator+(Vector v){ int x1, y1, z1; x1 = x + v.x; y1 = y + v.y; z1 = z + v.z; return Vector(x1, y1, z1);} // Subtract 2 vectorsVector Vector::operator-(Vector v){ int x1, y1, z1; x1 = x - v.x; y1 = y - v.y; z1 = z - v.z; return Vector(x1, y1, z1);} // Dot product of 2 vectorsint Vector::operator^(Vector v){ int x1, y1, z1; x1 = x * v.x; y1 = y * v.y; z1 = z * v.z; return (x1 + y1 + z1);} // Cross product of 2 vectorsVector Vector::operator*(Vector v){ int x1, y1, z1; x1 = y * v.z - z * v.y; y1 = z * v.x - x * v.z; z1 = x * v.y - y * v.x; return Vector(x1, y1, z1);} // Display Vectorostream& operator<<(ostream& out, const Vector& v){ out << v.x << "i "; if (v.y >= 0) out << "+ "; out << v.y << "j "; if (v.z >= 0) out << "+ "; out << v.z << "k" << endl; return out;} // calculate shortest dist. from point to linefloat shortDistance(Vector line_point1, Vector line_point2, Vector point){ Vector AB = line_point2 - line_point1; Vector AC = point - line_point1; float area = Vector(AB * AC).magnitude(); float CD = area / AB.magnitude(); return CD;} // Driver programint main(){ // Taking point C as (2, 2, 2) // Line Passes through A(4, 2, 1) // and B(8, 4, 2). Vector line_point1(4, 2, 1), line_point2(8, 4, 2); Vector point(2, 2, 2); cout << "Shortest Distance is : " << shortDistance(line_point1, line_point2, point); return 0;}
Shortest Distance is : 1.63299
Time Complexity: O(1)
Auxiliary Space: O(1)
ujjwalgoel1103
cpp-class
C++ Programs
Geometric
Mathematical
Mathematical
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C++ Program for QuickSort
Shallow Copy and Deep Copy in C++
cin in C++
Passing a function as a parameter in C++
Generics in C++
Closest Pair of Points using Divide and Conquer algorithm
How to check if a given point lies inside or outside a polygon?
How to check if two given line segments intersect?
Find if two rectangles overlap
Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping) | [
{
"code": null,
"e": 26433,
"s": 26405,
"text": "\n08 Feb, 2021"
},
{
"code": null,
"e": 26643,
"s": 26433,
"text": "Given a line passing through two points A and B and an arbitrary point C in a 3-D plane, the task is to find the shortest distance between the point C and the line passing through the points A and B.Examples: "
},
{
"code": null,
"e": 26809,
"s": 26643,
"text": "Input: A = (5, 2, 1), B = (3, 1, -1), C = (0, 2, 3)\nOutput: Shortest Distance is 5\n\nInput: A = (4, 2, 1), B = (3, 2, 1), C = (0, 2, 0)\nOutput: Shortest Distance is 1"
},
{
"code": null,
"e": 26899,
"s": 26809,
"text": "Consider a point C and a line that passes through A and B as shown in the below figure. "
},
{
"code": null,
"e": 27093,
"s": 26899,
"text": "Now Consider the vectors, AB and AC and the shortest distance as CD. The Shortest Distance is always the perpendicular distance. The point D is taken on AB such that CD is perpendicular to AB. "
},
{
"code": null,
"e": 27282,
"s": 27093,
"text": "Construct BP and CP as shown in the figure to form a Parallelogram. Now C is a vertex of parallelogram ABPC and CD is perpendicular to Side AB. Hence CD is the height of the parallelogram."
},
{
"code": null,
"e": 27592,
"s": 27282,
"text": "Note: In the case when D does not fall on line segment AB there will be a point D’ such that PD’ is perpendicular to AB and D’ lies on line segment AB with CD = PD’.The magnitude of cross product AB and AC gives the Area of the parallelogram. Also, the area of a parallelogram is Base * Height = AB * CD. So, "
},
{
"code": null,
"e": 27612,
"s": 27592,
"text": "CD = |ABxAC| / |AB|"
},
{
"code": null,
"e": 27670,
"s": 27612,
"text": "Below is the CPP program to find the shortest distance: "
},
{
"code": null,
"e": 27674,
"s": 27670,
"text": "CPP"
},
{
"code": "// C++ program to find the Shortest// Distance Between A line and a// Given point.#include<bits/stdc++.h>using namespace std; class Vector {private: int x, y, z; // 3D Coordinates of the Vector public: Vector(int x, int y, int z) { // Constructor this->x = x; this->y = y; this->z = z; } Vector operator+(Vector v); // ADD 2 Vectors Vector operator-(Vector v); // Subtraction int operator^(Vector v); // Dot Product Vector operator*(Vector v); // Cross Product float magnitude() { return sqrt(pow(x, 2) + pow(y, 2) + pow(z, 2)); } friend ostream& operator<<(ostream& out, const Vector& v); // To output the Vector}; // ADD 2 VectorsVector Vector::operator+(Vector v){ int x1, y1, z1; x1 = x + v.x; y1 = y + v.y; z1 = z + v.z; return Vector(x1, y1, z1);} // Subtract 2 vectorsVector Vector::operator-(Vector v){ int x1, y1, z1; x1 = x - v.x; y1 = y - v.y; z1 = z - v.z; return Vector(x1, y1, z1);} // Dot product of 2 vectorsint Vector::operator^(Vector v){ int x1, y1, z1; x1 = x * v.x; y1 = y * v.y; z1 = z * v.z; return (x1 + y1 + z1);} // Cross product of 2 vectorsVector Vector::operator*(Vector v){ int x1, y1, z1; x1 = y * v.z - z * v.y; y1 = z * v.x - x * v.z; z1 = x * v.y - y * v.x; return Vector(x1, y1, z1);} // Display Vectorostream& operator<<(ostream& out, const Vector& v){ out << v.x << \"i \"; if (v.y >= 0) out << \"+ \"; out << v.y << \"j \"; if (v.z >= 0) out << \"+ \"; out << v.z << \"k\" << endl; return out;} // calculate shortest dist. from point to linefloat shortDistance(Vector line_point1, Vector line_point2, Vector point){ Vector AB = line_point2 - line_point1; Vector AC = point - line_point1; float area = Vector(AB * AC).magnitude(); float CD = area / AB.magnitude(); return CD;} // Driver programint main(){ // Taking point C as (2, 2, 2) // Line Passes through A(4, 2, 1) // and B(8, 4, 2). Vector line_point1(4, 2, 1), line_point2(8, 4, 2); Vector point(2, 2, 2); cout << \"Shortest Distance is : \" << shortDistance(line_point1, line_point2, point); return 0;}",
"e": 29912,
"s": 27674,
"text": null
},
{
"code": null,
"e": 29943,
"s": 29912,
"text": "Shortest Distance is : 1.63299"
},
{
"code": null,
"e": 29967,
"s": 29945,
"text": "Time Complexity: O(1)"
},
{
"code": null,
"e": 29989,
"s": 29967,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 30004,
"s": 29989,
"text": "ujjwalgoel1103"
},
{
"code": null,
"e": 30014,
"s": 30004,
"text": "cpp-class"
},
{
"code": null,
"e": 30027,
"s": 30014,
"text": "C++ Programs"
},
{
"code": null,
"e": 30037,
"s": 30027,
"text": "Geometric"
},
{
"code": null,
"e": 30050,
"s": 30037,
"text": "Mathematical"
},
{
"code": null,
"e": 30063,
"s": 30050,
"text": "Mathematical"
},
{
"code": null,
"e": 30073,
"s": 30063,
"text": "Geometric"
},
{
"code": null,
"e": 30171,
"s": 30073,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30197,
"s": 30171,
"text": "C++ Program for QuickSort"
},
{
"code": null,
"e": 30231,
"s": 30197,
"text": "Shallow Copy and Deep Copy in C++"
},
{
"code": null,
"e": 30242,
"s": 30231,
"text": "cin in C++"
},
{
"code": null,
"e": 30283,
"s": 30242,
"text": "Passing a function as a parameter in C++"
},
{
"code": null,
"e": 30299,
"s": 30283,
"text": "Generics in C++"
},
{
"code": null,
"e": 30357,
"s": 30299,
"text": "Closest Pair of Points using Divide and Conquer algorithm"
},
{
"code": null,
"e": 30421,
"s": 30357,
"text": "How to check if a given point lies inside or outside a polygon?"
},
{
"code": null,
"e": 30472,
"s": 30421,
"text": "How to check if two given line segments intersect?"
},
{
"code": null,
"e": 30503,
"s": 30472,
"text": "Find if two rectangles overlap"
}
]
|
Find closest number in array - GeeksforGeeks | 10 Sep, 2021
Given an array of sorted integers. We need to find the closest value to the given number. Array may contain duplicate values and negative numbers.
Examples:
Input : arr[] = {1, 2, 4, 5, 6, 6, 8, 9}
Target number = 11
Output : 9
9 is closest to 11 in given array
Input :arr[] = {2, 5, 6, 7, 8, 8, 9};
Target number = 4
Output : 5
A simple solution is to traverse through the given array and keep track of absolute difference of current element with every element. Finally return the element that has minimum absolution difference.
An efficient solution is to use Binary Search.
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find element// closest to given target.#include <bits/stdc++.h>using namespace std; int getClosest(int, int, int); // Returns element closest to target in arr[]int findClosest(int arr[], int n, int target){ // Corner cases if (target <= arr[0]) return arr[0]; if (target >= arr[n - 1]) return arr[n - 1]; // Doing binary search int i = 0, j = n, mid = 0; while (i < j) { mid = (i + j) / 2; if (arr[mid] == target) return arr[mid]; /* If target is less than array element, then search in left */ if (target < arr[mid]) { // If target is greater than previous // to mid, return closest of two if (mid > 0 && target > arr[mid - 1]) return getClosest(arr[mid - 1], arr[mid], target); /* Repeat for left half */ j = mid; } // If target is greater than mid else { if (mid < n - 1 && target < arr[mid + 1]) return getClosest(arr[mid], arr[mid + 1], target); // update i i = mid + 1; } } // Only single element left after search return arr[mid];} // Method to compare which one is the more close.// We find the closest by taking the difference// between the target and both values. It assumes// that val2 is greater than val1 and target lies// between these two.int getClosest(int val1, int val2, int target){ if (target - val1 >= val2 - target) return val2; else return val1;} // Driver codeint main(){ int arr[] = { 1, 2, 4, 5, 6, 6, 8, 9 }; int n = sizeof(arr) / sizeof(arr[0]); int target = 11; cout << (findClosest(arr, n, target));} // This code is contributed bu Smitha Dinesh Semwal
// Java program to find element closest to given target.import java.util.*;import java.lang.*;import java.io.*; class FindClosestNumber { // Returns element closest to target in arr[] public static int findClosest(int arr[], int target) { int n = arr.length; // Corner cases if (target <= arr[0]) return arr[0]; if (target >= arr[n - 1]) return arr[n - 1]; // Doing binary search int i = 0, j = n, mid = 0; while (i < j) { mid = (i + j) / 2; if (arr[mid] == target) return arr[mid]; /* If target is less than array element, then search in left */ if (target < arr[mid]) { // If target is greater than previous // to mid, return closest of two if (mid > 0 && target > arr[mid - 1]) return getClosest(arr[mid - 1], arr[mid], target); /* Repeat for left half */ j = mid; } // If target is greater than mid else { if (mid < n-1 && target < arr[mid + 1]) return getClosest(arr[mid], arr[mid + 1], target); i = mid + 1; // update i } } // Only single element left after search return arr[mid]; } // Method to compare which one is the more close // We find the closest by taking the difference // between the target and both values. It assumes // that val2 is greater than val1 and target lies // between these two. public static int getClosest(int val1, int val2, int target) { if (target - val1 >= val2 - target) return val2; else return val1; } // Driver code public static void main(String[] args) { int arr[] = { 1, 2, 4, 5, 6, 6, 8, 9 }; int target = 11; System.out.println(findClosest(arr, target)); }}
# Python3 program to find element# closest to given target. # Returns element closest to target in arr[]def findClosest(arr, n, target): # Corner cases if (target <= arr[0]): return arr[0] if (target >= arr[n - 1]): return arr[n - 1] # Doing binary search i = 0; j = n; mid = 0 while (i < j): mid = (i + j) // 2 if (arr[mid] == target): return arr[mid] # If target is less than array # element, then search in left if (target < arr[mid]) : # If target is greater than previous # to mid, return closest of two if (mid > 0 and target > arr[mid - 1]): return getClosest(arr[mid - 1], arr[mid], target) # Repeat for left half j = mid # If target is greater than mid else : if (mid < n - 1 and target < arr[mid + 1]): return getClosest(arr[mid], arr[mid + 1], target) # update i i = mid + 1 # Only single element left after search return arr[mid] # Method to compare which one is the more close.# We find the closest by taking the difference# between the target and both values. It assumes# that val2 is greater than val1 and target lies# between these two.def getClosest(val1, val2, target): if (target - val1 >= val2 - target): return val2 else: return val1 # Driver codearr = [1, 2, 4, 5, 6, 6, 8, 9]n = len(arr)target = 11print(findClosest(arr, n, target)) # This code is contributed by Smitha Dinesh Semwal
// C# program to find element// closest to given target.using System; class GFG{ // Returns element closest // to target in arr[] public static int findClosest(int []arr, int target) { int n = arr.Length; // Corner cases if (target <= arr[0]) return arr[0]; if (target >= arr[n - 1]) return arr[n - 1]; // Doing binary search int i = 0, j = n, mid = 0; while (i < j) { mid = (i + j) / 2; if (arr[mid] == target) return arr[mid]; /* If target is less than array element, then search in left */ if (target < arr[mid]) { // If target is greater // than previous to mid, // return closest of two if (mid > 0 && target > arr[mid - 1]) return getClosest(arr[mid - 1], arr[mid], target); /* Repeat for left half */ j = mid; } // If target is // greater than mid else { if (mid < n-1 && target < arr[mid + 1]) return getClosest(arr[mid], arr[mid + 1], target); i = mid + 1; // update i } } // Only single element // left after search return arr[mid]; } // Method to compare which one // is the more close We find the // closest by taking the difference // between the target and both // values. It assumes that val2 is // greater than val1 and target // lies between these two. public static int getClosest(int val1, int val2, int target) { if (target - val1 >= val2 - target) return val2; else return val1; } // Driver code public static void Main() { int []arr = {1, 2, 4, 5, 6, 6, 8, 9}; int target = 11; Console.WriteLine(findClosest(arr, target)); }} // This code is contributed by anuj_67.
<?php// PHP program to find element closest// to given target. // Returns element closest to target in arr[]function findClosest($arr, $n, $target){ // Corner cases if ($target <= $arr[0]) return $arr[0]; if ($target >= $arr[$n - 1]) return $arr[$n - 1]; // Doing binary search $i = 0; $j = $n; $mid = 0; while ($i < $j) { $mid = ($i + $j) / 2; if ($arr[$mid] == $target) return $arr[$mid]; /* If target is less than array element, then search in left */ if ($target < $arr[$mid]) { // If target is greater than previous // to mid, return closest of two if ($mid > 0 && $target > $arr[$mid - 1]) return getClosest($arr[$mid - 1], $arr[$mid], $target); /* Repeat for left half */ $j = $mid; } // If target is greater than mid else { if ($mid < $n - 1 && $target < $arr[$mid + 1]) return getClosest($arr[$mid], $arr[$mid + 1], $target); // update i $i = $mid + 1; } } // Only single element left after search return $arr[$mid];} // Method to compare which one is the more close.// We find the closest by taking the difference// between the target and both values. It assumes// that val2 is greater than val1 and target lies// between these two.function getClosest($val1, $val2, $target){ if ($target - $val1 >= $val2 - $target) return $val2; else return $val1;} // Driver code$arr = array( 1, 2, 4, 5, 6, 6, 8, 9 );$n = sizeof($arr);$target = 11;echo (findClosest($arr, $n, $target)); // This code is contributed bu Sachin.?>
<script> // JavaScript program to find element// closest to given target. // Returns element closest to target in arr[]function findClosest(arr, target){ let n = arr.length; // Corner cases if (target <= arr[0]) return arr[0]; if (target >= arr[n - 1]) return arr[n - 1]; // Doing binary search let i = 0, j = n, mid = 0; while (i < j) { mid = (i + j) / 2; if (arr[mid] == target) return arr[mid]; // If target is less than array // element,then search in left if (target < arr[mid]) { // If target is greater than previous // to mid, return closest of two if (mid > 0 && target > arr[mid - 1]) return getClosest(arr[mid - 1], arr[mid], target); // Repeat for left half j = mid; } // If target is greater than mid else { if (mid < n - 1 && target < arr[mid + 1]) return getClosest(arr[mid], arr[mid + 1], target); i = mid + 1; // update i } } // Only single element left after search return arr[mid];} // Method to compare which one is the more close// We find the closest by taking the difference// between the target and both values. It assumes// that val2 is greater than val1 and target lies// between these two.function getClosest(val1, val2, target){ if (target - val1 >= val2 - target) return val2; else return val1; } // Driver Codelet arr = [ 1, 2, 4, 5, 6, 6, 8, 9 ];let target = 11; document.write(findClosest(arr, target)); // This code is contributed by code_hunt </script>
Output:
9
harishkumar88
vt_m
Sach_Code
code_hunt
mahee96
arorakashish0911
Binary Search
Arrays
Divide and Conquer
Searching
Arrays
Searching
Divide and Conquer
Binary Search
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Arrays
Multidimensional Arrays in Java
Linked List vs Array
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Python | Using 2D arrays/lists the right way
Merge Sort
QuickSort
Program for Tower of Hanoi
Count Inversions in an array | Set 1 (Using Merge Sort)
Divide and Conquer Algorithm | Introduction | [
{
"code": null,
"e": 25503,
"s": 25475,
"text": "\n10 Sep, 2021"
},
{
"code": null,
"e": 25651,
"s": 25503,
"text": "Given an array of sorted integers. We need to find the closest value to the given number. Array may contain duplicate values and negative numbers. "
},
{
"code": null,
"e": 25663,
"s": 25651,
"text": "Examples: "
},
{
"code": null,
"e": 25857,
"s": 25663,
"text": "Input : arr[] = {1, 2, 4, 5, 6, 6, 8, 9}\n Target number = 11\nOutput : 9\n9 is closest to 11 in given array\n\nInput :arr[] = {2, 5, 6, 7, 8, 8, 9}; \n Target number = 4\nOutput : 5"
},
{
"code": null,
"e": 26058,
"s": 25857,
"text": "A simple solution is to traverse through the given array and keep track of absolute difference of current element with every element. Finally return the element that has minimum absolution difference."
},
{
"code": null,
"e": 26107,
"s": 26058,
"text": "An efficient solution is to use Binary Search. "
},
{
"code": null,
"e": 26111,
"s": 26107,
"text": "C++"
},
{
"code": null,
"e": 26116,
"s": 26111,
"text": "Java"
},
{
"code": null,
"e": 26124,
"s": 26116,
"text": "Python3"
},
{
"code": null,
"e": 26127,
"s": 26124,
"text": "C#"
},
{
"code": null,
"e": 26131,
"s": 26127,
"text": "PHP"
},
{
"code": null,
"e": 26142,
"s": 26131,
"text": "Javascript"
},
{
"code": "// CPP program to find element// closest to given target.#include <bits/stdc++.h>using namespace std; int getClosest(int, int, int); // Returns element closest to target in arr[]int findClosest(int arr[], int n, int target){ // Corner cases if (target <= arr[0]) return arr[0]; if (target >= arr[n - 1]) return arr[n - 1]; // Doing binary search int i = 0, j = n, mid = 0; while (i < j) { mid = (i + j) / 2; if (arr[mid] == target) return arr[mid]; /* If target is less than array element, then search in left */ if (target < arr[mid]) { // If target is greater than previous // to mid, return closest of two if (mid > 0 && target > arr[mid - 1]) return getClosest(arr[mid - 1], arr[mid], target); /* Repeat for left half */ j = mid; } // If target is greater than mid else { if (mid < n - 1 && target < arr[mid + 1]) return getClosest(arr[mid], arr[mid + 1], target); // update i i = mid + 1; } } // Only single element left after search return arr[mid];} // Method to compare which one is the more close.// We find the closest by taking the difference// between the target and both values. It assumes// that val2 is greater than val1 and target lies// between these two.int getClosest(int val1, int val2, int target){ if (target - val1 >= val2 - target) return val2; else return val1;} // Driver codeint main(){ int arr[] = { 1, 2, 4, 5, 6, 6, 8, 9 }; int n = sizeof(arr) / sizeof(arr[0]); int target = 11; cout << (findClosest(arr, n, target));} // This code is contributed bu Smitha Dinesh Semwal",
"e": 27999,
"s": 26142,
"text": null
},
{
"code": "// Java program to find element closest to given target.import java.util.*;import java.lang.*;import java.io.*; class FindClosestNumber { // Returns element closest to target in arr[] public static int findClosest(int arr[], int target) { int n = arr.length; // Corner cases if (target <= arr[0]) return arr[0]; if (target >= arr[n - 1]) return arr[n - 1]; // Doing binary search int i = 0, j = n, mid = 0; while (i < j) { mid = (i + j) / 2; if (arr[mid] == target) return arr[mid]; /* If target is less than array element, then search in left */ if (target < arr[mid]) { // If target is greater than previous // to mid, return closest of two if (mid > 0 && target > arr[mid - 1]) return getClosest(arr[mid - 1], arr[mid], target); /* Repeat for left half */ j = mid; } // If target is greater than mid else { if (mid < n-1 && target < arr[mid + 1]) return getClosest(arr[mid], arr[mid + 1], target); i = mid + 1; // update i } } // Only single element left after search return arr[mid]; } // Method to compare which one is the more close // We find the closest by taking the difference // between the target and both values. It assumes // that val2 is greater than val1 and target lies // between these two. public static int getClosest(int val1, int val2, int target) { if (target - val1 >= val2 - target) return val2; else return val1; } // Driver code public static void main(String[] args) { int arr[] = { 1, 2, 4, 5, 6, 6, 8, 9 }; int target = 11; System.out.println(findClosest(arr, target)); }}",
"e": 30138,
"s": 27999,
"text": null
},
{
"code": "# Python3 program to find element# closest to given target. # Returns element closest to target in arr[]def findClosest(arr, n, target): # Corner cases if (target <= arr[0]): return arr[0] if (target >= arr[n - 1]): return arr[n - 1] # Doing binary search i = 0; j = n; mid = 0 while (i < j): mid = (i + j) // 2 if (arr[mid] == target): return arr[mid] # If target is less than array # element, then search in left if (target < arr[mid]) : # If target is greater than previous # to mid, return closest of two if (mid > 0 and target > arr[mid - 1]): return getClosest(arr[mid - 1], arr[mid], target) # Repeat for left half j = mid # If target is greater than mid else : if (mid < n - 1 and target < arr[mid + 1]): return getClosest(arr[mid], arr[mid + 1], target) # update i i = mid + 1 # Only single element left after search return arr[mid] # Method to compare which one is the more close.# We find the closest by taking the difference# between the target and both values. It assumes# that val2 is greater than val1 and target lies# between these two.def getClosest(val1, val2, target): if (target - val1 >= val2 - target): return val2 else: return val1 # Driver codearr = [1, 2, 4, 5, 6, 6, 8, 9]n = len(arr)target = 11print(findClosest(arr, n, target)) # This code is contributed by Smitha Dinesh Semwal",
"e": 31724,
"s": 30138,
"text": null
},
{
"code": "// C# program to find element// closest to given target.using System; class GFG{ // Returns element closest // to target in arr[] public static int findClosest(int []arr, int target) { int n = arr.Length; // Corner cases if (target <= arr[0]) return arr[0]; if (target >= arr[n - 1]) return arr[n - 1]; // Doing binary search int i = 0, j = n, mid = 0; while (i < j) { mid = (i + j) / 2; if (arr[mid] == target) return arr[mid]; /* If target is less than array element, then search in left */ if (target < arr[mid]) { // If target is greater // than previous to mid, // return closest of two if (mid > 0 && target > arr[mid - 1]) return getClosest(arr[mid - 1], arr[mid], target); /* Repeat for left half */ j = mid; } // If target is // greater than mid else { if (mid < n-1 && target < arr[mid + 1]) return getClosest(arr[mid], arr[mid + 1], target); i = mid + 1; // update i } } // Only single element // left after search return arr[mid]; } // Method to compare which one // is the more close We find the // closest by taking the difference // between the target and both // values. It assumes that val2 is // greater than val1 and target // lies between these two. public static int getClosest(int val1, int val2, int target) { if (target - val1 >= val2 - target) return val2; else return val1; } // Driver code public static void Main() { int []arr = {1, 2, 4, 5, 6, 6, 8, 9}; int target = 11; Console.WriteLine(findClosest(arr, target)); }} // This code is contributed by anuj_67.",
"e": 33956,
"s": 31724,
"text": null
},
{
"code": "<?php// PHP program to find element closest// to given target. // Returns element closest to target in arr[]function findClosest($arr, $n, $target){ // Corner cases if ($target <= $arr[0]) return $arr[0]; if ($target >= $arr[$n - 1]) return $arr[$n - 1]; // Doing binary search $i = 0; $j = $n; $mid = 0; while ($i < $j) { $mid = ($i + $j) / 2; if ($arr[$mid] == $target) return $arr[$mid]; /* If target is less than array element, then search in left */ if ($target < $arr[$mid]) { // If target is greater than previous // to mid, return closest of two if ($mid > 0 && $target > $arr[$mid - 1]) return getClosest($arr[$mid - 1], $arr[$mid], $target); /* Repeat for left half */ $j = $mid; } // If target is greater than mid else { if ($mid < $n - 1 && $target < $arr[$mid + 1]) return getClosest($arr[$mid], $arr[$mid + 1], $target); // update i $i = $mid + 1; } } // Only single element left after search return $arr[$mid];} // Method to compare which one is the more close.// We find the closest by taking the difference// between the target and both values. It assumes// that val2 is greater than val1 and target lies// between these two.function getClosest($val1, $val2, $target){ if ($target - $val1 >= $val2 - $target) return $val2; else return $val1;} // Driver code$arr = array( 1, 2, 4, 5, 6, 6, 8, 9 );$n = sizeof($arr);$target = 11;echo (findClosest($arr, $n, $target)); // This code is contributed bu Sachin.?>",
"e": 35748,
"s": 33956,
"text": null
},
{
"code": "<script> // JavaScript program to find element// closest to given target. // Returns element closest to target in arr[]function findClosest(arr, target){ let n = arr.length; // Corner cases if (target <= arr[0]) return arr[0]; if (target >= arr[n - 1]) return arr[n - 1]; // Doing binary search let i = 0, j = n, mid = 0; while (i < j) { mid = (i + j) / 2; if (arr[mid] == target) return arr[mid]; // If target is less than array // element,then search in left if (target < arr[mid]) { // If target is greater than previous // to mid, return closest of two if (mid > 0 && target > arr[mid - 1]) return getClosest(arr[mid - 1], arr[mid], target); // Repeat for left half j = mid; } // If target is greater than mid else { if (mid < n - 1 && target < arr[mid + 1]) return getClosest(arr[mid], arr[mid + 1], target); i = mid + 1; // update i } } // Only single element left after search return arr[mid];} // Method to compare which one is the more close// We find the closest by taking the difference// between the target and both values. It assumes// that val2 is greater than val1 and target lies// between these two.function getClosest(val1, val2, target){ if (target - val1 >= val2 - target) return val2; else return val1; } // Driver Codelet arr = [ 1, 2, 4, 5, 6, 6, 8, 9 ];let target = 11; document.write(findClosest(arr, target)); // This code is contributed by code_hunt </script>",
"e": 37565,
"s": 35748,
"text": null
},
{
"code": null,
"e": 37574,
"s": 37565,
"text": "Output: "
},
{
"code": null,
"e": 37576,
"s": 37574,
"text": "9"
},
{
"code": null,
"e": 37592,
"s": 37578,
"text": "harishkumar88"
},
{
"code": null,
"e": 37597,
"s": 37592,
"text": "vt_m"
},
{
"code": null,
"e": 37607,
"s": 37597,
"text": "Sach_Code"
},
{
"code": null,
"e": 37617,
"s": 37607,
"text": "code_hunt"
},
{
"code": null,
"e": 37625,
"s": 37617,
"text": "mahee96"
},
{
"code": null,
"e": 37642,
"s": 37625,
"text": "arorakashish0911"
},
{
"code": null,
"e": 37656,
"s": 37642,
"text": "Binary Search"
},
{
"code": null,
"e": 37663,
"s": 37656,
"text": "Arrays"
},
{
"code": null,
"e": 37682,
"s": 37663,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 37692,
"s": 37682,
"text": "Searching"
},
{
"code": null,
"e": 37699,
"s": 37692,
"text": "Arrays"
},
{
"code": null,
"e": 37709,
"s": 37699,
"text": "Searching"
},
{
"code": null,
"e": 37728,
"s": 37709,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 37742,
"s": 37728,
"text": "Binary Search"
},
{
"code": null,
"e": 37840,
"s": 37742,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37863,
"s": 37840,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 37895,
"s": 37863,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 37916,
"s": 37895,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 38001,
"s": 37916,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 38046,
"s": 38001,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 38057,
"s": 38046,
"text": "Merge Sort"
},
{
"code": null,
"e": 38067,
"s": 38057,
"text": "QuickSort"
},
{
"code": null,
"e": 38094,
"s": 38067,
"text": "Program for Tower of Hanoi"
},
{
"code": null,
"e": 38150,
"s": 38094,
"text": "Count Inversions in an array | Set 1 (Using Merge Sort)"
}
]
|
Python Program to check if given array is Monotonic - GeeksforGeeks | 05 Nov, 2018
Given an array A containing n integers. The task is to check whether the array is Monotonic or not. An array is monotonic if it is either monotone increasing or monotone decreasing.An array A is monotone increasing if for all i <= j, A[i] <= A[j]. An array A is monotone decreasing if for all i <= j, A[i] >= A[j].Return “True” if the given array A is monotonic else return “False” (without quotes).
Examples:
Input : 6 5 4 4
Output : true
Input : 5 15 20 10
Output : false
Approach:An array is monotonic if and only if it is monotone increasing, or monotone decreasing. Since p <= q and q <= r implies p <= r. So we only need to check adjacent elements to determine if the array is monotone increasing (or decreasing), respectively. We can check each of these properties in one pass.To check whether an array A is monotone increasing, we’ll check A[i] <= A[i+1] for all i indexing from 0 to len(A)-2. Similarly we can check for monotone decreasing where A[i] >= A[i+1] for all i indexing from 0 to len(A)-2.Note: Array with single element can be considered to be both monotonic increasing or decreasing, hence returns “True“.
Below is the implementation of above approach:
Python3
# Python3 program to find sum in Nth group # Check if given array is Monotonicdef isMonotonic(A): return (all(A[i] <= A[i + 1] for i in range(len(A) - 1)) or all(A[i] >= A[i + 1] for i in range(len(A) - 1))) # Driver programA = [6, 5, 4, 4] # Print required resultprint(isMonotonic(A)) # This code is written by# Sanjit_Prasad
True
Time Complexity: O(N), where N is the length of array.
Arrays
Greedy
Python Programs
Arrays
Greedy
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Arrays
Multidimensional Arrays in Java
Linked List vs Array
Python | Using 2D arrays/lists the right way
Search an element in a sorted and rotated array
Dijkstra's shortest path algorithm | Greedy Algo-7
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Write a program to print all permutations of a given string
Huffman Coding | Greedy Algo-3 | [
{
"code": null,
"e": 26497,
"s": 26469,
"text": "\n05 Nov, 2018"
},
{
"code": null,
"e": 26897,
"s": 26497,
"text": "Given an array A containing n integers. The task is to check whether the array is Monotonic or not. An array is monotonic if it is either monotone increasing or monotone decreasing.An array A is monotone increasing if for all i <= j, A[i] <= A[j]. An array A is monotone decreasing if for all i <= j, A[i] >= A[j].Return “True” if the given array A is monotonic else return “False” (without quotes)."
},
{
"code": null,
"e": 26907,
"s": 26897,
"text": "Examples:"
},
{
"code": null,
"e": 26973,
"s": 26907,
"text": "Input : 6 5 4 4\nOutput : true\n\nInput : 5 15 20 10\nOutput : false\n"
},
{
"code": null,
"e": 27626,
"s": 26973,
"text": "Approach:An array is monotonic if and only if it is monotone increasing, or monotone decreasing. Since p <= q and q <= r implies p <= r. So we only need to check adjacent elements to determine if the array is monotone increasing (or decreasing), respectively. We can check each of these properties in one pass.To check whether an array A is monotone increasing, we’ll check A[i] <= A[i+1] for all i indexing from 0 to len(A)-2. Similarly we can check for monotone decreasing where A[i] >= A[i+1] for all i indexing from 0 to len(A)-2.Note: Array with single element can be considered to be both monotonic increasing or decreasing, hence returns “True“."
},
{
"code": null,
"e": 27673,
"s": 27626,
"text": "Below is the implementation of above approach:"
},
{
"code": null,
"e": 27681,
"s": 27673,
"text": "Python3"
},
{
"code": "# Python3 program to find sum in Nth group # Check if given array is Monotonicdef isMonotonic(A): return (all(A[i] <= A[i + 1] for i in range(len(A) - 1)) or all(A[i] >= A[i + 1] for i in range(len(A) - 1))) # Driver programA = [6, 5, 4, 4] # Print required resultprint(isMonotonic(A)) # This code is written by# Sanjit_Prasad",
"e": 28028,
"s": 27681,
"text": null
},
{
"code": null,
"e": 28033,
"s": 28028,
"text": "True"
},
{
"code": null,
"e": 28088,
"s": 28033,
"text": "Time Complexity: O(N), where N is the length of array."
},
{
"code": null,
"e": 28095,
"s": 28088,
"text": "Arrays"
},
{
"code": null,
"e": 28102,
"s": 28095,
"text": "Greedy"
},
{
"code": null,
"e": 28118,
"s": 28102,
"text": "Python Programs"
},
{
"code": null,
"e": 28125,
"s": 28118,
"text": "Arrays"
},
{
"code": null,
"e": 28132,
"s": 28125,
"text": "Greedy"
},
{
"code": null,
"e": 28230,
"s": 28132,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28253,
"s": 28230,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 28285,
"s": 28253,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 28306,
"s": 28285,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 28351,
"s": 28306,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 28399,
"s": 28351,
"text": "Search an element in a sorted and rotated array"
},
{
"code": null,
"e": 28450,
"s": 28399,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 28508,
"s": 28450,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
},
{
"code": null,
"e": 28559,
"s": 28508,
"text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5"
},
{
"code": null,
"e": 28619,
"s": 28559,
"text": "Write a program to print all permutations of a given string"
}
]
|
Difference between Normal Processor and AI Processor - GeeksforGeeks | 17 Jul, 2020
Normal Processor :The processors mainly used in several personal computers are normal processors. Basically the central processing unit is described as a processor of the system. It uses integrated chips to organize all the components at a single place. Different brands provide different load based processors for computer systems and mobile systems. The processors are designed on the basis of versions and generations.Example:
Intel i5, AMD A8
AI processor :The processors used in artificial intelligence and machine learning-based systems are known as AI processors. These are basically the neuromorphic processing units which are designed on the basis of machine learning and artificial neural network. These processors are fast and able to read the human behavioural conditions and do computation the on basis of it.Example:
Intel Habana
Difference between Normal Processor and AI processor :
Computer Organization & Architecture
Difference Between
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Direct Access Media (DMA) Controller in Computer Architecture
Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard)
Architecture of 8085 microprocessor
Architecture of 8086
Pin diagram of 8086 microprocessor
Difference between BFS and DFS
Class method vs Static method in Python
Differences between TCP and UDP
Difference between var, let and const keywords in JavaScript
Differences between IPv4 and IPv6 | [
{
"code": null,
"e": 26101,
"s": 26073,
"text": "\n17 Jul, 2020"
},
{
"code": null,
"e": 26531,
"s": 26101,
"text": "Normal Processor :The processors mainly used in several personal computers are normal processors. Basically the central processing unit is described as a processor of the system. It uses integrated chips to organize all the components at a single place. Different brands provide different load based processors for computer systems and mobile systems. The processors are designed on the basis of versions and generations.Example:"
},
{
"code": null,
"e": 26548,
"s": 26531,
"text": "Intel i5, AMD A8"
},
{
"code": null,
"e": 26932,
"s": 26548,
"text": "AI processor :The processors used in artificial intelligence and machine learning-based systems are known as AI processors. These are basically the neuromorphic processing units which are designed on the basis of machine learning and artificial neural network. These processors are fast and able to read the human behavioural conditions and do computation the on basis of it.Example:"
},
{
"code": null,
"e": 26945,
"s": 26932,
"text": "Intel Habana"
},
{
"code": null,
"e": 27000,
"s": 26945,
"text": "Difference between Normal Processor and AI processor :"
},
{
"code": null,
"e": 27037,
"s": 27000,
"text": "Computer Organization & Architecture"
},
{
"code": null,
"e": 27056,
"s": 27037,
"text": "Difference Between"
},
{
"code": null,
"e": 27154,
"s": 27056,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27216,
"s": 27154,
"text": "Direct Access Media (DMA) Controller in Computer Architecture"
},
{
"code": null,
"e": 27307,
"s": 27216,
"text": "Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard)"
},
{
"code": null,
"e": 27343,
"s": 27307,
"text": "Architecture of 8085 microprocessor"
},
{
"code": null,
"e": 27364,
"s": 27343,
"text": "Architecture of 8086"
},
{
"code": null,
"e": 27399,
"s": 27364,
"text": "Pin diagram of 8086 microprocessor"
},
{
"code": null,
"e": 27430,
"s": 27399,
"text": "Difference between BFS and DFS"
},
{
"code": null,
"e": 27470,
"s": 27430,
"text": "Class method vs Static method in Python"
},
{
"code": null,
"e": 27502,
"s": 27470,
"text": "Differences between TCP and UDP"
},
{
"code": null,
"e": 27563,
"s": 27502,
"text": "Difference between var, let and const keywords in JavaScript"
}
]
|
CONCAT_WS() Function in MySQL - GeeksforGeeks | 03 Dec, 2020
CONCAT_WS() :This function in MySQL helps in joining two or more strings along with a separator. The separator must be specified by the user and it can also be a string. If the separator is NULL, then the result will also be NULL.
Syntax :
CONCAT_WS(separator, string1, string2, ...)
Parameters :
separator –A separator which will be added between the strings while concatenation string1, string2, etc.
[string1, string2 ...] –The input strings which needed to be concatenated.
Return :It will return a new string, after concatenating all given strings, along with a specified separator. And if all input strings are NULL, then the result will be NULL. If the separator is NULL, it will return NULL.
Example 1 :Concatenating 2 strings using CONCAT_WS Function as follows.
SELECT CONCAT_WS(": ", "Geek ", "Vansh ") AS ConcatWsStr;
Output :
Example-2 :Concatenating 3 strings using CONCAT_WS Function as follows.
SELECT CONCAT_WS("@ ", "Geek ", "Vansh ", 13 ) AS ConcatWsStr;
Output :
Example-3 :Concatenating a NULL string using NULL separator as follows.
SELECT CONCAT_WS(NULL, NULL, "Vansh ", 13 ) AS ConcatWsStr;
Output :
Example-4 :Concatenating the columns of a table using CONCAT_WS Function as follows.
Creating an Employee table :
CREATE TABLE Emp(
Employee_Id INT AUTO_INCREMENT,
FirstName VARCHAR(100) NOT NULL,
LastName VARCHAR(100) NOT NULL,
Residence VARCHAR(50) NOT NULL,
Salary INT NOT NULL,
PRIMARY KEY(Employee_Id )
);
Inserting data into the Table :
INSERT INTO Emp(FirstName, LastName, Residence, Salary )
VALUES
('Animesh', 'Garg', 'Delhi', 70000 ),
('Neshu', 'Sharma', 'Nepal', 73000 ),
('Aryan', 'Sharma', 'WestBengal', 72000 ),
('Abdul', 'Ali', 'Delhi', 73000 ),
('Seema', 'Sharma', 'Bihar', 70000 ) ;
To verify used the following command as follows.
Select * From Emp;
Output :
Now, concatenate FirstName and LastName of given Emp table using ‘_’ as a separator to form a new column as FullName.
SELECT CONCAT_WS('_', FirstName, LastName) AS FullName
From Emp;
Output :
DBMS-SQL
mysql
Technical Scripter 2020
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Update Multiple Columns in Single Update Statement in SQL?
How to Alter Multiple Columns at Once in SQL Server?
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
SQL | Subquery
SQL Query to Convert VARCHAR to INT
SQL | Date functions
SQL - SELECT from Multiple Tables with MS SQL Server
SQL Query to Insert Multiple Rows | [
{
"code": null,
"e": 24268,
"s": 24240,
"text": "\n03 Dec, 2020"
},
{
"code": null,
"e": 24499,
"s": 24268,
"text": "CONCAT_WS() :This function in MySQL helps in joining two or more strings along with a separator. The separator must be specified by the user and it can also be a string. If the separator is NULL, then the result will also be NULL."
},
{
"code": null,
"e": 24508,
"s": 24499,
"text": "Syntax :"
},
{
"code": null,
"e": 24552,
"s": 24508,
"text": "CONCAT_WS(separator, string1, string2, ...)"
},
{
"code": null,
"e": 24565,
"s": 24552,
"text": "Parameters :"
},
{
"code": null,
"e": 24671,
"s": 24565,
"text": "separator –A separator which will be added between the strings while concatenation string1, string2, etc."
},
{
"code": null,
"e": 24746,
"s": 24671,
"text": "[string1, string2 ...] –The input strings which needed to be concatenated."
},
{
"code": null,
"e": 24968,
"s": 24746,
"text": "Return :It will return a new string, after concatenating all given strings, along with a specified separator. And if all input strings are NULL, then the result will be NULL. If the separator is NULL, it will return NULL."
},
{
"code": null,
"e": 25040,
"s": 24968,
"text": "Example 1 :Concatenating 2 strings using CONCAT_WS Function as follows."
},
{
"code": null,
"e": 25098,
"s": 25040,
"text": "SELECT CONCAT_WS(\": \", \"Geek \", \"Vansh \") AS ConcatWsStr;"
},
{
"code": null,
"e": 25107,
"s": 25098,
"text": "Output :"
},
{
"code": null,
"e": 25179,
"s": 25107,
"text": "Example-2 :Concatenating 3 strings using CONCAT_WS Function as follows."
},
{
"code": null,
"e": 25242,
"s": 25179,
"text": "SELECT CONCAT_WS(\"@ \", \"Geek \", \"Vansh \", 13 ) AS ConcatWsStr;"
},
{
"code": null,
"e": 25251,
"s": 25242,
"text": "Output :"
},
{
"code": null,
"e": 25323,
"s": 25251,
"text": "Example-3 :Concatenating a NULL string using NULL separator as follows."
},
{
"code": null,
"e": 25383,
"s": 25323,
"text": "SELECT CONCAT_WS(NULL, NULL, \"Vansh \", 13 ) AS ConcatWsStr;"
},
{
"code": null,
"e": 25392,
"s": 25383,
"text": "Output :"
},
{
"code": null,
"e": 25477,
"s": 25392,
"text": "Example-4 :Concatenating the columns of a table using CONCAT_WS Function as follows."
},
{
"code": null,
"e": 25506,
"s": 25477,
"text": "Creating an Employee table :"
},
{
"code": null,
"e": 25707,
"s": 25506,
"text": "CREATE TABLE Emp(\nEmployee_Id INT AUTO_INCREMENT, \nFirstName VARCHAR(100) NOT NULL,\nLastName VARCHAR(100) NOT NULL,\nResidence VARCHAR(50) NOT NULL,\nSalary INT NOT NULL,\nPRIMARY KEY(Employee_Id )\n);\n"
},
{
"code": null,
"e": 25739,
"s": 25707,
"text": "Inserting data into the Table :"
},
{
"code": null,
"e": 25996,
"s": 25739,
"text": "INSERT INTO Emp(FirstName, LastName, Residence, Salary )\nVALUES\n('Animesh', 'Garg', 'Delhi', 70000 ),\n('Neshu', 'Sharma', 'Nepal', 73000 ),\n('Aryan', 'Sharma', 'WestBengal', 72000 ),\n('Abdul', 'Ali', 'Delhi', 73000 ),\n('Seema', 'Sharma', 'Bihar', 70000 ) ;"
},
{
"code": null,
"e": 26045,
"s": 25996,
"text": "To verify used the following command as follows."
},
{
"code": null,
"e": 26064,
"s": 26045,
"text": "Select * From Emp;"
},
{
"code": null,
"e": 26073,
"s": 26064,
"text": "Output :"
},
{
"code": null,
"e": 26191,
"s": 26073,
"text": "Now, concatenate FirstName and LastName of given Emp table using ‘_’ as a separator to form a new column as FullName."
},
{
"code": null,
"e": 26259,
"s": 26191,
"text": "SELECT CONCAT_WS('_', FirstName, LastName) AS FullName\nFrom Emp; "
},
{
"code": null,
"e": 26268,
"s": 26259,
"text": "Output :"
},
{
"code": null,
"e": 26277,
"s": 26268,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 26283,
"s": 26277,
"text": "mysql"
},
{
"code": null,
"e": 26307,
"s": 26283,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 26311,
"s": 26307,
"text": "SQL"
},
{
"code": null,
"e": 26315,
"s": 26311,
"text": "SQL"
},
{
"code": null,
"e": 26413,
"s": 26315,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26422,
"s": 26413,
"text": "Comments"
},
{
"code": null,
"e": 26435,
"s": 26422,
"text": "Old Comments"
},
{
"code": null,
"e": 26501,
"s": 26435,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 26554,
"s": 26501,
"text": "How to Alter Multiple Columns at Once in SQL Server?"
},
{
"code": null,
"e": 26586,
"s": 26554,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 26664,
"s": 26586,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 26681,
"s": 26664,
"text": "SQL using Python"
},
{
"code": null,
"e": 26696,
"s": 26681,
"text": "SQL | Subquery"
},
{
"code": null,
"e": 26732,
"s": 26696,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 26753,
"s": 26732,
"text": "SQL | Date functions"
},
{
"code": null,
"e": 26806,
"s": 26753,
"text": "SQL - SELECT from Multiple Tables with MS SQL Server"
}
]
|
Creating custom plotting functions with matplotlib | by Matias Calderini | Towards Data Science | TLDR: Define your own functions that involve plotting onto a specific axes with the following syntax:
def custom_plot(x, y, ax=None, **plt_kwargs): if ax is None: ax = plt.gca() ax.plot(x, y, **plt_kwargs) ## example plot here return(ax)def multiple_custom_plots(x, y, ax=None, plt_kwargs={}, sct_kwargs={}): if ax is None: ax = plt.gca() ax.plot(x, y, **plt_kwargs) #example plot1 ax.scatter(x, y, **sct_kwargs) #example plot2 return(ax)
You can find the original code repository at this link.
In a previous post, I showed you how to better organize your figures. We saw how you could neatly display your different plots using subplots, how to add free-floating axes and how to easily create a tiled organization of your axes with GridSpec.
Because the focus of that post was the general structure and presentation of the overall figure, the plots themselves were quite simple in that they were only using one pre-defined matplotlib function such as .plot or .hist with the default parameters. Often times though, within the nice tiled structure that you learned in the previous post, you will need to draw a specific plot of your own that combines information from different types of basic plotting functions along with calls to some other data-generating or data-processing function. For example, plotting the distribution of random samples with its corresponding theoretical density function on top.
Here, I will show you how to create your own custom plotting functions that can be easily used by calling them within your organized plots with something like the following:
fig, axes = plt.subplots(number_of_subplots)for ax in axes: my_custom_plotting_function(ax=ax, function_kwargs)
Together with a nice organization of the subplots, this will help you maximize your static plotting on matplotlib (foreshadowing a dynamics plots follow-up tutorial .... maybe...) and leverage information from different plots to share a comprehensive story of your data.
The first step in being able to have a series of custom plots within your figure is being able to connect an individual custom plot to an individual axes. The first step then is to be able to pass the axes on which we want to plot to our custom function. This can be done simply like this:
def custom_plot(x, y, ax=None, **plt_kwargs): if ax is None: ax = plt.gca() ax.plot(x, y, **plt_kwargs) ## example plot here return(ax)
So what did I do there? The first relevant part here is the argument ax. If you have used seaborn before, you might already know how to use this. Essentially, ax will be taking the axes object onto which you want to plot. This can be a subplot axes or a simple free floating inset axes. The idea is that the organization part of the plot would be dealt outside of this function, potentially by another function.
Why does ax default to None though? This is better answered by the lines:
if ax is None: ax = plt.gca()
we see that if no axes object was provided in ax, it defaults to None and triggers this if condition. In this case, since no axes was given, by default, the function would look for the last axes used in the current figure, or create one if there are none available, with the function .gca (which stands for get current axes) and use that as the axes on which to plot. At the end of the function, we also return this ax, in case we want to use it for other customizations (not needed but practical in some cases).
Let’s test this by first plotting without specifying the axes and then by providing a specific axes:
# Without providing axes (default to None -> gca())plt.figure(figsize=(10, 5))custom_plot([1, 2], [10, 20])plt.title('Our custom plot with no axes provided (defaults to .gca())')plt.xlabel('x')plt.ylabel('y')plt.show()
# Providing the axesfig, axes = plt.subplots(2, figsize=(10, 5))# Plotting with our functioncustom_plot([2, 3], [4, 15], ax=axes[0])axes[0].set(xlabel='x', ylabel='y', title='This is our custom plot on the specified axes')# Example plot to fill the second subplot (nothing to do with our function)axes[1].hist(np.random.normal(size=100))axes[1].set_title('This plot has nothing to do with our function. Just a histogram of some random numbers')plt.tight_layout() #This to avoid overlap of labels and titles across plotsplt.show()
So far so good; we can create a function to plot data and we can connect it to a specific axes of our plot (it even takes care of itself if no axes was provided). What about the **plt_kwargs though?
If you are not used to working with **kwargs (as in keyword arguments) in your functions (the actual name of the argument doesn't matter, you can name it **kwargs, **plt_kwargs, **literally_anything_else as long as you put the double asterisk " ** ") it will be easier to explain by first creating and using a new function that does not have **kwargs in it.
As an aside though, if you really haven’t see this type of asterisk notation before, the use of single asterisks * and double asterisks ** in python is quite useful in many situations, whether it is within or outside of functions, and definitely worth a google search (maybe even writing a blog post about it.... maybe...). Anyway, back to our example of custom_plot without **kwargs:
def no_kwargs_plot(x, y, ax=None): if ax is None: ax = plt.gca() ax.plot(x, y) ## example plot here return(ax)plt.figure(figsize=(10, 5))no_kwargs_plot([1, 2], [10, 20])plt.show()
No errors, no problems... However, what if you wanted to make the line thicker? Normally in .plot() we would simply set the argument linewidth to a thicker value. We could add linewidth to the list of inputs to no_kwargs_plot and then pass it to .plot() like this:
def no_kwargs_plot(x, y, ax=None, linewidth=1): if ax is None: ax = plt.gca() ax.plot(x, y, linewidth) ## example plot here
That would take care of the problem. But what about all the other possible arguments into .plot(). Having to write them all in our function along with their default values would be really long and not very practical:
def no_kwargs_plot(x, y, ax=None, linewidth=1, other=1,...): if ax is None: ax = plt.gca() ax.plot(x, y, linewidth, other,....) ## example plot here
That’s where the use of ** notation (**kwargs) becomes useful. When used on free key-value elements, such as orphan inputs in our function (those that are not associated with pre-defined arguments x, y and ax in our case) **name will pack all of this elements into a dictionary and store them in the variable name.
For example, if we were to use our plotting function as custom_plot(x=xdata, y=ydata, ax=axes[0], linewidth=2, c='g'), the resulting plt_kwargs dictionary would be {'linewidth':2, 'c':'g'}. If this is still not quite clear, look at the sample code below, the output (>>) and the schema underneath:
def print_kwargs_only(x, y, ax=None, **plt_kwargs): print(plt_kwargs) #to print the dictionary with all the orphan kwargsprint_kwargs_only(x=[1, 2], y=[10, 20], not_xyax=1, random_orphan_kwarg='so lonely', linewidth=2, c='g')>> {'not_xyax': 1, 'random_orphan_kwarg': 'so lonely', 'linewidth': 2, 'c': 'g'}
So using ** solves the problem of taking all the possible plotting inputs into our function without needing to explicitly pre-define them and having them ready to use inside a dictionary. How is this dictionary of supplementary keyword arguments used, though?
Previously, I mentioned that ** behaved like a packing function when used on free elements. When you use ** on a dictionary though (whether it was packed by ** or not), ** will actually do the opposite action it did before: it will unpack the dictionary into different free elements. In the custom_function, when we write **plt_kwargs inside .plot(), i.e. ax.plot(x, y, **plt_kwargs), we are actually asking python to take the dictionary plt_kwargs and unpack all of its key-value pairs separately into the .plot() function as individual inputs.
In that way, without knowing how many and which plot customizations will be used, we can pass them all to the part of our function that will be doing the plotting.
We can see this using again our original custom_plot function (you might notice that this time I used the axes returned by the function to show you how it can be used):
plt.figure(figsize=(10, 5))out_ax = custom_plot([1, 2], [10, 20], linewidth=5, c='g')out_ax.set(xlabel='xlabel', ylabel='ylabel', title='Testing out the usefulness of **kwargs')plt.show()
That takes care of the basic syntax then. With that you should already be able to start producing some more interesting plots.
Before going ham though, we need to take care of one potential issue you might run into when using **kwargs. That is, what if you were doing multiple plots inside of the custom_plot function? for example, what if you were plotting two lines and one should be dashed, while the other one was just solid. How would **kwargs know which arguments go into which plot?
The answer is that “**kwargs the packing machine" wouldn't work any more and would need to be replaced, but "**kwargs the unpacking machine" would work perfectly fine. What do I mean by this? Let's define a new function called multiple_custom_plots to clarify it:
def multiple_custom_plots(x, y, ax=None, plt_kwargs={}, sct_kwargs={}): if ax is None: ax = plt.gca() ax.plot(x, y, **plt_kwargs) ax.scatter(x, y, **sct_kwargs) return(ax)
What is different here and how should we use it? First, look at the list of possible inputs. Now, instead of having **kwargs, we have two new arguments, one for each of our plots. Also, by default, these arguments are empty dictionaries.
If you followed my explanation before about **kwargs hopefully this is already quite clear for you. The idea is that since we cannot ask the function to automatically pack all the orphan inputs into one dictionary (we need two separate dictionaries now) we will instead have to provide each dictionary of plotting parameters ourselves, pre-packed.
Using them later with the double asterisk is no different than original custom_plot since using ** on a dictionary still means that we want its values unpacked. We use empty dictionaries as default values because if you didn't provide a dictionary of customizations, we would run into problems when trying to unpack them (or the lack of them) with **. The empty dictionaries essentially are there to unpack nothing into the functions if nothing is provided.
Let’s see how we would use this:
plot_params = {'linewidth': 2, 'c': 'g', 'linestyle':'--'}scatter_params = {'c':'red', 'marker':'+', 's':100}xdata = [1, 2]ydata = [10, 20]plt.figure(figsize=(10, 5))multiple_custom_plots(xdata, ydata, plt_kwargs=plot_params, sct_kwargs=scatter_params)plt.show()
So, when it comes to creating custom functions from which you can plot, the previous section should be enough for you to have quite a bit of fun for a while with static plots. In this next section, I will simply give you an example of a plot using a custom function hopefully to inspire you to go do some plots of your own.
Imagine you wanted to see how the size of a sample from a given random variable affects the estimation of its underlying probability distribution.
Let’s assume we have a continuous random variable X that is normally distributed with a mean μ (mu) and a standard deviation σ (sigma) (i.e. X∼N(μ,σ2)). We would like to know how scipy’s kernel density estimator (kde) is affected by the size of our random sample (how many times we sample randomly from our normal distribution) by comparing it to the estimate of the underlying true probability density distribution (pdf).
We will do this by plotting the samples themselves, their kde and their underlying pdf for different values of N.
def sample_plot(mu=0, sigma=1, N=100, sct_kwargs={}, pdf_kwargs={}, kde_kwargs={}, ax=None): # generate sample sample = np.random.normal(loc=mu, scale=sigma, size=N) # generate pdf xrange = mu + 5*sigma*np.linspace(-1, 1, 100) pdf = stats.norm.pdf(xrange, loc=mu, scale=sigma) # generate kde estimation = stats.gaussian_kde(sample) kde = estimation(xrange) #Plotting if ax is None: ax = plt.gca() ax.scatter(sample, np.zeros_like(sample), **sct_kwargs) ax.plot(xrange, pdf, **pdf_kwargs) ax.plot(xrange, kde, **kde_kwargs) return(xrange)
Let’s deconstruct the function one step at a time:
First, the inputs. Here, instead of asking for arrays of data, we will be creating our own data from a Gaussian random number generator. So we need to ask for the relevant statistical parameters μ and σ (the mean and standard deviation respectively for Gaussian distributions). We also need to ask the number of samples N to be taken. We will actually be iterating over different values of N later to see the effect of the sample size on the estimation. The idea is to plot the samples as scatter points, and the pdf and kde as regular line plots. So we will provide as inputs a dictionary for their respective plotting parameters (linewidth, marker size, etc.). Finally, we will ask the axes of the figure on which we want to plot all three things.
The first section of the function will simply generate a random Gaussian sample of size N from the statistical parameters provided.
The second part of the code will create the x-y pairs of the line plot corresponding to the pdf of the normal distribution given by μ and σ. We limit the range of the pdf to ±5 standard deviations since anything further on either side is going to be quite small anyway.
The third part of the code is first calculating the kde of our sample and then applying it to the same range of values on the x-axis as our pdf.
Finally, in the fourth part of the code, we simply plot as a scatter plot all the sampled values on the x-axis (at a height of 0), and the pdf and kde as line plots. All three, with their respective plotting keyword arguments.
# Sample parameterssample_sizes = (10, 20, 100, 250, 500, 2_000)mean = 100std = 15# Plotting parametersscatter_params = {'alpha':0.1, 'c':'g', 's':100, 'label':'samples'}pdf_params = {"linewidth":2, 'c':'k', 'label':'pdf'}kde_params = {"linewidth":3, 'ls':'--', 'c':'g', 'label':'kde'}# Plottingfig, axes = plt.subplots(6, figsize=(15, 20))for ax, n in zip(axes, sample_sizes): sample_plot(mu=mean, sigma=std, N=n, ax=ax, sct_kwargs=scatter_params, pdf_kwargs=pdf_params, kde_kwargs=kde_params) ax.set_title(f'N={n}')axes[0].legend()axes[-1].set_xlabel('Sample Value', fontsize=13)plt.tight_layout()plt.savefig('finalplot')plt.show()
And that’s it! Hopefully you learned how to add plotting abilities to your functions by properly passing the corresponding axes and keyword arguments. This should help you have increasingly modular code to quickly explore and visualize your data.
Originally published at https://maticalderini.github.io on April 28, 2020. | [
{
"code": null,
"e": 274,
"s": 172,
"text": "TLDR: Define your own functions that involve plotting onto a specific axes with the following syntax:"
},
{
"code": null,
"e": 646,
"s": 274,
"text": "def custom_plot(x, y, ax=None, **plt_kwargs): if ax is None: ax = plt.gca() ax.plot(x, y, **plt_kwargs) ## example plot here return(ax)def multiple_custom_plots(x, y, ax=None, plt_kwargs={}, sct_kwargs={}): if ax is None: ax = plt.gca() ax.plot(x, y, **plt_kwargs) #example plot1 ax.scatter(x, y, **sct_kwargs) #example plot2 return(ax)"
},
{
"code": null,
"e": 702,
"s": 646,
"text": "You can find the original code repository at this link."
},
{
"code": null,
"e": 949,
"s": 702,
"text": "In a previous post, I showed you how to better organize your figures. We saw how you could neatly display your different plots using subplots, how to add free-floating axes and how to easily create a tiled organization of your axes with GridSpec."
},
{
"code": null,
"e": 1611,
"s": 949,
"text": "Because the focus of that post was the general structure and presentation of the overall figure, the plots themselves were quite simple in that they were only using one pre-defined matplotlib function such as .plot or .hist with the default parameters. Often times though, within the nice tiled structure that you learned in the previous post, you will need to draw a specific plot of your own that combines information from different types of basic plotting functions along with calls to some other data-generating or data-processing function. For example, plotting the distribution of random samples with its corresponding theoretical density function on top."
},
{
"code": null,
"e": 1785,
"s": 1611,
"text": "Here, I will show you how to create your own custom plotting functions that can be easily used by calling them within your organized plots with something like the following:"
},
{
"code": null,
"e": 1900,
"s": 1785,
"text": "fig, axes = plt.subplots(number_of_subplots)for ax in axes: my_custom_plotting_function(ax=ax, function_kwargs)"
},
{
"code": null,
"e": 2171,
"s": 1900,
"text": "Together with a nice organization of the subplots, this will help you maximize your static plotting on matplotlib (foreshadowing a dynamics plots follow-up tutorial .... maybe...) and leverage information from different plots to share a comprehensive story of your data."
},
{
"code": null,
"e": 2461,
"s": 2171,
"text": "The first step in being able to have a series of custom plots within your figure is being able to connect an individual custom plot to an individual axes. The first step then is to be able to pass the axes on which we want to plot to our custom function. This can be done simply like this:"
},
{
"code": null,
"e": 2613,
"s": 2461,
"text": "def custom_plot(x, y, ax=None, **plt_kwargs): if ax is None: ax = plt.gca() ax.plot(x, y, **plt_kwargs) ## example plot here return(ax)"
},
{
"code": null,
"e": 3025,
"s": 2613,
"text": "So what did I do there? The first relevant part here is the argument ax. If you have used seaborn before, you might already know how to use this. Essentially, ax will be taking the axes object onto which you want to plot. This can be a subplot axes or a simple free floating inset axes. The idea is that the organization part of the plot would be dealt outside of this function, potentially by another function."
},
{
"code": null,
"e": 3099,
"s": 3025,
"text": "Why does ax default to None though? This is better answered by the lines:"
},
{
"code": null,
"e": 3136,
"s": 3099,
"text": "if ax is None: ax = plt.gca()"
},
{
"code": null,
"e": 3649,
"s": 3136,
"text": "we see that if no axes object was provided in ax, it defaults to None and triggers this if condition. In this case, since no axes was given, by default, the function would look for the last axes used in the current figure, or create one if there are none available, with the function .gca (which stands for get current axes) and use that as the axes on which to plot. At the end of the function, we also return this ax, in case we want to use it for other customizations (not needed but practical in some cases)."
},
{
"code": null,
"e": 3750,
"s": 3649,
"text": "Let’s test this by first plotting without specifying the axes and then by providing a specific axes:"
},
{
"code": null,
"e": 3969,
"s": 3750,
"text": "# Without providing axes (default to None -> gca())plt.figure(figsize=(10, 5))custom_plot([1, 2], [10, 20])plt.title('Our custom plot with no axes provided (defaults to .gca())')plt.xlabel('x')plt.ylabel('y')plt.show()"
},
{
"code": null,
"e": 4499,
"s": 3969,
"text": "# Providing the axesfig, axes = plt.subplots(2, figsize=(10, 5))# Plotting with our functioncustom_plot([2, 3], [4, 15], ax=axes[0])axes[0].set(xlabel='x', ylabel='y', title='This is our custom plot on the specified axes')# Example plot to fill the second subplot (nothing to do with our function)axes[1].hist(np.random.normal(size=100))axes[1].set_title('This plot has nothing to do with our function. Just a histogram of some random numbers')plt.tight_layout() #This to avoid overlap of labels and titles across plotsplt.show()"
},
{
"code": null,
"e": 4698,
"s": 4499,
"text": "So far so good; we can create a function to plot data and we can connect it to a specific axes of our plot (it even takes care of itself if no axes was provided). What about the **plt_kwargs though?"
},
{
"code": null,
"e": 5056,
"s": 4698,
"text": "If you are not used to working with **kwargs (as in keyword arguments) in your functions (the actual name of the argument doesn't matter, you can name it **kwargs, **plt_kwargs, **literally_anything_else as long as you put the double asterisk \" ** \") it will be easier to explain by first creating and using a new function that does not have **kwargs in it."
},
{
"code": null,
"e": 5441,
"s": 5056,
"text": "As an aside though, if you really haven’t see this type of asterisk notation before, the use of single asterisks * and double asterisks ** in python is quite useful in many situations, whether it is within or outside of functions, and definitely worth a google search (maybe even writing a blog post about it.... maybe...). Anyway, back to our example of custom_plot without **kwargs:"
},
{
"code": null,
"e": 5637,
"s": 5441,
"text": "def no_kwargs_plot(x, y, ax=None): if ax is None: ax = plt.gca() ax.plot(x, y) ## example plot here return(ax)plt.figure(figsize=(10, 5))no_kwargs_plot([1, 2], [10, 20])plt.show()"
},
{
"code": null,
"e": 5902,
"s": 5637,
"text": "No errors, no problems... However, what if you wanted to make the line thicker? Normally in .plot() we would simply set the argument linewidth to a thicker value. We could add linewidth to the list of inputs to no_kwargs_plot and then pass it to .plot() like this:"
},
{
"code": null,
"e": 6039,
"s": 5902,
"text": "def no_kwargs_plot(x, y, ax=None, linewidth=1): if ax is None: ax = plt.gca() ax.plot(x, y, linewidth) ## example plot here"
},
{
"code": null,
"e": 6256,
"s": 6039,
"text": "That would take care of the problem. But what about all the other possible arguments into .plot(). Having to write them all in our function along with their default values would be really long and not very practical:"
},
{
"code": null,
"e": 6418,
"s": 6256,
"text": "def no_kwargs_plot(x, y, ax=None, linewidth=1, other=1,...): if ax is None: ax = plt.gca() ax.plot(x, y, linewidth, other,....) ## example plot here"
},
{
"code": null,
"e": 6733,
"s": 6418,
"text": "That’s where the use of ** notation (**kwargs) becomes useful. When used on free key-value elements, such as orphan inputs in our function (those that are not associated with pre-defined arguments x, y and ax in our case) **name will pack all of this elements into a dictionary and store them in the variable name."
},
{
"code": null,
"e": 7031,
"s": 6733,
"text": "For example, if we were to use our plotting function as custom_plot(x=xdata, y=ydata, ax=axes[0], linewidth=2, c='g'), the resulting plt_kwargs dictionary would be {'linewidth':2, 'c':'g'}. If this is still not quite clear, look at the sample code below, the output (>>) and the schema underneath:"
},
{
"code": null,
"e": 7342,
"s": 7031,
"text": "def print_kwargs_only(x, y, ax=None, **plt_kwargs): print(plt_kwargs) #to print the dictionary with all the orphan kwargsprint_kwargs_only(x=[1, 2], y=[10, 20], not_xyax=1, random_orphan_kwarg='so lonely', linewidth=2, c='g')>> {'not_xyax': 1, 'random_orphan_kwarg': 'so lonely', 'linewidth': 2, 'c': 'g'}"
},
{
"code": null,
"e": 7602,
"s": 7342,
"text": "So using ** solves the problem of taking all the possible plotting inputs into our function without needing to explicitly pre-define them and having them ready to use inside a dictionary. How is this dictionary of supplementary keyword arguments used, though?"
},
{
"code": null,
"e": 8148,
"s": 7602,
"text": "Previously, I mentioned that ** behaved like a packing function when used on free elements. When you use ** on a dictionary though (whether it was packed by ** or not), ** will actually do the opposite action it did before: it will unpack the dictionary into different free elements. In the custom_function, when we write **plt_kwargs inside .plot(), i.e. ax.plot(x, y, **plt_kwargs), we are actually asking python to take the dictionary plt_kwargs and unpack all of its key-value pairs separately into the .plot() function as individual inputs."
},
{
"code": null,
"e": 8312,
"s": 8148,
"text": "In that way, without knowing how many and which plot customizations will be used, we can pass them all to the part of our function that will be doing the plotting."
},
{
"code": null,
"e": 8481,
"s": 8312,
"text": "We can see this using again our original custom_plot function (you might notice that this time I used the axes returned by the function to show you how it can be used):"
},
{
"code": null,
"e": 8669,
"s": 8481,
"text": "plt.figure(figsize=(10, 5))out_ax = custom_plot([1, 2], [10, 20], linewidth=5, c='g')out_ax.set(xlabel='xlabel', ylabel='ylabel', title='Testing out the usefulness of **kwargs')plt.show()"
},
{
"code": null,
"e": 8796,
"s": 8669,
"text": "That takes care of the basic syntax then. With that you should already be able to start producing some more interesting plots."
},
{
"code": null,
"e": 9159,
"s": 8796,
"text": "Before going ham though, we need to take care of one potential issue you might run into when using **kwargs. That is, what if you were doing multiple plots inside of the custom_plot function? for example, what if you were plotting two lines and one should be dashed, while the other one was just solid. How would **kwargs know which arguments go into which plot?"
},
{
"code": null,
"e": 9423,
"s": 9159,
"text": "The answer is that “**kwargs the packing machine\" wouldn't work any more and would need to be replaced, but \"**kwargs the unpacking machine\" would work perfectly fine. What do I mean by this? Let's define a new function called multiple_custom_plots to clarify it:"
},
{
"code": null,
"e": 9614,
"s": 9423,
"text": "def multiple_custom_plots(x, y, ax=None, plt_kwargs={}, sct_kwargs={}): if ax is None: ax = plt.gca() ax.plot(x, y, **plt_kwargs) ax.scatter(x, y, **sct_kwargs) return(ax)"
},
{
"code": null,
"e": 9852,
"s": 9614,
"text": "What is different here and how should we use it? First, look at the list of possible inputs. Now, instead of having **kwargs, we have two new arguments, one for each of our plots. Also, by default, these arguments are empty dictionaries."
},
{
"code": null,
"e": 10200,
"s": 9852,
"text": "If you followed my explanation before about **kwargs hopefully this is already quite clear for you. The idea is that since we cannot ask the function to automatically pack all the orphan inputs into one dictionary (we need two separate dictionaries now) we will instead have to provide each dictionary of plotting parameters ourselves, pre-packed."
},
{
"code": null,
"e": 10658,
"s": 10200,
"text": "Using them later with the double asterisk is no different than original custom_plot since using ** on a dictionary still means that we want its values unpacked. We use empty dictionaries as default values because if you didn't provide a dictionary of customizations, we would run into problems when trying to unpack them (or the lack of them) with **. The empty dictionaries essentially are there to unpack nothing into the functions if nothing is provided."
},
{
"code": null,
"e": 10691,
"s": 10658,
"text": "Let’s see how we would use this:"
},
{
"code": null,
"e": 10954,
"s": 10691,
"text": "plot_params = {'linewidth': 2, 'c': 'g', 'linestyle':'--'}scatter_params = {'c':'red', 'marker':'+', 's':100}xdata = [1, 2]ydata = [10, 20]plt.figure(figsize=(10, 5))multiple_custom_plots(xdata, ydata, plt_kwargs=plot_params, sct_kwargs=scatter_params)plt.show()"
},
{
"code": null,
"e": 11278,
"s": 10954,
"text": "So, when it comes to creating custom functions from which you can plot, the previous section should be enough for you to have quite a bit of fun for a while with static plots. In this next section, I will simply give you an example of a plot using a custom function hopefully to inspire you to go do some plots of your own."
},
{
"code": null,
"e": 11425,
"s": 11278,
"text": "Imagine you wanted to see how the size of a sample from a given random variable affects the estimation of its underlying probability distribution."
},
{
"code": null,
"e": 11848,
"s": 11425,
"text": "Let’s assume we have a continuous random variable X that is normally distributed with a mean μ (mu) and a standard deviation σ (sigma) (i.e. X∼N(μ,σ2)). We would like to know how scipy’s kernel density estimator (kde) is affected by the size of our random sample (how many times we sample randomly from our normal distribution) by comparing it to the estimate of the underlying true probability density distribution (pdf)."
},
{
"code": null,
"e": 11962,
"s": 11848,
"text": "We will do this by plotting the samples themselves, their kde and their underlying pdf for different values of N."
},
{
"code": null,
"e": 12564,
"s": 11962,
"text": "def sample_plot(mu=0, sigma=1, N=100, sct_kwargs={}, pdf_kwargs={}, kde_kwargs={}, ax=None): # generate sample sample = np.random.normal(loc=mu, scale=sigma, size=N) # generate pdf xrange = mu + 5*sigma*np.linspace(-1, 1, 100) pdf = stats.norm.pdf(xrange, loc=mu, scale=sigma) # generate kde estimation = stats.gaussian_kde(sample) kde = estimation(xrange) #Plotting if ax is None: ax = plt.gca() ax.scatter(sample, np.zeros_like(sample), **sct_kwargs) ax.plot(xrange, pdf, **pdf_kwargs) ax.plot(xrange, kde, **kde_kwargs) return(xrange)"
},
{
"code": null,
"e": 12615,
"s": 12564,
"text": "Let’s deconstruct the function one step at a time:"
},
{
"code": null,
"e": 13365,
"s": 12615,
"text": "First, the inputs. Here, instead of asking for arrays of data, we will be creating our own data from a Gaussian random number generator. So we need to ask for the relevant statistical parameters μ and σ (the mean and standard deviation respectively for Gaussian distributions). We also need to ask the number of samples N to be taken. We will actually be iterating over different values of N later to see the effect of the sample size on the estimation. The idea is to plot the samples as scatter points, and the pdf and kde as regular line plots. So we will provide as inputs a dictionary for their respective plotting parameters (linewidth, marker size, etc.). Finally, we will ask the axes of the figure on which we want to plot all three things."
},
{
"code": null,
"e": 13497,
"s": 13365,
"text": "The first section of the function will simply generate a random Gaussian sample of size N from the statistical parameters provided."
},
{
"code": null,
"e": 13767,
"s": 13497,
"text": "The second part of the code will create the x-y pairs of the line plot corresponding to the pdf of the normal distribution given by μ and σ. We limit the range of the pdf to ±5 standard deviations since anything further on either side is going to be quite small anyway."
},
{
"code": null,
"e": 13912,
"s": 13767,
"text": "The third part of the code is first calculating the kde of our sample and then applying it to the same range of values on the x-axis as our pdf."
},
{
"code": null,
"e": 14139,
"s": 13912,
"text": "Finally, in the fourth part of the code, we simply plot as a scatter plot all the sampled values on the x-axis (at a height of 0), and the pdf and kde as line plots. All three, with their respective plotting keyword arguments."
},
{
"code": null,
"e": 14794,
"s": 14139,
"text": "# Sample parameterssample_sizes = (10, 20, 100, 250, 500, 2_000)mean = 100std = 15# Plotting parametersscatter_params = {'alpha':0.1, 'c':'g', 's':100, 'label':'samples'}pdf_params = {\"linewidth\":2, 'c':'k', 'label':'pdf'}kde_params = {\"linewidth\":3, 'ls':'--', 'c':'g', 'label':'kde'}# Plottingfig, axes = plt.subplots(6, figsize=(15, 20))for ax, n in zip(axes, sample_sizes): sample_plot(mu=mean, sigma=std, N=n, ax=ax, sct_kwargs=scatter_params, pdf_kwargs=pdf_params, kde_kwargs=kde_params) ax.set_title(f'N={n}')axes[0].legend()axes[-1].set_xlabel('Sample Value', fontsize=13)plt.tight_layout()plt.savefig('finalplot')plt.show()"
},
{
"code": null,
"e": 15041,
"s": 14794,
"text": "And that’s it! Hopefully you learned how to add plotting abilities to your functions by properly passing the corresponding axes and keyword arguments. This should help you have increasingly modular code to quickly explore and visualize your data."
}
]
|
Traffic Intersection Simulation using Pygame, Part 1 | by Mihir Gandhi | Towards Data Science | We are developing a simulation from scratch using Pygame to simulate the movement of vehicles across a traffic intersection having traffic lights with a timer. It contains a 4-way traffic intersection with traffic signals controlling the flow of traffic in each direction. Each signal has a timer on top of it which shows the time remaining for the signal to switch from green to yellow, yellow to red, or red to green. Vehicles such as cars, bikes, buses, and trucks are generated, and their movement is controlled according to the signals and the vehicles around them. This simulation can be further used for data analysis or to visualize AI or ML applications. The video below shows the final output of the simulation we will be building.
Before diving into coding and seeing our beautiful simulation come to life, let us get some images that we will need to build the simulation. Here’s a list of what we need:
4-way intersection
Traffic Signals: Red, Yellow, and Green
Car :
Bike :
Bus
Truck
Please make sure that you rename the images you download according to the caption of the images above. Next, we need to resize the images of traffic signals and the vehicles according to the size of the 4-way intersection image. This is the only step that will involve some trial-and-error, but as we are building the simulation from scratch, this is necessary.
Open up the 4-way intersection image in an application like Paint for Windows or Preview for Mac. Select an area equal to what you want a vehicle to look like in your final simulation. Note down the dimensions.
Now resize your vehicles to this size by opening them in any tool of your choice. Repeat the same process for the traffic signal images as well.
One last step remains before we move on to coding. As you may have noticed, we have images of vehicles facing towards right only. So rotate the images of vehicles and save each of them to get images facing all directions, as shown in the image below.
Create a folder ‘Traffic Intersection Simulation’ and within that create a folder ‘images’. Here we will store all of these images. The folder structure is as shown below where:
down: contains images of vehicles facing down
up: contains images of vehicles facing up
left: contains images of vehicles facing left
right: contains images of vehicles facing right
signals: contains the images of traffic signals
Now let us dive into coding.
Before installing PyGame, you need to have Python 3.1+ installed on your system. You can download Python from here. The easiest way to install Pygame is using pip. Simply run the following command in cmd/Terminal.
$ pip install pygame
We start by creating a file named ‘simulation.py’ and importing the libraries that we will require for developing this simulation.
import randomimport timeimport threadingimport pygameimport sys
Note that your folder structure should look something like this at this point.
Next, we define some constants that will be used in the movement of vehicles in the simulation as well as in control of traffic signal timers.
# Default values of signal timers in secondsdefaultGreen = {0:20, 1:20, 2:20, 3:20}defaultRed = 150defaultYellow = 5signals = []noOfSignals = 4currentGreen = 0 # Indicates which signal is green currentlynextGreen = (currentGreen+1)%noOfSignals currentYellow = 0 # Indicates whether yellow signal is on or offspeeds = {'car':2.25, 'bus':1.8, 'truck':1.8, 'bike':2.5} # average speeds of vehicles
The coordinates below are also extracted by opening the 4-way intersection image in Paint/Preview and getting the pixel values.
# Coordinates of vehicles’ startx = {‘right’:[0,0,0], ‘down’:[755,727,697], ‘left’:[1400,1400,1400], ‘up’:[602,627,657]}y = {‘right’:[348,370,398], ‘down’:[0,0,0], ‘left’:[498,466,436], ‘up’:[800,800,800]}vehicles = {‘right’: {0:[], 1:[], 2:[], ‘crossed’:0}, ‘down’: {0:[], 1:[], 2:[], ‘crossed’:0}, ‘left’: {0:[], 1:[], 2:[], ‘crossed’:0}, ‘up’: {0:[], 1:[], 2:[], ‘crossed’:0}}vehicleTypes = {0:’car’, 1:’bus’, 2:’truck’, 3:’bike’}directionNumbers = {0:’right’, 1:’down’, 2:’left’, 3:’up’}# Coordinates of signal image, timer, and vehicle countsignalCoods = [(530,230),(810,230),(810,570),(530,570)]signalTimerCoods = [(530,210),(810,210),(810,550),(530,550)]# Coordinates of stop linesstopLines = {‘right’: 590, ‘down’: 330, ‘left’: 800, ‘up’: 535}defaultStop = {‘right’: 580, ‘down’: 320, ‘left’: 810, ‘up’: 545}# Gap between vehiclesstoppingGap = 15 # stopping gapmovingGap = 15 # moving gap
Next, we initialize Pygame with the following code:
pygame.init()simulation = pygame.sprite.Group()
Now let us build some classes whose objects we will generate in the simulation. We have 2 classes that we need to define.
Traffic Signal: We need to generate 4 traffic signals for our simulation. So we build a TrafficSignal class that has the following attributes:
Traffic Signal: We need to generate 4 traffic signals for our simulation. So we build a TrafficSignal class that has the following attributes:
red: Value of red signal timer
yellow: Value of yellow signal timer
green: Value of green signal timer
signalText: Value of timer to display
class TrafficSignal: def __init__(self, red, yellow, green): self.red = red self.yellow = yellow self.green = green self.signalText = ""
2. Vehicle: This is a class that represents objects of vehicles that we will be generating in the simulation. The Vehicle class has the following attributes and methods:
vehicleClass: Represents the class of the vehicle such as car, bus, truck, or bike
speed: Represents the speed of the vehicle according to its class
direction_number: Represents the direction — 0 for right, 1 for down, 2 for left, and 3 for up
direction: Represents the direction in text format
x: Represents the current x-coordinate of the vehicle
y: Represents the current y-coordinate of the vehicle
crossed: Represents whether the vehicle has crossed the signal or not
index: Represents the relative position of the vehicle among the vehicles moving in the same direction and the same lane
image: Represents the image to be rendered
render(): To display the image on screen
move(): To control the movement of the vehicle according to the traffic light and the vehicles ahead
class Vehicle(pygame.sprite.Sprite): def __init__(self, lane, vehicleClass, direction_number, direction): pygame.sprite.Sprite.__init__(self) self.lane = lane self.vehicleClass = vehicleClass self.speed = speeds[vehicleClass] self.direction_number = direction_number self.direction = direction self.x = x[direction][lane] self.y = y[direction][lane] self.crossed = 0 vehicles[direction][lane].append(self) self.index = len(vehicles[direction][lane]) - 1 path = "images/" + direction + "/" + vehicleClass + ".png" self.image = pygame.image.load(path) if(len(vehicles[direction][lane])>1 and vehicles[direction][lane][self.index-1].crossed==0): if(direction=='right'): self.stop = vehicles[direction][lane][self.index-1].stop - vehicles[direction][lane][self.index-1].image.get_rect().width - stoppingGap elif(direction=='left'): self.stop = vehicles[direction][lane][self.index-1].stop + vehicles[direction][lane][self.index-1].image.get_rect().width + stoppingGap elif(direction=='down'): self.stop = vehicles[direction][lane][self.index-1].stop - vehicles[direction][lane][self.index-1].image.get_rect().height - stoppingGap elif(direction=='up'): self.stop = vehicles[direction][lane][self.index-1].stop + vehicles[direction][lane][self.index-1].image.get_rect().height + stoppingGap else: self.stop = defaultStop[direction] if(direction=='right'): temp = self.image.get_rect().width + stoppingGap x[direction][lane] -= temp elif(direction=='left'): temp = self.image.get_rect().width + stoppingGap x[direction][lane] += temp elif(direction=='down'): temp = self.image.get_rect().height + stoppingGap y[direction][lane] -= temp elif(direction=='up'): temp = self.image.get_rect().height + stoppingGap y[direction][lane] += temp simulation.add(self) def render(self, screen): screen.blit(self.image, (self.x, self.y))
Let us understand the latter part of the constructor.
In the constructor, after initializing all the variables, we are checking if there are vehicles already present in the same direction and lane as the current vehicle. If yes, we need to set the value of ‘stop’ of the current vehicle taking into consideration the value of ‘stop’ and the width/height of the vehicle ahead of it, as well as the stoppingGap. If there is no vehicle ahead already, then the stop value is set equal to defaultStop. This value of stop is used to control where the vehicles will stop when the signal is red. Once this is done, we update the coordinates from where the vehicles are generated. This is done to avoid overlapping of newly generated vehicles with the existing vehicles when there are a lot of vehicles stopped at a red light.
Now let’s talk about the move() function, which is one of the most important piece of code in our simulation. Note that this function is also a part of the Vehicle class defined above and needs to be indented accordingly.
def move(self): if(self.direction=='right'): if(self.crossed==0 and self.x+self.image.get_rect().width>stopLines[self.direction]): self.crossed = 1 if((self.x+self.image.get_rect().width<=self.stop or self.crossed == 1 or (currentGreen==0 and currentYellow==0)) and (self.index==0 or self.x+self.image.get_rect().width <(vehicles[self.direction][self.lane][self.index-1].x - movingGap))): self.x += self.speed elif(self.direction=='down'): if(self.crossed==0 and self.y+self.image.get_rect().height>stopLines[self.direction]): self.crossed = 1 if((self.y+self.image.get_rect().height<=self.stop or self.crossed == 1 or (currentGreen==1 and currentYellow==0)) and (self.index==0 or self.y+self.image.get_rect().height <(vehicles[self.direction][self.lane][self.index-1].y - movingGap))): self.y += self.speed elif(self.direction=='left'): if(self.crossed==0 and self.x<stopLines[self.direction]): self.crossed = 1 if((self.x>=self.stop or self.crossed == 1 or (currentGreen==2 and currentYellow==0)) and (self.index==0 or self.x >(vehicles[self.direction][self.lane][self.index-1].x + vehicles[self.direction][self.lane][self.index-1].image.get_rect().width + movingGap))): self.x -= self.speed elif(self.direction=='up'): if(self.crossed==0 and self.y<stopLines[self.direction]): self.crossed = 1 if((self.y>=self.stop or self.crossed == 1 or (currentGreen==3 and currentYellow==0)) and (self.index==0 or self.y >(vehicles[self.direction][self.lane][self.index-1].y + vehicles[self.direction][self.lane][self.index-1].image.get_rect().height + movingGap))): self.y -= self.speed
For each direction, we first check if the vehicle has crossed the intersection or not. This is important because if the vehicle has already crossed, then it can keep moving regardless of the signal being green or red. So when the vehicle crossed the intersection, we set the value of crossed to 1. Next, we decide when the vehicle moves and when it stops. There are 3 cases when the vehicle moves:
If it has not reached its stop point before the intersectionIf it has already crossed the intersectionIf the traffic signal controlling the direction in which the vehicle is moving is Green
If it has not reached its stop point before the intersection
If it has already crossed the intersection
If the traffic signal controlling the direction in which the vehicle is moving is Green
Only in these 3 cases, the coordinates of the vehicle is updated by incrementing/decrementing them by the speed of the vehicle, depending on their direction of motion. However, we need to consider one more possibility that there is a vehicle ahead moving in the same direction and lane. In this case, the vehicle can move only if there is a sufficient gap to the vehicle ahead, and this is decided by taking into consideration the coordinate and the width/height of the vehicle ahead of it, as well as the movingGap.
Next, we initialize 4 TrafficSignal objects, from top left to bottom left in a clockwise direction, with default values of signal timers. The red signal timer of ts2 is set equal to the sum of the yellow and green signal timer of ts1.
def initialize(): ts1 = TrafficSignal(0, defaultYellow, defaultGreen[0]) signals.append(ts1) ts2 = TrafficSignal(ts1.yellow+ts1.green, defaultYellow, defaultGreen[1]) signals.append(ts2) ts3 = TrafficSignal(defaultRed, defaultYellow, defaultGreen[2]) signals.append(ts3) ts4 = TrafficSignal(defaultRed, defaultYellow, defaultGreen[3]) signals.append(ts4) repeat()
The function repeat() that is called at the end of the initialize() function above is a recursive function that runs our entire simulation. This is the driving force of our simulation.
def repeat(): global currentGreen, currentYellow, nextGreen while(signals[currentGreen].green>0): updateValues() time.sleep(1) currentYellow = 1 for i in range(0,3): for vehicle in vehicles[directionNumbers[currentGreen]][i]: vehicle.stop=defaultStop[directionNumbers[currentGreen]] while(signals[currentGreen].yellow>0): updateValues() time.sleep(1) currentYellow = 0 signals[currentGreen].green = defaultGreen[currentGreen] signals[currentGreen].yellow = defaultYellow signals[currentGreen].red = defaultRed currentGreen = nextGreen nextGreen = (currentGreen+1)%noOfSignals signals[nextGreen].red = signals[currentGreen].yellow+signals[currentGreen].green repeat()
The repeat() function first calls the updateValues() function every second to update the signal timers until the green timer of the currentGreen signal reaches 0. It then sets that signal to yellow and resets the stop value of all vehicles moving in the direction controlled by the currentGreen signal. It then calls the updateValues() function again after every second until the yellow timer of the currentGreen signal reaches 0. The currentYellow value is now set to 0 as this signal will turn red now. Lastly, the values of the currentGreen signal are restored to the default values, the value of currentGreen and nextGreen is updated to point to the next signals in the cycle, and the value of nextGreen signal’s red timer is updated according to yellow and green of the updated currentGreen signal. The repeat() function then calls itself, and the process is repeated with the updated currentGreen signal.
The function updateValues() updates the timers of all signals after every second.
def updateValues(): for i in range(0, noOfSignals): if(i==currentGreen): if(currentYellow==0): signals[i].green-=1 else: signals[i].yellow-=1 else: signals[i].red-=1
The generateVehicles() function is used to generate the vehicles. The type of vehicle (car, bus, truck, or bike), the lane number (1 or 2) as well as the direction the vehicle moves towards is decided by using random numbers. The variable dist represents the cumulative distribution of vehicles in percentage. So a distribution of [25,50,75,100] means that there is an equal distribution (25% each) of vehicles across all 4 directions. Some other distributions can be [20,50,70,100], [10,20,30,100], and so on. A new vehicle is added to the simulation after every 1 second.
def generateVehicles(): while(True): vehicle_type = random.randint(0,3) lane_number = random.randint(1,2) temp = random.randint(0,99) direction_number = 0 dist= [25,50,75,100] if(temp<dist[0]): direction_number = 0 elif(temp<dist[1]): direction_number = 1 elif(temp<dist[2]): direction_number = 2 elif(temp<dist[3]): direction_number = 3 Vehicle(lane_number, vehicleTypes[vehicle_type], direction_number, directionNumbers[direction_number]) time.sleep(1)
And we have reached our last piece of code, the Main class, after which we can see our simulation in action.
class Main: thread1 = threading.Thread(name="initialization",target=initialize, args=()) thread1.daemon = True thread1.start() black = (0, 0, 0) white = (255, 255, 255) screenWidth = 1400 screenHeight = 800 screenSize = (screenWidth, screenHeight) background = pygame.image.load('images/intersection.png') screen = pygame.display.set_mode(screenSize) pygame.display.set_caption("SIMULATION") redSignal = pygame.image.load('images/signals/red.png') yellowSignal = pygame.image.load('images/signals/yellow.png') greenSignal = pygame.image.load('images/signals/green.png') font = pygame.font.Font(None, 30) thread2 = threading.Thread(name="generateVehicles",target=generateVehicles, args=()) thread2.daemon = True thread2.start() while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() screen.blit(background,(0,0)) for i in range(0,noOfSignals): if(i==currentGreen): if(currentYellow==1): signals[i].signalText = signals[i].yellow screen.blit(yellowSignal, signalCoods[i]) else: signals[i].signalText = signals[i].green screen.blit(greenSignal, signalCoods[i]) else: if(signals[i].red<=10): signals[i].signalText = signals[i].red else: signals[i].signalText = "---" screen.blit(redSignal, signalCoods[i]) signalTexts = ["","","",""] for i in range(0,noOfSignals): signalTexts[i] = font.render(str(signals[i].signalText), True, white, black) screen.blit(signalTexts[i],signalTimerCoods[i]) for vehicle in simulation: screen.blit(vehicle.image, [vehicle.x, vehicle.y]) vehicle.move() pygame.display.update()
Let us understand the Main() function by breaking it down into smaller pieces. We start by creating a separate thread for initialize() method, which instantiates the 4 TrafficSignal objects. Then we define 2 colours, white and black, that we will be using in our display. Next, we define the screen width and screen size, as well as the background and caption to be displayed in the simulation window. We then load the images of the 3 signals, i.e. red, yellow, and green. Now we create another thread for generateVehicles().
Next, we run an infinite loop that updates our simulation screen continuously. Within the loop, we first define the exit criteria. In the next section, we render the appropriate signal image and signal timer for each of the 4 traffic signals. Finally, we render the vehicles on the screen and call the function move() on each vehicle. This function causes the vehicles to move in the next update.
The blit() function is used to render the objects on the screen. It takes 2 arguments, the image to render and the coordinates. The coordinates point to the top-left of the image.
Almost done! Now we just need to call the Main() program, and our code is complete.
Main()
Time to see the results. Fire up a cmd/terminal and run the command:
$ python simulation.py
And voila! We have a fully functional simulation of a 4-way intersection that we have built from scratch, right from getting the image of the intersection, signals, and vehicles, to coding the logic for signal switching and vehicle movement.
Source code: https://github.com/mihir-m-gandhi/Basic-Traffic-Intersection-Simulation
This is the first part in a series of articles:
Traffic Intersection Simulation using Pygame, Part 1
Traffic Intersection Simulation using Pygame, Part 2
Traffic Intersection Simulation using Pygame, Part 3
This simulation was developed as part of a research project titled ‘Smart Control of Traffic Lights using Artificial Intelligence’. Check out its demonstration video here. This research work was presented at IEEE International Conference on Recent Advances and Innovations in Engineering (ICRAIE) 2020 and published in IEEE Xplore. Read the paper here.
Thanks for reading! I hope this article was helpful. If you have any doubts or need further clarification, feel free to reach out to me on LinkedIn. | [
{
"code": null,
"e": 914,
"s": 172,
"text": "We are developing a simulation from scratch using Pygame to simulate the movement of vehicles across a traffic intersection having traffic lights with a timer. It contains a 4-way traffic intersection with traffic signals controlling the flow of traffic in each direction. Each signal has a timer on top of it which shows the time remaining for the signal to switch from green to yellow, yellow to red, or red to green. Vehicles such as cars, bikes, buses, and trucks are generated, and their movement is controlled according to the signals and the vehicles around them. This simulation can be further used for data analysis or to visualize AI or ML applications. The video below shows the final output of the simulation we will be building."
},
{
"code": null,
"e": 1087,
"s": 914,
"text": "Before diving into coding and seeing our beautiful simulation come to life, let us get some images that we will need to build the simulation. Here’s a list of what we need:"
},
{
"code": null,
"e": 1106,
"s": 1087,
"text": "4-way intersection"
},
{
"code": null,
"e": 1146,
"s": 1106,
"text": "Traffic Signals: Red, Yellow, and Green"
},
{
"code": null,
"e": 1152,
"s": 1146,
"text": "Car :"
},
{
"code": null,
"e": 1159,
"s": 1152,
"text": "Bike :"
},
{
"code": null,
"e": 1163,
"s": 1159,
"text": "Bus"
},
{
"code": null,
"e": 1169,
"s": 1163,
"text": "Truck"
},
{
"code": null,
"e": 1531,
"s": 1169,
"text": "Please make sure that you rename the images you download according to the caption of the images above. Next, we need to resize the images of traffic signals and the vehicles according to the size of the 4-way intersection image. This is the only step that will involve some trial-and-error, but as we are building the simulation from scratch, this is necessary."
},
{
"code": null,
"e": 1742,
"s": 1531,
"text": "Open up the 4-way intersection image in an application like Paint for Windows or Preview for Mac. Select an area equal to what you want a vehicle to look like in your final simulation. Note down the dimensions."
},
{
"code": null,
"e": 1887,
"s": 1742,
"text": "Now resize your vehicles to this size by opening them in any tool of your choice. Repeat the same process for the traffic signal images as well."
},
{
"code": null,
"e": 2138,
"s": 1887,
"text": "One last step remains before we move on to coding. As you may have noticed, we have images of vehicles facing towards right only. So rotate the images of vehicles and save each of them to get images facing all directions, as shown in the image below."
},
{
"code": null,
"e": 2316,
"s": 2138,
"text": "Create a folder ‘Traffic Intersection Simulation’ and within that create a folder ‘images’. Here we will store all of these images. The folder structure is as shown below where:"
},
{
"code": null,
"e": 2362,
"s": 2316,
"text": "down: contains images of vehicles facing down"
},
{
"code": null,
"e": 2404,
"s": 2362,
"text": "up: contains images of vehicles facing up"
},
{
"code": null,
"e": 2450,
"s": 2404,
"text": "left: contains images of vehicles facing left"
},
{
"code": null,
"e": 2498,
"s": 2450,
"text": "right: contains images of vehicles facing right"
},
{
"code": null,
"e": 2546,
"s": 2498,
"text": "signals: contains the images of traffic signals"
},
{
"code": null,
"e": 2575,
"s": 2546,
"text": "Now let us dive into coding."
},
{
"code": null,
"e": 2789,
"s": 2575,
"text": "Before installing PyGame, you need to have Python 3.1+ installed on your system. You can download Python from here. The easiest way to install Pygame is using pip. Simply run the following command in cmd/Terminal."
},
{
"code": null,
"e": 2810,
"s": 2789,
"text": "$ pip install pygame"
},
{
"code": null,
"e": 2941,
"s": 2810,
"text": "We start by creating a file named ‘simulation.py’ and importing the libraries that we will require for developing this simulation."
},
{
"code": null,
"e": 3005,
"s": 2941,
"text": "import randomimport timeimport threadingimport pygameimport sys"
},
{
"code": null,
"e": 3084,
"s": 3005,
"text": "Note that your folder structure should look something like this at this point."
},
{
"code": null,
"e": 3227,
"s": 3084,
"text": "Next, we define some constants that will be used in the movement of vehicles in the simulation as well as in control of traffic signal timers."
},
{
"code": null,
"e": 3627,
"s": 3227,
"text": "# Default values of signal timers in secondsdefaultGreen = {0:20, 1:20, 2:20, 3:20}defaultRed = 150defaultYellow = 5signals = []noOfSignals = 4currentGreen = 0 # Indicates which signal is green currentlynextGreen = (currentGreen+1)%noOfSignals currentYellow = 0 # Indicates whether yellow signal is on or offspeeds = {'car':2.25, 'bus':1.8, 'truck':1.8, 'bike':2.5} # average speeds of vehicles"
},
{
"code": null,
"e": 3755,
"s": 3627,
"text": "The coordinates below are also extracted by opening the 4-way intersection image in Paint/Preview and getting the pixel values."
},
{
"code": null,
"e": 4657,
"s": 3755,
"text": "# Coordinates of vehicles’ startx = {‘right’:[0,0,0], ‘down’:[755,727,697], ‘left’:[1400,1400,1400], ‘up’:[602,627,657]}y = {‘right’:[348,370,398], ‘down’:[0,0,0], ‘left’:[498,466,436], ‘up’:[800,800,800]}vehicles = {‘right’: {0:[], 1:[], 2:[], ‘crossed’:0}, ‘down’: {0:[], 1:[], 2:[], ‘crossed’:0}, ‘left’: {0:[], 1:[], 2:[], ‘crossed’:0}, ‘up’: {0:[], 1:[], 2:[], ‘crossed’:0}}vehicleTypes = {0:’car’, 1:’bus’, 2:’truck’, 3:’bike’}directionNumbers = {0:’right’, 1:’down’, 2:’left’, 3:’up’}# Coordinates of signal image, timer, and vehicle countsignalCoods = [(530,230),(810,230),(810,570),(530,570)]signalTimerCoods = [(530,210),(810,210),(810,550),(530,550)]# Coordinates of stop linesstopLines = {‘right’: 590, ‘down’: 330, ‘left’: 800, ‘up’: 535}defaultStop = {‘right’: 580, ‘down’: 320, ‘left’: 810, ‘up’: 545}# Gap between vehiclesstoppingGap = 15 # stopping gapmovingGap = 15 # moving gap"
},
{
"code": null,
"e": 4709,
"s": 4657,
"text": "Next, we initialize Pygame with the following code:"
},
{
"code": null,
"e": 4757,
"s": 4709,
"text": "pygame.init()simulation = pygame.sprite.Group()"
},
{
"code": null,
"e": 4879,
"s": 4757,
"text": "Now let us build some classes whose objects we will generate in the simulation. We have 2 classes that we need to define."
},
{
"code": null,
"e": 5022,
"s": 4879,
"text": "Traffic Signal: We need to generate 4 traffic signals for our simulation. So we build a TrafficSignal class that has the following attributes:"
},
{
"code": null,
"e": 5165,
"s": 5022,
"text": "Traffic Signal: We need to generate 4 traffic signals for our simulation. So we build a TrafficSignal class that has the following attributes:"
},
{
"code": null,
"e": 5196,
"s": 5165,
"text": "red: Value of red signal timer"
},
{
"code": null,
"e": 5233,
"s": 5196,
"text": "yellow: Value of yellow signal timer"
},
{
"code": null,
"e": 5268,
"s": 5233,
"text": "green: Value of green signal timer"
},
{
"code": null,
"e": 5306,
"s": 5268,
"text": "signalText: Value of timer to display"
},
{
"code": null,
"e": 5474,
"s": 5306,
"text": "class TrafficSignal: def __init__(self, red, yellow, green): self.red = red self.yellow = yellow self.green = green self.signalText = \"\""
},
{
"code": null,
"e": 5644,
"s": 5474,
"text": "2. Vehicle: This is a class that represents objects of vehicles that we will be generating in the simulation. The Vehicle class has the following attributes and methods:"
},
{
"code": null,
"e": 5727,
"s": 5644,
"text": "vehicleClass: Represents the class of the vehicle such as car, bus, truck, or bike"
},
{
"code": null,
"e": 5793,
"s": 5727,
"text": "speed: Represents the speed of the vehicle according to its class"
},
{
"code": null,
"e": 5888,
"s": 5793,
"text": "direction_number: Represents the direction — 0 for right, 1 for down, 2 for left, and 3 for up"
},
{
"code": null,
"e": 5939,
"s": 5888,
"text": "direction: Represents the direction in text format"
},
{
"code": null,
"e": 5993,
"s": 5939,
"text": "x: Represents the current x-coordinate of the vehicle"
},
{
"code": null,
"e": 6047,
"s": 5993,
"text": "y: Represents the current y-coordinate of the vehicle"
},
{
"code": null,
"e": 6117,
"s": 6047,
"text": "crossed: Represents whether the vehicle has crossed the signal or not"
},
{
"code": null,
"e": 6238,
"s": 6117,
"text": "index: Represents the relative position of the vehicle among the vehicles moving in the same direction and the same lane"
},
{
"code": null,
"e": 6281,
"s": 6238,
"text": "image: Represents the image to be rendered"
},
{
"code": null,
"e": 6322,
"s": 6281,
"text": "render(): To display the image on screen"
},
{
"code": null,
"e": 6423,
"s": 6322,
"text": "move(): To control the movement of the vehicle according to the traffic light and the vehicles ahead"
},
{
"code": null,
"e": 8823,
"s": 6423,
"text": "class Vehicle(pygame.sprite.Sprite): def __init__(self, lane, vehicleClass, direction_number, direction): pygame.sprite.Sprite.__init__(self) self.lane = lane self.vehicleClass = vehicleClass self.speed = speeds[vehicleClass] self.direction_number = direction_number self.direction = direction self.x = x[direction][lane] self.y = y[direction][lane] self.crossed = 0 vehicles[direction][lane].append(self) self.index = len(vehicles[direction][lane]) - 1 path = \"images/\" + direction + \"/\" + vehicleClass + \".png\" self.image = pygame.image.load(path) if(len(vehicles[direction][lane])>1 and vehicles[direction][lane][self.index-1].crossed==0): if(direction=='right'): self.stop = vehicles[direction][lane][self.index-1].stop - vehicles[direction][lane][self.index-1].image.get_rect().width - stoppingGap elif(direction=='left'): self.stop = vehicles[direction][lane][self.index-1].stop + vehicles[direction][lane][self.index-1].image.get_rect().width + stoppingGap elif(direction=='down'): self.stop = vehicles[direction][lane][self.index-1].stop - vehicles[direction][lane][self.index-1].image.get_rect().height - stoppingGap elif(direction=='up'): self.stop = vehicles[direction][lane][self.index-1].stop + vehicles[direction][lane][self.index-1].image.get_rect().height + stoppingGap else: self.stop = defaultStop[direction] if(direction=='right'): temp = self.image.get_rect().width + stoppingGap x[direction][lane] -= temp elif(direction=='left'): temp = self.image.get_rect().width + stoppingGap x[direction][lane] += temp elif(direction=='down'): temp = self.image.get_rect().height + stoppingGap y[direction][lane] -= temp elif(direction=='up'): temp = self.image.get_rect().height + stoppingGap y[direction][lane] += temp simulation.add(self) def render(self, screen): screen.blit(self.image, (self.x, self.y))"
},
{
"code": null,
"e": 8877,
"s": 8823,
"text": "Let us understand the latter part of the constructor."
},
{
"code": null,
"e": 9641,
"s": 8877,
"text": "In the constructor, after initializing all the variables, we are checking if there are vehicles already present in the same direction and lane as the current vehicle. If yes, we need to set the value of ‘stop’ of the current vehicle taking into consideration the value of ‘stop’ and the width/height of the vehicle ahead of it, as well as the stoppingGap. If there is no vehicle ahead already, then the stop value is set equal to defaultStop. This value of stop is used to control where the vehicles will stop when the signal is red. Once this is done, we update the coordinates from where the vehicles are generated. This is done to avoid overlapping of newly generated vehicles with the existing vehicles when there are a lot of vehicles stopped at a red light."
},
{
"code": null,
"e": 9863,
"s": 9641,
"text": "Now let’s talk about the move() function, which is one of the most important piece of code in our simulation. Note that this function is also a part of the Vehicle class defined above and needs to be indented accordingly."
},
{
"code": null,
"e": 11939,
"s": 9863,
"text": " def move(self): if(self.direction=='right'): if(self.crossed==0 and self.x+self.image.get_rect().width>stopLines[self.direction]): self.crossed = 1 if((self.x+self.image.get_rect().width<=self.stop or self.crossed == 1 or (currentGreen==0 and currentYellow==0)) and (self.index==0 or self.x+self.image.get_rect().width <(vehicles[self.direction][self.lane][self.index-1].x - movingGap))): self.x += self.speed elif(self.direction=='down'): if(self.crossed==0 and self.y+self.image.get_rect().height>stopLines[self.direction]): self.crossed = 1 if((self.y+self.image.get_rect().height<=self.stop or self.crossed == 1 or (currentGreen==1 and currentYellow==0)) and (self.index==0 or self.y+self.image.get_rect().height <(vehicles[self.direction][self.lane][self.index-1].y - movingGap))): self.y += self.speed elif(self.direction=='left'): if(self.crossed==0 and self.x<stopLines[self.direction]): self.crossed = 1 if((self.x>=self.stop or self.crossed == 1 or (currentGreen==2 and currentYellow==0)) and (self.index==0 or self.x >(vehicles[self.direction][self.lane][self.index-1].x + vehicles[self.direction][self.lane][self.index-1].image.get_rect().width + movingGap))): self.x -= self.speed elif(self.direction=='up'): if(self.crossed==0 and self.y<stopLines[self.direction]): self.crossed = 1 if((self.y>=self.stop or self.crossed == 1 or (currentGreen==3 and currentYellow==0)) and (self.index==0 or self.y >(vehicles[self.direction][self.lane][self.index-1].y + vehicles[self.direction][self.lane][self.index-1].image.get_rect().height + movingGap))): self.y -= self.speed"
},
{
"code": null,
"e": 12337,
"s": 11939,
"text": "For each direction, we first check if the vehicle has crossed the intersection or not. This is important because if the vehicle has already crossed, then it can keep moving regardless of the signal being green or red. So when the vehicle crossed the intersection, we set the value of crossed to 1. Next, we decide when the vehicle moves and when it stops. There are 3 cases when the vehicle moves:"
},
{
"code": null,
"e": 12527,
"s": 12337,
"text": "If it has not reached its stop point before the intersectionIf it has already crossed the intersectionIf the traffic signal controlling the direction in which the vehicle is moving is Green"
},
{
"code": null,
"e": 12588,
"s": 12527,
"text": "If it has not reached its stop point before the intersection"
},
{
"code": null,
"e": 12631,
"s": 12588,
"text": "If it has already crossed the intersection"
},
{
"code": null,
"e": 12719,
"s": 12631,
"text": "If the traffic signal controlling the direction in which the vehicle is moving is Green"
},
{
"code": null,
"e": 13236,
"s": 12719,
"text": "Only in these 3 cases, the coordinates of the vehicle is updated by incrementing/decrementing them by the speed of the vehicle, depending on their direction of motion. However, we need to consider one more possibility that there is a vehicle ahead moving in the same direction and lane. In this case, the vehicle can move only if there is a sufficient gap to the vehicle ahead, and this is decided by taking into consideration the coordinate and the width/height of the vehicle ahead of it, as well as the movingGap."
},
{
"code": null,
"e": 13471,
"s": 13236,
"text": "Next, we initialize 4 TrafficSignal objects, from top left to bottom left in a clockwise direction, with default values of signal timers. The red signal timer of ts2 is set equal to the sum of the yellow and green signal timer of ts1."
},
{
"code": null,
"e": 13862,
"s": 13471,
"text": "def initialize(): ts1 = TrafficSignal(0, defaultYellow, defaultGreen[0]) signals.append(ts1) ts2 = TrafficSignal(ts1.yellow+ts1.green, defaultYellow, defaultGreen[1]) signals.append(ts2) ts3 = TrafficSignal(defaultRed, defaultYellow, defaultGreen[2]) signals.append(ts3) ts4 = TrafficSignal(defaultRed, defaultYellow, defaultGreen[3]) signals.append(ts4) repeat()"
},
{
"code": null,
"e": 14047,
"s": 13862,
"text": "The function repeat() that is called at the end of the initialize() function above is a recursive function that runs our entire simulation. This is the driving force of our simulation."
},
{
"code": null,
"e": 14818,
"s": 14047,
"text": "def repeat(): global currentGreen, currentYellow, nextGreen while(signals[currentGreen].green>0): updateValues() time.sleep(1) currentYellow = 1 for i in range(0,3): for vehicle in vehicles[directionNumbers[currentGreen]][i]: vehicle.stop=defaultStop[directionNumbers[currentGreen]] while(signals[currentGreen].yellow>0): updateValues() time.sleep(1) currentYellow = 0 signals[currentGreen].green = defaultGreen[currentGreen] signals[currentGreen].yellow = defaultYellow signals[currentGreen].red = defaultRed currentGreen = nextGreen nextGreen = (currentGreen+1)%noOfSignals signals[nextGreen].red = signals[currentGreen].yellow+signals[currentGreen].green repeat()"
},
{
"code": null,
"e": 15729,
"s": 14818,
"text": "The repeat() function first calls the updateValues() function every second to update the signal timers until the green timer of the currentGreen signal reaches 0. It then sets that signal to yellow and resets the stop value of all vehicles moving in the direction controlled by the currentGreen signal. It then calls the updateValues() function again after every second until the yellow timer of the currentGreen signal reaches 0. The currentYellow value is now set to 0 as this signal will turn red now. Lastly, the values of the currentGreen signal are restored to the default values, the value of currentGreen and nextGreen is updated to point to the next signals in the cycle, and the value of nextGreen signal’s red timer is updated according to yellow and green of the updated currentGreen signal. The repeat() function then calls itself, and the process is repeated with the updated currentGreen signal."
},
{
"code": null,
"e": 15811,
"s": 15729,
"text": "The function updateValues() updates the timers of all signals after every second."
},
{
"code": null,
"e": 16057,
"s": 15811,
"text": "def updateValues(): for i in range(0, noOfSignals): if(i==currentGreen): if(currentYellow==0): signals[i].green-=1 else: signals[i].yellow-=1 else: signals[i].red-=1"
},
{
"code": null,
"e": 16631,
"s": 16057,
"text": "The generateVehicles() function is used to generate the vehicles. The type of vehicle (car, bus, truck, or bike), the lane number (1 or 2) as well as the direction the vehicle moves towards is decided by using random numbers. The variable dist represents the cumulative distribution of vehicles in percentage. So a distribution of [25,50,75,100] means that there is an equal distribution (25% each) of vehicles across all 4 directions. Some other distributions can be [20,50,70,100], [10,20,30,100], and so on. A new vehicle is added to the simulation after every 1 second."
},
{
"code": null,
"e": 17210,
"s": 16631,
"text": "def generateVehicles(): while(True): vehicle_type = random.randint(0,3) lane_number = random.randint(1,2) temp = random.randint(0,99) direction_number = 0 dist= [25,50,75,100] if(temp<dist[0]): direction_number = 0 elif(temp<dist[1]): direction_number = 1 elif(temp<dist[2]): direction_number = 2 elif(temp<dist[3]): direction_number = 3 Vehicle(lane_number, vehicleTypes[vehicle_type], direction_number, directionNumbers[direction_number]) time.sleep(1)"
},
{
"code": null,
"e": 17319,
"s": 17210,
"text": "And we have reached our last piece of code, the Main class, after which we can see our simulation in action."
},
{
"code": null,
"e": 19267,
"s": 17319,
"text": "class Main: thread1 = threading.Thread(name=\"initialization\",target=initialize, args=()) thread1.daemon = True thread1.start() black = (0, 0, 0) white = (255, 255, 255) screenWidth = 1400 screenHeight = 800 screenSize = (screenWidth, screenHeight) background = pygame.image.load('images/intersection.png') screen = pygame.display.set_mode(screenSize) pygame.display.set_caption(\"SIMULATION\") redSignal = pygame.image.load('images/signals/red.png') yellowSignal = pygame.image.load('images/signals/yellow.png') greenSignal = pygame.image.load('images/signals/green.png') font = pygame.font.Font(None, 30) thread2 = threading.Thread(name=\"generateVehicles\",target=generateVehicles, args=()) thread2.daemon = True thread2.start() while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() screen.blit(background,(0,0)) for i in range(0,noOfSignals): if(i==currentGreen): if(currentYellow==1): signals[i].signalText = signals[i].yellow screen.blit(yellowSignal, signalCoods[i]) else: signals[i].signalText = signals[i].green screen.blit(greenSignal, signalCoods[i]) else: if(signals[i].red<=10): signals[i].signalText = signals[i].red else: signals[i].signalText = \"---\" screen.blit(redSignal, signalCoods[i]) signalTexts = [\"\",\"\",\"\",\"\"] for i in range(0,noOfSignals): signalTexts[i] = font.render(str(signals[i].signalText), True, white, black) screen.blit(signalTexts[i],signalTimerCoods[i]) for vehicle in simulation: screen.blit(vehicle.image, [vehicle.x, vehicle.y]) vehicle.move() pygame.display.update()"
},
{
"code": null,
"e": 19793,
"s": 19267,
"text": "Let us understand the Main() function by breaking it down into smaller pieces. We start by creating a separate thread for initialize() method, which instantiates the 4 TrafficSignal objects. Then we define 2 colours, white and black, that we will be using in our display. Next, we define the screen width and screen size, as well as the background and caption to be displayed in the simulation window. We then load the images of the 3 signals, i.e. red, yellow, and green. Now we create another thread for generateVehicles()."
},
{
"code": null,
"e": 20190,
"s": 19793,
"text": "Next, we run an infinite loop that updates our simulation screen continuously. Within the loop, we first define the exit criteria. In the next section, we render the appropriate signal image and signal timer for each of the 4 traffic signals. Finally, we render the vehicles on the screen and call the function move() on each vehicle. This function causes the vehicles to move in the next update."
},
{
"code": null,
"e": 20370,
"s": 20190,
"text": "The blit() function is used to render the objects on the screen. It takes 2 arguments, the image to render and the coordinates. The coordinates point to the top-left of the image."
},
{
"code": null,
"e": 20454,
"s": 20370,
"text": "Almost done! Now we just need to call the Main() program, and our code is complete."
},
{
"code": null,
"e": 20461,
"s": 20454,
"text": "Main()"
},
{
"code": null,
"e": 20530,
"s": 20461,
"text": "Time to see the results. Fire up a cmd/terminal and run the command:"
},
{
"code": null,
"e": 20553,
"s": 20530,
"text": "$ python simulation.py"
},
{
"code": null,
"e": 20795,
"s": 20553,
"text": "And voila! We have a fully functional simulation of a 4-way intersection that we have built from scratch, right from getting the image of the intersection, signals, and vehicles, to coding the logic for signal switching and vehicle movement."
},
{
"code": null,
"e": 20880,
"s": 20795,
"text": "Source code: https://github.com/mihir-m-gandhi/Basic-Traffic-Intersection-Simulation"
},
{
"code": null,
"e": 20928,
"s": 20880,
"text": "This is the first part in a series of articles:"
},
{
"code": null,
"e": 20981,
"s": 20928,
"text": "Traffic Intersection Simulation using Pygame, Part 1"
},
{
"code": null,
"e": 21034,
"s": 20981,
"text": "Traffic Intersection Simulation using Pygame, Part 2"
},
{
"code": null,
"e": 21087,
"s": 21034,
"text": "Traffic Intersection Simulation using Pygame, Part 3"
},
{
"code": null,
"e": 21440,
"s": 21087,
"text": "This simulation was developed as part of a research project titled ‘Smart Control of Traffic Lights using Artificial Intelligence’. Check out its demonstration video here. This research work was presented at IEEE International Conference on Recent Advances and Innovations in Engineering (ICRAIE) 2020 and published in IEEE Xplore. Read the paper here."
}
]
|
Apply function to every row in a Pandas DataFrame - GeeksforGeeks | 17 May, 2021
Python is a great language for performing data analysis tasks. It provides with a huge amount of Classes and function which help in analyzing and manipulating data in an easier way. One can use apply() function in order to apply function to every row in given dataframe. Let’s see the ways we can do this task.Example #1:
Python3
# Import pandas packageimport pandas as pd # Function to adddef add(a, b, c): return a + b + c def main(): # create a dictionary with # three fields each data = { 'A':[1, 2, 3], 'B':[4, 5, 6], 'C':[7, 8, 9] } # Convert the dictionary into DataFrame df = pd.DataFrame(data) print("Original DataFrame:\n", df) df['add'] = df.apply(lambda row : add(row['A'], row['B'], row['C']), axis = 1) print('\nAfter Applying Function: ') # printing the new dataframe print(df) if __name__ == '__main__': main()
Output:
Example #2:You can use the numpy function as the parameters to the dataframe as well.
Python3
import pandas as pdimport numpy as np def main(): # create a dictionary with # five fields each data = { 'A':[1, 2, 3], 'B':[4, 5, 6], 'C':[7, 8, 9] } # Convert the dictionary into DataFrame df = pd.DataFrame(data) print("Original DataFrame:\n", df) # applying function to each row in the dataframe # and storing result in a new column df['add'] = df.apply(np.sum, axis = 1) print('\nAfter Applying Function: ') # printing the new dataframe print(df) if __name__ == '__main__': main()
Output:
Example #3: Normalising Data
Python3
# Import pandas packageimport pandas as pd def normalize(x, y): x_new = ((x - np.mean([x, y])) / (max(x, y) - min(x, y))) # print(x_new) return x_new def main(): # create a dictionary with three fields each data = { 'X':[1, 2, 3], 'Y':[45, 65, 89] } # Convert the dictionary into DataFrame df = pd.DataFrame(data) print("Original DataFrame:\n", df) df['X'] = df.apply(lambda row : normalize(row['X'], row['Y']), axis = 1) print('\nNormalized:') print(df) if __name__ == '__main__': main()
Output:
Example #4: Generate range
Python3
import pandas as pdimport numpy as np pd.options.mode.chained_assignment = None # Function to generate rangedef generate_range(n): # printing the range for eg: # input is 67 output is 60-70 n = int(n) lower_limit = n//10 * 10 upper_limit = lower_limit + 10 return str(str(lower_limit) + '-' + str(upper_limit)) def replace(row): for i, item in enumerate(row): # updating the value of the row row[i] = generate_range(item) return row def main(): # create a dictionary with # three fields each data = { 'A':[0, 2, 3], 'B':[4, 15, 6], 'C':[47, 8, 19] } # Convert the dictionary into DataFrame df = pd.DataFrame(data) print('Before applying function: ') print(df) # applying function to each row in # dataframe and storing result in a new column df = df.apply(lambda row : replace(row)) print('After Applying Function: ') # printing the new dataframe print(df) if __name__ == '__main__': main()
Output:
sweetyty
pandas-dataframe-program
Picked
Python pandas-dataFrame
Python-pandas
Technical Scripter 2018
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
*args and **kwargs in Python | [
{
"code": null,
"e": 25114,
"s": 25086,
"text": "\n17 May, 2021"
},
{
"code": null,
"e": 25438,
"s": 25114,
"text": "Python is a great language for performing data analysis tasks. It provides with a huge amount of Classes and function which help in analyzing and manipulating data in an easier way. One can use apply() function in order to apply function to every row in given dataframe. Let’s see the ways we can do this task.Example #1: "
},
{
"code": null,
"e": 25446,
"s": 25438,
"text": "Python3"
},
{
"code": "# Import pandas packageimport pandas as pd # Function to adddef add(a, b, c): return a + b + c def main(): # create a dictionary with # three fields each data = { 'A':[1, 2, 3], 'B':[4, 5, 6], 'C':[7, 8, 9] } # Convert the dictionary into DataFrame df = pd.DataFrame(data) print(\"Original DataFrame:\\n\", df) df['add'] = df.apply(lambda row : add(row['A'], row['B'], row['C']), axis = 1) print('\\nAfter Applying Function: ') # printing the new dataframe print(df) if __name__ == '__main__': main()",
"e": 26050,
"s": 25446,
"text": null
},
{
"code": null,
"e": 26060,
"s": 26050,
"text": "Output: "
},
{
"code": null,
"e": 26149,
"s": 26060,
"text": " Example #2:You can use the numpy function as the parameters to the dataframe as well. "
},
{
"code": null,
"e": 26157,
"s": 26149,
"text": "Python3"
},
{
"code": "import pandas as pdimport numpy as np def main(): # create a dictionary with # five fields each data = { 'A':[1, 2, 3], 'B':[4, 5, 6], 'C':[7, 8, 9] } # Convert the dictionary into DataFrame df = pd.DataFrame(data) print(\"Original DataFrame:\\n\", df) # applying function to each row in the dataframe # and storing result in a new column df['add'] = df.apply(np.sum, axis = 1) print('\\nAfter Applying Function: ') # printing the new dataframe print(df) if __name__ == '__main__': main()",
"e": 26733,
"s": 26157,
"text": null
},
{
"code": null,
"e": 26743,
"s": 26733,
"text": "Output: "
},
{
"code": null,
"e": 26776,
"s": 26743,
"text": " Example #3: Normalising Data "
},
{
"code": null,
"e": 26784,
"s": 26776,
"text": "Python3"
},
{
"code": "# Import pandas packageimport pandas as pd def normalize(x, y): x_new = ((x - np.mean([x, y])) / (max(x, y) - min(x, y))) # print(x_new) return x_new def main(): # create a dictionary with three fields each data = { 'X':[1, 2, 3], 'Y':[45, 65, 89] } # Convert the dictionary into DataFrame df = pd.DataFrame(data) print(\"Original DataFrame:\\n\", df) df['X'] = df.apply(lambda row : normalize(row['X'], row['Y']), axis = 1) print('\\nNormalized:') print(df) if __name__ == '__main__': main()",
"e": 27391,
"s": 26784,
"text": null
},
{
"code": null,
"e": 27401,
"s": 27391,
"text": "Output: "
},
{
"code": null,
"e": 27431,
"s": 27401,
"text": " Example #4: Generate range "
},
{
"code": null,
"e": 27439,
"s": 27431,
"text": "Python3"
},
{
"code": "import pandas as pdimport numpy as np pd.options.mode.chained_assignment = None # Function to generate rangedef generate_range(n): # printing the range for eg: # input is 67 output is 60-70 n = int(n) lower_limit = n//10 * 10 upper_limit = lower_limit + 10 return str(str(lower_limit) + '-' + str(upper_limit)) def replace(row): for i, item in enumerate(row): # updating the value of the row row[i] = generate_range(item) return row def main(): # create a dictionary with # three fields each data = { 'A':[0, 2, 3], 'B':[4, 15, 6], 'C':[47, 8, 19] } # Convert the dictionary into DataFrame df = pd.DataFrame(data) print('Before applying function: ') print(df) # applying function to each row in # dataframe and storing result in a new column df = df.apply(lambda row : replace(row)) print('After Applying Function: ') # printing the new dataframe print(df) if __name__ == '__main__': main()",
"e": 28506,
"s": 27439,
"text": null
},
{
"code": null,
"e": 28516,
"s": 28506,
"text": "Output: "
},
{
"code": null,
"e": 28527,
"s": 28518,
"text": "sweetyty"
},
{
"code": null,
"e": 28552,
"s": 28527,
"text": "pandas-dataframe-program"
},
{
"code": null,
"e": 28559,
"s": 28552,
"text": "Picked"
},
{
"code": null,
"e": 28583,
"s": 28559,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 28597,
"s": 28583,
"text": "Python-pandas"
},
{
"code": null,
"e": 28621,
"s": 28597,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 28628,
"s": 28621,
"text": "Python"
},
{
"code": null,
"e": 28647,
"s": 28628,
"text": "Technical Scripter"
},
{
"code": null,
"e": 28745,
"s": 28647,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28754,
"s": 28745,
"text": "Comments"
},
{
"code": null,
"e": 28767,
"s": 28754,
"text": "Old Comments"
},
{
"code": null,
"e": 28785,
"s": 28767,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28820,
"s": 28785,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28842,
"s": 28820,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28874,
"s": 28842,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28904,
"s": 28874,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28946,
"s": 28904,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28989,
"s": 28946,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 29026,
"s": 28989,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 29070,
"s": 29026,
"text": "Reading and Writing to text files in Python"
}
]
|
How to create JavaFX slider with two thumbs? | In general, a slider is a component that displays a continuous range of values. This contains a track on which the numerical values are displayed. Along the track, there is a thumb pointing to the numbers. You can provide the maximum, minimum and initial values of the slider.
The slider JavaFX provides contains only one thumb if you want to create a slider with two thumbs you need to rely on an external library named org.controlsfx.control.
Following is the maven dependency for this library −
<dependency>
<groupId>org.controlsfx</groupId>
<artifactId>controlsfx</artifactId>
<version>11.0.1</version>
</dependency>
The RangeSlider class of this package is the JavaFXSlider but with two thumbs. Therefore to use it instantiate this class, add the required attributes, add it to the Node object.
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import org.controlsfx.control.RangeSlider;
public class SliderTwoThumbs extends Application {
public void start(Stage stage) {
//Instantiating the RangeSlider class
RangeSlider slider = new RangeSlider(0, 100, 10, 90);
//Setting the slider properties
slider.setShowTickLabels(true);
slider.setShowTickMarks(true);
slider.setMajorTickUnit(25);
slider.setBlockIncrement(10);
//VBox to arrange circle and the slider
VBox vbox = new VBox();
vbox.setPadding(new Insets(75));
vbox.setSpacing(150);
vbox.getChildren().addAll(slider);
//Preparing the scene
Scene scene = new Scene(vbox, 600, 200);
stage.setTitle("Slider Example");
stage.setScene(scene);
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
Output: | [
{
"code": null,
"e": 1339,
"s": 1062,
"text": "In general, a slider is a component that displays a continuous range of values. This contains a track on which the numerical values are displayed. Along the track, there is a thumb pointing to the numbers. You can provide the maximum, minimum and initial values of the slider."
},
{
"code": null,
"e": 1507,
"s": 1339,
"text": "The slider JavaFX provides contains only one thumb if you want to create a slider with two thumbs you need to rely on an external library named org.controlsfx.control."
},
{
"code": null,
"e": 1560,
"s": 1507,
"text": "Following is the maven dependency for this library −"
},
{
"code": null,
"e": 1692,
"s": 1560,
"text": "<dependency>\n <groupId>org.controlsfx</groupId>\n <artifactId>controlsfx</artifactId>\n <version>11.0.1</version>\n</dependency>"
},
{
"code": null,
"e": 1871,
"s": 1692,
"text": "The RangeSlider class of this package is the JavaFXSlider but with two thumbs. Therefore to use it instantiate this class, add the required attributes, add it to the Node object."
},
{
"code": null,
"e": 2869,
"s": 1871,
"text": "import javafx.application.Application;\nimport javafx.geometry.Insets;\nimport javafx.scene.Scene;\nimport javafx.scene.layout.VBox;\nimport javafx.stage.Stage;\nimport org.controlsfx.control.RangeSlider;\npublic class SliderTwoThumbs extends Application {\n public void start(Stage stage) {\n //Instantiating the RangeSlider class\n RangeSlider slider = new RangeSlider(0, 100, 10, 90);\n //Setting the slider properties\n slider.setShowTickLabels(true);\n slider.setShowTickMarks(true);\n slider.setMajorTickUnit(25);\n slider.setBlockIncrement(10);\n //VBox to arrange circle and the slider\n VBox vbox = new VBox();\n vbox.setPadding(new Insets(75));\n vbox.setSpacing(150);\n vbox.getChildren().addAll(slider);\n //Preparing the scene\n Scene scene = new Scene(vbox, 600, 200);\n stage.setTitle(\"Slider Example\");\n stage.setScene(scene);\n stage.show();\n }\n public static void main(String args[]){\n launch(args);\n }\n}"
},
{
"code": null,
"e": 2877,
"s": 2869,
"text": "Output:"
}
]
|
Contingency Table in Python - GeeksforGeeks | 21 Jan, 2019
Estimations like mean, median, standard deviation, and variance are very much useful in case of the univariate data analysis. But in the case of bivariate analysis(comparing two variables) correlation comes into play.
Contingency Table is one of the techniques for exploring two or even more variables. It is basically a tally of counts between two or more categorical variables.
To get the Loan Data click here.
Loading Libraries
import numpy as npimport pandas as pdimport matplotlib as plt
Loading Data
data = pd.read_csv("loan_status.csv") print (data.head(10))
Output:
Describe Data
data.describe()
Output:
Data Info
data.info()
Output:
Data Types
# data types of feature/attributes # in the datadata.dtypes
Output:
Code #1: Contingency Table showing correlation between Grades and loan status.
data_crosstab = pd.crosstab(data['grade'], data['loan_status'], margins = False)print(data_crosstab)
Output:
Code #2: Contingency Table showing correlation between Purpose and loan status.
data_crosstab = pd.crosstab(data['purpose'], data['loan_status'], margins = False)print(data_crosstab)
Output:
Code #3: Contingency Table showing correlation between Grades+Purpose and loan status.
data_crosstab = pd.crosstab([data.grade, data.purpose], data.loan_status, margins = False)print(data_crosstab)
Output:
So as in the code, Contingency Tables are giving clear correlation values between two and more variables. Thus making it much more useful to understand the data for further information extraction..
data-science
Python-pandas
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
Python | Decision tree implementation
Search Algorithms in AI
Decision Tree Introduction with example
Reinforcement learning
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe | [
{
"code": null,
"e": 24758,
"s": 24730,
"text": "\n21 Jan, 2019"
},
{
"code": null,
"e": 24976,
"s": 24758,
"text": "Estimations like mean, median, standard deviation, and variance are very much useful in case of the univariate data analysis. But in the case of bivariate analysis(comparing two variables) correlation comes into play."
},
{
"code": null,
"e": 25138,
"s": 24976,
"text": "Contingency Table is one of the techniques for exploring two or even more variables. It is basically a tally of counts between two or more categorical variables."
},
{
"code": null,
"e": 25171,
"s": 25138,
"text": "To get the Loan Data click here."
},
{
"code": null,
"e": 25189,
"s": 25171,
"text": "Loading Libraries"
},
{
"code": "import numpy as npimport pandas as pdimport matplotlib as plt",
"e": 25251,
"s": 25189,
"text": null
},
{
"code": null,
"e": 25264,
"s": 25251,
"text": "Loading Data"
},
{
"code": "data = pd.read_csv(\"loan_status.csv\") print (data.head(10))",
"e": 25325,
"s": 25264,
"text": null
},
{
"code": null,
"e": 25333,
"s": 25325,
"text": "Output:"
},
{
"code": null,
"e": 25347,
"s": 25333,
"text": "Describe Data"
},
{
"code": "data.describe()",
"e": 25363,
"s": 25347,
"text": null
},
{
"code": null,
"e": 25371,
"s": 25363,
"text": "Output:"
},
{
"code": null,
"e": 25381,
"s": 25371,
"text": "Data Info"
},
{
"code": "data.info()",
"e": 25393,
"s": 25381,
"text": null
},
{
"code": null,
"e": 25401,
"s": 25393,
"text": "Output:"
},
{
"code": null,
"e": 25412,
"s": 25401,
"text": "Data Types"
},
{
"code": "# data types of feature/attributes # in the datadata.dtypes",
"e": 25472,
"s": 25412,
"text": null
},
{
"code": null,
"e": 25480,
"s": 25472,
"text": "Output:"
},
{
"code": null,
"e": 25559,
"s": 25480,
"text": "Code #1: Contingency Table showing correlation between Grades and loan status."
},
{
"code": "data_crosstab = pd.crosstab(data['grade'], data['loan_status'], margins = False)print(data_crosstab)",
"e": 25718,
"s": 25559,
"text": null
},
{
"code": null,
"e": 25726,
"s": 25718,
"text": "Output:"
},
{
"code": null,
"e": 25806,
"s": 25726,
"text": "Code #2: Contingency Table showing correlation between Purpose and loan status."
},
{
"code": "data_crosstab = pd.crosstab(data['purpose'], data['loan_status'], margins = False)print(data_crosstab)",
"e": 25968,
"s": 25806,
"text": null
},
{
"code": null,
"e": 25976,
"s": 25968,
"text": "Output:"
},
{
"code": null,
"e": 26063,
"s": 25976,
"text": "Code #3: Contingency Table showing correlation between Grades+Purpose and loan status."
},
{
"code": "data_crosstab = pd.crosstab([data.grade, data.purpose], data.loan_status, margins = False)print(data_crosstab)",
"e": 26203,
"s": 26063,
"text": null
},
{
"code": null,
"e": 26211,
"s": 26203,
"text": "Output:"
},
{
"code": null,
"e": 26409,
"s": 26211,
"text": "So as in the code, Contingency Tables are giving clear correlation values between two and more variables. Thus making it much more useful to understand the data for further information extraction.."
},
{
"code": null,
"e": 26422,
"s": 26409,
"text": "data-science"
},
{
"code": null,
"e": 26436,
"s": 26422,
"text": "Python-pandas"
},
{
"code": null,
"e": 26453,
"s": 26436,
"text": "Machine Learning"
},
{
"code": null,
"e": 26460,
"s": 26453,
"text": "Python"
},
{
"code": null,
"e": 26477,
"s": 26460,
"text": "Machine Learning"
},
{
"code": null,
"e": 26575,
"s": 26477,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26598,
"s": 26575,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 26636,
"s": 26598,
"text": "Python | Decision tree implementation"
},
{
"code": null,
"e": 26660,
"s": 26636,
"text": "Search Algorithms in AI"
},
{
"code": null,
"e": 26700,
"s": 26660,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 26723,
"s": 26700,
"text": "Reinforcement learning"
},
{
"code": null,
"e": 26751,
"s": 26723,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 26801,
"s": 26751,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 26823,
"s": 26801,
"text": "Python map() function"
}
]
|
How to load html content in android webview? | This example demonstrate about How to load html content in android webview.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:app = "http://schemas.android.com/apk/res-auto"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:gravity = "center"
android:layout_height = "match_parent"
tools:context = ".MainActivity"
android:orientation = "vertical">
<WebView
android:id = "@+id/web_view"
android:layout_width = "match_parent"
android:layout_height = "match_parent" />
</LinearLayout>
In the above code, we have taken web view to show html content.
Step 3 − Add the following code to src/MainActivity.java
package com.example.myapplication;
import android.app.ProgressDialog;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
@RequiresApi(api = Build.VERSION_CODES.P)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading Data...");
progressDialog.setCancelable(false);
WebView web_view = findViewById(R.id.web_view);
web_view.requestFocus();
web_view.getSettings().setLightTouchEnabled(true);
web_view.getSettings().setJavaScriptEnabled(true);
web_view.getSettings().setGeolocationEnabled(true);
web_view.setSoundEffectsEnabled(true);
web_view.loadData("<html><body>Hello, world!</body></html>",
"text/html", "UTF-8");
web_view.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
if (progress < 100) {
progressDialog.show();
}
if (progress = = 100) {
progressDialog.dismiss();
}
}
});
}
}
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Click here to download the project code | [
{
"code": null,
"e": 1138,
"s": 1062,
"text": "This example demonstrate about How to load html content in android webview."
},
{
"code": null,
"e": 1267,
"s": 1138,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1332,
"s": 1267,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1899,
"s": 1332,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:app = \"http://schemas.android.com/apk/res-auto\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:gravity = \"center\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\"\n android:orientation = \"vertical\">\n <WebView\n android:id = \"@+id/web_view\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\" />\n</LinearLayout>"
},
{
"code": null,
"e": 1963,
"s": 1899,
"text": "In the above code, we have taken web view to show html content."
},
{
"code": null,
"e": 2020,
"s": 1963,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 3551,
"s": 2020,
"text": "package com.example.myapplication;\nimport android.app.ProgressDialog;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.annotation.RequiresApi;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.webkit.WebChromeClient;\nimport android.webkit.WebSettings;\nimport android.webkit.WebView;\nimport android.widget.EditText;\npublic class MainActivity extends AppCompatActivity {\n @RequiresApi(api = Build.VERSION_CODES.P)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n final ProgressDialog progressDialog = new ProgressDialog(this);\n progressDialog.setMessage(\"Loading Data...\");\n progressDialog.setCancelable(false);\n WebView web_view = findViewById(R.id.web_view);\n web_view.requestFocus();\n web_view.getSettings().setLightTouchEnabled(true);\n web_view.getSettings().setJavaScriptEnabled(true);\n web_view.getSettings().setGeolocationEnabled(true);\n web_view.setSoundEffectsEnabled(true);\n web_view.loadData(\"<html><body>Hello, world!</body></html>\",\n \"text/html\", \"UTF-8\");\n web_view.setWebChromeClient(new WebChromeClient() {\n public void onProgressChanged(WebView view, int progress) {\n if (progress < 100) {\n progressDialog.show();\n }\n if (progress = = 100) {\n progressDialog.dismiss();\n }\n }\n });\n }\n}"
},
{
"code": null,
"e": 3898,
"s": 3551,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –"
},
{
"code": null,
"e": 3938,
"s": 3898,
"text": "Click here to download the project code"
}
]
|
Deque iterator() method in Java - GeeksforGeeks | 20 Jun, 2020
The iterator() method of Deque Interface returns an iterator over the elements in this deque in a proper sequence. The elements will be returned in order from first (head) to last (tail). The returned iterator is a “weakly consistent” iterator.
Syntax:
Iterator iterator()
Parameters: This method does not accepts any parameter.
Returns: This method returns an iterator over the elements in this deque in a proper sequence.
Below programs illustrate iterator() method of Deque:
Program 1: With the help of ArrayDeque.
// Java Program Demonstrate iterator()// method of Dequeimport java.util.*; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Deque Deque<Integer> DQ = new ArrayDeque<Integer>(); // Add numbers to end of Deque DQ.add(7855642); DQ.add(35658786); DQ.add(5278367); DQ.add(74381793); // Call iterator() method of Deque Iterator iteratorVals = DQ.iterator(); // Print elements of iterator // created from Deque System.out.println("The iterator values" + " of Deque are:"); // prints the elements using an iterator while (iteratorVals.hasNext()) { System.out.println(iteratorVals.next()); } }}
The iterator values of Deque are:
7855642
35658786
5278367
74381793
Program 2: With the help of LinkedList.
// Java Program Demonstrate iterator()// method of Dequeimport java.util.*; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Deque Deque<Integer> DQ = new LinkedList<Integer>(); // Add numbers to end of Deque DQ.add(7855642); DQ.add(35658786); DQ.add(5278367); DQ.add(74381793); // Call iterator() method of Deque Iterator iteratorVals = DQ.iterator(); // Print elements of iterator // created from Deque System.out.println("The iterator values" + " of Deque are:"); // prints the elements using an iterator while (iteratorVals.hasNext()) { System.out.println(iteratorVals.next()); } }}
The iterator values of Deque are:
7855642
35658786
5278367
74381793
Program 3: With the help of LinkedBlockingDeque.
// Java Program Demonstrate iterator()// method of Dequeimport java.util.*;import java.util.concurrent.LinkedBlockingDeque; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Deque Deque<Integer> DQ = new LinkedBlockingDeque<Integer>(); // Add numbers to end of Deque DQ.add(7855642); DQ.add(35658786); DQ.add(5278367); DQ.add(74381793); // Call iterator() method of Deque Iterator iteratorVals = DQ.iterator(); // Print elements of iterator // created from Deque System.out.println("The iterator values" + " of Deque are:"); // prints the elements using an iterator while (iteratorVals.hasNext()) { System.out.println(iteratorVals.next()); } }}
The iterator values of Deque are:
7855642
35658786
5278367
74381793
Program 4: With the help of ConcurrentLinkedDeque.
// Java Program Demonstrate iterator()// method of Dequeimport java.util.*;import java.util.concurrent.ConcurrentLinkedDeque; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Deque Deque<Integer> DQ = new ConcurrentLinkedDeque<Integer>(); // Add numbers to end of Deque DQ.add(7855642); DQ.add(35658786); DQ.add(5278367); DQ.add(74381793); // Call iterator() method of Deque Iterator iteratorVals = DQ.iterator(); // Print elements of iterator // created from Deque System.out.println("The iterator values" + " of Deque are:"); // prints the elements using an iterator while (iteratorVals.hasNext()) { System.out.println(iteratorVals.next()); } }}
The iterator values of Deque are:
7855642
35658786
5278367
74381793
Reference: https://docs.oracle.com/javase/8/docs/api/java/util/Deque.html#iterator–
KaashyapMSK
Java - util package
java-deque
Java-Functions
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Different ways of Reading a text file in Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Generics in Java
Comparator Interface in Java with Examples
HashMap get() Method in Java
Introduction to Java
Difference between Abstract Class and Interface in Java | [
{
"code": null,
"e": 23948,
"s": 23920,
"text": "\n20 Jun, 2020"
},
{
"code": null,
"e": 24193,
"s": 23948,
"text": "The iterator() method of Deque Interface returns an iterator over the elements in this deque in a proper sequence. The elements will be returned in order from first (head) to last (tail). The returned iterator is a “weakly consistent” iterator."
},
{
"code": null,
"e": 24201,
"s": 24193,
"text": "Syntax:"
},
{
"code": null,
"e": 24221,
"s": 24201,
"text": "Iterator iterator()"
},
{
"code": null,
"e": 24277,
"s": 24221,
"text": "Parameters: This method does not accepts any parameter."
},
{
"code": null,
"e": 24372,
"s": 24277,
"text": "Returns: This method returns an iterator over the elements in this deque in a proper sequence."
},
{
"code": null,
"e": 24426,
"s": 24372,
"text": "Below programs illustrate iterator() method of Deque:"
},
{
"code": null,
"e": 24466,
"s": 24426,
"text": "Program 1: With the help of ArrayDeque."
},
{
"code": "// Java Program Demonstrate iterator()// method of Dequeimport java.util.*; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Deque Deque<Integer> DQ = new ArrayDeque<Integer>(); // Add numbers to end of Deque DQ.add(7855642); DQ.add(35658786); DQ.add(5278367); DQ.add(74381793); // Call iterator() method of Deque Iterator iteratorVals = DQ.iterator(); // Print elements of iterator // created from Deque System.out.println(\"The iterator values\" + \" of Deque are:\"); // prints the elements using an iterator while (iteratorVals.hasNext()) { System.out.println(iteratorVals.next()); } }}",
"e": 25293,
"s": 24466,
"text": null
},
{
"code": null,
"e": 25362,
"s": 25293,
"text": "The iterator values of Deque are:\n7855642\n35658786\n5278367\n74381793\n"
},
{
"code": null,
"e": 25402,
"s": 25362,
"text": "Program 2: With the help of LinkedList."
},
{
"code": "// Java Program Demonstrate iterator()// method of Dequeimport java.util.*; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Deque Deque<Integer> DQ = new LinkedList<Integer>(); // Add numbers to end of Deque DQ.add(7855642); DQ.add(35658786); DQ.add(5278367); DQ.add(74381793); // Call iterator() method of Deque Iterator iteratorVals = DQ.iterator(); // Print elements of iterator // created from Deque System.out.println(\"The iterator values\" + \" of Deque are:\"); // prints the elements using an iterator while (iteratorVals.hasNext()) { System.out.println(iteratorVals.next()); } }}",
"e": 26229,
"s": 25402,
"text": null
},
{
"code": null,
"e": 26298,
"s": 26229,
"text": "The iterator values of Deque are:\n7855642\n35658786\n5278367\n74381793\n"
},
{
"code": null,
"e": 26347,
"s": 26298,
"text": "Program 3: With the help of LinkedBlockingDeque."
},
{
"code": "// Java Program Demonstrate iterator()// method of Dequeimport java.util.*;import java.util.concurrent.LinkedBlockingDeque; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Deque Deque<Integer> DQ = new LinkedBlockingDeque<Integer>(); // Add numbers to end of Deque DQ.add(7855642); DQ.add(35658786); DQ.add(5278367); DQ.add(74381793); // Call iterator() method of Deque Iterator iteratorVals = DQ.iterator(); // Print elements of iterator // created from Deque System.out.println(\"The iterator values\" + \" of Deque are:\"); // prints the elements using an iterator while (iteratorVals.hasNext()) { System.out.println(iteratorVals.next()); } }}",
"e": 27231,
"s": 26347,
"text": null
},
{
"code": null,
"e": 27300,
"s": 27231,
"text": "The iterator values of Deque are:\n7855642\n35658786\n5278367\n74381793\n"
},
{
"code": null,
"e": 27351,
"s": 27300,
"text": "Program 4: With the help of ConcurrentLinkedDeque."
},
{
"code": "// Java Program Demonstrate iterator()// method of Dequeimport java.util.*;import java.util.concurrent.ConcurrentLinkedDeque; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Deque Deque<Integer> DQ = new ConcurrentLinkedDeque<Integer>(); // Add numbers to end of Deque DQ.add(7855642); DQ.add(35658786); DQ.add(5278367); DQ.add(74381793); // Call iterator() method of Deque Iterator iteratorVals = DQ.iterator(); // Print elements of iterator // created from Deque System.out.println(\"The iterator values\" + \" of Deque are:\"); // prints the elements using an iterator while (iteratorVals.hasNext()) { System.out.println(iteratorVals.next()); } }}",
"e": 28239,
"s": 27351,
"text": null
},
{
"code": null,
"e": 28308,
"s": 28239,
"text": "The iterator values of Deque are:\n7855642\n35658786\n5278367\n74381793\n"
},
{
"code": null,
"e": 28392,
"s": 28308,
"text": "Reference: https://docs.oracle.com/javase/8/docs/api/java/util/Deque.html#iterator–"
},
{
"code": null,
"e": 28404,
"s": 28392,
"text": "KaashyapMSK"
},
{
"code": null,
"e": 28424,
"s": 28404,
"text": "Java - util package"
},
{
"code": null,
"e": 28435,
"s": 28424,
"text": "java-deque"
},
{
"code": null,
"e": 28450,
"s": 28435,
"text": "Java-Functions"
},
{
"code": null,
"e": 28455,
"s": 28450,
"text": "Java"
},
{
"code": null,
"e": 28460,
"s": 28455,
"text": "Java"
},
{
"code": null,
"e": 28558,
"s": 28460,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28573,
"s": 28558,
"text": "Stream In Java"
},
{
"code": null,
"e": 28619,
"s": 28573,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 28640,
"s": 28619,
"text": "Constructors in Java"
},
{
"code": null,
"e": 28659,
"s": 28640,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 28689,
"s": 28659,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 28706,
"s": 28689,
"text": "Generics in Java"
},
{
"code": null,
"e": 28749,
"s": 28706,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 28778,
"s": 28749,
"text": "HashMap get() Method in Java"
},
{
"code": null,
"e": 28799,
"s": 28778,
"text": "Introduction to Java"
}
]
|
What are different types of constants in C language? | Constant is a value that cannot be changed during program execution; it is fixed.
In C language, a number or character or string of characters is called a constant. And it can be any data type. Constants are also called as literals.
There are two types of constants −
Primary constants − Integer, float, and character are called as Primary constants.
Secondary constants − Array, structures, pointers, Enum, etc., called as secondary constants.
const datatype variable;
Live Demo
#include<stdio.h>
int main(){
const int height=20;
const int base=40;
float area;
area=0.5 * height*base;
printf("The area of triangle :%f", area);
return 0;
}
The area of triangle :400.000000
Live Demo
include<stdio.h>
void main(){
int a;
int *p;
a=10;
p=&a;
printf("a=%d\n",a);//10//
printf("p=%d\n",p);//address value of p//
*p=12;
printf("a=%d\n",a);//12//
printf("p=%d\n",p);//address value of p//
}
a=10
p=6422036
a=12
p=6422036 | [
{
"code": null,
"e": 1144,
"s": 1062,
"text": "Constant is a value that cannot be changed during program execution; it is fixed."
},
{
"code": null,
"e": 1295,
"s": 1144,
"text": "In C language, a number or character or string of characters is called a constant. And it can be any data type. Constants are also called as literals."
},
{
"code": null,
"e": 1330,
"s": 1295,
"text": "There are two types of constants −"
},
{
"code": null,
"e": 1413,
"s": 1330,
"text": "Primary constants − Integer, float, and character are called as Primary constants."
},
{
"code": null,
"e": 1507,
"s": 1413,
"text": "Secondary constants − Array, structures, pointers, Enum, etc., called as secondary constants."
},
{
"code": null,
"e": 1532,
"s": 1507,
"text": "const datatype variable;"
},
{
"code": null,
"e": 1543,
"s": 1532,
"text": " Live Demo"
},
{
"code": null,
"e": 1721,
"s": 1543,
"text": "#include<stdio.h>\nint main(){\n const int height=20;\n const int base=40;\n float area;\n area=0.5 * height*base;\n printf(\"The area of triangle :%f\", area);\n return 0;\n}"
},
{
"code": null,
"e": 1754,
"s": 1721,
"text": "The area of triangle :400.000000"
},
{
"code": null,
"e": 1765,
"s": 1754,
"text": " Live Demo"
},
{
"code": null,
"e": 1994,
"s": 1765,
"text": "include<stdio.h>\nvoid main(){\n int a;\n int *p;\n a=10;\n p=&a;\n printf(\"a=%d\\n\",a);//10//\n printf(\"p=%d\\n\",p);//address value of p//\n *p=12;\n printf(\"a=%d\\n\",a);//12//\n printf(\"p=%d\\n\",p);//address value of p//\n}"
},
{
"code": null,
"e": 2024,
"s": 1994,
"text": "a=10\np=6422036\na=12\np=6422036"
}
]
|
Landcover Analysis using Python and ArcGIS | by Ben Chamblee | Towards Data Science | ArcGIS is one of the top platforms for geostatistical analysis. Using ArcGIS libraries with python gives you the ability to analyze shapefiles, display Landsat satellite imagery, create data maps, and much more all within a Jupyter notebook! There are a limitless amount of data science projects you can create using this library but for this article, I’ll focus on a simple NDVI (Normalized Difference Vegetation Index) analysis.
Before we get started, make sure you have all the necessary libraries installed check out arcpy on ESRI’s site to learn more about what you need. Here are all the libraries I used for this analysis:
import pandas as pdfrom datetime import datetimefrom IPython.display import Imagefrom IPython.display import HTMLimport matplotlib.pyplot as pltimport sysimport arcgisfrom arcgis.gis import GISfrom arcgis.raster.functions import apply, clip, remap, colormapfrom arcgis.geometry import lengths, areas_and_lengths, projectfrom arcgis.geometry import Point, Polyline, Polygon, Geometryfrom arcgis.geocoding import geocodefrom arcgis.features import FeatureLayer
This part is entirely up to you, for this project I’m going to use New York City. After you’ve chosen an area you’ll then need to find the FeatureLayer file associated with that location. Usually, this can be found by using ESRI’s RESTful API, here’s how I found NYC’s FeatureLayer:
nyc_fl = FeatureLayer('https://gisservices.its.ny.gov/arcgis/rest/services/NYS_Civil_Boundaries/FeatureServer/4')ny_df = pd.DataFrame.spatial.from_layer(nyc_fl)nyc_df = ny_df.iloc[32:33]
This gave me a GeoDataFrame, I singled out the 32nd row which covered New York County. After I determined the area I just took the spatial component and converted it to a shapefile.
This is how we can define the land cover of our FeatureLayer. NDVI analysis works by analyzing the color based on each pixel of a satellite image. The easiest way to do this is to use Landsat imagery from ESRI:
landsat_item = gis.content.search('title:Multispectral Landsat', 'Imagery Layer', outside_org=True)[0]landsat = landsat_item.layers[0]
Then you can take the Landsat item, define the ideal cloud cover percentage (keep this as low as possible) and set a start and end date:
selected = landsat.filter_by(where="(Category = 1) AND (cloudcover <=0.05)",time=[datetime(2020, 4, 1), datetime(2020, 6, 30)], geometry=arcgis.geometry.filters.intersects(area['extent'])) df = selected.query(out_fields="AcquisitionDate, GroupName, CloudCover, DayOfYear", order_by_fields="AcquisitionDate").sdf df['AcquisitionDate'] = pd.to_datetime(df['AcquisitionDate'], unit='ms')
Now that you have your satellite imagery you can apply the ‘NDVI Raw’ function to calculate the NDVI for each pixel
nyc_colorized = apply(nyc_image, 'NDVI Raw')
Then you can use the shapefile we defined early to get a perfect clip of your area
nyc_clip = clip(nyc_colorized,nyc_poly)nyc_clip.extent = area['extent']
NDVI values range from -1 to 1, it’s up to you to decide how to classify your land cover but I would suggest reading more about what this value represents. For this project, I divided the land cover into three groups: water, concrete, and vegetation.
masked = colormap(remap(nyc_clip, input_ranges=[-1,0, # water -0.1, 0.4, # Concrete 0.4, 1], # Vegetation, Trees output_values=[1, 2, 3]), colormap=[[1, 1, 255, 248], [2, 144, 148, 148], [3,14,247,22]], astype='u8')
Now that you have your colormap, you can analyze it!
xpixel = (nyc_clip.extent['xmax'] - nyc_clip.extent['xmin']) / 800ypixel = (nyc_clip.extent['ymax'] - nyc_clip.extent['ymin']) / 400full_res = masked.compute_histograms(nyc_clip.extent, pixel_size={'x':xpixel, 'y': ypixel})total_pix = 0hist = full_res['histograms'][0]['counts'][0:]for x in hist[1:]: total_pix += xcolors=['#0EF716','#01FFF8','#909494']labels =[ (hist[1]/sum(hist)), (hist[2]/sum(hist)), (hist[3]/sum(hist)) ]plt.pie(hist, labels=['', 'Water', 'Concrete', 'Green Cover'],colors=colors, shadow=True)plt.title('Landcover of New York City')plt.show()
This is just one project idea, but I hope you can use it as inspiration to create something even better. Want to know how the land cover of your location has changed over the year? Change the start and end dates to create multiple colormaps. Want to know how cloud cover impacts accuracy? Raise the cloud cover percentage and compare the two. Want to add a unique, spatially-focused data science project to your resume? Considered using ArcGIS with python!
Thank you for reading!
Full notebook: https://github.com/Bench-amblee/geo/blob/main/nyc_landcover.ipynb | [
{
"code": null,
"e": 603,
"s": 172,
"text": "ArcGIS is one of the top platforms for geostatistical analysis. Using ArcGIS libraries with python gives you the ability to analyze shapefiles, display Landsat satellite imagery, create data maps, and much more all within a Jupyter notebook! There are a limitless amount of data science projects you can create using this library but for this article, I’ll focus on a simple NDVI (Normalized Difference Vegetation Index) analysis."
},
{
"code": null,
"e": 802,
"s": 603,
"text": "Before we get started, make sure you have all the necessary libraries installed check out arcpy on ESRI’s site to learn more about what you need. Here are all the libraries I used for this analysis:"
},
{
"code": null,
"e": 1261,
"s": 802,
"text": "import pandas as pdfrom datetime import datetimefrom IPython.display import Imagefrom IPython.display import HTMLimport matplotlib.pyplot as pltimport sysimport arcgisfrom arcgis.gis import GISfrom arcgis.raster.functions import apply, clip, remap, colormapfrom arcgis.geometry import lengths, areas_and_lengths, projectfrom arcgis.geometry import Point, Polyline, Polygon, Geometryfrom arcgis.geocoding import geocodefrom arcgis.features import FeatureLayer"
},
{
"code": null,
"e": 1544,
"s": 1261,
"text": "This part is entirely up to you, for this project I’m going to use New York City. After you’ve chosen an area you’ll then need to find the FeatureLayer file associated with that location. Usually, this can be found by using ESRI’s RESTful API, here’s how I found NYC’s FeatureLayer:"
},
{
"code": null,
"e": 1731,
"s": 1544,
"text": "nyc_fl = FeatureLayer('https://gisservices.its.ny.gov/arcgis/rest/services/NYS_Civil_Boundaries/FeatureServer/4')ny_df = pd.DataFrame.spatial.from_layer(nyc_fl)nyc_df = ny_df.iloc[32:33]"
},
{
"code": null,
"e": 1913,
"s": 1731,
"text": "This gave me a GeoDataFrame, I singled out the 32nd row which covered New York County. After I determined the area I just took the spatial component and converted it to a shapefile."
},
{
"code": null,
"e": 2124,
"s": 1913,
"text": "This is how we can define the land cover of our FeatureLayer. NDVI analysis works by analyzing the color based on each pixel of a satellite image. The easiest way to do this is to use Landsat imagery from ESRI:"
},
{
"code": null,
"e": 2259,
"s": 2124,
"text": "landsat_item = gis.content.search('title:Multispectral Landsat', 'Imagery Layer', outside_org=True)[0]landsat = landsat_item.layers[0]"
},
{
"code": null,
"e": 2396,
"s": 2259,
"text": "Then you can take the Landsat item, define the ideal cloud cover percentage (keep this as low as possible) and set a start and end date:"
},
{
"code": null,
"e": 2829,
"s": 2396,
"text": "selected = landsat.filter_by(where=\"(Category = 1) AND (cloudcover <=0.05)\",time=[datetime(2020, 4, 1), datetime(2020, 6, 30)], geometry=arcgis.geometry.filters.intersects(area['extent'])) df = selected.query(out_fields=\"AcquisitionDate, GroupName, CloudCover, DayOfYear\", order_by_fields=\"AcquisitionDate\").sdf df['AcquisitionDate'] = pd.to_datetime(df['AcquisitionDate'], unit='ms')"
},
{
"code": null,
"e": 2945,
"s": 2829,
"text": "Now that you have your satellite imagery you can apply the ‘NDVI Raw’ function to calculate the NDVI for each pixel"
},
{
"code": null,
"e": 2990,
"s": 2945,
"text": "nyc_colorized = apply(nyc_image, 'NDVI Raw')"
},
{
"code": null,
"e": 3073,
"s": 2990,
"text": "Then you can use the shapefile we defined early to get a perfect clip of your area"
},
{
"code": null,
"e": 3145,
"s": 3073,
"text": "nyc_clip = clip(nyc_colorized,nyc_poly)nyc_clip.extent = area['extent']"
},
{
"code": null,
"e": 3396,
"s": 3145,
"text": "NDVI values range from -1 to 1, it’s up to you to decide how to classify your land cover but I would suggest reading more about what this value represents. For this project, I divided the land cover into three groups: water, concrete, and vegetation."
},
{
"code": null,
"e": 3766,
"s": 3396,
"text": "masked = colormap(remap(nyc_clip, input_ranges=[-1,0, # water -0.1, 0.4, # Concrete 0.4, 1], # Vegetation, Trees output_values=[1, 2, 3]), colormap=[[1, 1, 255, 248], [2, 144, 148, 148], [3,14,247,22]], astype='u8')"
},
{
"code": null,
"e": 3819,
"s": 3766,
"text": "Now that you have your colormap, you can analyze it!"
},
{
"code": null,
"e": 4428,
"s": 3819,
"text": "xpixel = (nyc_clip.extent['xmax'] - nyc_clip.extent['xmin']) / 800ypixel = (nyc_clip.extent['ymax'] - nyc_clip.extent['ymin']) / 400full_res = masked.compute_histograms(nyc_clip.extent, pixel_size={'x':xpixel, 'y': ypixel})total_pix = 0hist = full_res['histograms'][0]['counts'][0:]for x in hist[1:]: total_pix += xcolors=['#0EF716','#01FFF8','#909494']labels =[ (hist[1]/sum(hist)), (hist[2]/sum(hist)), (hist[3]/sum(hist)) ]plt.pie(hist, labels=['', 'Water', 'Concrete', 'Green Cover'],colors=colors, shadow=True)plt.title('Landcover of New York City')plt.show()"
},
{
"code": null,
"e": 4885,
"s": 4428,
"text": "This is just one project idea, but I hope you can use it as inspiration to create something even better. Want to know how the land cover of your location has changed over the year? Change the start and end dates to create multiple colormaps. Want to know how cloud cover impacts accuracy? Raise the cloud cover percentage and compare the two. Want to add a unique, spatially-focused data science project to your resume? Considered using ArcGIS with python!"
},
{
"code": null,
"e": 4908,
"s": 4885,
"text": "Thank you for reading!"
}
]
|
Flutter - Introduction to Gestures | Gestures are primarily a way for a user to interact with a mobile (or any touch based device) application. Gestures are generally defined as any physical action / movement of a user in the intention of activating a specific control of the mobile device. Gestures are as simple as tapping the screen of the mobile device to more complex actions used in gaming applications.
Some of the widely used gestures are mentioned here −
Tap − Touching the surface of the device with fingertip for a short period and then releasing the fingertip.
Tap − Touching the surface of the device with fingertip for a short period and then releasing the fingertip.
Double Tap − Tapping twice in a short time.
Double Tap − Tapping twice in a short time.
Drag − Touching the surface of the device with fingertip and then moving the fingertip in a steady manner and then finally releasing the fingertip.
Drag − Touching the surface of the device with fingertip and then moving the fingertip in a steady manner and then finally releasing the fingertip.
Flick − Similar to dragging, but doing it in a speeder way.
Flick − Similar to dragging, but doing it in a speeder way.
Pinch − Pinching the surface of the device using two fingers.
Pinch − Pinching the surface of the device using two fingers.
Spread/Zoom − Opposite of pinching.
Spread/Zoom − Opposite of pinching.
Panning − Touching the surface of the device with fingertip and moving it in any direction without releasing the fingertip.
Panning − Touching the surface of the device with fingertip and moving it in any direction without releasing the fingertip.
Flutter provides an excellent support for all type of gestures through its exclusive widget, GestureDetector. GestureDetector is a non-visual widget primarily used for detecting the user’s gesture. To identify a gesture targeted on a widget, the widget can be placed inside GestureDetector widget. GestureDetector will capture the gesture and dispatch multiple events based on the gesture.
Some of the gestures and the corresponding events are given below −
Tap
onTapDown
onTapUp
onTap
onTapCancel
Double tap
onDoubleTap
Long press
onLongPress
Vertical drag
onVerticalDragStart
onVerticalDragUpdate
onVerticalDragEnd
Horizontal drag
onHorizontalDragStart
onHorizontalDragUpdate
onHorizontalDragEnd
Pan
onPanStart
onPanUpdate
onPanEnd
Now, let us modify the hello world application to include gesture detection feature and try to understand the concept.
Change the body content of the MyHomePage widget as shown below −
Change the body content of the MyHomePage widget as shown below −
body: Center(
child: GestureDetector(
onTap: () {
_showDialog(context);
},
child: Text( 'Hello World', )
)
),
Observe that here we have placed the GestureDetector widget above the Text widget in the widget hierarchy, captured the onTap event and then finally shown a dialog window.
Observe that here we have placed the GestureDetector widget above the Text widget in the widget hierarchy, captured the onTap event and then finally shown a dialog window.
Implement the *_showDialog* function to present a dialog when user tabs the hello world message. It uses the generic showDialog and AlertDialog widget to create a new dialog widget. The code is shown below −
Implement the *_showDialog* function to present a dialog when user tabs the hello world message. It uses the generic showDialog and AlertDialog widget to create a new dialog widget. The code is shown below −
// user defined function void _showDialog(BuildContext context) {
// flutter defined function
showDialog(
context: context, builder: (BuildContext context) {
// return object of type Dialog
return AlertDialog(
title: new Text("Message"),
content: new Text("Hello World"),
actions: <Widget>[
new FlatButton(
child: new Text("Close"),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
The application will reload in the device using Hot Reload feature. Now, simply click the message, Hello World and it will show the dialog as below −
The application will reload in the device using Hot Reload feature. Now, simply click the message, Hello World and it will show the dialog as below −
Now, close the dialog by clicking the close option in the dialog.
Now, close the dialog by clicking the close option in the dialog.
The complete code (main.dart) is as follows −
The complete code (main.dart) is as follows −
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Hello World Demo Application',
theme: ThemeData( primarySwatch: Colors.blue,),
home: MyHomePage(title: 'Home page'),
);
}
}
class MyHomePage extends StatelessWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
// user defined function
void _showDialog(BuildContext context) {
// flutter defined function showDialog(
context: context, builder: (BuildContext context) {
// return object of type Dialog return AlertDialog(
title: new Text("Message"),
content: new Text("Hello World"),
actions: <Widget>[
new FlatButton(
child: new Text("Close"),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(this.title),),
body: Center(
child: GestureDetector(
onTap: () {
_showDialog(context);
},
child: Text( 'Hello World', )
)
),
);
}
}
Finally, Flutter also provides a low-level gesture detection mechanism through Listener widget. It will detect all user interactions and then dispatches the following events −
PointerDownEvent
PointerMoveEvent
PointerUpEvent
PointerCancelEvent
Flutter also provides a small set of widgets to do specific as well as advanced gestures. The widgets are listed below −
Dismissible − Supports flick gesture to dismiss the widget.
Dismissible − Supports flick gesture to dismiss the widget.
Draggable − Supports drag gesture to move the widget.
Draggable − Supports drag gesture to move the widget.
LongPressDraggable − Supports drag gesture to move a widget, when its parent widget is also draggable.
LongPressDraggable − Supports drag gesture to move a widget, when its parent widget is also draggable.
DragTarget − Accepts any Draggable widget
DragTarget − Accepts any Draggable widget
IgnorePointer − Hides the widget and its children from the gesture detection process.
IgnorePointer − Hides the widget and its children from the gesture detection process.
AbsorbPointer − Stops the gesture detection process itself and so any overlapping widget also can not able to participate in the gesture detection process and hence, no event is raised.
AbsorbPointer − Stops the gesture detection process itself and so any overlapping widget also can not able to participate in the gesture detection process and hence, no event is raised.
Scrollable − Support scrolling of the content available inside the widget.
Scrollable − Support scrolling of the content available inside the widget.
34 Lectures
4 hours
Sriyank Siddhartha
117 Lectures
10 hours
Frahaan Hussain
27 Lectures
1 hours
Skillbakerystudios
17 Lectures
51 mins
Harsh Kumar Khatri
17 Lectures
1.5 hours
Pramila Rawat
85 Lectures
16.5 hours
Rahul Agarwal
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2591,
"s": 2218,
"text": "Gestures are primarily a way for a user to interact with a mobile (or any touch based device) application. Gestures are generally defined as any physical action / movement of a user in the intention of activating a specific control of the mobile device. Gestures are as simple as tapping the screen of the mobile device to more complex actions used in gaming applications."
},
{
"code": null,
"e": 2645,
"s": 2591,
"text": "Some of the widely used gestures are mentioned here −"
},
{
"code": null,
"e": 2754,
"s": 2645,
"text": "Tap − Touching the surface of the device with fingertip for a short period and then releasing the fingertip."
},
{
"code": null,
"e": 2863,
"s": 2754,
"text": "Tap − Touching the surface of the device with fingertip for a short period and then releasing the fingertip."
},
{
"code": null,
"e": 2907,
"s": 2863,
"text": "Double Tap − Tapping twice in a short time."
},
{
"code": null,
"e": 2951,
"s": 2907,
"text": "Double Tap − Tapping twice in a short time."
},
{
"code": null,
"e": 3099,
"s": 2951,
"text": "Drag − Touching the surface of the device with fingertip and then moving the fingertip in a steady manner and then finally releasing the fingertip."
},
{
"code": null,
"e": 3247,
"s": 3099,
"text": "Drag − Touching the surface of the device with fingertip and then moving the fingertip in a steady manner and then finally releasing the fingertip."
},
{
"code": null,
"e": 3307,
"s": 3247,
"text": "Flick − Similar to dragging, but doing it in a speeder way."
},
{
"code": null,
"e": 3367,
"s": 3307,
"text": "Flick − Similar to dragging, but doing it in a speeder way."
},
{
"code": null,
"e": 3429,
"s": 3367,
"text": "Pinch − Pinching the surface of the device using two fingers."
},
{
"code": null,
"e": 3491,
"s": 3429,
"text": "Pinch − Pinching the surface of the device using two fingers."
},
{
"code": null,
"e": 3527,
"s": 3491,
"text": "Spread/Zoom − Opposite of pinching."
},
{
"code": null,
"e": 3563,
"s": 3527,
"text": "Spread/Zoom − Opposite of pinching."
},
{
"code": null,
"e": 3687,
"s": 3563,
"text": "Panning − Touching the surface of the device with fingertip and moving it in any direction without releasing the fingertip."
},
{
"code": null,
"e": 3811,
"s": 3687,
"text": "Panning − Touching the surface of the device with fingertip and moving it in any direction without releasing the fingertip."
},
{
"code": null,
"e": 4201,
"s": 3811,
"text": "Flutter provides an excellent support for all type of gestures through its exclusive widget, GestureDetector. GestureDetector is a non-visual widget primarily used for detecting the user’s gesture. To identify a gesture targeted on a widget, the widget can be placed inside GestureDetector widget. GestureDetector will capture the gesture and dispatch multiple events based on the gesture."
},
{
"code": null,
"e": 4269,
"s": 4201,
"text": "Some of the gestures and the corresponding events are given below −"
},
{
"code": null,
"e": 4273,
"s": 4269,
"text": "Tap"
},
{
"code": null,
"e": 4283,
"s": 4273,
"text": "onTapDown"
},
{
"code": null,
"e": 4291,
"s": 4283,
"text": "onTapUp"
},
{
"code": null,
"e": 4297,
"s": 4291,
"text": "onTap"
},
{
"code": null,
"e": 4309,
"s": 4297,
"text": "onTapCancel"
},
{
"code": null,
"e": 4320,
"s": 4309,
"text": "Double tap"
},
{
"code": null,
"e": 4332,
"s": 4320,
"text": "onDoubleTap"
},
{
"code": null,
"e": 4343,
"s": 4332,
"text": "Long press"
},
{
"code": null,
"e": 4355,
"s": 4343,
"text": "onLongPress"
},
{
"code": null,
"e": 4369,
"s": 4355,
"text": "Vertical drag"
},
{
"code": null,
"e": 4389,
"s": 4369,
"text": "onVerticalDragStart"
},
{
"code": null,
"e": 4410,
"s": 4389,
"text": "onVerticalDragUpdate"
},
{
"code": null,
"e": 4428,
"s": 4410,
"text": "onVerticalDragEnd"
},
{
"code": null,
"e": 4444,
"s": 4428,
"text": "Horizontal drag"
},
{
"code": null,
"e": 4466,
"s": 4444,
"text": "onHorizontalDragStart"
},
{
"code": null,
"e": 4489,
"s": 4466,
"text": "onHorizontalDragUpdate"
},
{
"code": null,
"e": 4509,
"s": 4489,
"text": "onHorizontalDragEnd"
},
{
"code": null,
"e": 4513,
"s": 4509,
"text": "Pan"
},
{
"code": null,
"e": 4524,
"s": 4513,
"text": "onPanStart"
},
{
"code": null,
"e": 4536,
"s": 4524,
"text": "onPanUpdate"
},
{
"code": null,
"e": 4545,
"s": 4536,
"text": "onPanEnd"
},
{
"code": null,
"e": 4664,
"s": 4545,
"text": "Now, let us modify the hello world application to include gesture detection feature and try to understand the concept."
},
{
"code": null,
"e": 4730,
"s": 4664,
"text": "Change the body content of the MyHomePage widget as shown below −"
},
{
"code": null,
"e": 4796,
"s": 4730,
"text": "Change the body content of the MyHomePage widget as shown below −"
},
{
"code": null,
"e": 4946,
"s": 4796,
"text": "body: Center( \n child: GestureDetector( \n onTap: () { \n _showDialog(context); \n }, \n child: Text( 'Hello World', ) \n ) \n),"
},
{
"code": null,
"e": 5118,
"s": 4946,
"text": "Observe that here we have placed the GestureDetector widget above the Text widget in the widget hierarchy, captured the onTap event and then finally shown a dialog window."
},
{
"code": null,
"e": 5290,
"s": 5118,
"text": "Observe that here we have placed the GestureDetector widget above the Text widget in the widget hierarchy, captured the onTap event and then finally shown a dialog window."
},
{
"code": null,
"e": 5498,
"s": 5290,
"text": "Implement the *_showDialog* function to present a dialog when user tabs the hello world message. It uses the generic showDialog and AlertDialog widget to create a new dialog widget. The code is shown below −"
},
{
"code": null,
"e": 5706,
"s": 5498,
"text": "Implement the *_showDialog* function to present a dialog when user tabs the hello world message. It uses the generic showDialog and AlertDialog widget to create a new dialog widget. The code is shown below −"
},
{
"code": null,
"e": 6329,
"s": 5706,
"text": "// user defined function void _showDialog(BuildContext context) { \n // flutter defined function \n showDialog( \n context: context, builder: (BuildContext context) { \n // return object of type Dialog\n return AlertDialog( \n title: new Text(\"Message\"), \n content: new Text(\"Hello World\"), \n actions: <Widget>[ \n new FlatButton( \n child: new Text(\"Close\"), \n onPressed: () { \n Navigator.of(context).pop(); \n }, \n ), \n ], \n ); \n }, \n ); \n}"
},
{
"code": null,
"e": 6479,
"s": 6329,
"text": "The application will reload in the device using Hot Reload feature. Now, simply click the message, Hello World and it will show the dialog as below −"
},
{
"code": null,
"e": 6629,
"s": 6479,
"text": "The application will reload in the device using Hot Reload feature. Now, simply click the message, Hello World and it will show the dialog as below −"
},
{
"code": null,
"e": 6695,
"s": 6629,
"text": "Now, close the dialog by clicking the close option in the dialog."
},
{
"code": null,
"e": 6761,
"s": 6695,
"text": "Now, close the dialog by clicking the close option in the dialog."
},
{
"code": null,
"e": 6807,
"s": 6761,
"text": "The complete code (main.dart) is as follows −"
},
{
"code": null,
"e": 6853,
"s": 6807,
"text": "The complete code (main.dart) is as follows −"
},
{
"code": null,
"e": 8419,
"s": 6853,
"text": "import 'package:flutter/material.dart'; \nvoid main() => runApp(MyApp()); \n\nclass MyApp extends StatelessWidget { \n // This widget is the root of your application. \n @override \n Widget build(BuildContext context) {\n return MaterialApp(\n title: 'Hello World Demo Application', \n theme: ThemeData( primarySwatch: Colors.blue,), \n home: MyHomePage(title: 'Home page'), \n ); \n }\n}\nclass MyHomePage extends StatelessWidget {\n MyHomePage({Key key, this.title}) : super(key: key); \n final String title; \n \n // user defined function \n void _showDialog(BuildContext context) { \n // flutter defined function showDialog( \n context: context, builder: (BuildContext context) { \n // return object of type Dialog return AlertDialog(\n title: new Text(\"Message\"), \n content: new Text(\"Hello World\"), \n actions: <Widget>[\n new FlatButton(\n child: new Text(\"Close\"), \n onPressed: () { \n Navigator.of(context).pop(); \n }, \n ), \n ],\n );\n },\n );\n }\n @override \n Widget build(BuildContext context) {\n return Scaffold(\n appBar: AppBar(title: Text(this.title),),\n body: Center(\n child: GestureDetector( \n onTap: () {\n _showDialog(context);\n },\n child: Text( 'Hello World', )\n )\n ),\n );\n }\n}"
},
{
"code": null,
"e": 8595,
"s": 8419,
"text": "Finally, Flutter also provides a low-level gesture detection mechanism through Listener widget. It will detect all user interactions and then dispatches the following events −"
},
{
"code": null,
"e": 8612,
"s": 8595,
"text": "PointerDownEvent"
},
{
"code": null,
"e": 8629,
"s": 8612,
"text": "PointerMoveEvent"
},
{
"code": null,
"e": 8644,
"s": 8629,
"text": "PointerUpEvent"
},
{
"code": null,
"e": 8663,
"s": 8644,
"text": "PointerCancelEvent"
},
{
"code": null,
"e": 8784,
"s": 8663,
"text": "Flutter also provides a small set of widgets to do specific as well as advanced gestures. The widgets are listed below −"
},
{
"code": null,
"e": 8844,
"s": 8784,
"text": "Dismissible − Supports flick gesture to dismiss the widget."
},
{
"code": null,
"e": 8904,
"s": 8844,
"text": "Dismissible − Supports flick gesture to dismiss the widget."
},
{
"code": null,
"e": 8958,
"s": 8904,
"text": "Draggable − Supports drag gesture to move the widget."
},
{
"code": null,
"e": 9012,
"s": 8958,
"text": "Draggable − Supports drag gesture to move the widget."
},
{
"code": null,
"e": 9115,
"s": 9012,
"text": "LongPressDraggable − Supports drag gesture to move a widget, when its parent widget is also draggable."
},
{
"code": null,
"e": 9218,
"s": 9115,
"text": "LongPressDraggable − Supports drag gesture to move a widget, when its parent widget is also draggable."
},
{
"code": null,
"e": 9260,
"s": 9218,
"text": "DragTarget − Accepts any Draggable widget"
},
{
"code": null,
"e": 9302,
"s": 9260,
"text": "DragTarget − Accepts any Draggable widget"
},
{
"code": null,
"e": 9388,
"s": 9302,
"text": "IgnorePointer − Hides the widget and its children from the gesture detection process."
},
{
"code": null,
"e": 9474,
"s": 9388,
"text": "IgnorePointer − Hides the widget and its children from the gesture detection process."
},
{
"code": null,
"e": 9660,
"s": 9474,
"text": "AbsorbPointer − Stops the gesture detection process itself and so any overlapping widget also can not able to participate in the gesture detection process and hence, no event is raised."
},
{
"code": null,
"e": 9846,
"s": 9660,
"text": "AbsorbPointer − Stops the gesture detection process itself and so any overlapping widget also can not able to participate in the gesture detection process and hence, no event is raised."
},
{
"code": null,
"e": 9921,
"s": 9846,
"text": "Scrollable − Support scrolling of the content available inside the widget."
},
{
"code": null,
"e": 9996,
"s": 9921,
"text": "Scrollable − Support scrolling of the content available inside the widget."
},
{
"code": null,
"e": 10029,
"s": 9996,
"text": "\n 34 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 10049,
"s": 10029,
"text": " Sriyank Siddhartha"
},
{
"code": null,
"e": 10084,
"s": 10049,
"text": "\n 117 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 10101,
"s": 10084,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 10134,
"s": 10101,
"text": "\n 27 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 10154,
"s": 10134,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 10186,
"s": 10154,
"text": "\n 17 Lectures \n 51 mins\n"
},
{
"code": null,
"e": 10206,
"s": 10186,
"text": " Harsh Kumar Khatri"
},
{
"code": null,
"e": 10241,
"s": 10206,
"text": "\n 17 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 10256,
"s": 10241,
"text": " Pramila Rawat"
},
{
"code": null,
"e": 10292,
"s": 10256,
"text": "\n 85 Lectures \n 16.5 hours \n"
},
{
"code": null,
"e": 10307,
"s": 10292,
"text": " Rahul Agarwal"
},
{
"code": null,
"e": 10314,
"s": 10307,
"text": " Print"
},
{
"code": null,
"e": 10325,
"s": 10314,
"text": " Add Notes"
}
]
|
Bootcamp Website Template using HTML and CSS - GeeksforGeeks | 08 Nov, 2021
In this article, we will see how to design a simple Bootcamp Website Template using HTML and CSS.
Creating an attractive template will be difficult for those who are not experts in CSS. Without using CSS, you will not be able to make the web page more attractive. So in order to make a web page, we need to have a knowledge of HTML and CSS. In this article, we will use HTML and CSS to make the website template. In order to design a template, we need to first create an HTML web structure.
Step 1: Creating web structure using HTML – In this section, we will create a simple structure of the web page by using <div>, <li>, and <section> tags as well as class and id attributes. We will have the following sections: Navbar, Banner, Courses, About, and at the last, we will have the contact us section. So this will create a simple interface that you can check by running the following code.
HTML Code:
index.html
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content= "width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>BOOTCAMP</title> <link rel="stylesheet" href="style.css" /> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" integrity="sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf" crossorigin="anonymous" /></head> <body> <div class="container"> <!-------- Creating Navbar ---------> <nav> <a href="#">BOOTCAMP</a> <div class="navbar"> <ul> <li><a href="index.html">Home</a></li> <li><a href="#">Courses</a></li> <li><a href="#">About</a></li> <li><a href="#">Contact</a></li> </ul> </div> </nav> <!--------- Creating Banner --------> <div class="main-banner"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20211022104311/coding.jpeg" alt="banner" /> </div> <!-------- Courses or services -------> <section class="service"> <h1>Courses</h1> <div class="col"> <i class="fab fa-algolia fa-3x ip"></i> <h3>Web Designing</h3> <p> If you are looking for a way to use your artistic side, web design is a great way to do it.In today's world, learning how to design websites can be an incredibly useful skill. </p> <a href="#">Know More</a> </div> <div class="col"> <i class="fas fa-code fa-3x ip"></i> <h3>Web Development</h3> <p> Web development gives you the opportunity to express yourself creatively on the internet. Fortunately, the high demand, easy-to-learn, fun-to-experience life. </p> <a href="#">Know More</a> </div> <div class="col"> <i class="fab fa-android fa-3x ip"></i> <h3>Android</h3> <p> By learning Android Development, you give yourself the best possible chance to reach any career goals you set. Once you get started, within no time, you'll land in your dream job. </p> <a href="#">Know More</a> </div> </section> <section class="about"> <h1>Why choose us?</h1> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20211022104311/coding.jpeg" alt="about us" /> <p> In today’s digital world, when there are thousands of online platforms (maybe more than that!) available over the web, it becomes quite difficult for students to opt for a quality, relevant and reliable platform for themselves. BOOTCAMP will help you excel in your choice of domain by giving industry equivalent experience. </p> <a href="#">More</a> </section> <section id="contact"> <div class="services-info"> <h1>Get in<span id="blue">Touch</span></h1> <p> We are Available</p> </div> <div class="contact-row"> <div class="contact-left-col"> <div class="form"> <input type="text" name="" placeholder="E-mail"> <input type="text" name="" placeholder="Subject"><br> <textarea rows="10" cols="40" placeholder="Message"> </textarea> <br> <button class="c_btn"> Send </button> </div> </div> <div class="contact-right-col"> <h1> <i class="fa fa-envelope" aria-hidden="true"></i> E-mail </h1> <p>[email protected]</p><br> <h1> <i class="fa fa-phone" aria-hidden="true"></i> Mobile </h1> <p>8212341487, 9080140989</p> <br> <h1> <i class="fa fa-location-arrow" aria-hidden="true"></i> Address </h1> <p> Noida Sector 136<br> Metro Pillar- 237 </p> </div> </div> </section> <footer> <small>Copyright © 2021 || Designed by Geeks </small> </footer> </div></body> </html>
Step 2: Designing the web structure using CSS – We will use CSS to give proper design effects to the HTML web structure that we have created in HTML code. We will give styling to the classes and ids that we have used in the above code. We will be using the flex property so that It is easy to position child elements and the main container. The margin doesn’t collapse with the content margins. The order of any element can be easily changed without editing the HTML section.
CSS code:
style.css
/* Write CSS Here */* { margin: 0px; padding: 0px; box-sizing: border-box;} body { background-color: #e3e3e3;}.container { width: 1000px; margin-left: auto; margin-right: auto; margin-bottom: 10px;} nav { background-color: #089de3;} nav > a { color: #fff; font-size: 30px; text-decoration: none; /* top right bottom left*/ padding: 10px 10px 10px 30px; float: left;} .navbar > ul { list-style: none; float: right;} .navbar > ul > li { display: inline-block; line-height: 60px; /*top-bottom right-left*/ padding: 0px 20px;} .navbar > ul:last-child { padding-right: 100px;} .navbar > ul > li > a { text-decoration: none; font-size: 18px; color: #fff;} .navbar > ul > li:hover { background-color: #111111;} nav::after { content: " "; display: block; clear: both; *zoom: 1;} /* Navbar End */ /* Banner Start */.main-banner { height: 400px;}.main-banner > img { width: 100%; height: 400px; object-fit: cover;}/* Banner End */ /* Service Start */.service { background-color: #fff;} .service > h1 { font-size: 30px; text-align: center; padding: 30px;} .col { width: 300px; text-align: center; margin-left: 20px; border-right: solid #bebebe 1px; padding-bottom: 30px; float: left;} .col:last-child { border-right: none;} .col > h3 { /* top-bottom right-left */ padding: 10px 0px; color: grey;} .col > p { padding-bottom: 20px;} .col > a { background-color: #089de3; color: #fff; font-size: 17px; text-decoration: none; border: solid white 2px; padding: 5px 10px; border-radius: 20px;} .col > a:hover { background-color: #111111; border: solid #111111 2px;}.service::after { content: " "; display: block; clear: both; *zoom: 1;}/* Service End */ /* about Start */.about { background-color: #089de3; min-height: 300px; text-align: center; padding: 20px; color: #fff;} .about > h1 { font-size: 30px; padding-bottom: 20px;} .about > img { border: solid 2px; width: 100px; height: 100px; border-radius: 50px; object-fit: cover;} .about > p { font-size: 18px; margin: 10px 200px; padding-bottom: 10px; line-height: 25px;} .about > a { color: #fff; font-size: 17px; text-decoration: none; border: solid white 1px; padding: 5px 20px;} .about > a:hover { background-color: #111111; border: solid #111111 1px;}/* about End */ #contact{ padding: 30px 0px;} .contact-row{ display: flex; justify-content: center; align-items: center;}.contact-left-col{ flex-basis: 50%; padding-top: 50px;}.contact-right-col{ flex-basis: 50%; max-width: 450px; margin: auto;}.contact-right-col i{ font-size: 20px; padding: 10px; background:#089de3; color: white; }.contact-right-col p{ margin-top: 10px; margin-bottom: 20px;} .form{ width: 70%; margin:auto; text-align: center;}.form input[type="text"]{ width: 70%; padding: 10px; margin-bottom: 10px;}textarea{ width: 70%; padding: 10px; margin-bottom: 10px;} .c_btn{ background: black; color: white; padding: 10px; width: 50%; border:none;} /* Footer Start */footer { background-color: #089de3; text-align: center; padding: 10px;} footer > small { color: #fff;} footer > small > a { color: #fff; text-decoration: none;}/* Footer End */
Output: Open with the live server in Visual Studio Code or if you are using any other code editor just open the index.html file in the browser.
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
CSS-Properties
CSS-Questions
HTML-Questions
HTML-Tags
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a web page using HTML and CSS
Form validation using jQuery
How to set space between the flexbox ?
Search Bar using HTML, CSS and JavaScript
How to Create Time-Table schedule using HTML ?
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Hide or show elements in HTML using display property
How to Insert Form Data into Database using PHP ?
REST API (Introduction) | [
{
"code": null,
"e": 25376,
"s": 25348,
"text": "\n08 Nov, 2021"
},
{
"code": null,
"e": 25475,
"s": 25376,
"text": "In this article, we will see how to design a simple Bootcamp Website Template using HTML and CSS. "
},
{
"code": null,
"e": 25868,
"s": 25475,
"text": "Creating an attractive template will be difficult for those who are not experts in CSS. Without using CSS, you will not be able to make the web page more attractive. So in order to make a web page, we need to have a knowledge of HTML and CSS. In this article, we will use HTML and CSS to make the website template. In order to design a template, we need to first create an HTML web structure."
},
{
"code": null,
"e": 26268,
"s": 25868,
"text": "Step 1: Creating web structure using HTML – In this section, we will create a simple structure of the web page by using <div>, <li>, and <section> tags as well as class and id attributes. We will have the following sections: Navbar, Banner, Courses, About, and at the last, we will have the contact us section. So this will create a simple interface that you can check by running the following code."
},
{
"code": null,
"e": 26281,
"s": 26270,
"text": "HTML Code:"
},
{
"code": null,
"e": 26292,
"s": 26281,
"text": "index.html"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\" /> <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\" /> <title>BOOTCAMP</title> <link rel=\"stylesheet\" href=\"style.css\" /> <link rel=\"stylesheet\" href=\"https://use.fontawesome.com/releases/v5.8.1/css/all.css\" integrity=\"sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf\" crossorigin=\"anonymous\" /></head> <body> <div class=\"container\"> <!-------- Creating Navbar ---------> <nav> <a href=\"#\">BOOTCAMP</a> <div class=\"navbar\"> <ul> <li><a href=\"index.html\">Home</a></li> <li><a href=\"#\">Courses</a></li> <li><a href=\"#\">About</a></li> <li><a href=\"#\">Contact</a></li> </ul> </div> </nav> <!--------- Creating Banner --------> <div class=\"main-banner\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20211022104311/coding.jpeg\" alt=\"banner\" /> </div> <!-------- Courses or services -------> <section class=\"service\"> <h1>Courses</h1> <div class=\"col\"> <i class=\"fab fa-algolia fa-3x ip\"></i> <h3>Web Designing</h3> <p> If you are looking for a way to use your artistic side, web design is a great way to do it.In today's world, learning how to design websites can be an incredibly useful skill. </p> <a href=\"#\">Know More</a> </div> <div class=\"col\"> <i class=\"fas fa-code fa-3x ip\"></i> <h3>Web Development</h3> <p> Web development gives you the opportunity to express yourself creatively on the internet. Fortunately, the high demand, easy-to-learn, fun-to-experience life. </p> <a href=\"#\">Know More</a> </div> <div class=\"col\"> <i class=\"fab fa-android fa-3x ip\"></i> <h3>Android</h3> <p> By learning Android Development, you give yourself the best possible chance to reach any career goals you set. Once you get started, within no time, you'll land in your dream job. </p> <a href=\"#\">Know More</a> </div> </section> <section class=\"about\"> <h1>Why choose us?</h1> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20211022104311/coding.jpeg\" alt=\"about us\" /> <p> In today’s digital world, when there are thousands of online platforms (maybe more than that!) available over the web, it becomes quite difficult for students to opt for a quality, relevant and reliable platform for themselves. BOOTCAMP will help you excel in your choice of domain by giving industry equivalent experience. </p> <a href=\"#\">More</a> </section> <section id=\"contact\"> <div class=\"services-info\"> <h1>Get in<span id=\"blue\">Touch</span></h1> <p> We are Available</p> </div> <div class=\"contact-row\"> <div class=\"contact-left-col\"> <div class=\"form\"> <input type=\"text\" name=\"\" placeholder=\"E-mail\"> <input type=\"text\" name=\"\" placeholder=\"Subject\"><br> <textarea rows=\"10\" cols=\"40\" placeholder=\"Message\"> </textarea> <br> <button class=\"c_btn\"> Send </button> </div> </div> <div class=\"contact-right-col\"> <h1> <i class=\"fa fa-envelope\" aria-hidden=\"true\"></i> E-mail </h1> <p>[email protected]</p><br> <h1> <i class=\"fa fa-phone\" aria-hidden=\"true\"></i> Mobile </h1> <p>8212341487, 9080140989</p> <br> <h1> <i class=\"fa fa-location-arrow\" aria-hidden=\"true\"></i> Address </h1> <p> Noida Sector 136<br> Metro Pillar- 237 </p> </div> </div> </section> <footer> <small>Copyright © 2021 || Designed by Geeks </small> </footer> </div></body> </html>",
"e": 31658,
"s": 26292,
"text": null
},
{
"code": null,
"e": 32134,
"s": 31658,
"text": "Step 2: Designing the web structure using CSS – We will use CSS to give proper design effects to the HTML web structure that we have created in HTML code. We will give styling to the classes and ids that we have used in the above code. We will be using the flex property so that It is easy to position child elements and the main container. The margin doesn’t collapse with the content margins. The order of any element can be easily changed without editing the HTML section."
},
{
"code": null,
"e": 32144,
"s": 32134,
"text": "CSS code:"
},
{
"code": null,
"e": 32154,
"s": 32144,
"text": "style.css"
},
{
"code": "/* Write CSS Here */* { margin: 0px; padding: 0px; box-sizing: border-box;} body { background-color: #e3e3e3;}.container { width: 1000px; margin-left: auto; margin-right: auto; margin-bottom: 10px;} nav { background-color: #089de3;} nav > a { color: #fff; font-size: 30px; text-decoration: none; /* top right bottom left*/ padding: 10px 10px 10px 30px; float: left;} .navbar > ul { list-style: none; float: right;} .navbar > ul > li { display: inline-block; line-height: 60px; /*top-bottom right-left*/ padding: 0px 20px;} .navbar > ul:last-child { padding-right: 100px;} .navbar > ul > li > a { text-decoration: none; font-size: 18px; color: #fff;} .navbar > ul > li:hover { background-color: #111111;} nav::after { content: \" \"; display: block; clear: both; *zoom: 1;} /* Navbar End */ /* Banner Start */.main-banner { height: 400px;}.main-banner > img { width: 100%; height: 400px; object-fit: cover;}/* Banner End */ /* Service Start */.service { background-color: #fff;} .service > h1 { font-size: 30px; text-align: center; padding: 30px;} .col { width: 300px; text-align: center; margin-left: 20px; border-right: solid #bebebe 1px; padding-bottom: 30px; float: left;} .col:last-child { border-right: none;} .col > h3 { /* top-bottom right-left */ padding: 10px 0px; color: grey;} .col > p { padding-bottom: 20px;} .col > a { background-color: #089de3; color: #fff; font-size: 17px; text-decoration: none; border: solid white 2px; padding: 5px 10px; border-radius: 20px;} .col > a:hover { background-color: #111111; border: solid #111111 2px;}.service::after { content: \" \"; display: block; clear: both; *zoom: 1;}/* Service End */ /* about Start */.about { background-color: #089de3; min-height: 300px; text-align: center; padding: 20px; color: #fff;} .about > h1 { font-size: 30px; padding-bottom: 20px;} .about > img { border: solid 2px; width: 100px; height: 100px; border-radius: 50px; object-fit: cover;} .about > p { font-size: 18px; margin: 10px 200px; padding-bottom: 10px; line-height: 25px;} .about > a { color: #fff; font-size: 17px; text-decoration: none; border: solid white 1px; padding: 5px 20px;} .about > a:hover { background-color: #111111; border: solid #111111 1px;}/* about End */ #contact{ padding: 30px 0px;} .contact-row{ display: flex; justify-content: center; align-items: center;}.contact-left-col{ flex-basis: 50%; padding-top: 50px;}.contact-right-col{ flex-basis: 50%; max-width: 450px; margin: auto;}.contact-right-col i{ font-size: 20px; padding: 10px; background:#089de3; color: white; }.contact-right-col p{ margin-top: 10px; margin-bottom: 20px;} .form{ width: 70%; margin:auto; text-align: center;}.form input[type=\"text\"]{ width: 70%; padding: 10px; margin-bottom: 10px;}textarea{ width: 70%; padding: 10px; margin-bottom: 10px;} .c_btn{ background: black; color: white; padding: 10px; width: 50%; border:none;} /* Footer Start */footer { background-color: #089de3; text-align: center; padding: 10px;} footer > small { color: #fff;} footer > small > a { color: #fff; text-decoration: none;}/* Footer End */",
"e": 35422,
"s": 32154,
"text": null
},
{
"code": null,
"e": 35566,
"s": 35422,
"text": "Output: Open with the live server in Visual Studio Code or if you are using any other code editor just open the index.html file in the browser."
},
{
"code": null,
"e": 35703,
"s": 35566,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 35718,
"s": 35703,
"text": "CSS-Properties"
},
{
"code": null,
"e": 35732,
"s": 35718,
"text": "CSS-Questions"
},
{
"code": null,
"e": 35747,
"s": 35732,
"text": "HTML-Questions"
},
{
"code": null,
"e": 35757,
"s": 35747,
"text": "HTML-Tags"
},
{
"code": null,
"e": 35761,
"s": 35757,
"text": "CSS"
},
{
"code": null,
"e": 35766,
"s": 35761,
"text": "HTML"
},
{
"code": null,
"e": 35783,
"s": 35766,
"text": "Web Technologies"
},
{
"code": null,
"e": 35788,
"s": 35783,
"text": "HTML"
},
{
"code": null,
"e": 35886,
"s": 35788,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35923,
"s": 35886,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 35952,
"s": 35923,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 35991,
"s": 35952,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 36033,
"s": 35991,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 36080,
"s": 36033,
"text": "How to Create Time-Table schedule using HTML ?"
},
{
"code": null,
"e": 36140,
"s": 36080,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 36201,
"s": 36140,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 36254,
"s": 36201,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 36304,
"s": 36254,
"text": "How to Insert Form Data into Database using PHP ?"
}
]
|
Software Development Life Cycle (SDLC) | 05 Jul, 2021
Software Development is the development of software for distinct purposes. For software development, there is a specific programming language like Java, Python, C/C++, etc. The entire process of software development isn’t as simple as its definition, it’s a complicated process. Accordingly, it requires an efficient approach from the developer in the form of the Software Development Life Cycle (SDLC).
Proper planning and execution are the key components of a successful software development process. The entire software development process includes 6 stages. Software Development Life Cycle (SDLC) is the common term to summarize these 6 stages.
SDLC specifies the task(s) to be performed at various stages by a software engineer/developer. It ensures that the end product is able to meet the customer’s expectations and fits in the overall budget. Hence, it’s vital for a software developer to have prior knowledge of this software development process.
These 6 stages are discussed below.
Stage-1: Planning And Requirement Analysis: Planning is the crucial step in everything and so as in software development. In this same stage, requirement analysis is also performed by the developers of the organization. This is attained from the inputs from the customers, sales department/market surveys. The information from this analysis forms the building block of a basic project. The quality proof of the project is a result of planning. Thus, in this stage, the basic project is designed with all the available information.
The information from this analysis forms the building block of a basic project. The quality proof of the project is a result of planning. Thus, in this stage, the basic project is designed with all the available information.
Stage-2: Defining Requirements: In this stage, all the requirements for the target software are specified. These requirements get approval from the customers, market analysts, and stakeholders. This is fulfilled by utilizing SRS (Software Requirement Specification). This is a sort of document that specifies all those things that need to be defined and created during the entire project cycle.
Stage-3: Designing Architecture: SRS is a reference for software designers to come out with the best architecture for the software. Hence, with the requirements defined in SRS, multiple designs for the product architecture are present in the Design Document Specification (DDS). This DDS is assessed by market analysts and stakeholders. After evaluating all the possible factors, the most practical and logical design is chosen for the development.
Stage-4: Developing Product: At this stage, the fundamental development of the product starts. For this, developers use a specific programming code as per the design in the DDS. Hence, it is important for the coders to follow the protocols set by the association. Conventional programming tools like compilers, interpreters, debuggers, etc. are also put into use at this stage. Some popular languages like C/C++, Python, Java, etc. are put into use as per the software regulations.
Stage-5: Product Testing and Integration: After the development of the product, testing of the software is necessary to ensure its smooth execution. Although, minimal testing is conducted at every stage of SDLC. Therefore, at this stage, all the probable flaws are tracked, fixed, and retested. This ensures that the product confronts the quality requirements of SRS.
Therefore, at this stage, all the probable flaws are tracked, fixed, and retested. This ensures that the product confronts the quality requirements of SRS.
Documentation, Training and Support: Software documentation is an essential part of the software development life cycle. A well-written document acts as a tool and means to information repository necessary to know about software processes, functions and maintenance. Documentation also provides information about how to use the product. Thoroughly-written documentation should involve the required documentation. Software architecture documentation, technical documentation and user documentation. Training in an attempt to improve the current or future employee performance by increasing an employee’s ability to work through learning, usually by changing his attitude and developing his skills and understanding.
Stage 6: Deployment and Maintenance Of Product: After detailed testing, the conclusive product is released in phases as per the organization’s strategy. Then it is tested in a real industrial environment. Because it is important to ensure its smooth performance. If it performs well, the organization sends out the product as a whole. After retrieving beneficial feedback, the company releases it as it is or with auxiliary improvements to make it further helpful for the customers. However, this alone is not enough. Therefore, along with the deployment, the product’s supervision.
ankit_kumar_
ankitmishrar
Software Engineering
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n05 Jul, 2021"
},
{
"code": null,
"e": 457,
"s": 52,
"text": "Software Development is the development of software for distinct purposes. For software development, there is a specific programming language like Java, Python, C/C++, etc. The entire process of software development isn’t as simple as its definition, it’s a complicated process. Accordingly, it requires an efficient approach from the developer in the form of the Software Development Life Cycle (SDLC). "
},
{
"code": null,
"e": 703,
"s": 457,
"text": "Proper planning and execution are the key components of a successful software development process. The entire software development process includes 6 stages. Software Development Life Cycle (SDLC) is the common term to summarize these 6 stages. "
},
{
"code": null,
"e": 1012,
"s": 703,
"text": "SDLC specifies the task(s) to be performed at various stages by a software engineer/developer. It ensures that the end product is able to meet the customer’s expectations and fits in the overall budget. Hence, it’s vital for a software developer to have prior knowledge of this software development process. "
},
{
"code": null,
"e": 1050,
"s": 1012,
"text": "These 6 stages are discussed below. "
},
{
"code": null,
"e": 1583,
"s": 1050,
"text": "Stage-1: Planning And Requirement Analysis: Planning is the crucial step in everything and so as in software development. In this same stage, requirement analysis is also performed by the developers of the organization. This is attained from the inputs from the customers, sales department/market surveys. The information from this analysis forms the building block of a basic project. The quality proof of the project is a result of planning. Thus, in this stage, the basic project is designed with all the available information. "
},
{
"code": null,
"e": 1810,
"s": 1583,
"text": "The information from this analysis forms the building block of a basic project. The quality proof of the project is a result of planning. Thus, in this stage, the basic project is designed with all the available information. "
},
{
"code": null,
"e": 2207,
"s": 1810,
"text": "Stage-2: Defining Requirements: In this stage, all the requirements for the target software are specified. These requirements get approval from the customers, market analysts, and stakeholders. This is fulfilled by utilizing SRS (Software Requirement Specification). This is a sort of document that specifies all those things that need to be defined and created during the entire project cycle. "
},
{
"code": null,
"e": 2658,
"s": 2207,
"text": "Stage-3: Designing Architecture: SRS is a reference for software designers to come out with the best architecture for the software. Hence, with the requirements defined in SRS, multiple designs for the product architecture are present in the Design Document Specification (DDS). This DDS is assessed by market analysts and stakeholders. After evaluating all the possible factors, the most practical and logical design is chosen for the development. "
},
{
"code": null,
"e": 3142,
"s": 2658,
"text": "Stage-4: Developing Product: At this stage, the fundamental development of the product starts. For this, developers use a specific programming code as per the design in the DDS. Hence, it is important for the coders to follow the protocols set by the association. Conventional programming tools like compilers, interpreters, debuggers, etc. are also put into use at this stage. Some popular languages like C/C++, Python, Java, etc. are put into use as per the software regulations. "
},
{
"code": null,
"e": 3512,
"s": 3142,
"text": "Stage-5: Product Testing and Integration: After the development of the product, testing of the software is necessary to ensure its smooth execution. Although, minimal testing is conducted at every stage of SDLC. Therefore, at this stage, all the probable flaws are tracked, fixed, and retested. This ensures that the product confronts the quality requirements of SRS. "
},
{
"code": null,
"e": 3670,
"s": 3512,
"text": "Therefore, at this stage, all the probable flaws are tracked, fixed, and retested. This ensures that the product confronts the quality requirements of SRS. "
},
{
"code": null,
"e": 4518,
"s": 3670,
"text": "Documentation, Training and Support: Software documentation is an essential part of the software development life cycle. A well-written document acts as a tool and means to information repository necessary to know about software processes, functions and maintenance. Documentation also provides information about how to use the product. Thoroughly-written documentation should involve the required documentation. Software architecture documentation, technical documentation and user documentation. Training in an attempt to improve the current or future employee performance by increasing an employee’s ability to work through learning, usually by changing his attitude and developing his skills and understanding. "
},
{
"code": null,
"e": 5102,
"s": 4518,
"text": "Stage 6: Deployment and Maintenance Of Product: After detailed testing, the conclusive product is released in phases as per the organization’s strategy. Then it is tested in a real industrial environment. Because it is important to ensure its smooth performance. If it performs well, the organization sends out the product as a whole. After retrieving beneficial feedback, the company releases it as it is or with auxiliary improvements to make it further helpful for the customers. However, this alone is not enough. Therefore, along with the deployment, the product’s supervision. "
},
{
"code": null,
"e": 5115,
"s": 5102,
"text": "ankit_kumar_"
},
{
"code": null,
"e": 5128,
"s": 5115,
"text": "ankitmishrar"
},
{
"code": null,
"e": 5149,
"s": 5128,
"text": "Software Engineering"
}
]
|
JavaScript Quiz | Set-1 | 02 Jun, 2020
Prerequisite: Basic understanding of JavaScript concepts
1. What is the HTML tag under which one can write the JavaScript code?A) <javascript>B) <scripted>C) <script>D) <js>
Ans: Option CExplanation: If we want to write a JavaScript code under HTML tag, you will have to use the “script” tag.
2. Choose the correct JavaScript syntax to change the content of the following HTML code.
<p id="geek">GeeksforGeeks</p>
A) document.getElement(“geek”).innerHTML=”I am a Geek”;B) document.getElementById(“geek”).innerHTML=”I am a Geek”;C) document.getId(“geek”)=”I am a Geek”;D) document.getElementById(“geek”).innerHTML=I am a Geek;
Ans: BExplanation: The correct syntax to access the element is document.getElementById(“geek”). Here we want to access the content written under that id, so we used .innerHTML to specify that and finally we replaced the content with whatever is written inside the quotes.
3. Which of the following is the correct syntax to display “GeeksforGeeks” in an alert box using JavaScript?
A. alertbox(“GeeksforGeeks”);B. msg(“GeeksforGeeks”);C. msgbox(“GeeksforGeeks”);D. alert(“GeeksforGeeks”);
Ans: DExplanation: To display any text in the alert box, you need to write it as alert(“GeeksforGeeks”);.
4. What is the correct syntax for referring to an external script called “geek.js”?
A. <script src=”geek.js”>B. <script href=”geek.js”>C. <script ref=”geek.js”>D. <script name=”geek.js”>
Ans: AExplanation: The “src” term is used to refer to any JavaScript file.
5. The external JavaScript file must contain <script> tag. True or False?
A. TrueB. False
Ans: BExplanation: It is not necessary for any external javascript file to have <script> tag.
6. Predict the output of the following JavaScript code.
<script type="text/javascript">a = 8 + "8";document.write(a);</script>
A) 16B) Compilation ErrorC) 88D) Run Time Error
Ans: Option CExplanation: In the above given code, 8+”8′′ have first integer and second string data types. Rather than adding the two numbers, it concatenated the two.
7. Predict the output of the following JavaScript code.
<script type="text/javascript">var a="GeeksforGeeks";var x=a.lastIndexOf("G");document.write(x);</script>
A) 8B) 0C) 9D) Error
Ans: AExplanation: The index starts with 0 in JavaScript. Here, x searches for the last occurrence of “G” in the text.
8. Which of the following is not a reserved word in JavaScript?
A. interfaceB. throwsC. programD. short
Ans: CExplanation: In JavaScript, interface, throws and short are reserved keywords.
9. Predict the output of the following JavaScript code.
<script type="text/javascript" language="javascript"> var a = "GeeksforGeeks";var result = a.substring(4, 5);document.write(result); </script>
A. sfB. ksC. sD. k
Ans: CExplanation: The substring command selects the substring starting from 4 to 5, excluding the 5th index. The indexing starts from 0. So, the output here is just “s” rather than sf.
10. Predict the output of the following JavaScript code.
<script type="text/javascript" language="javascript"> var x=5;var y=6;var res=eval("x*y");document.write(res); </script>
A. “30”B. 30C. 5*6D. “5*6”
Ans: BExplanation: eval command will evaluate the operation. Here it is 5*6=30.
Akanksha_Rai
JavaScript
Quizzes
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
SDE SHEET - A Complete Guide for SDE Preparation
time.h localtime() function in C with Examples
Length of race track based on the final distance between participants
TCS DIGITAL PUZZLE | Lateral Thinking
Find index after traversing a permutation Array of 1 to N by K steps | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n02 Jun, 2020"
},
{
"code": null,
"e": 109,
"s": 52,
"text": "Prerequisite: Basic understanding of JavaScript concepts"
},
{
"code": null,
"e": 226,
"s": 109,
"text": "1. What is the HTML tag under which one can write the JavaScript code?A) <javascript>B) <scripted>C) <script>D) <js>"
},
{
"code": null,
"e": 345,
"s": 226,
"text": "Ans: Option CExplanation: If we want to write a JavaScript code under HTML tag, you will have to use the “script” tag."
},
{
"code": null,
"e": 435,
"s": 345,
"text": "2. Choose the correct JavaScript syntax to change the content of the following HTML code."
},
{
"code": "<p id=\"geek\">GeeksforGeeks</p>",
"e": 466,
"s": 435,
"text": null
},
{
"code": null,
"e": 678,
"s": 466,
"text": "A) document.getElement(“geek”).innerHTML=”I am a Geek”;B) document.getElementById(“geek”).innerHTML=”I am a Geek”;C) document.getId(“geek”)=”I am a Geek”;D) document.getElementById(“geek”).innerHTML=I am a Geek;"
},
{
"code": null,
"e": 950,
"s": 678,
"text": "Ans: BExplanation: The correct syntax to access the element is document.getElementById(“geek”). Here we want to access the content written under that id, so we used .innerHTML to specify that and finally we replaced the content with whatever is written inside the quotes."
},
{
"code": null,
"e": 1059,
"s": 950,
"text": "3. Which of the following is the correct syntax to display “GeeksforGeeks” in an alert box using JavaScript?"
},
{
"code": null,
"e": 1166,
"s": 1059,
"text": "A. alertbox(“GeeksforGeeks”);B. msg(“GeeksforGeeks”);C. msgbox(“GeeksforGeeks”);D. alert(“GeeksforGeeks”);"
},
{
"code": null,
"e": 1272,
"s": 1166,
"text": "Ans: DExplanation: To display any text in the alert box, you need to write it as alert(“GeeksforGeeks”);."
},
{
"code": null,
"e": 1356,
"s": 1272,
"text": "4. What is the correct syntax for referring to an external script called “geek.js”?"
},
{
"code": null,
"e": 1459,
"s": 1356,
"text": "A. <script src=”geek.js”>B. <script href=”geek.js”>C. <script ref=”geek.js”>D. <script name=”geek.js”>"
},
{
"code": null,
"e": 1534,
"s": 1459,
"text": "Ans: AExplanation: The “src” term is used to refer to any JavaScript file."
},
{
"code": null,
"e": 1608,
"s": 1534,
"text": "5. The external JavaScript file must contain <script> tag. True or False?"
},
{
"code": null,
"e": 1624,
"s": 1608,
"text": "A. TrueB. False"
},
{
"code": null,
"e": 1718,
"s": 1624,
"text": "Ans: BExplanation: It is not necessary for any external javascript file to have <script> tag."
},
{
"code": null,
"e": 1774,
"s": 1718,
"text": "6. Predict the output of the following JavaScript code."
},
{
"code": "<script type=\"text/javascript\">a = 8 + \"8\";document.write(a);</script>",
"e": 1845,
"s": 1774,
"text": null
},
{
"code": null,
"e": 1893,
"s": 1845,
"text": "A) 16B) Compilation ErrorC) 88D) Run Time Error"
},
{
"code": null,
"e": 2061,
"s": 1893,
"text": "Ans: Option CExplanation: In the above given code, 8+”8′′ have first integer and second string data types. Rather than adding the two numbers, it concatenated the two."
},
{
"code": null,
"e": 2117,
"s": 2061,
"text": "7. Predict the output of the following JavaScript code."
},
{
"code": "<script type=\"text/javascript\">var a=\"GeeksforGeeks\";var x=a.lastIndexOf(\"G\");document.write(x);</script>",
"e": 2223,
"s": 2117,
"text": null
},
{
"code": null,
"e": 2244,
"s": 2223,
"text": "A) 8B) 0C) 9D) Error"
},
{
"code": null,
"e": 2363,
"s": 2244,
"text": "Ans: AExplanation: The index starts with 0 in JavaScript. Here, x searches for the last occurrence of “G” in the text."
},
{
"code": null,
"e": 2427,
"s": 2363,
"text": "8. Which of the following is not a reserved word in JavaScript?"
},
{
"code": null,
"e": 2467,
"s": 2427,
"text": "A. interfaceB. throwsC. programD. short"
},
{
"code": null,
"e": 2552,
"s": 2467,
"text": "Ans: CExplanation: In JavaScript, interface, throws and short are reserved keywords."
},
{
"code": null,
"e": 2608,
"s": 2552,
"text": "9. Predict the output of the following JavaScript code."
},
{
"code": "<script type=\"text/javascript\" language=\"javascript\"> var a = \"GeeksforGeeks\";var result = a.substring(4, 5);document.write(result); </script>",
"e": 2753,
"s": 2608,
"text": null
},
{
"code": null,
"e": 2772,
"s": 2753,
"text": "A. sfB. ksC. sD. k"
},
{
"code": null,
"e": 2958,
"s": 2772,
"text": "Ans: CExplanation: The substring command selects the substring starting from 4 to 5, excluding the 5th index. The indexing starts from 0. So, the output here is just “s” rather than sf."
},
{
"code": null,
"e": 3015,
"s": 2958,
"text": "10. Predict the output of the following JavaScript code."
},
{
"code": "<script type=\"text/javascript\" language=\"javascript\"> var x=5;var y=6;var res=eval(\"x*y\");document.write(res); </script>",
"e": 3138,
"s": 3015,
"text": null
},
{
"code": null,
"e": 3165,
"s": 3138,
"text": "A. “30”B. 30C. 5*6D. “5*6”"
},
{
"code": null,
"e": 3245,
"s": 3165,
"text": "Ans: BExplanation: eval command will evaluate the operation. Here it is 5*6=30."
},
{
"code": null,
"e": 3258,
"s": 3245,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 3269,
"s": 3258,
"text": "JavaScript"
},
{
"code": null,
"e": 3277,
"s": 3269,
"text": "Quizzes"
},
{
"code": null,
"e": 3375,
"s": 3277,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3436,
"s": 3375,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3508,
"s": 3436,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 3548,
"s": 3508,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 3589,
"s": 3548,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 3631,
"s": 3589,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 3680,
"s": 3631,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 3727,
"s": 3680,
"text": "time.h localtime() function in C with Examples"
},
{
"code": null,
"e": 3797,
"s": 3727,
"text": "Length of race track based on the final distance between participants"
},
{
"code": null,
"e": 3835,
"s": 3797,
"text": "TCS DIGITAL PUZZLE | Lateral Thinking"
}
]
|
Dart Programming - Map.forEach() Function | Applies the specified function on every Map entry. In other words, forEach enables iterating through the Map’s entries.
Map.forEach(void f(K key, V value));
f(K key, V value) − Applies f to each key-value pair of the map.
Calling f must not add or remove keys from the map
f(K key, V value) − Applies f to each key-value pair of the map.
Calling f must not add or remove keys from the map
Return Type − void.
void main() {
var usrMap = {"name": "Tom", 'Email': '[email protected]'};
usrMap.forEach((k,v) => print('${k}: ${v}'));
}
It will produce the following output − | [
{
"code": null,
"e": 2779,
"s": 2659,
"text": "Applies the specified function on every Map entry. In other words, forEach enables iterating through the Map’s entries."
},
{
"code": null,
"e": 2817,
"s": 2779,
"text": "Map.forEach(void f(K key, V value));\n"
},
{
"code": null,
"e": 2934,
"s": 2817,
"text": "f(K key, V value) − Applies f to each key-value pair of the map.\nCalling f must not add or remove keys from the map\n"
},
{
"code": null,
"e": 2999,
"s": 2934,
"text": "f(K key, V value) − Applies f to each key-value pair of the map."
},
{
"code": null,
"e": 3050,
"s": 2999,
"text": "Calling f must not add or remove keys from the map"
},
{
"code": null,
"e": 3070,
"s": 3050,
"text": "Return Type − void."
},
{
"code": null,
"e": 3196,
"s": 3070,
"text": "void main() { \n var usrMap = {\"name\": \"Tom\", 'Email': '[email protected]'}; \n usrMap.forEach((k,v) => print('${k}: ${v}')); \n} "
}
]
|
Python program to find the string weight | 05 Jul, 2021
Given a String, each character mapped with a weight( number), compute the total weight of the string.
Input : test_str = ‘GeeksforGeeks’, {“G” : 1, “e” : 2, “k” : 5, “f” : 3, “s” : 15, “o” : 4, “r” : 6} Output : 63 Explanation : 2 (G*2) + 8(e*4) + 30(s*2) + 10(k*2) + 4(o) + 6(r) +3(f) = 63.
Input : test_str = ‘Geeks’, {“G” : 1, “e” : 2, “k” : 5, “s” : 15} Output : 25
Method#1 : Using loop
This is one of the ways in which this task can be performed. In this, we iterate for all the characters and sum all the weights mapped from dictionary.
Python3
# Python3 code to demonstrate working of# String Weight# Using loop # initializing stringtest_str = 'GeeksforGeeks' # printing original stringprint("The original string is : " + str(test_str)) # initializing sum dictionarysum_dict = {"G" : 5, "e" : 2, "k" : 10, "f" : 3, "s" : 15, "o" : 4, "r" : 6} # referring dict for sum# iteration using loopres = 0for ele in test_str: res += sum_dict[ele] # printing resultprint("The weighted sum : " + str(res))
The original string is : GeeksforGeeks
The weighted sum : 81
Method #2 : Using sum()
This is one more way in which this task can be performed. In this, we use generator expression, and sum() is used to compute the summation of individual weights.
Python3
# Python3 code to demonstrate working of# String Weight# Using sum() # initializing stringtest_str = 'GeeksforGeeks' # printing original stringprint("The original string is : " + str(test_str)) # initializing sum dictionarysum_dict = {"G" : 5, "e" : 2, "k" : 10, "f" : 3, "s" : 15, "o" : 4, "r" : 6} # sum() used to get summationres = sum(sum_dict[ele] for ele in test_str) # printing resultprint("The weighted sum : " + str(res))
The original string is : GeeksforGeeks
The weighted sum : 81
saurabh1990aror
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Split string into list of characters | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Jul, 2021"
},
{
"code": null,
"e": 130,
"s": 28,
"text": "Given a String, each character mapped with a weight( number), compute the total weight of the string."
},
{
"code": null,
"e": 320,
"s": 130,
"text": "Input : test_str = ‘GeeksforGeeks’, {“G” : 1, “e” : 2, “k” : 5, “f” : 3, “s” : 15, “o” : 4, “r” : 6} Output : 63 Explanation : 2 (G*2) + 8(e*4) + 30(s*2) + 10(k*2) + 4(o) + 6(r) +3(f) = 63."
},
{
"code": null,
"e": 400,
"s": 320,
"text": "Input : test_str = ‘Geeks’, {“G” : 1, “e” : 2, “k” : 5, “s” : 15} Output : 25 "
},
{
"code": null,
"e": 422,
"s": 400,
"text": "Method#1 : Using loop"
},
{
"code": null,
"e": 574,
"s": 422,
"text": "This is one of the ways in which this task can be performed. In this, we iterate for all the characters and sum all the weights mapped from dictionary."
},
{
"code": null,
"e": 582,
"s": 574,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# String Weight# Using loop # initializing stringtest_str = 'GeeksforGeeks' # printing original stringprint(\"The original string is : \" + str(test_str)) # initializing sum dictionarysum_dict = {\"G\" : 5, \"e\" : 2, \"k\" : 10, \"f\" : 3, \"s\" : 15, \"o\" : 4, \"r\" : 6} # referring dict for sum# iteration using loopres = 0for ele in test_str: res += sum_dict[ele] # printing resultprint(\"The weighted sum : \" + str(res))",
"e": 1047,
"s": 582,
"text": null
},
{
"code": null,
"e": 1108,
"s": 1047,
"text": "The original string is : GeeksforGeeks\nThe weighted sum : 81"
},
{
"code": null,
"e": 1132,
"s": 1108,
"text": "Method #2 : Using sum()"
},
{
"code": null,
"e": 1294,
"s": 1132,
"text": "This is one more way in which this task can be performed. In this, we use generator expression, and sum() is used to compute the summation of individual weights."
},
{
"code": null,
"e": 1302,
"s": 1294,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# String Weight# Using sum() # initializing stringtest_str = 'GeeksforGeeks' # printing original stringprint(\"The original string is : \" + str(test_str)) # initializing sum dictionarysum_dict = {\"G\" : 5, \"e\" : 2, \"k\" : 10, \"f\" : 3, \"s\" : 15, \"o\" : 4, \"r\" : 6} # sum() used to get summationres = sum(sum_dict[ele] for ele in test_str) # printing resultprint(\"The weighted sum : \" + str(res))",
"e": 1744,
"s": 1302,
"text": null
},
{
"code": null,
"e": 1805,
"s": 1744,
"text": "The original string is : GeeksforGeeks\nThe weighted sum : 81"
},
{
"code": null,
"e": 1821,
"s": 1805,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 1844,
"s": 1821,
"text": "Python string-programs"
},
{
"code": null,
"e": 1851,
"s": 1844,
"text": "Python"
},
{
"code": null,
"e": 1867,
"s": 1851,
"text": "Python Programs"
},
{
"code": null,
"e": 1965,
"s": 1867,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1997,
"s": 1965,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2024,
"s": 1997,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2045,
"s": 2024,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2068,
"s": 2045,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2124,
"s": 2068,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2146,
"s": 2124,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2185,
"s": 2146,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2223,
"s": 2185,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 2260,
"s": 2223,
"text": "Python Program for Fibonacci numbers"
}
]
|
Minimum amount of lamps needed to be installed | 31 May, 2022
Given string str containing only dots and asterisk. A dot represents free spaces and represents lamps. A lamp at position can spread its light at locations i-1, i, and i+1. Determine the minimum number of lamps needed to illuminate the whole string.
Examples:
Input: str = “......” Output: 2 There are initially no lamps so the whole string is in dark.We will install lamps at position 2 and 5.The lamp at position 2 will illuminate 1, 2, 3 and lamp at position 5 will illuminate 4, 5, 6 thus the whole string is illuminated.
Input: str = “*.*” Output: 0
Approach: If we don’t have an asterisk then for every 3 dots we need one lamp, so the answer is ceil(D/3) where D is the number of dots. The problem can be solved by creating a copy of the given string, and for each asterisk in the first string, we place an asterisk at its adjacent indices in the second string. So if the given string is “...**..” then the second string will be “..****.”. After that, we count the number of dots in each block of consecutive dots and find the number of needed lamps for that block, For each block, the answer will be ceil(D/3) and the total sum of these lamps will be the answer for the complete string.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; void check(int n, string s){ // Create the modified string with // v[i-1] = v[i + 1] = * where s[i] = * char v[n]; for(int i = 0; i < n; i++) { if (s[i] == '*') { v[i] = '*'; // Checking valid index and then replacing // "." with "*" on the surrounding of a * if (i > 0 && i < n - 1) { v[i + 1] = '*'; v[i - 1] = '*'; } if (i == 0 && n != 1) { v[i + 1] = '*'; } if (i == n - 1 && n != 1) { v[i - 1] = '*'; } } else { // Just copying if the character is a "." if (v[i] != '*') { v[i] = '.'; } } } // Creating the string with the list v string str(v); string word = ""; char dl = '*'; // to count the number of split strings int num = 0; // adding delimiter character at the end // of 'str' str = str + dl; // length of 'str' int l = str.size(); // traversing 'str' from left to right vector<string> res; for (int i = 0; i < l; i++) { // if str[i] is not equal to the delimiter // character then accumulate it to 'word' if (str[i] != dl) word += str[i]; else { // if 'word' is not an empty string, // then add this 'word' to the array // 'substr_list[]' if ((int)word.size() != 0) res.push_back(word); // reset 'word' word = ""; } } int ans = 0; for(auto x : res) { // Continuing if the string length is 0 if (x.length() == 0) { continue; } // Adding number of lamps for each block of "." ans += ceil(x.length() * 1.0 / 3); } cout << ans << "\n";} int main() { string s = "....."; int n = s.length(); check(n, s); return 0;} // This code is contributed by NishaBharti.
// Java implementation of the above approachimport java.io.*;import java.lang.*;import java.util.*; class GFG{ // Function to print minimum amount// of lamps needed to be installedstatic void check(int n, String s){ // Create the modified string with // v[i-1] = v[i + 1] = * where s[i] = * char v[] = new char[n]; for(int i = 0; i < n; i++) { if (s.charAt(i) == '*') { v[i] = '*'; // Checking valid index and then replacing // "." with "*" on the surrounding of a * if (i > 0 && i < n - 1) { v[i + 1] = '*'; v[i - 1] = '*'; } if (i == 0 && n != 1) { v[i + 1] = '*'; } if (i == n - 1 && n != 1) { v[i - 1] = '*'; } } else { // Just copying if the character is a "." if (v[i] != '*') { v[i] = '.'; } } } // Creating the string with the list v String xx = new String(v); // Splitting the string into blocks // with "*" as delimiter String x[] = xx.split("\\*"); int ans = 0; for(String xi : x) { // Continuing if the string length is 0 if (xi.length() == 0) { continue; } // Adding number of lamps for each block of "." ans += Math.ceil(xi.length() * 1.0 / 3); } System.out.println(ans);} // Driver Codepublic static void main(String[] args){ String s = "......"; int n = s.length(); check(n, s);}} // This code is contributed by Kingash
# Python3 implementation of the above approachimport math # Function to print minimum amount# of lamps needed to be installeddef check(n, s): # Create the modified string with # v[i-1] = v[i + 1] = * where s[i] = * v = [""] * n for i in range(n): if (s[i] == "*"): v[i] = "*" # Checking valid index and then replacing # "." with "*" on the surrounding of a * if (i > 0 and i < n - 1): v[i + 1] = "*" v[i - 1] = "*" if (i == 0 and n != 1): v[i + 1] = "*" if (i == n - 1 and n != 1): v[i - 1] = "*" else: # Just copying if the character is a "." if (v[i] != "*"): v[i] = "." # Creating the string with the list v xx = ''.join(v) # Splitting the string into blocks # with "*" as delimiter x = xx.split("*") s = 0 for i in range(len(x)): # Continuing if the string length is 0 if (x[i] == ""): continue # Adding number of lamps for each block of "." s += math.ceil(len(x[i]) / 3) print(s) # Driver codes = "......"n = len(s)check(n, s)
// C# implementation of the above approachusing System;class GFG { // Function to print minimum amount // of lamps needed to be installed static void check(int n, string s) { // Create the modified string with // v[i-1] = v[i + 1] = * where s[i] = * char[] v = new char[n]; for (int i = 0; i < n; i++) { if (s[i] == '*') { v[i] = '*'; // Checking valid index and then replacing // "." with "*" on the surrounding of a * if (i > 0 && i < n - 1) { v[i + 1] = '*'; v[i - 1] = '*'; } if (i == 0 && n != 1) { v[i + 1] = '*'; } if (i == n - 1 && n != 1) { v[i - 1] = '*'; } } else { // Just copying if the character is a "." if (v[i] != '*') { v[i] = '.'; } } } // Creating the string with the list v string xx = new string(v); // Splitting the string into blocks // with "*" as delimiter string[] x = xx.Split("\\*"); int ans = 0; foreach(string xi in x) { // Continuing if the string length is 0 if (xi.Length == 0) { continue; } // Adding number of lamps for each block of "." ans += (int)(Math.Ceiling(xi.Length * 1.0 / 3)); } Console.Write(ans); } // Driver Code public static void Main(string[] args) { string s = "......"; int n = s.Length; check(n, s); }} // This code is contributed by ukasp.
<script> // JavaScript implementation of the above approach const check = (n, s) => { // Create the modified string with // v[i-1] = v[i + 1] = * where s[i] = * let v = new Array(n).fill(''); for (let i = 0; i < n; i++) { if (s[i] == '*') { v[i] = '*'; // Checking valid index and then replacing // "." with "*" on the surrounding of a * if (i > 0 && i < n - 1) { v[i + 1] = '*'; v[i - 1] = '*'; } if (i == 0 && n != 1) { v[i + 1] = '*'; } if (i == n - 1 && n != 1) { v[i - 1] = '*'; } } else { // Just copying if the character is a "." if (v[i] != '*') { v[i] = '.'; } } } // Creating the string with the list v let str = v.join(''); let word = ""; let dl = '*'; // to count the number of split strings let num = 0; // adding delimiter character at the end // of 'str' str = str + dl; // length of 'str' let l = str.length; // traversing 'str' from left to right let res = []; for (let i = 0; i < l; i++) { // if str[i] is not equal to the delimiter // character then accumulate it to 'word' if (str[i] != dl) word = word + str[i]; else { // if 'word' is not an empty string, // then add this 'word' to the array // 'substr_list[]' if (word.length != 0) res.push(word); // reset 'word' word = ""; } } let ans = 0; for (let x in res) { // Continuing if the string length is 0 if (res[x].length == 0) { continue; } // Adding number of lamps for each block of "." ans += Math.ceil(res[x].length * 1.0 / 3); } document.write(`${ans}<br/>`); } let s = "....."; let n = s.length; check(n, s); // This code is contributed by rakeshsahni </script>
2
Time Complexity : O(n) as we are dooing single loop traversal
Space Complexity : O(n) as we are creating a character array
Note : where n is size of string given
Kingash
NishaBharti
themacson
surinderdawra388
ukasp
rakeshsahni
kchandramani5265
sweetyty
programming-puzzle
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 50 String Coding Problems for Interviews
What is Data Structure: Types, Classifications and Applications
Print all the duplicates in the input string
Print all subsequences of a string
A Program to check if strings are rotations of each other or not
String class in Java | Set 1
Remove first and last character of a string in Java
Find the smallest window in a string containing all characters of another string
Program to count occurrence of a given character in a string
Return maximum occurring character in an input string | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n31 May, 2022"
},
{
"code": null,
"e": 304,
"s": 54,
"text": "Given string str containing only dots and asterisk. A dot represents free spaces and represents lamps. A lamp at position can spread its light at locations i-1, i, and i+1. Determine the minimum number of lamps needed to illuminate the whole string."
},
{
"code": null,
"e": 315,
"s": 304,
"text": "Examples: "
},
{
"code": null,
"e": 581,
"s": 315,
"text": "Input: str = “......” Output: 2 There are initially no lamps so the whole string is in dark.We will install lamps at position 2 and 5.The lamp at position 2 will illuminate 1, 2, 3 and lamp at position 5 will illuminate 4, 5, 6 thus the whole string is illuminated."
},
{
"code": null,
"e": 611,
"s": 581,
"text": "Input: str = “*.*” Output: 0 "
},
{
"code": null,
"e": 1250,
"s": 611,
"text": "Approach: If we don’t have an asterisk then for every 3 dots we need one lamp, so the answer is ceil(D/3) where D is the number of dots. The problem can be solved by creating a copy of the given string, and for each asterisk in the first string, we place an asterisk at its adjacent indices in the second string. So if the given string is “...**..” then the second string will be “..****.”. After that, we count the number of dots in each block of consecutive dots and find the number of needed lamps for that block, For each block, the answer will be ceil(D/3) and the total sum of these lamps will be the answer for the complete string."
},
{
"code": null,
"e": 1302,
"s": 1250,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1306,
"s": 1302,
"text": "C++"
},
{
"code": null,
"e": 1311,
"s": 1306,
"text": "Java"
},
{
"code": null,
"e": 1319,
"s": 1311,
"text": "Python3"
},
{
"code": null,
"e": 1322,
"s": 1319,
"text": "C#"
},
{
"code": null,
"e": 1333,
"s": 1322,
"text": "Javascript"
},
{
"code": "// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; void check(int n, string s){ // Create the modified string with // v[i-1] = v[i + 1] = * where s[i] = * char v[n]; for(int i = 0; i < n; i++) { if (s[i] == '*') { v[i] = '*'; // Checking valid index and then replacing // \".\" with \"*\" on the surrounding of a * if (i > 0 && i < n - 1) { v[i + 1] = '*'; v[i - 1] = '*'; } if (i == 0 && n != 1) { v[i + 1] = '*'; } if (i == n - 1 && n != 1) { v[i - 1] = '*'; } } else { // Just copying if the character is a \".\" if (v[i] != '*') { v[i] = '.'; } } } // Creating the string with the list v string str(v); string word = \"\"; char dl = '*'; // to count the number of split strings int num = 0; // adding delimiter character at the end // of 'str' str = str + dl; // length of 'str' int l = str.size(); // traversing 'str' from left to right vector<string> res; for (int i = 0; i < l; i++) { // if str[i] is not equal to the delimiter // character then accumulate it to 'word' if (str[i] != dl) word += str[i]; else { // if 'word' is not an empty string, // then add this 'word' to the array // 'substr_list[]' if ((int)word.size() != 0) res.push_back(word); // reset 'word' word = \"\"; } } int ans = 0; for(auto x : res) { // Continuing if the string length is 0 if (x.length() == 0) { continue; } // Adding number of lamps for each block of \".\" ans += ceil(x.length() * 1.0 / 3); } cout << ans << \"\\n\";} int main() { string s = \".....\"; int n = s.length(); check(n, s); return 0;} // This code is contributed by NishaBharti.",
"e": 3519,
"s": 1333,
"text": null
},
{
"code": "// Java implementation of the above approachimport java.io.*;import java.lang.*;import java.util.*; class GFG{ // Function to print minimum amount// of lamps needed to be installedstatic void check(int n, String s){ // Create the modified string with // v[i-1] = v[i + 1] = * where s[i] = * char v[] = new char[n]; for(int i = 0; i < n; i++) { if (s.charAt(i) == '*') { v[i] = '*'; // Checking valid index and then replacing // \".\" with \"*\" on the surrounding of a * if (i > 0 && i < n - 1) { v[i + 1] = '*'; v[i - 1] = '*'; } if (i == 0 && n != 1) { v[i + 1] = '*'; } if (i == n - 1 && n != 1) { v[i - 1] = '*'; } } else { // Just copying if the character is a \".\" if (v[i] != '*') { v[i] = '.'; } } } // Creating the string with the list v String xx = new String(v); // Splitting the string into blocks // with \"*\" as delimiter String x[] = xx.split(\"\\\\*\"); int ans = 0; for(String xi : x) { // Continuing if the string length is 0 if (xi.length() == 0) { continue; } // Adding number of lamps for each block of \".\" ans += Math.ceil(xi.length() * 1.0 / 3); } System.out.println(ans);} // Driver Codepublic static void main(String[] args){ String s = \"......\"; int n = s.length(); check(n, s);}} // This code is contributed by Kingash",
"e": 5207,
"s": 3519,
"text": null
},
{
"code": "# Python3 implementation of the above approachimport math # Function to print minimum amount# of lamps needed to be installeddef check(n, s): # Create the modified string with # v[i-1] = v[i + 1] = * where s[i] = * v = [\"\"] * n for i in range(n): if (s[i] == \"*\"): v[i] = \"*\" # Checking valid index and then replacing # \".\" with \"*\" on the surrounding of a * if (i > 0 and i < n - 1): v[i + 1] = \"*\" v[i - 1] = \"*\" if (i == 0 and n != 1): v[i + 1] = \"*\" if (i == n - 1 and n != 1): v[i - 1] = \"*\" else: # Just copying if the character is a \".\" if (v[i] != \"*\"): v[i] = \".\" # Creating the string with the list v xx = ''.join(v) # Splitting the string into blocks # with \"*\" as delimiter x = xx.split(\"*\") s = 0 for i in range(len(x)): # Continuing if the string length is 0 if (x[i] == \"\"): continue # Adding number of lamps for each block of \".\" s += math.ceil(len(x[i]) / 3) print(s) # Driver codes = \"......\"n = len(s)check(n, s)",
"e": 6398,
"s": 5207,
"text": null
},
{
"code": "// C# implementation of the above approachusing System;class GFG { // Function to print minimum amount // of lamps needed to be installed static void check(int n, string s) { // Create the modified string with // v[i-1] = v[i + 1] = * where s[i] = * char[] v = new char[n]; for (int i = 0; i < n; i++) { if (s[i] == '*') { v[i] = '*'; // Checking valid index and then replacing // \".\" with \"*\" on the surrounding of a * if (i > 0 && i < n - 1) { v[i + 1] = '*'; v[i - 1] = '*'; } if (i == 0 && n != 1) { v[i + 1] = '*'; } if (i == n - 1 && n != 1) { v[i - 1] = '*'; } } else { // Just copying if the character is a \".\" if (v[i] != '*') { v[i] = '.'; } } } // Creating the string with the list v string xx = new string(v); // Splitting the string into blocks // with \"*\" as delimiter string[] x = xx.Split(\"\\\\*\"); int ans = 0; foreach(string xi in x) { // Continuing if the string length is 0 if (xi.Length == 0) { continue; } // Adding number of lamps for each block of \".\" ans += (int)(Math.Ceiling(xi.Length * 1.0 / 3)); } Console.Write(ans); } // Driver Code public static void Main(string[] args) { string s = \"......\"; int n = s.Length; check(n, s); }} // This code is contributed by ukasp.",
"e": 8147,
"s": 6398,
"text": null
},
{
"code": "<script> // JavaScript implementation of the above approach const check = (n, s) => { // Create the modified string with // v[i-1] = v[i + 1] = * where s[i] = * let v = new Array(n).fill(''); for (let i = 0; i < n; i++) { if (s[i] == '*') { v[i] = '*'; // Checking valid index and then replacing // \".\" with \"*\" on the surrounding of a * if (i > 0 && i < n - 1) { v[i + 1] = '*'; v[i - 1] = '*'; } if (i == 0 && n != 1) { v[i + 1] = '*'; } if (i == n - 1 && n != 1) { v[i - 1] = '*'; } } else { // Just copying if the character is a \".\" if (v[i] != '*') { v[i] = '.'; } } } // Creating the string with the list v let str = v.join(''); let word = \"\"; let dl = '*'; // to count the number of split strings let num = 0; // adding delimiter character at the end // of 'str' str = str + dl; // length of 'str' let l = str.length; // traversing 'str' from left to right let res = []; for (let i = 0; i < l; i++) { // if str[i] is not equal to the delimiter // character then accumulate it to 'word' if (str[i] != dl) word = word + str[i]; else { // if 'word' is not an empty string, // then add this 'word' to the array // 'substr_list[]' if (word.length != 0) res.push(word); // reset 'word' word = \"\"; } } let ans = 0; for (let x in res) { // Continuing if the string length is 0 if (res[x].length == 0) { continue; } // Adding number of lamps for each block of \".\" ans += Math.ceil(res[x].length * 1.0 / 3); } document.write(`${ans}<br/>`); } let s = \".....\"; let n = s.length; check(n, s); // This code is contributed by rakeshsahni </script>",
"e": 10477,
"s": 8147,
"text": null
},
{
"code": null,
"e": 10479,
"s": 10477,
"text": "2"
},
{
"code": null,
"e": 10543,
"s": 10481,
"text": "Time Complexity : O(n) as we are dooing single loop traversal"
},
{
"code": null,
"e": 10604,
"s": 10543,
"text": "Space Complexity : O(n) as we are creating a character array"
},
{
"code": null,
"e": 10644,
"s": 10604,
"text": " Note : where n is size of string given"
},
{
"code": null,
"e": 10652,
"s": 10644,
"text": "Kingash"
},
{
"code": null,
"e": 10664,
"s": 10652,
"text": "NishaBharti"
},
{
"code": null,
"e": 10674,
"s": 10664,
"text": "themacson"
},
{
"code": null,
"e": 10691,
"s": 10674,
"text": "surinderdawra388"
},
{
"code": null,
"e": 10697,
"s": 10691,
"text": "ukasp"
},
{
"code": null,
"e": 10709,
"s": 10697,
"text": "rakeshsahni"
},
{
"code": null,
"e": 10726,
"s": 10709,
"text": "kchandramani5265"
},
{
"code": null,
"e": 10735,
"s": 10726,
"text": "sweetyty"
},
{
"code": null,
"e": 10754,
"s": 10735,
"text": "programming-puzzle"
},
{
"code": null,
"e": 10762,
"s": 10754,
"text": "Strings"
},
{
"code": null,
"e": 10770,
"s": 10762,
"text": "Strings"
},
{
"code": null,
"e": 10868,
"s": 10770,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 10913,
"s": 10868,
"text": "Top 50 String Coding Problems for Interviews"
},
{
"code": null,
"e": 10977,
"s": 10913,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 11022,
"s": 10977,
"text": "Print all the duplicates in the input string"
},
{
"code": null,
"e": 11057,
"s": 11022,
"text": "Print all subsequences of a string"
},
{
"code": null,
"e": 11122,
"s": 11057,
"text": "A Program to check if strings are rotations of each other or not"
},
{
"code": null,
"e": 11151,
"s": 11122,
"text": "String class in Java | Set 1"
},
{
"code": null,
"e": 11203,
"s": 11151,
"text": "Remove first and last character of a string in Java"
},
{
"code": null,
"e": 11284,
"s": 11203,
"text": "Find the smallest window in a string containing all characters of another string"
},
{
"code": null,
"e": 11345,
"s": 11284,
"text": "Program to count occurrence of a given character in a string"
}
]
|
Python 3 - Tkinter Button | The Button widget is used to add buttons in a Python application. These buttons can display text or images that convey the purpose of the buttons. You can attach a function or a method to a button which is called automatically when you click the button.
Here is the simple syntax to create this widget −
w = Button ( master, option = value, ... )
master − This represents the parent window.
master − This represents the parent window.
options − Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas.
options − Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas.
activebackground
Background color when the button is under the cursor.
activeforeground
Foreground color when the button is under the cursor.
bd
Border width in pixels. Default is 2.
bg
Normal background color.
command
Function or method to be called when the button is clicked.
fg
Normal foreground (text) color.
font
Text font to be used for the button's label.
height
Height of the button in text lines (for textual buttons) or pixels (for images).
highlightcolor
The color of the focus highlight when the widget has focus.
image
Image to be displayed on the button (instead of text).
justify
How to show multiple text lines: LEFT to left-justify each line; CENTER to center them; or RIGHT to right-justify.
padx
Additional padding left and right of the text.
pady
Additional padding above and below the text.
relief
Relief specifies the type of the border. Some of the values are SUNKEN, RAISED, GROOVE, and RIDGE.
state
Set this option to DISABLED to gray out the button and make it unresponsive. Has the value ACTIVE when the mouse is over it. Default is NORMAL.
underline
Default is -1, meaning that no character of the text on the button will be underlined. If nonnegative, the corresponding text character will be underlined.
width
Width of the button in letters (if displaying text) or pixels (if displaying an image).
wraplength
If this value is set to a positive number, the text lines will be wrapped to fit within this length.
Following are commonly used methods for this widget −
flash()
Causes the button to flash several times between active and normal colors. Leaves the button in the state it was in originally. Ignored if the button is disabled.
invoke()
Calls the button's callback, and returns what that function returns. Has no effect if the button is disabled or there is no callback.
Try the following example yourself −
# !/usr/bin/python3
from tkinter import *
from tkinter import messagebox
top = Tk()
top.geometry("100x100")
def helloCallBack():
msg = messagebox.showinfo( "Hello Python", "Hello World")
B = Button(top, text = "Hello", command = helloCallBack)
B.place(x = 50,y = 50)
top.mainloop()
When the above code is executed, it produces the following result − | [
{
"code": null,
"e": 2728,
"s": 2474,
"text": "The Button widget is used to add buttons in a Python application. These buttons can display text or images that convey the purpose of the buttons. You can attach a function or a method to a button which is called automatically when you click the button."
},
{
"code": null,
"e": 2778,
"s": 2728,
"text": "Here is the simple syntax to create this widget −"
},
{
"code": null,
"e": 2822,
"s": 2778,
"text": "w = Button ( master, option = value, ... )\n"
},
{
"code": null,
"e": 2866,
"s": 2822,
"text": "master − This represents the parent window."
},
{
"code": null,
"e": 2910,
"s": 2866,
"text": "master − This represents the parent window."
},
{
"code": null,
"e": 3050,
"s": 2910,
"text": "options − Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas."
},
{
"code": null,
"e": 3190,
"s": 3050,
"text": "options − Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas."
},
{
"code": null,
"e": 3207,
"s": 3190,
"text": "activebackground"
},
{
"code": null,
"e": 3261,
"s": 3207,
"text": "Background color when the button is under the cursor."
},
{
"code": null,
"e": 3278,
"s": 3261,
"text": "activeforeground"
},
{
"code": null,
"e": 3332,
"s": 3278,
"text": "Foreground color when the button is under the cursor."
},
{
"code": null,
"e": 3335,
"s": 3332,
"text": "bd"
},
{
"code": null,
"e": 3373,
"s": 3335,
"text": "Border width in pixels. Default is 2."
},
{
"code": null,
"e": 3376,
"s": 3373,
"text": "bg"
},
{
"code": null,
"e": 3401,
"s": 3376,
"text": "Normal background color."
},
{
"code": null,
"e": 3409,
"s": 3401,
"text": "command"
},
{
"code": null,
"e": 3469,
"s": 3409,
"text": "Function or method to be called when the button is clicked."
},
{
"code": null,
"e": 3472,
"s": 3469,
"text": "fg"
},
{
"code": null,
"e": 3504,
"s": 3472,
"text": "Normal foreground (text) color."
},
{
"code": null,
"e": 3509,
"s": 3504,
"text": "font"
},
{
"code": null,
"e": 3554,
"s": 3509,
"text": "Text font to be used for the button's label."
},
{
"code": null,
"e": 3561,
"s": 3554,
"text": "height"
},
{
"code": null,
"e": 3642,
"s": 3561,
"text": "Height of the button in text lines (for textual buttons) or pixels (for images)."
},
{
"code": null,
"e": 3658,
"s": 3642,
"text": "highlightcolor\n"
},
{
"code": null,
"e": 3718,
"s": 3658,
"text": "The color of the focus highlight when the widget has focus."
},
{
"code": null,
"e": 3724,
"s": 3718,
"text": "image"
},
{
"code": null,
"e": 3779,
"s": 3724,
"text": "Image to be displayed on the button (instead of text)."
},
{
"code": null,
"e": 3787,
"s": 3779,
"text": "justify"
},
{
"code": null,
"e": 3902,
"s": 3787,
"text": "How to show multiple text lines: LEFT to left-justify each line; CENTER to center them; or RIGHT to right-justify."
},
{
"code": null,
"e": 3907,
"s": 3902,
"text": "padx"
},
{
"code": null,
"e": 3954,
"s": 3907,
"text": "Additional padding left and right of the text."
},
{
"code": null,
"e": 3959,
"s": 3954,
"text": "pady"
},
{
"code": null,
"e": 4004,
"s": 3959,
"text": "Additional padding above and below the text."
},
{
"code": null,
"e": 4011,
"s": 4004,
"text": "relief"
},
{
"code": null,
"e": 4110,
"s": 4011,
"text": "Relief specifies the type of the border. Some of the values are SUNKEN, RAISED, GROOVE, and RIDGE."
},
{
"code": null,
"e": 4116,
"s": 4110,
"text": "state"
},
{
"code": null,
"e": 4260,
"s": 4116,
"text": "Set this option to DISABLED to gray out the button and make it unresponsive. Has the value ACTIVE when the mouse is over it. Default is NORMAL."
},
{
"code": null,
"e": 4270,
"s": 4260,
"text": "underline"
},
{
"code": null,
"e": 4426,
"s": 4270,
"text": "Default is -1, meaning that no character of the text on the button will be underlined. If nonnegative, the corresponding text character will be underlined."
},
{
"code": null,
"e": 4432,
"s": 4426,
"text": "width"
},
{
"code": null,
"e": 4520,
"s": 4432,
"text": "Width of the button in letters (if displaying text) or pixels (if displaying an image)."
},
{
"code": null,
"e": 4531,
"s": 4520,
"text": "wraplength"
},
{
"code": null,
"e": 4632,
"s": 4531,
"text": "If this value is set to a positive number, the text lines will be wrapped to fit within this length."
},
{
"code": null,
"e": 4686,
"s": 4632,
"text": "Following are commonly used methods for this widget −"
},
{
"code": null,
"e": 4694,
"s": 4686,
"text": "flash()"
},
{
"code": null,
"e": 4857,
"s": 4694,
"text": "Causes the button to flash several times between active and normal colors. Leaves the button in the state it was in originally. Ignored if the button is disabled."
},
{
"code": null,
"e": 4866,
"s": 4857,
"text": "invoke()"
},
{
"code": null,
"e": 5000,
"s": 4866,
"text": "Calls the button's callback, and returns what that function returns. Has no effect if the button is disabled or there is no callback."
},
{
"code": null,
"e": 5037,
"s": 5000,
"text": "Try the following example yourself −"
},
{
"code": null,
"e": 5325,
"s": 5037,
"text": "# !/usr/bin/python3\nfrom tkinter import *\n\nfrom tkinter import messagebox\n\ntop = Tk()\ntop.geometry(\"100x100\")\ndef helloCallBack():\n msg = messagebox.showinfo( \"Hello Python\", \"Hello World\")\n\nB = Button(top, text = \"Hello\", command = helloCallBack)\nB.place(x = 50,y = 50)\ntop.mainloop()"
}
]
|
Pulsing Heart Animation Effect Using HTML & CSS | 10 Mar, 2021
This article will teach you about widely fascinated and used HTML & CSS animation i.e. Pulsating Heart Animation. In this article, basically we will learn two methods to implement the animation. This animation is beneficial while making footer of the most website with some common text like Made with Love. So, Let’s have a look on the animation first :
Pulsating Heart Animation
Method 1 (from Scratch): In this method, we will accomplish this animation in two steps:
Building the heartAnimating the heart pulse
Building the heart
Animating the heart pulse
1. Building the heart: Given below is the basic structural HTML file.
HTML
<!DOCTYPE html><html lang="en"> <head> <link rel = "stylesheet" href = "style.css"></head> <body> <div class = "heart"></div></body> </html>
Given below is the CSS file named as style.css for styling & animation.
style.css
body { display:flex; align-items: center; justify-content: center; min-height:100vh; margin: 0; background-color: lightcoral;} .heart { background: red; position: relative; height: 100px; width:100px; /* Animation */ transform: rotate(-45deg) scale(1); animation: pulse 2s linear infinite;} .heart::after { /* background:blue; */ background:inherit; border-radius: 50%; /* To make circle */ content:''; position:absolute; /* top: -100px;*/ top: -50%; /* Inherit properties of parent */ /* left: -100px; */ left:0; height: 100px; width:100px;}.heart::before { /* background:green; */ background:inherit; border-radius: 50%; /* To make circle */ content:''; position:absolute; top:0; right:-50%; /* Inherit properties of parent */ height: 100px; width:100px;} @keyframes pulse{ 0% { transform: rotate(-45deg) scale(1); opacity: 0; }/* 10% { transform: rotate(-45deg) scale(1.3); } 20% { transform: rotate(-45deg) scale(0.9); } 30% { transform: rotate(-45deg) scale(1.2); } 40% { transform: rotate(-45deg) scale(0.9); }*/ 50% { transform: rotate(-45deg) scale(1.3); opacity: 1; }/* 60% { transform: rotate(-45deg) scale(0.95); } 70% { transform: rotate(-45deg) scale(1); } */ 100% { transform: rotate(-45deg) scale(1); opacity: 1; }}
Note: After combining and successfully running the code, it will give the desired result.
Explanation: First we have created a division in body of webpage with class heart. Then in style.css file, we did some general body and class styling to take all the content in the center of the body. Now basically let’s understand how we will make the heart. We will make a heart with the help of the block we have created through basic styling before then through before and after effects as well as the absolute & relative position concept. We will create two circles, for better understanding you can change colors as blue and green respectively in after and before effects of heart class without transforming it. It will look like the below figures :
After positioning circles and block before rotating
Before positioning circles and block
So as you can see after positioning, it is something that looks to be heart but just in a tilted manner though. Please note that keep the color same of the block and both circles to get the required effect. These colors were only chosen for better understanding. Now again so, what to do with a tilted heart, lets make it straight by transforming & rotating it in a clockwise direction at -45 degrees. There you get a straight red heart with a pinkish background. 2. Animating the heart pulse: Let’s go to our second step now. Let’s introduce a pulse animation in heart class of some duration about 1-2 seconds with linear infinite iterations. Then we will apply certain keyframes to make the required animated pulsating heart with a change in transformation scale as well as opacity too.
Concepts Used: 1. Related to Positioning:
absolute: An element is positioned relative to the nearest positioned parent element. One uses the positioning attributes top, left, bottom, and right to set the location.
relative: An element is positioned relative to its normal position. If you set position: relative; of an element but no other positioning attributes (top, left, bottom or right), it will have no effect on it’s positioning at all. But if one give it some other positioning attribute, say, right: 20px;, it will shift its position 20 pixels left from where it would be normally.
2. After and Before Effects: The ::before and ::after are the pseudo-elements in CSS allows you to insert content onto a page without it needing to be in the HTML.
3. About Animating & Inheritance:Syntax:
animation: <animation name> <animation duration>
<animation-timing function> <animation-iteration-count>
There are many other sub-properties in which we can use the animation effect. The animation property in CSS can be used to animate many other CSS properties such as borders, shapes, background-color, height, or width. Each animation needs to be defined with the @keyframes or mechanism how animation will work and what properties to follow.We have also used inheritance property in background color in our example as heart class is parent and heart::after & heart::before are child classes which have inherited the background color used in parent one.
4. About Keyframes:Syntax:
@keyframes <animation name>
Each @keyframes at-rule defines what should happen at specific moments during the animation. For example, 0% is the beginning of the animation, 50 % is the middle of the animation duration and 100% is the end of the animation.
5. About Rotating, Scaling & Opacity:
Syntax:
transform: rotate (<angle>) scale(<value>)
The amount of rotation created by rotate() function is specified by an <angle>. If positive, the movement will be clockwise else it will be counter-clockwise. A rotation by 180° is called point reflection. In our example, we have rotated that tilted heart around y=x line in anticlockwise manner to make it straight.The scale() function is specified with either one or two values, which represent the amount of scaling to be applied in each direction.
Syntax:
scale(x, y). Default value is 1
The opacity property in CSS specifies how transparent an element is. Default value is 1, it means that element is opaque at that duration and visible too. Values range from 0 to 1 representing the opacity of the element.
Method 2: In this method, we will follow two steps that we followed in Method-1 that are building the heart and thus animating it with pulse then.1. Building the heart: We will not build the heart from scratch. You just have to take icon’s HTML & CSS code from different free websites out there. We will recommend Bootstrap Font Awesome icons. Then you just have to apply that code in HTML part of our animation like this:
HTML
<!DOCTYPE html><html lang="en"><head> <link rel = "stylesheet" href = "style.css"> <link rel="stylesheet" href= "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css" integrity="sha512-+4zCK9k+qNFUR5X+cKL9EIR+ZOhtIloNl9GIKS57V1MyNsYpYcUrUeQc9vNfzsWfV28IaLL3i96P9sdNyeRssA==" crossorigin="anonymous" /></head> <body> <div> <i class="fas fa-heart" aria-hidden="true"></i> </div></body> </html>
You can apply CSS in the following manner with name of file as style.css:
style.css
/* General Styling */body { display:flex; align-items: center; justify-content: center; min-height:100vh; margin: 0; background: lightcoral;} /* Styling Heart */.fa-heart { color: red; font-size: 250px; height: 100px; width:100px; /* Animating heart */ animation: pulse 1s linear infinite;} @keyframes pulse { 0%{ transform: scale(1); opacity: 0; } 50%{ transform: scale(1.3); opacity:1; } 100%{ transform: scale(1); opacity:0; }}
Note: After combining and successfully running the code, it will give the desired result.
After just general styling of body and icon’s class, you will get a heart at the center of the body of a webpage.
2. Animating the heart: Please take note of it that here we don’t need pseudo CSS elements’ (after and before) as we have structured the heart with the help of free icons & classes available. Now let’s move to the second step, there you go with the same animation we did in Method – 1. You will get the required animation. Generally, Method – 2 is given more preference while building large websites, Again, creativity has no limits. You can apply this animation wherever you find it needful as well you can build a new animation from your own by inspiring from it.
CSS-Questions
HTML-Questions
Technical Scripter 2020
CSS
HTML
Technical Scripter
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a Tribute Page using HTML & CSS
How to set space between the flexbox ?
Build a Survey Form using HTML and CSS
Design a web page using HTML and CSS
Form validation using jQuery
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Design a Tribute Page using HTML & CSS | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n10 Mar, 2021"
},
{
"code": null,
"e": 409,
"s": 54,
"text": "This article will teach you about widely fascinated and used HTML & CSS animation i.e. Pulsating Heart Animation. In this article, basically we will learn two methods to implement the animation. This animation is beneficial while making footer of the most website with some common text like Made with Love. So, Let’s have a look on the animation first : "
},
{
"code": null,
"e": 435,
"s": 409,
"text": "Pulsating Heart Animation"
},
{
"code": null,
"e": 524,
"s": 435,
"text": "Method 1 (from Scratch): In this method, we will accomplish this animation in two steps:"
},
{
"code": null,
"e": 568,
"s": 524,
"text": "Building the heartAnimating the heart pulse"
},
{
"code": null,
"e": 587,
"s": 568,
"text": "Building the heart"
},
{
"code": null,
"e": 613,
"s": 587,
"text": "Animating the heart pulse"
},
{
"code": null,
"e": 683,
"s": 613,
"text": "1. Building the heart: Given below is the basic structural HTML file."
},
{
"code": null,
"e": 688,
"s": 683,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <link rel = \"stylesheet\" href = \"style.css\"></head> <body> <div class = \"heart\"></div></body> </html>",
"e": 838,
"s": 688,
"text": null
},
{
"code": null,
"e": 910,
"s": 838,
"text": "Given below is the CSS file named as style.css for styling & animation."
},
{
"code": null,
"e": 920,
"s": 910,
"text": "style.css"
},
{
"code": "body { display:flex; align-items: center; justify-content: center; min-height:100vh; margin: 0; background-color: lightcoral;} .heart { background: red; position: relative; height: 100px; width:100px; /* Animation */ transform: rotate(-45deg) scale(1); animation: pulse 2s linear infinite;} .heart::after { /* background:blue; */ background:inherit; border-radius: 50%; /* To make circle */ content:''; position:absolute; /* top: -100px;*/ top: -50%; /* Inherit properties of parent */ /* left: -100px; */ left:0; height: 100px; width:100px;}.heart::before { /* background:green; */ background:inherit; border-radius: 50%; /* To make circle */ content:''; position:absolute; top:0; right:-50%; /* Inherit properties of parent */ height: 100px; width:100px;} @keyframes pulse{ 0% { transform: rotate(-45deg) scale(1); opacity: 0; }/* 10% { transform: rotate(-45deg) scale(1.3); } 20% { transform: rotate(-45deg) scale(0.9); } 30% { transform: rotate(-45deg) scale(1.2); } 40% { transform: rotate(-45deg) scale(0.9); }*/ 50% { transform: rotate(-45deg) scale(1.3); opacity: 1; }/* 60% { transform: rotate(-45deg) scale(0.95); } 70% { transform: rotate(-45deg) scale(1); } */ 100% { transform: rotate(-45deg) scale(1); opacity: 1; }}",
"e": 2394,
"s": 920,
"text": null
},
{
"code": null,
"e": 2484,
"s": 2394,
"text": "Note: After combining and successfully running the code, it will give the desired result."
},
{
"code": null,
"e": 3140,
"s": 2484,
"text": "Explanation: First we have created a division in body of webpage with class heart. Then in style.css file, we did some general body and class styling to take all the content in the center of the body. Now basically let’s understand how we will make the heart. We will make a heart with the help of the block we have created through basic styling before then through before and after effects as well as the absolute & relative position concept. We will create two circles, for better understanding you can change colors as blue and green respectively in after and before effects of heart class without transforming it. It will look like the below figures :"
},
{
"code": null,
"e": 3192,
"s": 3140,
"text": "After positioning circles and block before rotating"
},
{
"code": null,
"e": 3229,
"s": 3192,
"text": "Before positioning circles and block"
},
{
"code": null,
"e": 4018,
"s": 3229,
"text": "So as you can see after positioning, it is something that looks to be heart but just in a tilted manner though. Please note that keep the color same of the block and both circles to get the required effect. These colors were only chosen for better understanding. Now again so, what to do with a tilted heart, lets make it straight by transforming & rotating it in a clockwise direction at -45 degrees. There you get a straight red heart with a pinkish background. 2. Animating the heart pulse: Let’s go to our second step now. Let’s introduce a pulse animation in heart class of some duration about 1-2 seconds with linear infinite iterations. Then we will apply certain keyframes to make the required animated pulsating heart with a change in transformation scale as well as opacity too."
},
{
"code": null,
"e": 4060,
"s": 4018,
"text": "Concepts Used: 1. Related to Positioning:"
},
{
"code": null,
"e": 4232,
"s": 4060,
"text": "absolute: An element is positioned relative to the nearest positioned parent element. One uses the positioning attributes top, left, bottom, and right to set the location."
},
{
"code": null,
"e": 4609,
"s": 4232,
"text": "relative: An element is positioned relative to its normal position. If you set position: relative; of an element but no other positioning attributes (top, left, bottom or right), it will have no effect on it’s positioning at all. But if one give it some other positioning attribute, say, right: 20px;, it will shift its position 20 pixels left from where it would be normally."
},
{
"code": null,
"e": 4774,
"s": 4609,
"text": "2. After and Before Effects: The ::before and ::after are the pseudo-elements in CSS allows you to insert content onto a page without it needing to be in the HTML. "
},
{
"code": null,
"e": 4815,
"s": 4774,
"text": "3. About Animating & Inheritance:Syntax:"
},
{
"code": null,
"e": 4923,
"s": 4815,
"text": "animation: <animation name> <animation duration> \n <animation-timing function> <animation-iteration-count>"
},
{
"code": null,
"e": 5476,
"s": 4923,
"text": "There are many other sub-properties in which we can use the animation effect. The animation property in CSS can be used to animate many other CSS properties such as borders, shapes, background-color, height, or width. Each animation needs to be defined with the @keyframes or mechanism how animation will work and what properties to follow.We have also used inheritance property in background color in our example as heart class is parent and heart::after & heart::before are child classes which have inherited the background color used in parent one. "
},
{
"code": null,
"e": 5503,
"s": 5476,
"text": "4. About Keyframes:Syntax:"
},
{
"code": null,
"e": 5531,
"s": 5503,
"text": "@keyframes <animation name>"
},
{
"code": null,
"e": 5759,
"s": 5531,
"text": "Each @keyframes at-rule defines what should happen at specific moments during the animation. For example, 0% is the beginning of the animation, 50 % is the middle of the animation duration and 100% is the end of the animation. "
},
{
"code": null,
"e": 5797,
"s": 5759,
"text": "5. About Rotating, Scaling & Opacity:"
},
{
"code": null,
"e": 5806,
"s": 5797,
"text": "Syntax: "
},
{
"code": null,
"e": 5849,
"s": 5806,
"text": "transform: rotate (<angle>) scale(<value>)"
},
{
"code": null,
"e": 6302,
"s": 5849,
"text": "The amount of rotation created by rotate() function is specified by an <angle>. If positive, the movement will be clockwise else it will be counter-clockwise. A rotation by 180° is called point reflection. In our example, we have rotated that tilted heart around y=x line in anticlockwise manner to make it straight.The scale() function is specified with either one or two values, which represent the amount of scaling to be applied in each direction. "
},
{
"code": null,
"e": 6311,
"s": 6302,
"text": "Syntax: "
},
{
"code": null,
"e": 6343,
"s": 6311,
"text": "scale(x, y). Default value is 1"
},
{
"code": null,
"e": 6565,
"s": 6343,
"text": "The opacity property in CSS specifies how transparent an element is. Default value is 1, it means that element is opaque at that duration and visible too. Values range from 0 to 1 representing the opacity of the element. "
},
{
"code": null,
"e": 6988,
"s": 6565,
"text": "Method 2: In this method, we will follow two steps that we followed in Method-1 that are building the heart and thus animating it with pulse then.1. Building the heart: We will not build the heart from scratch. You just have to take icon’s HTML & CSS code from different free websites out there. We will recommend Bootstrap Font Awesome icons. Then you just have to apply that code in HTML part of our animation like this:"
},
{
"code": null,
"e": 6993,
"s": 6988,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <link rel = \"stylesheet\" href = \"style.css\"> <link rel=\"stylesheet\" href= \"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css\" integrity=\"sha512-+4zCK9k+qNFUR5X+cKL9EIR+ZOhtIloNl9GIKS57V1MyNsYpYcUrUeQc9vNfzsWfV28IaLL3i96P9sdNyeRssA==\" crossorigin=\"anonymous\" /></head> <body> <div> <i class=\"fas fa-heart\" aria-hidden=\"true\"></i> </div></body> </html>",
"e": 7447,
"s": 6993,
"text": null
},
{
"code": null,
"e": 7522,
"s": 7447,
"text": "You can apply CSS in the following manner with name of file as style.css: "
},
{
"code": null,
"e": 7532,
"s": 7522,
"text": "style.css"
},
{
"code": "/* General Styling */body { display:flex; align-items: center; justify-content: center; min-height:100vh; margin: 0; background: lightcoral;} /* Styling Heart */.fa-heart { color: red; font-size: 250px; height: 100px; width:100px; /* Animating heart */ animation: pulse 1s linear infinite;} @keyframes pulse { 0%{ transform: scale(1); opacity: 0; } 50%{ transform: scale(1.3); opacity:1; } 100%{ transform: scale(1); opacity:0; }}",
"e": 8049,
"s": 7532,
"text": null
},
{
"code": null,
"e": 8139,
"s": 8049,
"text": "Note: After combining and successfully running the code, it will give the desired result."
},
{
"code": null,
"e": 8253,
"s": 8139,
"text": "After just general styling of body and icon’s class, you will get a heart at the center of the body of a webpage."
},
{
"code": null,
"e": 8819,
"s": 8253,
"text": "2. Animating the heart: Please take note of it that here we don’t need pseudo CSS elements’ (after and before) as we have structured the heart with the help of free icons & classes available. Now let’s move to the second step, there you go with the same animation we did in Method – 1. You will get the required animation. Generally, Method – 2 is given more preference while building large websites, Again, creativity has no limits. You can apply this animation wherever you find it needful as well you can build a new animation from your own by inspiring from it."
},
{
"code": null,
"e": 8833,
"s": 8819,
"text": "CSS-Questions"
},
{
"code": null,
"e": 8848,
"s": 8833,
"text": "HTML-Questions"
},
{
"code": null,
"e": 8872,
"s": 8848,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 8876,
"s": 8872,
"text": "CSS"
},
{
"code": null,
"e": 8881,
"s": 8876,
"text": "HTML"
},
{
"code": null,
"e": 8900,
"s": 8881,
"text": "Technical Scripter"
},
{
"code": null,
"e": 8917,
"s": 8900,
"text": "Web Technologies"
},
{
"code": null,
"e": 8922,
"s": 8917,
"text": "HTML"
},
{
"code": null,
"e": 9020,
"s": 8922,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9059,
"s": 9020,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 9098,
"s": 9059,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 9137,
"s": 9098,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 9174,
"s": 9137,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 9203,
"s": 9174,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 9227,
"s": 9203,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 9280,
"s": 9227,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 9340,
"s": 9280,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 9401,
"s": 9340,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
]
|
PostgreSQL – CASE | 28 Aug, 2020
PostgreSQL has a conditional expression called CASE to form conditional queries. The PostgreSQL CASE expression is the same as IF/ELSE statement in other programming languages. PostgreSQL provides two forms of the CASE expressions.
Syntax:
CASE
WHEN condition_1 THEN result_1
WHEN condition_2 THEN result_2
[WHEN ...]
[ELSE result_n]
END
For examples we will be using the sample database (ie, dvdrental).
Example 1:Here we will work on the film table of the sample database. Suppose you want to assign a price segment to a film with the following logic:
Mass if the rental rate is 0.99
Economic if the rental rate is 1.99
Luxury if the rental rate is 4.99
We will query for number of films in each segment using the below statement:
SELECT
SUM (
CASE
WHEN rental_rate = 0.99 THEN
1
ELSE
0
END
) AS "Mass",
SUM (
CASE
WHEN rental_rate = 2.99 THEN
1
ELSE
0
END
) AS "Economic",
SUM (
CASE
WHEN rental_rate = 4.99 THEN
1
ELSE
0
END
) AS "Luxury"
FROM
film;
Output:
Example 2:PostgreSQL provides another form of the CASE expression called simple form as follows:
CASE expression
WHEN value_1 THEN
result_1
WHEN value_2 THEN
result_2
[WHEN ...]
ELSE
result_n
END;
We can rewrite the general CASE expression using the simple CASE as follows:
SELECT
SUM (
CASE rental_rate
WHEN 0.99 THEN
1
ELSE
0
END
) AS "Mass",
SUM (
CASE rental_rate
WHEN 2.99 THEN
1
ELSE
0
END
) AS "Economic",
SUM (
CASE rental_rate
WHEN 4.99 THEN
1
ELSE
0
END
) AS "Luxury"
FROM
film;
Output:The query returns the same result as the first CASE example.
postgreSQL-basics
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - Psql commands
PostgreSQL - Change Column Type
PostgreSQL - For Loops
PostgreSQL - LIMIT with OFFSET clause
PostgreSQL - Function Returning A Table
PostgreSQL - ARRAY_AGG() Function
PostgreSQL - DROP INDEX
PostgreSQL - Create Auto-increment Column using SERIAL
PostgreSQL - Copy Table
PostgreSQL - ROW_NUMBER Function | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Aug, 2020"
},
{
"code": null,
"e": 260,
"s": 28,
"text": "PostgreSQL has a conditional expression called CASE to form conditional queries. The PostgreSQL CASE expression is the same as IF/ELSE statement in other programming languages. PostgreSQL provides two forms of the CASE expressions."
},
{
"code": null,
"e": 393,
"s": 260,
"text": "Syntax:\nCASE \n WHEN condition_1 THEN result_1\n WHEN condition_2 THEN result_2\n [WHEN ...]\n [ELSE result_n]\nEND"
},
{
"code": null,
"e": 460,
"s": 393,
"text": "For examples we will be using the sample database (ie, dvdrental)."
},
{
"code": null,
"e": 609,
"s": 460,
"text": "Example 1:Here we will work on the film table of the sample database. Suppose you want to assign a price segment to a film with the following logic:"
},
{
"code": null,
"e": 641,
"s": 609,
"text": "Mass if the rental rate is 0.99"
},
{
"code": null,
"e": 677,
"s": 641,
"text": "Economic if the rental rate is 1.99"
},
{
"code": null,
"e": 711,
"s": 677,
"text": "Luxury if the rental rate is 4.99"
},
{
"code": null,
"e": 788,
"s": 711,
"text": "We will query for number of films in each segment using the below statement:"
},
{
"code": null,
"e": 1205,
"s": 788,
"text": "SELECT\n SUM (\n CASE\n WHEN rental_rate = 0.99 THEN\n 1\n ELSE\n 0\n END\n ) AS \"Mass\",\n SUM (\n CASE\n WHEN rental_rate = 2.99 THEN\n 1\n ELSE\n 0\n END\n ) AS \"Economic\",\n SUM (\n CASE\n WHEN rental_rate = 4.99 THEN\n 1\n ELSE\n 0\n END\n ) AS \"Luxury\"\nFROM\n film;"
},
{
"code": null,
"e": 1213,
"s": 1205,
"text": "Output:"
},
{
"code": null,
"e": 1310,
"s": 1213,
"text": "Example 2:PostgreSQL provides another form of the CASE expression called simple form as follows:"
},
{
"code": null,
"e": 1423,
"s": 1310,
"text": "CASE expression\nWHEN value_1 THEN\n result_1\nWHEN value_2 THEN\n result_2 \n[WHEN ...]\nELSE\n result_n\nEND;"
},
{
"code": null,
"e": 1500,
"s": 1423,
"text": "We can rewrite the general CASE expression using the simple CASE as follows:"
},
{
"code": null,
"e": 1911,
"s": 1500,
"text": "SELECT\n SUM (\n CASE rental_rate\n WHEN 0.99 THEN\n 1\n ELSE\n 0\n END\n ) AS \"Mass\",\n SUM (\n CASE rental_rate\n WHEN 2.99 THEN\n 1\n ELSE\n 0\n END\n ) AS \"Economic\",\n SUM (\n CASE rental_rate\n WHEN 4.99 THEN\n 1\n ELSE\n 0\n END\n ) AS \"Luxury\"\nFROM\n film;"
},
{
"code": null,
"e": 1979,
"s": 1911,
"text": "Output:The query returns the same result as the first CASE example."
},
{
"code": null,
"e": 1997,
"s": 1979,
"text": "postgreSQL-basics"
},
{
"code": null,
"e": 2008,
"s": 1997,
"text": "PostgreSQL"
},
{
"code": null,
"e": 2106,
"s": 2008,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2133,
"s": 2106,
"text": "PostgreSQL - Psql commands"
},
{
"code": null,
"e": 2165,
"s": 2133,
"text": "PostgreSQL - Change Column Type"
},
{
"code": null,
"e": 2188,
"s": 2165,
"text": "PostgreSQL - For Loops"
},
{
"code": null,
"e": 2226,
"s": 2188,
"text": "PostgreSQL - LIMIT with OFFSET clause"
},
{
"code": null,
"e": 2266,
"s": 2226,
"text": "PostgreSQL - Function Returning A Table"
},
{
"code": null,
"e": 2300,
"s": 2266,
"text": "PostgreSQL - ARRAY_AGG() Function"
},
{
"code": null,
"e": 2324,
"s": 2300,
"text": "PostgreSQL - DROP INDEX"
},
{
"code": null,
"e": 2379,
"s": 2324,
"text": "PostgreSQL - Create Auto-increment Column using SERIAL"
},
{
"code": null,
"e": 2403,
"s": 2379,
"text": "PostgreSQL - Copy Table"
}
]
|
How to count the number of values that satisfy a condition in an R vector? | Sometimes we want to find the frequency of values that satisfy a certain condition. For example, if we have a vector say x that contains randomly selected integers starting from 1 and ends at 100, in this case we might want to find how many values are exactly equal to 10. This can be done by using which and length function.
Live Demo
> x1<-rpois(10,5)
> x1
[1] 5 7 3 3 2 7 3 7 6 3
> length(which(x1==5))
[1] 1
> length(which(x1==7))
[1] 3
> length(which(x1==3))
[1] 4
Live Demo
> x2<-sample(0:9,300,replace=TRUE)
> x2
[1] 4 1 5 5 5 3 8 9 8 4 8 1 6 3 6 1 0 0 9 4 5 4 5 1 2 3 3 3 4 9 1 4 7 0 7 7 8
[38] 3 5 8 0 3 6 5 0 7 9 8 2 7 3 9 6 5 2 7 6 4 6 3 3 7 7 2 2 6 0 0 1 5 1 2 9 8
[75] 9 9 3 9 0 9 5 7 9 1 0 4 7 2 7 9 9 5 8 9 2 8 1 3 3 8 4 8 5 5 2 4 5 8 0 8 4
[112] 4 5 2 4 5 9 8 5 5 9 4 4 6 6 9 2 5 2 9 0 3 8 7 5 8 1 3 1 0 2 6 8 5 6 1 0 2
[149] 6 3 6 2 4 2 9 2 7 8 3 8 4 7 3 1 9 3 2 0 7 0 3 8 9 7 1 2 3 5 8 9 0 4 6 9 8
[186] 6 7 5 6 3 5 3 4 3 7 6 8 0 1 1 7 8 7 4 1 2 3 9 7 5 0 0 6 3 5 8 1 2 1 6 5 2
[223] 1 0 5 0 8 3 9 2 6 5 2 6 3 7 7 1 4 3 7 6 1 2 3 4 7 2 5 5 5 8 4 2 0 9 1 7 1
[260] 2 1 9 8 2 9 1 5 2 0 5 0 0 1 2 1 7 6 3 8 4 1 9 8 0 9 2 1 6 7 5 1 2 7 2 9 5
[297] 6 8 7 1
> length(which(x2==0))
[1] 26
> length(which(x2==1))
[1] 32
> length(which(x2==2))
[1] 34
> length(which(x2==3))
[1] 31
> length(which(x2==4))
[1] 24
> length(which(x2==5))
[1] 36
> length(which(x2==6))
[1] 25
> length(which(x2==7))
[1] 30
> length(which(x2==8))
[1] 31
> length(which(x2==9))
[1] 31
Live Demo
> x3<-sample(501:999,200)
> x3
[1] 977 775 630 693 624 602 903 755 819 779 754 914 731 507 946 836 780 826
[19] 718 899 762 897 583 880 712 669 551 620 959 753 832 835 786 725 803 881
[37] 520 541 795 691 957 888 635 738 562 673 746 665 807 855 666 778 664 657
[55] 985 752 701 967 513 548 997 504 814 722 646 893 992 975 675 645 870 760
[73] 920 894 909 770 982 613 817 581 651 704 568 911 763 523 766 872 929 816
[91] 535 518 956 689 802 848 822 621 506 632 991 811 842 570 923 838 873 567
[109] 812 720 884 958 653 879 854 859 663 919 680 833 601 994 988 576 839 950
[127] 698 768 649 517 626 867 690 594 952 623 895 783 892 970 785 815 672 813
[145] 863 682 986 707 948 983 544 622 606 761 937 906 990 740 688 844 799 684
[163] 589 960 998 976 515 627 925 658 685 913 694 596 784 933 687 522 503 600
[181] 751 558 856 525 963 827 514 907 774 579 509 508 700 717 900 656 918 901
[199] 532 829
> length(which(x3==501))
[1] 0
> length(which(x3==502))
[1] 0
> length(which(x3==620))
[1] 1
> length(which(x3==920))
[1] 1
Live Demo
> x4<-round(runif(300,5,10),0)
> x4
[1] 8 5 9 5 9 10 8 5 6 7 8 10 7 5 8 10 10 9 7 6 9 6 10 8 9
[26] 10 7 6 7 10 9 9 8 5 9 6 5 7 7 8 5 7 7 7 6 7 9 9 9 9
[51] 6 8 9 8 8 6 5 8 9 9 5 9 9 6 8 9 6 6 7 10 9 7 9 8 9
[76] 10 8 9 6 10 7 8 10 6 6 6 7 5 7 5 10 10 7 5 10 6 7 7 6 5
[101] 5 7 7 10 10 10 9 10 9 8 10 9 9 7 10 8 10 9 6 9 8 9 8 7 6
[126] 9 10 7 8 9 5 6 6 10 5 5 8 9 7 8 5 6 9 8 10 6 10 6 7 5
[151] 6 6 8 5 8 9 10 7 6 8 7 8 5 7 7 8 8 9 7 6 5 9 8 6 9
[176] 6 7 8 5 5 5 10 8 5 9 7 5 7 9 9 6 9 8 9 6 10 7 5 9 6
[201] 9 7 6 5 9 6 5 8 7 8 6 7 7 8 8 9 9 7 9 6 8 7 9 8 8
[226] 9 6 7 9 9 5 7 6 8 9 10 9 9 8 9 7 5 7 5 8 5 9 5 6 7
[251] 6 7 7 5 7 10 7 8 8 7 7 9 10 6 6 9 9 7 8 10 6 8 6 7 7
[276] 10 9 8 10 7 9 9 9 8 7 6 9 7 9 8 5 6 10 6 10 8 9 7 8 10
> length(which(x4==5))
[1] 37
> length(which(x4==6))
[1] 48
> length(which(x4==7))
[1] 59
> length(which(x4==8))
[1] 52
> length(which(x4==9))
[1] 67
> length(which(x4==10))
[1] 37
Live Demo
> x5<-sample(11:15,150,replace=TRUE)
> x5
[1] 12 15 12 11 15 15 15 15 13 12 12 11 15 15 13 15 15 14 14 12 15 11 13 14 11
[26] 13 13 15 13 13 15 12 13 15 12 12 12 13 14 13 12 14 15 11 14 13 14 14 12 13
[51] 11 11 13 11 12 12 15 15 14 11 11 11 14 13 14 13 12 12 11 12 12 14 13 13 15
[76] 11 11 14 14 14 14 12 11 12 13 15 12 12 15 14 14 13 12 13 15 11 11 14 13 12
[101] 15 14 15 12 13 13 15 11 14 11 14 15 12 11 13 13 12 11 15 12 13 14 11 15 12
[126] 12 11 14 15 12 12 14 14 11 14 11 12 13 12 15 13 11 15 11 13 12 12 14 13 11
> length(which(x5==11))
[1] 28
> length(which(x5==12))
[1] 35
> length(which(x5==13))
[1] 30
> length(which(x5==14))
[1] 28
> length(which(x5==15))
[1] 29 | [
{
"code": null,
"e": 1513,
"s": 1187,
"text": "Sometimes we want to find the frequency of values that satisfy a certain condition. For example, if we have a vector say x that contains randomly selected integers starting from 1 and ends at 100, in this case we might want to find how many values are exactly equal to 10. This can be done by using which and length function."
},
{
"code": null,
"e": 1523,
"s": 1513,
"text": "Live Demo"
},
{
"code": null,
"e": 1546,
"s": 1523,
"text": "> x1<-rpois(10,5)\n> x1"
},
{
"code": null,
"e": 1570,
"s": 1546,
"text": "[1] 5 7 3 3 2 7 3 7 6 3"
},
{
"code": null,
"e": 1657,
"s": 1570,
"text": "> length(which(x1==5))\n[1] 1\n> length(which(x1==7))\n[1] 3\n> length(which(x1==3))\n[1] 4"
},
{
"code": null,
"e": 1667,
"s": 1657,
"text": "Live Demo"
},
{
"code": null,
"e": 1707,
"s": 1667,
"text": "> x2<-sample(0:9,300,replace=TRUE)\n> x2"
},
{
"code": null,
"e": 2357,
"s": 1707,
"text": "[1] 4 1 5 5 5 3 8 9 8 4 8 1 6 3 6 1 0 0 9 4 5 4 5 1 2 3 3 3 4 9 1 4 7 0 7 7 8\n[38] 3 5 8 0 3 6 5 0 7 9 8 2 7 3 9 6 5 2 7 6 4 6 3 3 7 7 2 2 6 0 0 1 5 1 2 9 8\n[75] 9 9 3 9 0 9 5 7 9 1 0 4 7 2 7 9 9 5 8 9 2 8 1 3 3 8 4 8 5 5 2 4 5 8 0 8 4\n[112] 4 5 2 4 5 9 8 5 5 9 4 4 6 6 9 2 5 2 9 0 3 8 7 5 8 1 3 1 0 2 6 8 5 6 1 0 2\n[149] 6 3 6 2 4 2 9 2 7 8 3 8 4 7 3 1 9 3 2 0 7 0 3 8 9 7 1 2 3 5 8 9 0 4 6 9 8\n[186] 6 7 5 6 3 5 3 4 3 7 6 8 0 1 1 7 8 7 4 1 2 3 9 7 5 0 0 6 3 5 8 1 2 1 6 5 2\n[223] 1 0 5 0 8 3 9 2 6 5 2 6 3 7 7 1 4 3 7 6 1 2 3 4 7 2 5 5 5 8 4 2 0 9 1 7 1\n[260] 2 1 9 8 2 9 1 5 2 0 5 0 0 1 2 1 7 6 3 8 4 1 9 8 0 9 2 1 6 7 5 1 2 7 2 9 5\n[297] 6 8 7 1"
},
{
"code": null,
"e": 2657,
"s": 2357,
"text": "> length(which(x2==0))\n[1] 26\n> length(which(x2==1))\n[1] 32\n> length(which(x2==2))\n[1] 34\n> length(which(x2==3))\n[1] 31\n> length(which(x2==4))\n[1] 24\n> length(which(x2==5))\n[1] 36\n> length(which(x2==6))\n[1] 25\n> length(which(x2==7))\n[1] 30\n> length(which(x2==8))\n[1] 31\n> length(which(x2==9))\n[1] 31"
},
{
"code": null,
"e": 2667,
"s": 2657,
"text": "Live Demo"
},
{
"code": null,
"e": 2698,
"s": 2667,
"text": "> x3<-sample(501:999,200)\n> x3"
},
{
"code": null,
"e": 3563,
"s": 2698,
"text": "[1] 977 775 630 693 624 602 903 755 819 779 754 914 731 507 946 836 780 826\n[19] 718 899 762 897 583 880 712 669 551 620 959 753 832 835 786 725 803 881\n[37] 520 541 795 691 957 888 635 738 562 673 746 665 807 855 666 778 664 657\n[55] 985 752 701 967 513 548 997 504 814 722 646 893 992 975 675 645 870 760\n[73] 920 894 909 770 982 613 817 581 651 704 568 911 763 523 766 872 929 816\n[91] 535 518 956 689 802 848 822 621 506 632 991 811 842 570 923 838 873 567\n[109] 812 720 884 958 653 879 854 859 663 919 680 833 601 994 988 576 839 950\n[127] 698 768 649 517 626 867 690 594 952 623 895 783 892 970 785 815 672 813\n[145] 863 682 986 707 948 983 544 622 606 761 937 906 990 740 688 844 799 684\n[163] 589 960 998 976 515 627 925 658 685 913 694 596 784 933 687 522 503 600\n[181] 751 558 856 525 963 827 514 907 774 579 509 508 700 717 900 656 918 901\n[199] 532 829"
},
{
"code": null,
"e": 3687,
"s": 3563,
"text": "> length(which(x3==501))\n[1] 0\n> length(which(x3==502))\n[1] 0\n> length(which(x3==620))\n[1] 1\n> length(which(x3==920))\n[1] 1"
},
{
"code": null,
"e": 3697,
"s": 3687,
"text": "Live Demo"
},
{
"code": null,
"e": 3733,
"s": 3697,
"text": "> x4<-round(runif(300,5,10),0)\n> x4"
},
{
"code": null,
"e": 4437,
"s": 3733,
"text": "[1] 8 5 9 5 9 10 8 5 6 7 8 10 7 5 8 10 10 9 7 6 9 6 10 8 9\n[26] 10 7 6 7 10 9 9 8 5 9 6 5 7 7 8 5 7 7 7 6 7 9 9 9 9\n[51] 6 8 9 8 8 6 5 8 9 9 5 9 9 6 8 9 6 6 7 10 9 7 9 8 9\n[76] 10 8 9 6 10 7 8 10 6 6 6 7 5 7 5 10 10 7 5 10 6 7 7 6 5\n[101] 5 7 7 10 10 10 9 10 9 8 10 9 9 7 10 8 10 9 6 9 8 9 8 7 6\n[126] 9 10 7 8 9 5 6 6 10 5 5 8 9 7 8 5 6 9 8 10 6 10 6 7 5\n[151] 6 6 8 5 8 9 10 7 6 8 7 8 5 7 7 8 8 9 7 6 5 9 8 6 9\n[176] 6 7 8 5 5 5 10 8 5 9 7 5 7 9 9 6 9 8 9 6 10 7 5 9 6\n[201] 9 7 6 5 9 6 5 8 7 8 6 7 7 8 8 9 9 7 9 6 8 7 9 8 8\n[226] 9 6 7 9 9 5 7 6 8 9 10 9 9 8 9 7 5 7 5 8 5 9 5 6 7\n[251] 6 7 7 5 7 10 7 8 8 7 7 9 10 6 6 9 9 7 8 10 6 8 6 7 7\n[276] 10 9 8 10 7 9 9 9 8 7 6 9 7 9 8 5 6 10 6 10 8 9 7 8 10"
},
{
"code": null,
"e": 4618,
"s": 4437,
"text": "> length(which(x4==5))\n[1] 37\n> length(which(x4==6))\n[1] 48\n> length(which(x4==7))\n[1] 59\n> length(which(x4==8))\n[1] 52\n> length(which(x4==9))\n[1] 67\n> length(which(x4==10))\n[1] 37"
},
{
"code": null,
"e": 4628,
"s": 4618,
"text": "Live Demo"
},
{
"code": null,
"e": 4670,
"s": 4628,
"text": "> x5<-sample(11:15,150,replace=TRUE)\n> x5"
},
{
"code": null,
"e": 5151,
"s": 4670,
"text": "[1] 12 15 12 11 15 15 15 15 13 12 12 11 15 15 13 15 15 14 14 12 15 11 13 14 11\n[26] 13 13 15 13 13 15 12 13 15 12 12 12 13 14 13 12 14 15 11 14 13 14 14 12 13\n[51] 11 11 13 11 12 12 15 15 14 11 11 11 14 13 14 13 12 12 11 12 12 14 13 13 15\n[76] 11 11 14 14 14 14 12 11 12 13 15 12 12 15 14 14 13 12 13 15 11 11 14 13 12\n[101] 15 14 15 12 13 13 15 11 14 11 14 15 12 11 13 13 12 11 15 12 13 14 11 15 12\n[126] 12 11 14 15 12 12 14 14 11 14 11 12 13 12 15 13 11 15 11 13 12 12 14 13 11"
},
{
"code": null,
"e": 5306,
"s": 5151,
"text": "> length(which(x5==11))\n[1] 28\n> length(which(x5==12))\n[1] 35\n> length(which(x5==13))\n[1] 30\n> length(which(x5==14))\n[1] 28\n> length(which(x5==15))\n[1] 29"
}
]
|
Java program to check if a number is prime or not | 18 Oct, 2018
Given a positive integer, check if the number is prime or not. A prime is a natural number greater than 1 that has no positive divisors other than 1 and itself. Examples of first few prime numbers are {2, 3, 5,Examples :
Input: n = 11
Output: true
Input: n = 15
Output: false
Input: n = 1
Output: false
School MethodA simple solution is to iterate through all numbers from 2 to n-1 and for every number check if it divides n. If we find any number that divides, we return false.
// A school method based JAVA program// to check if a number is primeclass GFG { static boolean isPrime(int n) { // Corner case if (n <= 1) return false; // Check from 2 to n-1 for (int i = 2; i < n; i++) if (n % i == 0) return false; return true; } // Driver Program public static void main(String args[]) { if (isPrime(11)) System.out.println(" true"); else System.out.println(" false"); if (isPrime(15)) System.out.println(" true"); else System.out.println(" false"); }}
true
false
Time complexity of this solution is O(n)
Optimized School MethodWe can do following optimizations:
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.
Instead of checking till n, we can check till √n because a larger factor of n must be a multiple of smaller factor that has been already checked.The algorithm can be improved further by observing that all primes are of the form 6k ± 1, with the exception of 2 and 3. This is because all integers can be expressed as (6k + i) for some integer k and for i = ?1, 0, 1, 2, 3, or 4; 2 divides (6k + 0), (6k + 2), (6k + 4); and 3 divides (6k + 3). So a more efficient method is to test if n is divisible by 2 or 3, then to check through all the numbers of form 6k ± 1. (Source: wikipedia)// A optimized school method based Java// program to check if a number is primeimport java.io.*; class GFG { static boolean isPrime(int n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } // Driver Program public static void main(String args[]) { if (isPrime(11)) System.out.println(" true"); else System.out.println(" false"); if (isPrime(15)) System.out.println(" true"); else System.out.println(" false"); }}Output:true
false
Time complexity of this solution is O(√n)Primality Test (Introduction and School Method) | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersPrimality Test (Introduction and School Method) | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou'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.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:44•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=AaNUzEHiDpI" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Main Article : Primality Test | Set 1 (Introduction and School Method)References:https://en.wikipedia.org/wiki/Prime_numberhttp://www.cse.iitk.ac.in/users/manindra/presentations/FLTBasedTests.pdfhttps://en.wikipedia.org/wiki/Primality_testThis article is contributed by Ajay. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed aboveMy Personal Notes
arrow_drop_upSave
Instead of checking till n, we can check till √n because a larger factor of n must be a multiple of smaller factor that has been already checked.
The algorithm can be improved further by observing that all primes are of the form 6k ± 1, with the exception of 2 and 3. This is because all integers can be expressed as (6k + i) for some integer k and for i = ?1, 0, 1, 2, 3, or 4; 2 divides (6k + 0), (6k + 2), (6k + 4); and 3 divides (6k + 3). So a more efficient method is to test if n is divisible by 2 or 3, then to check through all the numbers of form 6k ± 1. (Source: wikipedia)
// A optimized school method based Java// program to check if a number is primeimport java.io.*; class GFG { static boolean isPrime(int n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } // Driver Program public static void main(String args[]) { if (isPrime(11)) System.out.println(" true"); else System.out.println(" false"); if (isPrime(15)) System.out.println(" true"); else System.out.println(" false"); }}
true
false
Time complexity of this solution is O(√n)
Main Article : Primality Test | Set 1 (Introduction and School Method)
References:https://en.wikipedia.org/wiki/Prime_numberhttp://www.cse.iitk.ac.in/users/manindra/presentations/FLTBasedTests.pdfhttps://en.wikipedia.org/wiki/Primality_test
This article is contributed by Ajay. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
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
How to Convert Char to String in Java?
How to Get Elements By Index from HashSet in Java? | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n18 Oct, 2018"
},
{
"code": null,
"e": 273,
"s": 52,
"text": "Given a positive integer, check if the number is prime or not. A prime is a natural number greater than 1 that has no positive divisors other than 1 and itself. Examples of first few prime numbers are {2, 3, 5,Examples :"
},
{
"code": null,
"e": 361,
"s": 273,
"text": "Input: n = 11\nOutput: true\n\nInput: n = 15\nOutput: false\n\nInput: n = 1\nOutput: false\n"
},
{
"code": null,
"e": 537,
"s": 361,
"text": "School MethodA simple solution is to iterate through all numbers from 2 to n-1 and for every number check if it divides n. If we find any number that divides, we return false."
},
{
"code": "// A school method based JAVA program// to check if a number is primeclass GFG { static boolean isPrime(int n) { // Corner case if (n <= 1) return false; // Check from 2 to n-1 for (int i = 2; i < n; i++) if (n % i == 0) return false; return true; } // Driver Program public static void main(String args[]) { if (isPrime(11)) System.out.println(\" true\"); else System.out.println(\" false\"); if (isPrime(15)) System.out.println(\" true\"); else System.out.println(\" false\"); }}",
"e": 1184,
"s": 537,
"text": null
},
{
"code": null,
"e": 1197,
"s": 1184,
"text": "true\n false\n"
},
{
"code": null,
"e": 1238,
"s": 1197,
"text": "Time complexity of this solution is O(n)"
},
{
"code": null,
"e": 1296,
"s": 1238,
"text": "Optimized School MethodWe can do following optimizations:"
},
{
"code": null,
"e": 1305,
"s": 1296,
"text": "Chapters"
},
{
"code": null,
"e": 1332,
"s": 1305,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 1382,
"s": 1332,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 1405,
"s": 1382,
"text": "captions off, selected"
},
{
"code": null,
"e": 1413,
"s": 1405,
"text": "English"
},
{
"code": null,
"e": 1437,
"s": 1413,
"text": "This is a modal window."
},
{
"code": null,
"e": 1506,
"s": 1437,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 1528,
"s": 1506,
"text": "End of dialog window."
},
{
"code": null,
"e": 4390,
"s": 1528,
"text": "Instead of checking till n, we can check till √n because a larger factor of n must be a multiple of smaller factor that has been already checked.The algorithm can be improved further by observing that all primes are of the form 6k ± 1, with the exception of 2 and 3. This is because all integers can be expressed as (6k + i) for some integer k and for i = ?1, 0, 1, 2, 3, or 4; 2 divides (6k + 0), (6k + 2), (6k + 4); and 3 divides (6k + 3). So a more efficient method is to test if n is divisible by 2 or 3, then to check through all the numbers of form 6k ± 1. (Source: wikipedia)// A optimized school method based Java// program to check if a number is primeimport java.io.*; class GFG { static boolean isPrime(int n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } // Driver Program public static void main(String args[]) { if (isPrime(11)) System.out.println(\" true\"); else System.out.println(\" false\"); if (isPrime(15)) System.out.println(\" true\"); else System.out.println(\" false\"); }}Output:true\n false\nTime complexity of this solution is O(√n)Primality Test (Introduction and School Method) | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersPrimality Test (Introduction and School Method) | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou'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.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:44•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=AaNUzEHiDpI\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Main Article : Primality Test | Set 1 (Introduction and School Method)References:https://en.wikipedia.org/wiki/Prime_numberhttp://www.cse.iitk.ac.in/users/manindra/presentations/FLTBasedTests.pdfhttps://en.wikipedia.org/wiki/Primality_testThis article is contributed by Ajay. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed aboveMy Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 4536,
"s": 4390,
"text": "Instead of checking till n, we can check till √n because a larger factor of n must be a multiple of smaller factor that has been already checked."
},
{
"code": null,
"e": 4974,
"s": 4536,
"text": "The algorithm can be improved further by observing that all primes are of the form 6k ± 1, with the exception of 2 and 3. This is because all integers can be expressed as (6k + i) for some integer k and for i = ?1, 0, 1, 2, 3, or 4; 2 divides (6k + 0), (6k + 2), (6k + 4); and 3 divides (6k + 3). So a more efficient method is to test if n is divisible by 2 or 3, then to check through all the numbers of form 6k ± 1. (Source: wikipedia)"
},
{
"code": "// A optimized school method based Java// program to check if a number is primeimport java.io.*; class GFG { static boolean isPrime(int n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } // Driver Program public static void main(String args[]) { if (isPrime(11)) System.out.println(\" true\"); else System.out.println(\" false\"); if (isPrime(15)) System.out.println(\" true\"); else System.out.println(\" false\"); }}",
"e": 5849,
"s": 4974,
"text": null
},
{
"code": null,
"e": 5862,
"s": 5849,
"text": "true\n false\n"
},
{
"code": null,
"e": 5904,
"s": 5862,
"text": "Time complexity of this solution is O(√n)"
},
{
"code": null,
"e": 5975,
"s": 5904,
"text": "Main Article : Primality Test | Set 1 (Introduction and School Method)"
},
{
"code": null,
"e": 6145,
"s": 5975,
"text": "References:https://en.wikipedia.org/wiki/Prime_numberhttp://www.cse.iitk.ac.in/users/manindra/presentations/FLTBasedTests.pdfhttps://en.wikipedia.org/wiki/Primality_test"
},
{
"code": null,
"e": 6306,
"s": 6145,
"text": "This article is contributed by Ajay. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 6320,
"s": 6306,
"text": "Java Programs"
},
{
"code": null,
"e": 6418,
"s": 6320,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6456,
"s": 6418,
"text": "Factory method design pattern in Java"
},
{
"code": null,
"e": 6513,
"s": 6456,
"text": "Java Program to Remove Duplicate Elements From the Array"
},
{
"code": null,
"e": 6542,
"s": 6513,
"text": "Iterate through List in Java"
},
{
"code": null,
"e": 6623,
"s": 6542,
"text": "Java program to count the occurrence of each character in a string using Hashmap"
},
{
"code": null,
"e": 6655,
"s": 6623,
"text": "How to Iterate HashMap in Java?"
},
{
"code": null,
"e": 6707,
"s": 6655,
"text": "Remove first and last character of a string in Java"
},
{
"code": null,
"e": 6751,
"s": 6707,
"text": "Program to print ASCII Value of a character"
},
{
"code": null,
"e": 6799,
"s": 6751,
"text": "Iterate Over the Characters of a String in Java"
},
{
"code": null,
"e": 6838,
"s": 6799,
"text": "How to Convert Char to String in Java?"
}
]
|
How to Get the Input From Tkinter Text Box? | 11 Dec, 2020
Tkinter Text box widget is used to insert multi-line text. This widget can be used for messaging, displaying information, and many other tasks. The important task is to get the inserted text for further processing. For this, we have to use the get() method for the textbox widget.
Syntax: get(start, [end])
where,
start is starting index of required text in TextBox
end is ending index of required text in TextBox
If end is not provided, only character at provided start index will be retrieved.
Create Tkinter window
Create a TextBox widget
Create a Button widget
Create a function that will return text from textbox using get() method after hitting a button
Below is the implementation:
Python3
import tkinter as tk # Top level windowframe = tk.Tk()frame.title("TextBox Input")frame.geometry('400x200')# Function for getting Input# from textbox and printing it # at label widget def printInput(): inp = inputtxt.get(1.0, "end-1c") lbl.config(text = "Provided Input: "+inp) # TextBox Creationinputtxt = tk.Text(frame, height = 5, width = 20) inputtxt.pack() # Button CreationprintButton = tk.Button(frame, text = "Print", command = printInput)printButton.pack() # Label Creationlbl = tk.Label(frame, text = "")lbl.pack()frame.mainloop()
Output:
Snapshot after pressing Print button for above code
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n11 Dec, 2020"
},
{
"code": null,
"e": 335,
"s": 54,
"text": "Tkinter Text box widget is used to insert multi-line text. This widget can be used for messaging, displaying information, and many other tasks. The important task is to get the inserted text for further processing. For this, we have to use the get() method for the textbox widget."
},
{
"code": null,
"e": 361,
"s": 335,
"text": "Syntax: get(start, [end])"
},
{
"code": null,
"e": 368,
"s": 361,
"text": "where,"
},
{
"code": null,
"e": 420,
"s": 368,
"text": "start is starting index of required text in TextBox"
},
{
"code": null,
"e": 468,
"s": 420,
"text": "end is ending index of required text in TextBox"
},
{
"code": null,
"e": 550,
"s": 468,
"text": "If end is not provided, only character at provided start index will be retrieved."
},
{
"code": null,
"e": 572,
"s": 550,
"text": "Create Tkinter window"
},
{
"code": null,
"e": 596,
"s": 572,
"text": "Create a TextBox widget"
},
{
"code": null,
"e": 619,
"s": 596,
"text": "Create a Button widget"
},
{
"code": null,
"e": 714,
"s": 619,
"text": "Create a function that will return text from textbox using get() method after hitting a button"
},
{
"code": null,
"e": 743,
"s": 714,
"text": "Below is the implementation:"
},
{
"code": null,
"e": 751,
"s": 743,
"text": "Python3"
},
{
"code": "import tkinter as tk # Top level windowframe = tk.Tk()frame.title(\"TextBox Input\")frame.geometry('400x200')# Function for getting Input# from textbox and printing it # at label widget def printInput(): inp = inputtxt.get(1.0, \"end-1c\") lbl.config(text = \"Provided Input: \"+inp) # TextBox Creationinputtxt = tk.Text(frame, height = 5, width = 20) inputtxt.pack() # Button CreationprintButton = tk.Button(frame, text = \"Print\", command = printInput)printButton.pack() # Label Creationlbl = tk.Label(frame, text = \"\")lbl.pack()frame.mainloop()",
"e": 1387,
"s": 751,
"text": null
},
{
"code": null,
"e": 1395,
"s": 1387,
"text": "Output:"
},
{
"code": null,
"e": 1447,
"s": 1395,
"text": "Snapshot after pressing Print button for above code"
},
{
"code": null,
"e": 1462,
"s": 1447,
"text": "Python-tkinter"
},
{
"code": null,
"e": 1469,
"s": 1462,
"text": "Python"
}
]
|
How to Show Percentages in Stacked Column Chart in Excel? | 17 Dec, 2021
In this article, you will learn how to create a stacked column chart in excel. Show percentages instead of actual data values on chart data labels.
By default, the data labels are shown in the form of chart data Value (Image 1). But very often user needs to plot charts with actual data and show percentages/custom values on the chart instead of default data. For that we have an option “Value From Cells” in chart “Format Data Label” (Image 2) to select a custom range.
Image 1
Image 2
Follow the below steps to show percentages in stacked column chart In Excel:
Step 1: Open excel and create a data table as below
Step 2: Select the entire data table.
Step 3: To create a column chart in excel for your data table. Go to “Insert” >> “Column or Bar Chart” >> Select Stacked Column Chart
Step 4: Add Data labels to the chart. Goto “Chart Design” >> “Add Chart Element” >> “Data Labels” >> “Center”. You can see all your chart data are in Columns stacked bar.
Step 5: Steps to add percentages/custom values in Chart.
Create a percentage table for your chart data. Copy header text in cells “b1 to E1” to cells “G1 to J1”.
Insert below formula in cell “G2”.
=B2/SUM($B2:$E2)– make sure the “$” symbol are placed in-front of the characters (B and E) in formula
Step 6: Drag down/across the formula to fill cells G2:J6. Click Percent style (1) to convert your new table to show number with Percentage Symbol
Step 7: Select chart data labels and right-click, then choose “Format Data Labels”.
Step 8: Check “Values From Cells”.
Step 9: Above step popup an input box for the user to select a range of cells to display on the chart instead of default values.
In our example, Qtr_04 series default values are in E2:E6. But we select range J2:J6 to show respective percentages. Press “OK”
Step 10: Un-check “Value” to hide the actual value from the chart.
Step 11: Repeat steps 7 to 10 for each series of our data.
Output:
Excel-Charts
Picked
Excel
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Dec, 2021"
},
{
"code": null,
"e": 177,
"s": 28,
"text": "In this article, you will learn how to create a stacked column chart in excel. Show percentages instead of actual data values on chart data labels."
},
{
"code": null,
"e": 501,
"s": 177,
"text": "By default, the data labels are shown in the form of chart data Value (Image 1). But very often user needs to plot charts with actual data and show percentages/custom values on the chart instead of default data. For that we have an option “Value From Cells” in chart “Format Data Label” (Image 2) to select a custom range."
},
{
"code": null,
"e": 509,
"s": 501,
"text": "Image 1"
},
{
"code": null,
"e": 517,
"s": 509,
"text": "Image 2"
},
{
"code": null,
"e": 594,
"s": 517,
"text": "Follow the below steps to show percentages in stacked column chart In Excel:"
},
{
"code": null,
"e": 646,
"s": 594,
"text": "Step 1: Open excel and create a data table as below"
},
{
"code": null,
"e": 684,
"s": 646,
"text": "Step 2: Select the entire data table."
},
{
"code": null,
"e": 821,
"s": 684,
"text": "Step 3: To create a column chart in excel for your data table. Go to “Insert” >> “Column or Bar Chart” >> Select Stacked Column Chart "
},
{
"code": null,
"e": 994,
"s": 821,
"text": "Step 4: Add Data labels to the chart. Goto “Chart Design” >> “Add Chart Element” >> “Data Labels” >> “Center”. You can see all your chart data are in Columns stacked bar."
},
{
"code": null,
"e": 1053,
"s": 994,
"text": "Step 5: Steps to add percentages/custom values in Chart. "
},
{
"code": null,
"e": 1161,
"s": 1053,
"text": "Create a percentage table for your chart data. Copy header text in cells “b1 to E1” to cells “G1 to J1”. "
},
{
"code": null,
"e": 1196,
"s": 1161,
"text": "Insert below formula in cell “G2”."
},
{
"code": null,
"e": 1298,
"s": 1196,
"text": "=B2/SUM($B2:$E2)– make sure the “$” symbol are placed in-front of the characters (B and E) in formula"
},
{
"code": null,
"e": 1444,
"s": 1298,
"text": "Step 6: Drag down/across the formula to fill cells G2:J6. Click Percent style (1) to convert your new table to show number with Percentage Symbol"
},
{
"code": null,
"e": 1529,
"s": 1444,
"text": "Step 7: Select chart data labels and right-click, then choose “Format Data Labels”. "
},
{
"code": null,
"e": 1564,
"s": 1529,
"text": "Step 8: Check “Values From Cells”."
},
{
"code": null,
"e": 1695,
"s": 1564,
"text": "Step 9: Above step popup an input box for the user to select a range of cells to display on the chart instead of default values. "
},
{
"code": null,
"e": 1824,
"s": 1695,
"text": "In our example, Qtr_04 series default values are in E2:E6. But we select range J2:J6 to show respective percentages. Press “OK”"
},
{
"code": null,
"e": 1891,
"s": 1824,
"text": "Step 10: Un-check “Value” to hide the actual value from the chart."
},
{
"code": null,
"e": 1950,
"s": 1891,
"text": "Step 11: Repeat steps 7 to 10 for each series of our data."
},
{
"code": null,
"e": 1958,
"s": 1950,
"text": "Output:"
},
{
"code": null,
"e": 1971,
"s": 1958,
"text": "Excel-Charts"
},
{
"code": null,
"e": 1978,
"s": 1971,
"text": "Picked"
},
{
"code": null,
"e": 1984,
"s": 1978,
"text": "Excel"
}
]
|
DataTables initComplete Option | 11 Sep, 2021
DataTables is jQuery plugin that can be used for adding interactive and advanced controls to HTML tables for the webpage. This also allows the data in the table to be searched, sorted, and filtered according to the needs of the user. The DataTable also exposes a powerful API that can be further used to modify how the data is displayed.
The initComplete option is used to specify the function that will be invoked when the DataTable has fully loaded all the data. This can be useful information in situations where one might require to modify the table in any manner after the data has loaded. It has the JSON parameter as a callback that returns the data that was returned by the server.
Syntax:
function initComplete( settings, json )
Parameters: This option has a two parameters as mentioned above and described below:
settings: This is the settings object of the DataTable containing all the settings with which the table was initialized.
json: This is the JSON data that is retrieved from the server when the ajax option is used. It is undefined when this option is not used.
The examples below illustrate the use of this option.
Example 1: In this example we use the initComplete callback to log to the console that the table has been initialized.
HTML
<!DOCTYPE html><html><head> <!-- jQuery --> <script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.js"> </script> <!-- DataTables CSS --> <link rel="stylesheet" href="https://cdn.datatables.net/1.10.23/css/jquery.dataTables.min.css"> <!-- DataTables JS --> <script src="https://cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js"> </script> </head><body> <h1 style="color: green;"> GeeksForGeeks </h1> <h3>DataTables initComplete Option</h3> <!-- HTML table with random data --> <table id="tableID" class="display nowrap"> <thead> <tr> <th>Day</th> <th>Name</th> <th>Age</th> </tr> </thead> <tbody> <tr> <td>2</td> <td>Patricia</td> <td>22</td> </tr> <tr> <td>2</td> <td>Caleb</td> <td>47</td> </tr> <tr> <td>1</td> <td>Abigail</td> <td>48</td> </tr> <tr> <td>5</td> <td>Rahim</td> <td>44</td> </tr> <tr> <td>5</td> <td>Sheila</td> <td>22</td> </tr> <tr> <td>2</td> <td>Lance</td> <td>48</td> </tr> <tr> <td>5</td> <td>Erin</td> <td>48</td> </tr> <tr> <td>1</td> <td>Christopher</td> <td>28</td> </tr> <tr> <td>2</td> <td>Roary</td> <td>35</td> </tr> <tr> <td>2</td> <td>Astra</td> <td>37</td> </tr> </tbody> </table> <script> // Initialize the DataTable $(document).ready(function () { $('#tableID').DataTable({ initComplete: function () { console.log("The Table has been initialized!") } }); }); </script></body></html>
Output:
Example 2: In this example we use the callback to change the color of the table after it is initialized.
HTML
<!DOCTYPE html><html><head> <!-- jQuery --> <script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.js"> </script> <!-- DataTables CSS --> <link rel="stylesheet" href="https://cdn.datatables.net/1.10.23/css/jquery.dataTables.min.css"> <!-- DataTables JS --> <script src= "https://cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js"> </script> </head><body> <h1 style="color: green;"> GeeksForGeeks </h1> <h3>DataTables initComplete Option</h3> <!-- HTML table with random data --> <table id="tableID" class="display nowrap"> <thead> <tr> <th>Day</th> <th>Name</th> <th>Age</th> </tr> </thead> <tbody> <tr> <td>2</td> <td>Patricia</td> <td>22</td> </tr> <tr> <td>2</td> <td>Caleb</td> <td>47</td> </tr> <tr> <td>1</td> <td>Abigail</td> <td>48</td> </tr> <tr> <td>5</td> <td>Rahim</td> <td>44</td> </tr> <tr> <td>5</td> <td>Sheila</td> <td>22</td> </tr> <tr> <td>2</td> <td>Lance</td> <td>48</td> </tr> <tr> <td>5</td> <td>Erin</td> <td>48</td> </tr> <tr> <td>1</td> <td>Christopher</td> <td>28</td> </tr> <tr> <td>2</td> <td>Roary</td> <td>35</td> </tr> <tr> <td>2</td> <td>Astra</td> <td>37</td> </tr> </tbody> </table> <script> // Initialize the DataTable $(document).ready(function () { $('#tableID').DataTable({ initComplete: function (settings, json) { // Set the background color of the table // to green after the initialisation of the // table has completed $("#tableID, td, tr") .css("background-color", "lightgreen" ); console.log( "The color of the table has changed!" ) } }); }); </script></body></html>
Output:
jQuery-DataTables
JQuery
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": "\n11 Sep, 2021"
},
{
"code": null,
"e": 366,
"s": 28,
"text": "DataTables is jQuery plugin that can be used for adding interactive and advanced controls to HTML tables for the webpage. This also allows the data in the table to be searched, sorted, and filtered according to the needs of the user. The DataTable also exposes a powerful API that can be further used to modify how the data is displayed."
},
{
"code": null,
"e": 718,
"s": 366,
"text": "The initComplete option is used to specify the function that will be invoked when the DataTable has fully loaded all the data. This can be useful information in situations where one might require to modify the table in any manner after the data has loaded. It has the JSON parameter as a callback that returns the data that was returned by the server."
},
{
"code": null,
"e": 726,
"s": 718,
"text": "Syntax:"
},
{
"code": null,
"e": 766,
"s": 726,
"text": "function initComplete( settings, json )"
},
{
"code": null,
"e": 851,
"s": 766,
"text": "Parameters: This option has a two parameters as mentioned above and described below:"
},
{
"code": null,
"e": 972,
"s": 851,
"text": "settings: This is the settings object of the DataTable containing all the settings with which the table was initialized."
},
{
"code": null,
"e": 1110,
"s": 972,
"text": "json: This is the JSON data that is retrieved from the server when the ajax option is used. It is undefined when this option is not used."
},
{
"code": null,
"e": 1164,
"s": 1110,
"text": "The examples below illustrate the use of this option."
},
{
"code": null,
"e": 1283,
"s": 1164,
"text": "Example 1: In this example we use the initComplete callback to log to the console that the table has been initialized."
},
{
"code": null,
"e": 1288,
"s": 1283,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <!-- jQuery --> <script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-3.5.1.js\"> </script> <!-- DataTables CSS --> <link rel=\"stylesheet\" href=\"https://cdn.datatables.net/1.10.23/css/jquery.dataTables.min.css\"> <!-- DataTables JS --> <script src=\"https://cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js\"> </script> </head><body> <h1 style=\"color: green;\"> GeeksForGeeks </h1> <h3>DataTables initComplete Option</h3> <!-- HTML table with random data --> <table id=\"tableID\" class=\"display nowrap\"> <thead> <tr> <th>Day</th> <th>Name</th> <th>Age</th> </tr> </thead> <tbody> <tr> <td>2</td> <td>Patricia</td> <td>22</td> </tr> <tr> <td>2</td> <td>Caleb</td> <td>47</td> </tr> <tr> <td>1</td> <td>Abigail</td> <td>48</td> </tr> <tr> <td>5</td> <td>Rahim</td> <td>44</td> </tr> <tr> <td>5</td> <td>Sheila</td> <td>22</td> </tr> <tr> <td>2</td> <td>Lance</td> <td>48</td> </tr> <tr> <td>5</td> <td>Erin</td> <td>48</td> </tr> <tr> <td>1</td> <td>Christopher</td> <td>28</td> </tr> <tr> <td>2</td> <td>Roary</td> <td>35</td> </tr> <tr> <td>2</td> <td>Astra</td> <td>37</td> </tr> </tbody> </table> <script> // Initialize the DataTable $(document).ready(function () { $('#tableID').DataTable({ initComplete: function () { console.log(\"The Table has been initialized!\") } }); }); </script></body></html>",
"e": 3075,
"s": 1288,
"text": null
},
{
"code": null,
"e": 3083,
"s": 3075,
"text": "Output:"
},
{
"code": null,
"e": 3188,
"s": 3083,
"text": "Example 2: In this example we use the callback to change the color of the table after it is initialized."
},
{
"code": null,
"e": 3193,
"s": 3188,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <!-- jQuery --> <script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-3.5.1.js\"> </script> <!-- DataTables CSS --> <link rel=\"stylesheet\" href=\"https://cdn.datatables.net/1.10.23/css/jquery.dataTables.min.css\"> <!-- DataTables JS --> <script src= \"https://cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js\"> </script> </head><body> <h1 style=\"color: green;\"> GeeksForGeeks </h1> <h3>DataTables initComplete Option</h3> <!-- HTML table with random data --> <table id=\"tableID\" class=\"display nowrap\"> <thead> <tr> <th>Day</th> <th>Name</th> <th>Age</th> </tr> </thead> <tbody> <tr> <td>2</td> <td>Patricia</td> <td>22</td> </tr> <tr> <td>2</td> <td>Caleb</td> <td>47</td> </tr> <tr> <td>1</td> <td>Abigail</td> <td>48</td> </tr> <tr> <td>5</td> <td>Rahim</td> <td>44</td> </tr> <tr> <td>5</td> <td>Sheila</td> <td>22</td> </tr> <tr> <td>2</td> <td>Lance</td> <td>48</td> </tr> <tr> <td>5</td> <td>Erin</td> <td>48</td> </tr> <tr> <td>1</td> <td>Christopher</td> <td>28</td> </tr> <tr> <td>2</td> <td>Roary</td> <td>35</td> </tr> <tr> <td>2</td> <td>Astra</td> <td>37</td> </tr> </tbody> </table> <script> // Initialize the DataTable $(document).ready(function () { $('#tableID').DataTable({ initComplete: function (settings, json) { // Set the background color of the table // to green after the initialisation of the // table has completed $(\"#tableID, td, tr\") .css(\"background-color\", \"lightgreen\" ); console.log( \"The color of the table has changed!\" ) } }); }); </script></body></html>",
"e": 5262,
"s": 3193,
"text": null
},
{
"code": null,
"e": 5270,
"s": 5262,
"text": "Output:"
},
{
"code": null,
"e": 5288,
"s": 5270,
"text": "jQuery-DataTables"
},
{
"code": null,
"e": 5295,
"s": 5288,
"text": "JQuery"
},
{
"code": null,
"e": 5312,
"s": 5295,
"text": "Web Technologies"
}
]
|
Python Pandas - Panel | A panel is a 3D container of data. The term Panel data is derived from econometrics and is partially responsible for the name pandas − pan(el)-da(ta)-s.
The names for the 3 axes are intended to give some semantic meaning to describing operations involving panel data. They are −
items − axis 0, each item corresponds to a DataFrame contained inside.
items − axis 0, each item corresponds to a DataFrame contained inside.
major_axis − axis 1, it is the index (rows) of each of the DataFrames.
major_axis − axis 1, it is the index (rows) of each of the DataFrames.
minor_axis − axis 2, it is the columns of each of the DataFrames.
minor_axis − axis 2, it is the columns of each of the DataFrames.
A Panel can be created using the following constructor −
pandas.Panel(data, items, major_axis, minor_axis, dtype, copy)
The parameters of the constructor are as follows −
A Panel can be created using multiple ways like −
From ndarrays
From dict of DataFrames
# creating an empty panel
import pandas as pd
import numpy as np
data = np.random.rand(2,4,5)
p = pd.Panel(data)
print p
Its output is as follows −
<class 'pandas.core.panel.Panel'>
Dimensions: 2 (items) x 4 (major_axis) x 5 (minor_axis)
Items axis: 0 to 1
Major_axis axis: 0 to 3
Minor_axis axis: 0 to 4
Note − Observe the dimensions of the empty panel and the above panel, all the objects are different.
#creating an empty panel
import pandas as pd
import numpy as np
data = {'Item1' : pd.DataFrame(np.random.randn(4, 3)),
'Item2' : pd.DataFrame(np.random.randn(4, 2))}
p = pd.Panel(data)
print p
Its output is as follows −
Dimensions: 2 (items) x 4 (major_axis) x 3 (minor_axis)
Items axis: Item1 to Item2
Major_axis axis: 0 to 3
Minor_axis axis: 0 to 2
An empty panel can be created using the Panel constructor as follows −
#creating an empty panel
import pandas as pd
p = pd.Panel()
print p
Its output is as follows −
<class 'pandas.core.panel.Panel'>
Dimensions: 0 (items) x 0 (major_axis) x 0 (minor_axis)
Items axis: None
Major_axis axis: None
Minor_axis axis: None
Select the data from the panel using −
Items
Major_axis
Minor_axis
# creating an empty panel
import pandas as pd
import numpy as np
data = {'Item1' : pd.DataFrame(np.random.randn(4, 3)),
'Item2' : pd.DataFrame(np.random.randn(4, 2))}
p = pd.Panel(data)
print p['Item1']
Its output is as follows −
0 1 2
0 0.488224 -0.128637 0.930817
1 0.417497 0.896681 0.576657
2 -2.775266 0.571668 0.290082
3 -0.400538 -0.144234 1.110535
We have two items, and we retrieved item1. The result is a DataFrame with 4 rows and 3 columns, which are the Major_axis and Minor_axis dimensions.
Data can be accessed using the method panel.major_axis(index).
# creating an empty panel
import pandas as pd
import numpy as np
data = {'Item1' : pd.DataFrame(np.random.randn(4, 3)),
'Item2' : pd.DataFrame(np.random.randn(4, 2))}
p = pd.Panel(data)
print p.major_xs(1)
Its output is as follows −
Item1 Item2
0 0.417497 0.748412
1 0.896681 -0.557322
2 0.576657 NaN
Data can be accessed using the method panel.minor_axis(index).
# creating an empty panel
import pandas as pd
import numpy as np
data = {'Item1' : pd.DataFrame(np.random.randn(4, 3)),
'Item2' : pd.DataFrame(np.random.randn(4, 2))}
p = pd.Panel(data)
print p.minor_xs(1)
Its output is as follows −
Item1 Item2
0 -0.128637 -1.047032
1 0.896681 -0.557322
2 0.571668 0.431953
3 -0.144234 1.302466
Note − Observe the changes in the dimensions. | [
{
"code": null,
"e": 2730,
"s": 2577,
"text": "A panel is a 3D container of data. The term Panel data is derived from econometrics and is partially responsible for the name pandas − pan(el)-da(ta)-s."
},
{
"code": null,
"e": 2856,
"s": 2730,
"text": "The names for the 3 axes are intended to give some semantic meaning to describing operations involving panel data. They are −"
},
{
"code": null,
"e": 2927,
"s": 2856,
"text": "items − axis 0, each item corresponds to a DataFrame contained inside."
},
{
"code": null,
"e": 2998,
"s": 2927,
"text": "items − axis 0, each item corresponds to a DataFrame contained inside."
},
{
"code": null,
"e": 3069,
"s": 2998,
"text": "major_axis − axis 1, it is the index (rows) of each of the DataFrames."
},
{
"code": null,
"e": 3140,
"s": 3069,
"text": "major_axis − axis 1, it is the index (rows) of each of the DataFrames."
},
{
"code": null,
"e": 3206,
"s": 3140,
"text": "minor_axis − axis 2, it is the columns of each of the DataFrames."
},
{
"code": null,
"e": 3272,
"s": 3206,
"text": "minor_axis − axis 2, it is the columns of each of the DataFrames."
},
{
"code": null,
"e": 3329,
"s": 3272,
"text": "A Panel can be created using the following constructor −"
},
{
"code": null,
"e": 3393,
"s": 3329,
"text": "pandas.Panel(data, items, major_axis, minor_axis, dtype, copy)\n"
},
{
"code": null,
"e": 3444,
"s": 3393,
"text": "The parameters of the constructor are as follows −"
},
{
"code": null,
"e": 3494,
"s": 3444,
"text": "A Panel can be created using multiple ways like −"
},
{
"code": null,
"e": 3508,
"s": 3494,
"text": "From ndarrays"
},
{
"code": null,
"e": 3532,
"s": 3508,
"text": "From dict of DataFrames"
},
{
"code": null,
"e": 3654,
"s": 3532,
"text": "# creating an empty panel\nimport pandas as pd\nimport numpy as np\n\ndata = np.random.rand(2,4,5)\np = pd.Panel(data)\nprint p"
},
{
"code": null,
"e": 3681,
"s": 3654,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 3839,
"s": 3681,
"text": "<class 'pandas.core.panel.Panel'>\nDimensions: 2 (items) x 4 (major_axis) x 5 (minor_axis)\nItems axis: 0 to 1\nMajor_axis axis: 0 to 3\nMinor_axis axis: 0 to 4\n"
},
{
"code": null,
"e": 3940,
"s": 3839,
"text": "Note − Observe the dimensions of the empty panel and the above panel, all the objects are different."
},
{
"code": null,
"e": 4138,
"s": 3940,
"text": "#creating an empty panel\nimport pandas as pd\nimport numpy as np\n\ndata = {'Item1' : pd.DataFrame(np.random.randn(4, 3)), \n 'Item2' : pd.DataFrame(np.random.randn(4, 2))}\np = pd.Panel(data)\nprint p"
},
{
"code": null,
"e": 4165,
"s": 4138,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 4297,
"s": 4165,
"text": "Dimensions: 2 (items) x 4 (major_axis) x 3 (minor_axis)\nItems axis: Item1 to Item2\nMajor_axis axis: 0 to 3\nMinor_axis axis: 0 to 2\n"
},
{
"code": null,
"e": 4368,
"s": 4297,
"text": "An empty panel can be created using the Panel constructor as follows −"
},
{
"code": null,
"e": 4436,
"s": 4368,
"text": "#creating an empty panel\nimport pandas as pd\np = pd.Panel()\nprint p"
},
{
"code": null,
"e": 4463,
"s": 4436,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 4615,
"s": 4463,
"text": "<class 'pandas.core.panel.Panel'>\nDimensions: 0 (items) x 0 (major_axis) x 0 (minor_axis)\nItems axis: None\nMajor_axis axis: None\nMinor_axis axis: None\n"
},
{
"code": null,
"e": 4654,
"s": 4615,
"text": "Select the data from the panel using −"
},
{
"code": null,
"e": 4660,
"s": 4654,
"text": "Items"
},
{
"code": null,
"e": 4671,
"s": 4660,
"text": "Major_axis"
},
{
"code": null,
"e": 4682,
"s": 4671,
"text": "Minor_axis"
},
{
"code": null,
"e": 4889,
"s": 4682,
"text": "# creating an empty panel\nimport pandas as pd\nimport numpy as np\ndata = {'Item1' : pd.DataFrame(np.random.randn(4, 3)), \n 'Item2' : pd.DataFrame(np.random.randn(4, 2))}\np = pd.Panel(data)\nprint p['Item1']"
},
{
"code": null,
"e": 4916,
"s": 4889,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 5097,
"s": 4916,
"text": " 0 1 2\n0 0.488224 -0.128637 0.930817\n1 0.417497 0.896681 0.576657\n2 -2.775266 0.571668 0.290082\n3 -0.400538 -0.144234 1.110535\n"
},
{
"code": null,
"e": 5245,
"s": 5097,
"text": "We have two items, and we retrieved item1. The result is a DataFrame with 4 rows and 3 columns, which are the Major_axis and Minor_axis dimensions."
},
{
"code": null,
"e": 5308,
"s": 5245,
"text": "Data can be accessed using the method panel.major_axis(index)."
},
{
"code": null,
"e": 5518,
"s": 5308,
"text": "# creating an empty panel\nimport pandas as pd\nimport numpy as np\ndata = {'Item1' : pd.DataFrame(np.random.randn(4, 3)), \n 'Item2' : pd.DataFrame(np.random.randn(4, 2))}\np = pd.Panel(data)\nprint p.major_xs(1)"
},
{
"code": null,
"e": 5545,
"s": 5518,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 5643,
"s": 5545,
"text": " Item1 Item2\n0 0.417497 0.748412\n1 0.896681 -0.557322\n2 0.576657 NaN\n"
},
{
"code": null,
"e": 5706,
"s": 5643,
"text": "Data can be accessed using the method panel.minor_axis(index)."
},
{
"code": null,
"e": 5916,
"s": 5706,
"text": "# creating an empty panel\nimport pandas as pd\nimport numpy as np\ndata = {'Item1' : pd.DataFrame(np.random.randn(4, 3)), \n 'Item2' : pd.DataFrame(np.random.randn(4, 2))}\np = pd.Panel(data)\nprint p.minor_xs(1)"
},
{
"code": null,
"e": 5943,
"s": 5916,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 6073,
"s": 5943,
"text": " Item1 Item2\n0 -0.128637 -1.047032\n1 0.896681 -0.557322\n2 0.571668 0.431953\n3 -0.144234 1.302466\n"
}
]
|
HTTP GET and POST Methods in PHP - GeeksforGeeks | 06 Dec, 2021
In this article, we will know what HTTP GET and POST methods are in PHP, how to implement these HTTP methods & their usage, by understanding them through the examples.
HTTP: The Hypertext Transfer Protocol (HTTP) is designed to enable communications between clients and servers. HTTP works as a request-response protocol between a client and server. A web browser may be the client, and an application on a computer that hosts a website may be the server. A client (browser) submits an HTTP request to the server; then the server returns a response to the client. The response contains status information about the request and may also contain the requested content.
There are 2 HTTP request methods:
GET: Requests data from a specified resource.
POST: Submits data to be processed to a specified resource.
We will understand both these methods in detail through the examples.
GET Method: In the GET method, the data is sent as URL parameters that are usually strings of name and value pairs separated by ampersands (&). In general, a URL with GET data will look like this:
Example: Consider the below example:
http://www.example.com/action.php?name=Sam&weight=55
Here, the bold parts in the URL denote the GET parameters and the italic parts denote the value of those parameters. More than one parameter=value can be embedded in the URL by concatenating with ampersands (&). One can only send simple text data via GET method.
Example: This example illustrates the HTTP GET method in PHP.
HTML
<?php error_reporting(0); if( $_GET["name"] || $_GET["weight"] ) { echo "Welcome ". $_GET['name']. "<br />"; echo "You are ". $_GET['weight']. " kgs in weight."; exit(); }?><html><body> <form action="<?php $_PHP_SELF ?>" method="GET"> Name: <input type="text" name="name" /> Weight:<input type="text" name="weight" /> <input type="submit" /> </form></body></html>
Output:
GET() method
Advantages:
Since the data sent by the GET method are displayed in the URL, it is possible to bookmark the page with specific query string values.
GET requests can be cached and GET requests to remain in the browser history.
GET requests can be bookmarked.
Disadvantages:
The GET method is not suitable for passing sensitive information such as the username and password, because these are fully visible in the URL query string as well as potentially stored in the client browser’s memory as a visited page.
Because the GET method assigns data to a server environment variable, the length of the URL is limited. So, there is a limitation for the total data to be sent.
POST Method: In the POST method, the data is sent to the server as a package in a separate communication with the processing script. Data sent through the POST method will not be visible in the URL.
Example: Consider the below example:
POST /test/demo_form.php HTTP/1.1
Host: gfs.com
SAM=451&MAT=62
The query string (name/weight) is sent in the HTTP message body of a POST request.
Example: This example illustrates the HTTP POST method in PHP. Here, we have used the preg_match() function to search string for a pattern, returns true if a pattern exists, otherwise returns false.
HTML
<?php error_reporting(0); if( $_POST["name"] || $_POST["weight"] ) { if (preg_match("/[^A-Za-z'-]/",$_POST['name'] )) { die ("invalid name and name should be alpha"); } echo "Welcome ". $_POST['name']. "<br />"; echo "You are ". $_POST['weight']. " kgs in weight."; exit(); }?><html><body> <form action = "<?php $_PHP_SELF ?>" method = "POST"> Name: <input type = "text" name = "name" /> Weight: <input type = "text" name = "weight" /> <input type = "submit" /> </form></body></html>
Output:
POST() method
Advantages:
It is more secure than GET because user-entered information is never visible in the URL query string or in the server logs.
There is a much larger limit on the amount of data that can be passed and one can send text data as well as binary data (uploading a file) using POST.
Disadvantages:
Since the data sent by the POST method is not visible in the URL, so it is not possible to bookmark the page with a specific query.
POST requests are never cached
POST requests do not remain in the browser history.
Please refer to the Difference between HTTP GET and POST Methods article for the differences between them in detail.
bhaskargeeksforgeeks
PHP
Technical Scripter
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
Comparing two dates in PHP
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 24674,
"s": 24646,
"text": "\n06 Dec, 2021"
},
{
"code": null,
"e": 24842,
"s": 24674,
"text": "In this article, we will know what HTTP GET and POST methods are in PHP, how to implement these HTTP methods & their usage, by understanding them through the examples."
},
{
"code": null,
"e": 25341,
"s": 24842,
"text": "HTTP: The Hypertext Transfer Protocol (HTTP) is designed to enable communications between clients and servers. HTTP works as a request-response protocol between a client and server. A web browser may be the client, and an application on a computer that hosts a website may be the server. A client (browser) submits an HTTP request to the server; then the server returns a response to the client. The response contains status information about the request and may also contain the requested content."
},
{
"code": null,
"e": 25375,
"s": 25341,
"text": "There are 2 HTTP request methods:"
},
{
"code": null,
"e": 25421,
"s": 25375,
"text": "GET: Requests data from a specified resource."
},
{
"code": null,
"e": 25481,
"s": 25421,
"text": "POST: Submits data to be processed to a specified resource."
},
{
"code": null,
"e": 25551,
"s": 25481,
"text": "We will understand both these methods in detail through the examples."
},
{
"code": null,
"e": 25748,
"s": 25551,
"text": "GET Method: In the GET method, the data is sent as URL parameters that are usually strings of name and value pairs separated by ampersands (&). In general, a URL with GET data will look like this:"
},
{
"code": null,
"e": 25785,
"s": 25748,
"text": "Example: Consider the below example:"
},
{
"code": null,
"e": 25839,
"s": 25785,
"text": "http://www.example.com/action.php?name=Sam&weight=55 "
},
{
"code": null,
"e": 26102,
"s": 25839,
"text": "Here, the bold parts in the URL denote the GET parameters and the italic parts denote the value of those parameters. More than one parameter=value can be embedded in the URL by concatenating with ampersands (&). One can only send simple text data via GET method."
},
{
"code": null,
"e": 26164,
"s": 26102,
"text": "Example: This example illustrates the HTTP GET method in PHP."
},
{
"code": null,
"e": 26169,
"s": 26164,
"text": "HTML"
},
{
"code": "<?php error_reporting(0); if( $_GET[\"name\"] || $_GET[\"weight\"] ) { echo \"Welcome \". $_GET['name']. \"<br />\"; echo \"You are \". $_GET['weight']. \" kgs in weight.\"; exit(); }?><html><body> <form action=\"<?php $_PHP_SELF ?>\" method=\"GET\"> Name: <input type=\"text\" name=\"name\" /> Weight:<input type=\"text\" name=\"weight\" /> <input type=\"submit\" /> </form></body></html>",
"e": 26570,
"s": 26169,
"text": null
},
{
"code": null,
"e": 26578,
"s": 26570,
"text": "Output:"
},
{
"code": null,
"e": 26591,
"s": 26578,
"text": "GET() method"
},
{
"code": null,
"e": 26603,
"s": 26591,
"text": "Advantages:"
},
{
"code": null,
"e": 26738,
"s": 26603,
"text": "Since the data sent by the GET method are displayed in the URL, it is possible to bookmark the page with specific query string values."
},
{
"code": null,
"e": 26816,
"s": 26738,
"text": "GET requests can be cached and GET requests to remain in the browser history."
},
{
"code": null,
"e": 26848,
"s": 26816,
"text": "GET requests can be bookmarked."
},
{
"code": null,
"e": 26863,
"s": 26848,
"text": "Disadvantages:"
},
{
"code": null,
"e": 27099,
"s": 26863,
"text": "The GET method is not suitable for passing sensitive information such as the username and password, because these are fully visible in the URL query string as well as potentially stored in the client browser’s memory as a visited page."
},
{
"code": null,
"e": 27260,
"s": 27099,
"text": "Because the GET method assigns data to a server environment variable, the length of the URL is limited. So, there is a limitation for the total data to be sent."
},
{
"code": null,
"e": 27460,
"s": 27260,
"text": "POST Method: In the POST method, the data is sent to the server as a package in a separate communication with the processing script. Data sent through the POST method will not be visible in the URL. "
},
{
"code": null,
"e": 27497,
"s": 27460,
"text": "Example: Consider the below example:"
},
{
"code": null,
"e": 27563,
"s": 27497,
"text": "POST /test/demo_form.php HTTP/1.1 \nHost: gfs.com \nSAM=451&MAT=62 "
},
{
"code": null,
"e": 27646,
"s": 27563,
"text": "The query string (name/weight) is sent in the HTTP message body of a POST request."
},
{
"code": null,
"e": 27845,
"s": 27646,
"text": "Example: This example illustrates the HTTP POST method in PHP. Here, we have used the preg_match() function to search string for a pattern, returns true if a pattern exists, otherwise returns false."
},
{
"code": null,
"e": 27850,
"s": 27845,
"text": "HTML"
},
{
"code": "<?php error_reporting(0); if( $_POST[\"name\"] || $_POST[\"weight\"] ) { if (preg_match(\"/[^A-Za-z'-]/\",$_POST['name'] )) { die (\"invalid name and name should be alpha\"); } echo \"Welcome \". $_POST['name']. \"<br />\"; echo \"You are \". $_POST['weight']. \" kgs in weight.\"; exit(); }?><html><body> <form action = \"<?php $_PHP_SELF ?>\" method = \"POST\"> Name: <input type = \"text\" name = \"name\" /> Weight: <input type = \"text\" name = \"weight\" /> <input type = \"submit\" /> </form></body></html>",
"e": 28422,
"s": 27850,
"text": null
},
{
"code": null,
"e": 28430,
"s": 28422,
"text": "Output:"
},
{
"code": null,
"e": 28444,
"s": 28430,
"text": "POST() method"
},
{
"code": null,
"e": 28456,
"s": 28444,
"text": "Advantages:"
},
{
"code": null,
"e": 28580,
"s": 28456,
"text": "It is more secure than GET because user-entered information is never visible in the URL query string or in the server logs."
},
{
"code": null,
"e": 28731,
"s": 28580,
"text": "There is a much larger limit on the amount of data that can be passed and one can send text data as well as binary data (uploading a file) using POST."
},
{
"code": null,
"e": 28746,
"s": 28731,
"text": "Disadvantages:"
},
{
"code": null,
"e": 28878,
"s": 28746,
"text": "Since the data sent by the POST method is not visible in the URL, so it is not possible to bookmark the page with a specific query."
},
{
"code": null,
"e": 28909,
"s": 28878,
"text": "POST requests are never cached"
},
{
"code": null,
"e": 28961,
"s": 28909,
"text": "POST requests do not remain in the browser history."
},
{
"code": null,
"e": 29078,
"s": 28961,
"text": "Please refer to the Difference between HTTP GET and POST Methods article for the differences between them in detail."
},
{
"code": null,
"e": 29099,
"s": 29078,
"text": "bhaskargeeksforgeeks"
},
{
"code": null,
"e": 29103,
"s": 29099,
"text": "PHP"
},
{
"code": null,
"e": 29122,
"s": 29103,
"text": "Technical Scripter"
},
{
"code": null,
"e": 29139,
"s": 29122,
"text": "Web Technologies"
},
{
"code": null,
"e": 29143,
"s": 29139,
"text": "PHP"
},
{
"code": null,
"e": 29241,
"s": 29143,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29250,
"s": 29241,
"text": "Comments"
},
{
"code": null,
"e": 29263,
"s": 29250,
"text": "Old Comments"
},
{
"code": null,
"e": 29313,
"s": 29263,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 29353,
"s": 29313,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 29414,
"s": 29353,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 29464,
"s": 29414,
"text": "How to check whether an array is empty using PHP?"
},
{
"code": null,
"e": 29491,
"s": 29464,
"text": "Comparing two dates in PHP"
},
{
"code": null,
"e": 29533,
"s": 29491,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 29566,
"s": 29533,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29628,
"s": 29566,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 29671,
"s": 29628,
"text": "How to fetch data from an API in ReactJS ?"
}
]
|
Feature Engineering of DateTime Variables for Data Science, Machine Learning, Python | Samarth Agrawal | Fast_ml | Towards Data Science | DateTime fields require Feature Engineering to turn them from data to insightful information that can be used by our Machine Learning Models. This post is divided into 3 parts and a Bonus section towards the end, we will use a combination of inbuilt pandas and NumPy functions as well as our functions to extract useful features.
Part 1 — Extract Date / Time Components
Part 2 — Create Boolean Flags
Part 3 — Calculate Date / Time Differences
Bonus — Feature Engineering in 2 lines of code using fast_ml
Whenever I have worked on e-commerce related data, in some way or the other dataset contains DateTime columns.
User registration date-time
User login date-time
Transaction date-time
Disputed transaction date-time
... and many more
At the outset, this date field gives us nothing more than a specific point on a timeline. But these DateTime fields are potential treasure troves of data. These fields are immensely powerful ‘if used rightly’ for uncovering patterns.
As a Data Scientist, your job is to bring the insight to the table, and for that, you are required to ask the right questions. For Ex.
Ques 1 — When do you see most carts getting created?
Ques 2 — When do you see most carts getting abandoned?
Ques 3 — When do you see the most fraudulent transactions?
Ques 4 — When do the maximum users subscribe?
Ques 5 — When are certain items purchased most often?
Ques 6 — After how many days/hours after registration user makes the first order?
Ques 7 — After how many days of inactivity customer never returns to your site?
... etc
Now, To answer these questions, you get back to data to engineer these DateTime fields. And then a whole lot of patterns can be discovered.
Part 1 of the post will provide you feature engineering steps to answer questions like 1,2 & 3
Ans 1 — When do you see most carts getting created? The first week of the month
Ans 2 — When do you see most carts getting abandoned? Wednesday-Afternoon
Ans 3 — When do you see the most fraudulent transactions? Friday-Late nite
Part 2 of the post will provide you feature engineering steps to answer questions like in 4 & 5
Ans 4 — When do the maximum users subscribe? At the start of the year
Ans 5 — When are certain items purchased most often? At the start of the month
Part 3 of the post will provide you feature engineering steps to answer questions like in 6 & 7
Ans 6 — After how many days/hours after registration user makes the first order? Within 2 hours
Ans 7 — After how many days of inactivity customer never returns to your site? After 14 days of inactivity
I have used an example of e-commerce data where I have personally found a lot of use cases but by no means the scope of extracting information is related to just that. We will see in this post how some of the behaviors that can be learned by asking the right question ie. doing the right feature engineering has proved useful in multiple industries across a variety of problems.
import pandas as pddf = pd.read_csv('/kaggle/input/loan-data/loan.csv', parse_dates = ['date_issued', 'date_last_payment'])
Pandas provide a very simple yet very powerful way to deal with DateTime-related variables by parsing them as dates. You can pass as a list all the variables that are date-time related in the parameter parse_dates .
Let’s say you are not aware of the DateTime variables upfront and after investigating the data you found that some of the variables are date-time. So instead of reloading the data, pandas provide another useful function to_datetime to convert the data type to DateTime.
df['date_issued'] = pd.to_datetime(df['date_issued'], errors = 'coerce')
As illustrated in the example above, we can extract the component of the date-time part (year, quarter, month, day, day_of_week, day_of_year, week_of_year, time, hour, minute, second, day_part) from the given date-time variable. The below list provides several of such components that can be extracted using pandas inbuilt functions.
We can extract all these components using .dt accessor. Read more about the date accessors here
Below is the code as shown in the image. All the other components can also be extracted in a similar way
#1df[‘date_issued:year’] = df[‘date_issued’].dt.year#2df[‘date_issued:month’] = df[‘date_issued’].dt.month#3df[‘date_issued:day_of_week’] = df[‘date_issued’].dt.day_of_week#4df[‘date_issued:week_of_year’] = df[‘date_issued’].dt.week_of_year#5df[‘date_issued:hour’] = df[‘date_issued’].dt.hour
Note:
For Monday : day_of_week = 0,
Tuesday : day_of_week=1,
...
Sunday : day_of_week=6
#day_part functiondef day_part(hour): if hour in [4,5]: return "dawn" elif hour in [6,7]: return "early morning" elif hour in [8,9,10]: return "late morning" elif hour in [11,12,13]: return "noon" elif hour in [14,15,16]: return "afternoon" elif hour in [17, 18,19]: return "evening" elif hour in [20, 21, 22]: return "night" elif hour in [23,24,1,2,3]: return "midnight" #Run function with apply methoddf['date_issued:day_part'] = df['date_issued:hour'].apply(day_part)df.head()
As illustrated in the example above, we can extract a lot of boolean Flags (is_month_start, is_month_end, is_quarter_start, is_quarter_end, is_year_start, is_year_end, is_weekend ) from the given date-time variable. The below list provides several of such components that can be extracted using pandas inbuilt functions as well as by creating some of our functions.
Again, we can use .dt accessor to extract a lot of these boolean flags.
#1df['date_issued:is_year_start'] = df['date_issued'].dt.is_year_start#2df['date_issued:is_quarter_start'] = df['date_issued'].dt.is_quarter_start#3df['date_issued:is_month_start'] = df['date_issued'].dt.is_month_start#4df['date_issued:is_month_end'] = df['date_issued'].dt.is_month_end
If we check the calendar, we will see that 26th of Oct, 2013 was a Saturday — a weekend.
df['date_issued:is_weekend'] = np.where(df['date_issued:day_of_week'].isin([5,6]), 1,0)
Often your questions/analysis will be relative to another point of reference. Like,
After how many days/hours after registration user makes the first order? registration_date & first_order_dateIn how many days/hours customer’s complaint was resolved? complain_date & resolution_dateFrom today, how recently customer ordered from your site? today & last_order_date...etc
After how many days/hours after registration user makes the first order? registration_date & first_order_date
In how many days/hours customer’s complaint was resolved? complain_date & resolution_date
From today, how recently customer ordered from your site? today & last_order_date
...etc
In our example dataset, we have two columns date_last_payment & date_issued. Let’s see what happens when we just take a difference of these 2 columns.
Pandas by default provide the difference in ‘days’. Notice the dtype: timedelta64[ns].
From the numpy documentation:
“Because NumPy doesn’t have a physical quantities system in its core, the timedelta64 data type was created to complement datetime64”
Now, if we just want the numeric part and not the entire string 947 days, we can do that by using the .dt accessor.
Unfortunately, we can’t get the months in a similar fashion.
Here the timedelta64 from NumPy becomes very useful.
In order to get the number of months between date loan was issued and date last payment was done, we will write this
(df['date_last_payment'] - df['date_issued'])/np.timedelta64(1, 'M')
timedelta64 can take following parameters for calculating the difference between 2 dates:
‘D’ → for Days
‘W’ → for Weeks
‘M’ → for Months
‘Y’ → for Years
‘h’ → for Hours
You can use fast_ml to create all these datetime features
First, install fast_ml package
!pip install fast_ml — upgrade
And then, from the feature_engineering module import the method for engineering date time features
from fast_ml.feature_engineering import FeatureEngineering_DateTime
Now, this works in the exact same way as other transformers, preprocessors from sklearn.
Instantiate
Fit
Transform
#Instantiatedt_fe = FeatureEngineering_DateTime()#Fitdt_fe.fit(df, datetime_variables=['date_issued'], prefix = 'date_issued:')#Transformdf = dt_fe.transform(df)df.head()
All the columns are not visible in the screenshot. Let’s just look at the columns of the dataset
df.columns---Output---Index(['customer_id', 'disbursed_amount', 'interest', 'market', 'employment', 'time_employed', 'householder', 'income', 'date_issued', 'target', 'loan_purpose', 'number_open_accounts', 'date_last_payment', 'number_credit_lines_12',(Notice from here ------->)'date_issued:year', 'date_issued:quarter', 'date_issued:month', 'date_issued:day', 'date_issued:day_of_week', 'date_issued:day_of_year', 'date_issued:weekofyear', 'date_issued:is_month_end', 'date_issued:is_month_start', 'date_issued:is_quarter_end', 'date_issued:is_quarter_start', 'date_issued:is_year_end', 'date_issued:is_year_start', 'date_issued:time', 'date_issued:hour', 'date_issued:minute', 'date_issued:second', 'date_issued:is_weekend', 'date_issued:day_part'],dtype='object')
If you enjoyed this, follow me on medium for more.
Interested in collaborating? Let’s connect on Linkedin.
Please feel free to write your thoughts/suggestions/feedback.
Kaggle link
Fast_ml link
Notebook is available at the following location with fully functional code: | [
{
"code": null,
"e": 502,
"s": 172,
"text": "DateTime fields require Feature Engineering to turn them from data to insightful information that can be used by our Machine Learning Models. This post is divided into 3 parts and a Bonus section towards the end, we will use a combination of inbuilt pandas and NumPy functions as well as our functions to extract useful features."
},
{
"code": null,
"e": 542,
"s": 502,
"text": "Part 1 — Extract Date / Time Components"
},
{
"code": null,
"e": 572,
"s": 542,
"text": "Part 2 — Create Boolean Flags"
},
{
"code": null,
"e": 615,
"s": 572,
"text": "Part 3 — Calculate Date / Time Differences"
},
{
"code": null,
"e": 676,
"s": 615,
"text": "Bonus — Feature Engineering in 2 lines of code using fast_ml"
},
{
"code": null,
"e": 787,
"s": 676,
"text": "Whenever I have worked on e-commerce related data, in some way or the other dataset contains DateTime columns."
},
{
"code": null,
"e": 815,
"s": 787,
"text": "User registration date-time"
},
{
"code": null,
"e": 836,
"s": 815,
"text": "User login date-time"
},
{
"code": null,
"e": 858,
"s": 836,
"text": "Transaction date-time"
},
{
"code": null,
"e": 889,
"s": 858,
"text": "Disputed transaction date-time"
},
{
"code": null,
"e": 907,
"s": 889,
"text": "... and many more"
},
{
"code": null,
"e": 1141,
"s": 907,
"text": "At the outset, this date field gives us nothing more than a specific point on a timeline. But these DateTime fields are potential treasure troves of data. These fields are immensely powerful ‘if used rightly’ for uncovering patterns."
},
{
"code": null,
"e": 1276,
"s": 1141,
"text": "As a Data Scientist, your job is to bring the insight to the table, and for that, you are required to ask the right questions. For Ex."
},
{
"code": null,
"e": 1329,
"s": 1276,
"text": "Ques 1 — When do you see most carts getting created?"
},
{
"code": null,
"e": 1384,
"s": 1329,
"text": "Ques 2 — When do you see most carts getting abandoned?"
},
{
"code": null,
"e": 1443,
"s": 1384,
"text": "Ques 3 — When do you see the most fraudulent transactions?"
},
{
"code": null,
"e": 1489,
"s": 1443,
"text": "Ques 4 — When do the maximum users subscribe?"
},
{
"code": null,
"e": 1543,
"s": 1489,
"text": "Ques 5 — When are certain items purchased most often?"
},
{
"code": null,
"e": 1625,
"s": 1543,
"text": "Ques 6 — After how many days/hours after registration user makes the first order?"
},
{
"code": null,
"e": 1705,
"s": 1625,
"text": "Ques 7 — After how many days of inactivity customer never returns to your site?"
},
{
"code": null,
"e": 1713,
"s": 1705,
"text": "... etc"
},
{
"code": null,
"e": 1853,
"s": 1713,
"text": "Now, To answer these questions, you get back to data to engineer these DateTime fields. And then a whole lot of patterns can be discovered."
},
{
"code": null,
"e": 1948,
"s": 1853,
"text": "Part 1 of the post will provide you feature engineering steps to answer questions like 1,2 & 3"
},
{
"code": null,
"e": 2028,
"s": 1948,
"text": "Ans 1 — When do you see most carts getting created? The first week of the month"
},
{
"code": null,
"e": 2102,
"s": 2028,
"text": "Ans 2 — When do you see most carts getting abandoned? Wednesday-Afternoon"
},
{
"code": null,
"e": 2177,
"s": 2102,
"text": "Ans 3 — When do you see the most fraudulent transactions? Friday-Late nite"
},
{
"code": null,
"e": 2273,
"s": 2177,
"text": "Part 2 of the post will provide you feature engineering steps to answer questions like in 4 & 5"
},
{
"code": null,
"e": 2343,
"s": 2273,
"text": "Ans 4 — When do the maximum users subscribe? At the start of the year"
},
{
"code": null,
"e": 2422,
"s": 2343,
"text": "Ans 5 — When are certain items purchased most often? At the start of the month"
},
{
"code": null,
"e": 2518,
"s": 2422,
"text": "Part 3 of the post will provide you feature engineering steps to answer questions like in 6 & 7"
},
{
"code": null,
"e": 2614,
"s": 2518,
"text": "Ans 6 — After how many days/hours after registration user makes the first order? Within 2 hours"
},
{
"code": null,
"e": 2721,
"s": 2614,
"text": "Ans 7 — After how many days of inactivity customer never returns to your site? After 14 days of inactivity"
},
{
"code": null,
"e": 3100,
"s": 2721,
"text": "I have used an example of e-commerce data where I have personally found a lot of use cases but by no means the scope of extracting information is related to just that. We will see in this post how some of the behaviors that can be learned by asking the right question ie. doing the right feature engineering has proved useful in multiple industries across a variety of problems."
},
{
"code": null,
"e": 3241,
"s": 3100,
"text": "import pandas as pddf = pd.read_csv('/kaggle/input/loan-data/loan.csv', parse_dates = ['date_issued', 'date_last_payment'])"
},
{
"code": null,
"e": 3457,
"s": 3241,
"text": "Pandas provide a very simple yet very powerful way to deal with DateTime-related variables by parsing them as dates. You can pass as a list all the variables that are date-time related in the parameter parse_dates ."
},
{
"code": null,
"e": 3727,
"s": 3457,
"text": "Let’s say you are not aware of the DateTime variables upfront and after investigating the data you found that some of the variables are date-time. So instead of reloading the data, pandas provide another useful function to_datetime to convert the data type to DateTime."
},
{
"code": null,
"e": 3835,
"s": 3727,
"text": "df['date_issued'] = pd.to_datetime(df['date_issued'], errors = 'coerce')"
},
{
"code": null,
"e": 4169,
"s": 3835,
"text": "As illustrated in the example above, we can extract the component of the date-time part (year, quarter, month, day, day_of_week, day_of_year, week_of_year, time, hour, minute, second, day_part) from the given date-time variable. The below list provides several of such components that can be extracted using pandas inbuilt functions."
},
{
"code": null,
"e": 4265,
"s": 4169,
"text": "We can extract all these components using .dt accessor. Read more about the date accessors here"
},
{
"code": null,
"e": 4370,
"s": 4265,
"text": "Below is the code as shown in the image. All the other components can also be extracted in a similar way"
},
{
"code": null,
"e": 4663,
"s": 4370,
"text": "#1df[‘date_issued:year’] = df[‘date_issued’].dt.year#2df[‘date_issued:month’] = df[‘date_issued’].dt.month#3df[‘date_issued:day_of_week’] = df[‘date_issued’].dt.day_of_week#4df[‘date_issued:week_of_year’] = df[‘date_issued’].dt.week_of_year#5df[‘date_issued:hour’] = df[‘date_issued’].dt.hour"
},
{
"code": null,
"e": 4669,
"s": 4663,
"text": "Note:"
},
{
"code": null,
"e": 4699,
"s": 4669,
"text": "For Monday : day_of_week = 0,"
},
{
"code": null,
"e": 4724,
"s": 4699,
"text": "Tuesday : day_of_week=1,"
},
{
"code": null,
"e": 4728,
"s": 4724,
"text": "..."
},
{
"code": null,
"e": 4751,
"s": 4728,
"text": "Sunday : day_of_week=6"
},
{
"code": null,
"e": 5318,
"s": 4751,
"text": "#day_part functiondef day_part(hour): if hour in [4,5]: return \"dawn\" elif hour in [6,7]: return \"early morning\" elif hour in [8,9,10]: return \"late morning\" elif hour in [11,12,13]: return \"noon\" elif hour in [14,15,16]: return \"afternoon\" elif hour in [17, 18,19]: return \"evening\" elif hour in [20, 21, 22]: return \"night\" elif hour in [23,24,1,2,3]: return \"midnight\" #Run function with apply methoddf['date_issued:day_part'] = df['date_issued:hour'].apply(day_part)df.head()"
},
{
"code": null,
"e": 5684,
"s": 5318,
"text": "As illustrated in the example above, we can extract a lot of boolean Flags (is_month_start, is_month_end, is_quarter_start, is_quarter_end, is_year_start, is_year_end, is_weekend ) from the given date-time variable. The below list provides several of such components that can be extracted using pandas inbuilt functions as well as by creating some of our functions."
},
{
"code": null,
"e": 5756,
"s": 5684,
"text": "Again, we can use .dt accessor to extract a lot of these boolean flags."
},
{
"code": null,
"e": 6043,
"s": 5756,
"text": "#1df['date_issued:is_year_start'] = df['date_issued'].dt.is_year_start#2df['date_issued:is_quarter_start'] = df['date_issued'].dt.is_quarter_start#3df['date_issued:is_month_start'] = df['date_issued'].dt.is_month_start#4df['date_issued:is_month_end'] = df['date_issued'].dt.is_month_end"
},
{
"code": null,
"e": 6132,
"s": 6043,
"text": "If we check the calendar, we will see that 26th of Oct, 2013 was a Saturday — a weekend."
},
{
"code": null,
"e": 6220,
"s": 6132,
"text": "df['date_issued:is_weekend'] = np.where(df['date_issued:day_of_week'].isin([5,6]), 1,0)"
},
{
"code": null,
"e": 6304,
"s": 6220,
"text": "Often your questions/analysis will be relative to another point of reference. Like,"
},
{
"code": null,
"e": 6590,
"s": 6304,
"text": "After how many days/hours after registration user makes the first order? registration_date & first_order_dateIn how many days/hours customer’s complaint was resolved? complain_date & resolution_dateFrom today, how recently customer ordered from your site? today & last_order_date...etc"
},
{
"code": null,
"e": 6700,
"s": 6590,
"text": "After how many days/hours after registration user makes the first order? registration_date & first_order_date"
},
{
"code": null,
"e": 6790,
"s": 6700,
"text": "In how many days/hours customer’s complaint was resolved? complain_date & resolution_date"
},
{
"code": null,
"e": 6872,
"s": 6790,
"text": "From today, how recently customer ordered from your site? today & last_order_date"
},
{
"code": null,
"e": 6879,
"s": 6872,
"text": "...etc"
},
{
"code": null,
"e": 7030,
"s": 6879,
"text": "In our example dataset, we have two columns date_last_payment & date_issued. Let’s see what happens when we just take a difference of these 2 columns."
},
{
"code": null,
"e": 7117,
"s": 7030,
"text": "Pandas by default provide the difference in ‘days’. Notice the dtype: timedelta64[ns]."
},
{
"code": null,
"e": 7147,
"s": 7117,
"text": "From the numpy documentation:"
},
{
"code": null,
"e": 7281,
"s": 7147,
"text": "“Because NumPy doesn’t have a physical quantities system in its core, the timedelta64 data type was created to complement datetime64”"
},
{
"code": null,
"e": 7397,
"s": 7281,
"text": "Now, if we just want the numeric part and not the entire string 947 days, we can do that by using the .dt accessor."
},
{
"code": null,
"e": 7458,
"s": 7397,
"text": "Unfortunately, we can’t get the months in a similar fashion."
},
{
"code": null,
"e": 7511,
"s": 7458,
"text": "Here the timedelta64 from NumPy becomes very useful."
},
{
"code": null,
"e": 7628,
"s": 7511,
"text": "In order to get the number of months between date loan was issued and date last payment was done, we will write this"
},
{
"code": null,
"e": 7697,
"s": 7628,
"text": "(df['date_last_payment'] - df['date_issued'])/np.timedelta64(1, 'M')"
},
{
"code": null,
"e": 7787,
"s": 7697,
"text": "timedelta64 can take following parameters for calculating the difference between 2 dates:"
},
{
"code": null,
"e": 7802,
"s": 7787,
"text": "‘D’ → for Days"
},
{
"code": null,
"e": 7818,
"s": 7802,
"text": "‘W’ → for Weeks"
},
{
"code": null,
"e": 7835,
"s": 7818,
"text": "‘M’ → for Months"
},
{
"code": null,
"e": 7851,
"s": 7835,
"text": "‘Y’ → for Years"
},
{
"code": null,
"e": 7867,
"s": 7851,
"text": "‘h’ → for Hours"
},
{
"code": null,
"e": 7925,
"s": 7867,
"text": "You can use fast_ml to create all these datetime features"
},
{
"code": null,
"e": 7956,
"s": 7925,
"text": "First, install fast_ml package"
},
{
"code": null,
"e": 7987,
"s": 7956,
"text": "!pip install fast_ml — upgrade"
},
{
"code": null,
"e": 8086,
"s": 7987,
"text": "And then, from the feature_engineering module import the method for engineering date time features"
},
{
"code": null,
"e": 8154,
"s": 8086,
"text": "from fast_ml.feature_engineering import FeatureEngineering_DateTime"
},
{
"code": null,
"e": 8243,
"s": 8154,
"text": "Now, this works in the exact same way as other transformers, preprocessors from sklearn."
},
{
"code": null,
"e": 8255,
"s": 8243,
"text": "Instantiate"
},
{
"code": null,
"e": 8259,
"s": 8255,
"text": "Fit"
},
{
"code": null,
"e": 8269,
"s": 8259,
"text": "Transform"
},
{
"code": null,
"e": 8450,
"s": 8269,
"text": "#Instantiatedt_fe = FeatureEngineering_DateTime()#Fitdt_fe.fit(df, datetime_variables=['date_issued'], prefix = 'date_issued:')#Transformdf = dt_fe.transform(df)df.head()"
},
{
"code": null,
"e": 8547,
"s": 8450,
"text": "All the columns are not visible in the screenshot. Let’s just look at the columns of the dataset"
},
{
"code": null,
"e": 9316,
"s": 8547,
"text": "df.columns---Output---Index(['customer_id', 'disbursed_amount', 'interest', 'market', 'employment', 'time_employed', 'householder', 'income', 'date_issued', 'target', 'loan_purpose', 'number_open_accounts', 'date_last_payment', 'number_credit_lines_12',(Notice from here ------->)'date_issued:year', 'date_issued:quarter', 'date_issued:month', 'date_issued:day', 'date_issued:day_of_week', 'date_issued:day_of_year', 'date_issued:weekofyear', 'date_issued:is_month_end', 'date_issued:is_month_start', 'date_issued:is_quarter_end', 'date_issued:is_quarter_start', 'date_issued:is_year_end', 'date_issued:is_year_start', 'date_issued:time', 'date_issued:hour', 'date_issued:minute', 'date_issued:second', 'date_issued:is_weekend', 'date_issued:day_part'],dtype='object')"
},
{
"code": null,
"e": 9367,
"s": 9316,
"text": "If you enjoyed this, follow me on medium for more."
},
{
"code": null,
"e": 9423,
"s": 9367,
"text": "Interested in collaborating? Let’s connect on Linkedin."
},
{
"code": null,
"e": 9485,
"s": 9423,
"text": "Please feel free to write your thoughts/suggestions/feedback."
},
{
"code": null,
"e": 9497,
"s": 9485,
"text": "Kaggle link"
},
{
"code": null,
"e": 9510,
"s": 9497,
"text": "Fast_ml link"
}
]
|
JDBC - LIKE Clause Example | This chapter provides an example on how to select records from a table using JDBC application. This would add additional conditions using LIKE clause while selecting records from the table. Before executing the following example, make sure you have the following in place −
To execute the following example you can replace the username and password with your actual user name and password.
To execute the following example you can replace the username and password with your actual user name and password.
Your MySQL or whatever database you are using, is up and running.
Your MySQL or whatever database you are using, is up and running.
The following steps are required to create a new Database using JDBC application −
Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice.
Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice.
Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server.
Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server.
Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to fetch records from a table which meet given condition. This Query makes use of LIKE clause to select records to select all the students whose first name starts with "za".
Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to fetch records from a table which meet given condition. This Query makes use of LIKE clause to select records to select all the students whose first name starts with "za".
Clean up the environment − try with resources automatically closes the resources.
Clean up the environment − try with resources automatically closes the resources.
Copy and paste the following example in JDBCExample.java, compile and run as follows −
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCExample {
static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
static final String QUERY = "SELECT id, first, last, age FROM Registration";
public static void main(String[] args) {
// Open a connection
try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
Statement stmt = conn.createStatement();) {
System.out.println("Fetching records without condition...");
ResultSet rs = stmt.executeQuery(QUERY);
while(rs.next()){
//Display values
System.out.print("ID: " + rs.getInt("id"));
System.out.print(", Age: " + rs.getInt("age"));
System.out.print(", First: " + rs.getString("first"));
System.out.println(", Last: " + rs.getString("last"));
}
// Select all records having ID equal or greater than 101
System.out.println("Fetching records with condition...");
String sql = "SELECT id, first, last, age FROM Registration" +
" WHERE first LIKE '%za%'";
rs = stmt.executeQuery(sql);
while(rs.next()){
//Display values
System.out.print("ID: " + rs.getInt("id"));
System.out.print(", Age: " + rs.getInt("age"));
System.out.print(", First: " + rs.getString("first"));
System.out.println(", Last: " + rs.getString("last"));
}
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Now let us compile the above example as follows −
C:\>javac JDBCExample.java
C:\>
When you run JDBCExample, it produces the following result −
C:\>java JDBCExample
Fetching records without condition...
ID: 100, Age: 30, First: Zara, Last: Ali
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal
Fetching records with condition...
ID: 100, Age: 30, First: Zara, Last: Ali
ID: 102, Age: 30, First: Zaid, Last: Khan
C:\>
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": 2436,
"s": 2162,
"text": "This chapter provides an example on how to select records from a table using JDBC application. This would add additional conditions using LIKE clause while selecting records from the table. Before executing the following example, make sure you have the following in place −"
},
{
"code": null,
"e": 2552,
"s": 2436,
"text": "To execute the following example you can replace the username and password with your actual user name and password."
},
{
"code": null,
"e": 2668,
"s": 2552,
"text": "To execute the following example you can replace the username and password with your actual user name and password."
},
{
"code": null,
"e": 2734,
"s": 2668,
"text": "Your MySQL or whatever database you are using, is up and running."
},
{
"code": null,
"e": 2800,
"s": 2734,
"text": "Your MySQL or whatever database you are using, is up and running."
},
{
"code": null,
"e": 2883,
"s": 2800,
"text": "The following steps are required to create a new Database using JDBC application −"
},
{
"code": null,
"e": 3055,
"s": 2883,
"text": "Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice."
},
{
"code": null,
"e": 3227,
"s": 3055,
"text": "Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice."
},
{
"code": null,
"e": 3397,
"s": 3227,
"text": "Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server."
},
{
"code": null,
"e": 3567,
"s": 3397,
"text": "Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server."
},
{
"code": null,
"e": 3847,
"s": 3567,
"text": "Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to fetch records from a table which meet given condition. This Query makes use of LIKE clause to select records to select all the students whose first name starts with \"za\"."
},
{
"code": null,
"e": 4127,
"s": 3847,
"text": "Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to fetch records from a table which meet given condition. This Query makes use of LIKE clause to select records to select all the students whose first name starts with \"za\"."
},
{
"code": null,
"e": 4210,
"s": 4127,
"text": "Clean up the environment − try with resources automatically closes the resources.\n"
},
{
"code": null,
"e": 4292,
"s": 4210,
"text": "Clean up the environment − try with resources automatically closes the resources."
},
{
"code": null,
"e": 4379,
"s": 4292,
"text": "Copy and paste the following example in JDBCExample.java, compile and run as follows −"
},
{
"code": null,
"e": 6134,
"s": 4379,
"text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport java.sql.Statement;\n\npublic class JDBCExample {\n static final String DB_URL = \"jdbc:mysql://localhost/TUTORIALSPOINT\";\n static final String USER = \"guest\";\n static final String PASS = \"guest123\";\n static final String QUERY = \"SELECT id, first, last, age FROM Registration\";\n\n public static void main(String[] args) {\n // Open a connection\n try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);\n Statement stmt = conn.createStatement();) {\t\t \n System.out.println(\"Fetching records without condition...\");\n ResultSet rs = stmt.executeQuery(QUERY);\n while(rs.next()){\n //Display values\n System.out.print(\"ID: \" + rs.getInt(\"id\"));\n System.out.print(\", Age: \" + rs.getInt(\"age\"));\n System.out.print(\", First: \" + rs.getString(\"first\"));\n System.out.println(\", Last: \" + rs.getString(\"last\"));\n }\n\n // Select all records having ID equal or greater than 101\n System.out.println(\"Fetching records with condition...\");\n String sql = \"SELECT id, first, last, age FROM Registration\" +\n \" WHERE first LIKE '%za%'\";\n rs = stmt.executeQuery(sql);\n\n while(rs.next()){\n //Display values\n System.out.print(\"ID: \" + rs.getInt(\"id\"));\n System.out.print(\", Age: \" + rs.getInt(\"age\"));\n System.out.print(\", First: \" + rs.getString(\"first\"));\n System.out.println(\", Last: \" + rs.getString(\"last\"));\n }\n rs.close();\n } catch (SQLException e) {\n e.printStackTrace();\n } \n }\n}"
},
{
"code": null,
"e": 6184,
"s": 6134,
"text": "Now let us compile the above example as follows −"
},
{
"code": null,
"e": 6216,
"s": 6184,
"text": "C:\\>javac JDBCExample.java\nC:\\>"
},
{
"code": null,
"e": 6277,
"s": 6216,
"text": "When you run JDBCExample, it produces the following result −"
},
{
"code": null,
"e": 6588,
"s": 6277,
"text": "C:\\>java JDBCExample\nFetching records without condition...\nID: 100, Age: 30, First: Zara, Last: Ali\nID: 102, Age: 30, First: Zaid, Last: Khan\nID: 103, Age: 28, First: Sumit, Last: Mittal\nFetching records with condition...\nID: 100, Age: 30, First: Zara, Last: Ali\nID: 102, Age: 30, First: Zaid, Last: Khan\nC:\\>\n"
},
{
"code": null,
"e": 6621,
"s": 6588,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 6637,
"s": 6621,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 6670,
"s": 6637,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 6686,
"s": 6670,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 6721,
"s": 6686,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6735,
"s": 6721,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 6769,
"s": 6735,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 6783,
"s": 6769,
"text": " Tushar Kale"
},
{
"code": null,
"e": 6820,
"s": 6783,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 6835,
"s": 6820,
"text": " Monica Mittal"
},
{
"code": null,
"e": 6868,
"s": 6835,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 6887,
"s": 6868,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6894,
"s": 6887,
"text": " Print"
},
{
"code": null,
"e": 6905,
"s": 6894,
"text": " Add Notes"
}
]
|
How can we add multiple columns, with single command, to an existing MySQL table? | We can also add multiple columns to an existing table with the help of ALTER command. The syntax for it would be as follows −
Alter table table-name ADD (column-name1 datatype, column-name2 datatype,... column-nameN datatype);
In the example below, with the help of ALTER Command, columns ‘Address’, ‘Phone’ and ‘Email’ are added to the table ‘Student’.
mysql> Alter Table Student ADD(Address Varchar(25), Phone INT, Email Varchar(20));
Query OK, 5 rows affected (0.38 sec)
Records: 5 Duplicates: 0 Warnings: 0 | [
{
"code": null,
"e": 1188,
"s": 1062,
"text": "We can also add multiple columns to an existing table with the help of ALTER command. The syntax for it would be as follows −"
},
{
"code": null,
"e": 1289,
"s": 1188,
"text": "Alter table table-name ADD (column-name1 datatype, column-name2 datatype,... column-nameN datatype);"
},
{
"code": null,
"e": 1416,
"s": 1289,
"text": "In the example below, with the help of ALTER Command, columns ‘Address’, ‘Phone’ and ‘Email’ are added to the table ‘Student’."
},
{
"code": null,
"e": 1573,
"s": 1416,
"text": "mysql> Alter Table Student ADD(Address Varchar(25), Phone INT, Email Varchar(20));\nQuery OK, 5 rows affected (0.38 sec)\nRecords: 5 Duplicates: 0 Warnings: 0"
}
]
|
Python program to count upper and lower case characters without using inbuilt functions | In this article, we will learn about the solution and approach to solve the given problem statement.
Given a string input, we need to find the number of uppercase & lowercase characters in the given strings.
Here we will we checking ASCII value of each character by the help of built-in ord() function.
Here we have assigned two counters to 0 and we are traversing the input string and checking their ASCII values and incrementing their counter respectively.
Now let’s see the implementation below −
Live Demo
def upperlower(string):
upper = 0
lower = 0
for i in range(len(string)):
# For lowercase
if (ord(string[i]) >= 97 and
ord(string[i]) <= 122):
lower += 1
# For uppercase
elif (ord(string[i]) >= 65 and
ord(string[i]) <= 90):
upper += 1
print('Lower case characters = %s' %lower,
'Upper case characters = %s' %upper)
# Driver Code
string = 'Tutorialspoint'
upperlower(string)
Lower case characters = 13 Upper case characters = 1
All variables and functions are declared in global scope as shown in the figure below.
In this article, we learned about the approach to count upper and lower case characters without using inbuilt functions. | [
{
"code": null,
"e": 1163,
"s": 1062,
"text": "In this article, we will learn about the solution and approach to solve the given problem statement."
},
{
"code": null,
"e": 1270,
"s": 1163,
"text": "Given a string input, we need to find the number of uppercase & lowercase characters in the given strings."
},
{
"code": null,
"e": 1365,
"s": 1270,
"text": "Here we will we checking ASCII value of each character by the help of built-in ord() function."
},
{
"code": null,
"e": 1521,
"s": 1365,
"text": "Here we have assigned two counters to 0 and we are traversing the input string and checking their ASCII values and incrementing their counter respectively."
},
{
"code": null,
"e": 1562,
"s": 1521,
"text": "Now let’s see the implementation below −"
},
{
"code": null,
"e": 1573,
"s": 1562,
"text": " Live Demo"
},
{
"code": null,
"e": 2024,
"s": 1573,
"text": "def upperlower(string):\n upper = 0\n lower = 0\n for i in range(len(string)):\n # For lowercase\n if (ord(string[i]) >= 97 and\n ord(string[i]) <= 122):\n lower += 1\n # For uppercase\n elif (ord(string[i]) >= 65 and\n ord(string[i]) <= 90):\n upper += 1\n print('Lower case characters = %s' %lower,\n 'Upper case characters = %s' %upper)\n# Driver Code\nstring = 'Tutorialspoint'\nupperlower(string)"
},
{
"code": null,
"e": 2077,
"s": 2024,
"text": "Lower case characters = 13 Upper case characters = 1"
},
{
"code": null,
"e": 2164,
"s": 2077,
"text": "All variables and functions are declared in global scope as shown in the figure below."
},
{
"code": null,
"e": 2285,
"s": 2164,
"text": "In this article, we learned about the approach to count upper and lower case characters without using inbuilt functions."
}
]
|
Number of Segments in a String in C++ | Suppose we have a string s. We have to count the number of segments in a string, where a segment is defined to be a contiguous sequence of characters (no whitespace).
So, if the input is like "Hello, I love programming", then the output will be 4, as there are 4 segments.
To solve this, we will follow these steps −
n := 0
n := 0
for initialize i := 0, when i < size of s, update (increase i by 1), do −if s[i] is not equal to white space, then −(increase n by 1)while (i < size of s and s[i] is not equal to white space), do −(increase i by 1)
for initialize i := 0, when i < size of s, update (increase i by 1), do −
if s[i] is not equal to white space, then −(increase n by 1)
if s[i] is not equal to white space, then −
(increase n by 1)
(increase n by 1)
while (i < size of s and s[i] is not equal to white space), do −(increase i by 1)
while (i < size of s and s[i] is not equal to white space), do −
(increase i by 1)
(increase i by 1)
return n
return n
Let us see the following implementation to get a better understanding −
Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int countSegments(string s) {
int n = 0;
for(int i = 0; i < s.size(); i++){
if(s[i] != ' ')
n++;
while( i < s.size() && s[i] != ' ')
i++;
}
return n;
}
};
main(){
Solution ob;
cout << (ob.countSegments("Hello, I love programming"));
}
"Hello, I love programming"
4 | [
{
"code": null,
"e": 1229,
"s": 1062,
"text": "Suppose we have a string s. We have to count the number of segments in a string, where a segment is defined to be a contiguous sequence of characters (no whitespace)."
},
{
"code": null,
"e": 1335,
"s": 1229,
"text": "So, if the input is like \"Hello, I love programming\", then the output will be 4, as there are 4 segments."
},
{
"code": null,
"e": 1379,
"s": 1335,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1386,
"s": 1379,
"text": "n := 0"
},
{
"code": null,
"e": 1393,
"s": 1386,
"text": "n := 0"
},
{
"code": null,
"e": 1608,
"s": 1393,
"text": "for initialize i := 0, when i < size of s, update (increase i by 1), do −if s[i] is not equal to white space, then −(increase n by 1)while (i < size of s and s[i] is not equal to white space), do −(increase i by 1)"
},
{
"code": null,
"e": 1682,
"s": 1608,
"text": "for initialize i := 0, when i < size of s, update (increase i by 1), do −"
},
{
"code": null,
"e": 1743,
"s": 1682,
"text": "if s[i] is not equal to white space, then −(increase n by 1)"
},
{
"code": null,
"e": 1787,
"s": 1743,
"text": "if s[i] is not equal to white space, then −"
},
{
"code": null,
"e": 1805,
"s": 1787,
"text": "(increase n by 1)"
},
{
"code": null,
"e": 1823,
"s": 1805,
"text": "(increase n by 1)"
},
{
"code": null,
"e": 1905,
"s": 1823,
"text": "while (i < size of s and s[i] is not equal to white space), do −(increase i by 1)"
},
{
"code": null,
"e": 1970,
"s": 1905,
"text": "while (i < size of s and s[i] is not equal to white space), do −"
},
{
"code": null,
"e": 1988,
"s": 1970,
"text": "(increase i by 1)"
},
{
"code": null,
"e": 2006,
"s": 1988,
"text": "(increase i by 1)"
},
{
"code": null,
"e": 2015,
"s": 2006,
"text": "return n"
},
{
"code": null,
"e": 2024,
"s": 2015,
"text": "return n"
},
{
"code": null,
"e": 2096,
"s": 2024,
"text": "Let us see the following implementation to get a better understanding −"
},
{
"code": null,
"e": 2107,
"s": 2096,
"text": " Live Demo"
},
{
"code": null,
"e": 2491,
"s": 2107,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\npublic:\n int countSegments(string s) {\n int n = 0;\n for(int i = 0; i < s.size(); i++){\n if(s[i] != ' ')\n n++;\n while( i < s.size() && s[i] != ' ')\n i++;\n }\n return n;\n }\n};\nmain(){\n Solution ob;\n cout << (ob.countSegments(\"Hello, I love programming\"));\n}"
},
{
"code": null,
"e": 2519,
"s": 2491,
"text": "\"Hello, I love programming\""
},
{
"code": null,
"e": 2521,
"s": 2519,
"text": "4"
}
]
|
Great Expectations. “Validate what you expect from your... | by Andreas Hopfgartner | Towards Data Science | More and more decisions of relevance to business are made on the basis of automatically generated data. Testing only the correctness of the source code of transformations is no longer sufficient. The correctness of the data, which is typically compiled from different, rapidly changing sources, must also be checked... In the worst case, a wrong decision may be made due to poor data quality. This is not necessarily a new finding, but unfortunately the tool support for data quality checks in the open source environment has so far been unsatisfactory. This blog shows a methodology and a Python tool for so-called pipeline tests, which fill exactly this gap.
The great importance of data as a raw material in all areas of an enterprise is already quite well-known. Data warehouse structures are fed with information ranging from sensor data to target data from all such areas. A machine learning model works on the basis of the data it has seen in the training process. Data that is very far away from what the model has seen in the training process can lead to wrong behavior. Data that has been falsified by error-prone sources or processing steps will certainly lead to false results. From the raw data source to the dashboard, a data set typically passes through multiple processes (transformation, loading, data models, machine-learning models). Monitoring of data quality and validation is often neglected here. Provided next is a closer look at a new open-source tool called Great Expectations for validating data before before running a machine learning model or otherwise using numbers.
Data scientists are aware of the problem: We have a dashboard with key figures derived from different data sources. Underlying some of the key figures is a machine-learning model, e.g. for scoring. One of the key figures suddenly changes so drastically that it no longer makes sense or becomes NaN because the value can no longer be calculated.
Test-driven development has become a standard approach in the field of software development. Writing unit tests is part of good style and helps keep code quality high and avoid errors.
In the meantime, however, complexity is often no longer only manifested in the code itself, but in the data as-well. Unexpected behaviour occurring during running a machine-learning model may actually reflect true anomalous behavior, or the data may be erroneous. Often, the cause is an uncommunicated change in the data model of the source system.
Machine-learning models themselves now consist of a pipeline with several transformation steps:
Loading of data (from a raw-data source or a data warehouse / another DBMS)
Cleaning and preparation
Aggregations
Features
Dimensionality reduction
Normalization or scaling of data
The need for a data quality verification tool in all these steps is obvious. Unlike unit tests which check executable code (mostly at compile or build/deploy time), data tests are called pipeline tests and executed like batches.
Python has established itself as a development language in the area of machine learning. The Great Expectations tool is a Python package, installable via pip or conda.
pip install great-expectationsconda install conda-forge::great-expectations
Because its scope of application is highly complex, the tool has a very abstract and generic structure. Though this might initially result in a steep learning curve, it flattens as soon as the first use case is dealt with. The developers of Great Expectations have set up a discussion forum providing lucid introductory examples. There is also a slack channel for conversation.
After installation of the Python package, each new project is started by:
great-expectations init
This command creates the basic folder of a Great Expectations (GE) project (also called DataContext in GE jargon); it can be followed immediately by a
to manage the project’s versions with git.
Example of the folder structure created by Great Expectations after an initialization call
Column “ID” must not be null.
Column “ID” must increase monotonically.
Column “ID” must be of type integer.
Column “A” must always be greater than column “B”.
Column “B” must lie between 0 and 1000.
....
During the initialization process, you are asked about the location of your data sources; this step may be skipped and carried out manually. Diverse data sources are recognized here, ranging from local CSV through SQLAlchemy Connector to Spark and Hadoop (a partitioned parquet on HDFS, e.g.).
The basic principle of GE are expectations and validations. Once a project has been initialized and data sources have been selected, you can immediately start loading a batch (data excerpt) and defining expectations. Here are some examples of expectations:
A large number of expectation templates are available, including statistical (distribution) tests. For exploratory development of expectations in a new data set, examples of notebooks for the various connectors (csv, SQL, pySpark) are available in the folder great_expectations/notebooks/.
Once a set of expectations has been defined, the expectations need to be validated with a new data batch (for example, after arrival of new data from the last day).
During the validation process it is also possible to parameterize expectation variables. Suppose you have a streaming data source containing a time column with unixtime values. The data is persisted and once a day a batch of the previous day is to be validated. The fact that the time stamps should lie within the day bounds can be easily validated by setting the expectations
batch.expect_column_values_to_be_between('timestamp', {'$PARAMETER': 'start_time'}, {'$PARAMETER': 'end_time'})
and during the validation process
batch.validate(evaluation_parameters={'start_time': unixtime_start, 'end_time': unixtime_end})
A nice feature of this tool is the DataDocs which are created and then maintained in the course of pipeline tests. There, a catalogue of data sources, expectations and validations tracked by the GE project is stored in a transparent website format (also in the GE folder, under great_expectations/uncommitted/data_docs) and versioned. This way, we can always find out which data sources are being monitored, which tests (expectations) are defined, and whether the tests had positive or negative results.
Configuration keys which we don’t want to commit to a GitHub repository can be easily saved in a yml-file in the uncommitted folder, so that passwords and access keys remain securely stored.
Once we have obtained a set of expectations with which data sources are to be validated in future, we save our expectation suite. It is stored as a JSON file in the project folder. Now is a good time to trigger a git commit to save the expectation suite under version management.
Great Expectations is not intended to be a pipeline automation tool (pipeline execution), but can be integrated into one ( Airflow, Oozie, ...) in order to perform validations in a timed manner, e.g. daily.
Once the pattern according to which GE operates has been understood, it can be extended very easily. Additional expectations can be defined, or new data sources can be integrated. It also makes sense to monitor the same data source repeatedly on its way through the processing pipeline, in order to identify any intermediate steps affecting data quality.
An end-to-end example of loading a database with a data source can be studied in this following GitHub repository . There, a CSV generated newly every day is first validated as raw data, and then validated again after loading into a MySQL database.
Great Expectations is a fast growing tool allowing comprehensive use to ensure data quality for the operation of a machine-learning model. The tool has been developed with special importance attached to providing the most generic possible framework and offering users many interfaces which allow them to adapt Great Expectations to their own project and extend it according to their own needs. Available, for example, is an action operator which can automatically generate slack notification after validation. This and other templates can be used to design interfaces to other systems.
The development rate and the major players like Databricks promoting the tool at conferences denote the importance and quality of this tool. At the same time, there is a great need to take data quality testing into the world of modern data sources and development approaches with the help of a modern tool. It is therefore worth getting to know Great Expectations and integrating it into your own data pipelines; the tool will certainly accompany us for longer.
Originally published at https://www.btelligent.com. | [
{
"code": null,
"e": 708,
"s": 47,
"text": "More and more decisions of relevance to business are made on the basis of automatically generated data. Testing only the correctness of the source code of transformations is no longer sufficient. The correctness of the data, which is typically compiled from different, rapidly changing sources, must also be checked... In the worst case, a wrong decision may be made due to poor data quality. This is not necessarily a new finding, but unfortunately the tool support for data quality checks in the open source environment has so far been unsatisfactory. This blog shows a methodology and a Python tool for so-called pipeline tests, which fill exactly this gap."
},
{
"code": null,
"e": 1645,
"s": 708,
"text": "The great importance of data as a raw material in all areas of an enterprise is already quite well-known. Data warehouse structures are fed with information ranging from sensor data to target data from all such areas. A machine learning model works on the basis of the data it has seen in the training process. Data that is very far away from what the model has seen in the training process can lead to wrong behavior. Data that has been falsified by error-prone sources or processing steps will certainly lead to false results. From the raw data source to the dashboard, a data set typically passes through multiple processes (transformation, loading, data models, machine-learning models). Monitoring of data quality and validation is often neglected here. Provided next is a closer look at a new open-source tool called Great Expectations for validating data before before running a machine learning model or otherwise using numbers."
},
{
"code": null,
"e": 1990,
"s": 1645,
"text": "Data scientists are aware of the problem: We have a dashboard with key figures derived from different data sources. Underlying some of the key figures is a machine-learning model, e.g. for scoring. One of the key figures suddenly changes so drastically that it no longer makes sense or becomes NaN because the value can no longer be calculated."
},
{
"code": null,
"e": 2175,
"s": 1990,
"text": "Test-driven development has become a standard approach in the field of software development. Writing unit tests is part of good style and helps keep code quality high and avoid errors."
},
{
"code": null,
"e": 2524,
"s": 2175,
"text": "In the meantime, however, complexity is often no longer only manifested in the code itself, but in the data as-well. Unexpected behaviour occurring during running a machine-learning model may actually reflect true anomalous behavior, or the data may be erroneous. Often, the cause is an uncommunicated change in the data model of the source system."
},
{
"code": null,
"e": 2620,
"s": 2524,
"text": "Machine-learning models themselves now consist of a pipeline with several transformation steps:"
},
{
"code": null,
"e": 2696,
"s": 2620,
"text": "Loading of data (from a raw-data source or a data warehouse / another DBMS)"
},
{
"code": null,
"e": 2721,
"s": 2696,
"text": "Cleaning and preparation"
},
{
"code": null,
"e": 2734,
"s": 2721,
"text": "Aggregations"
},
{
"code": null,
"e": 2743,
"s": 2734,
"text": "Features"
},
{
"code": null,
"e": 2768,
"s": 2743,
"text": "Dimensionality reduction"
},
{
"code": null,
"e": 2801,
"s": 2768,
"text": "Normalization or scaling of data"
},
{
"code": null,
"e": 3030,
"s": 2801,
"text": "The need for a data quality verification tool in all these steps is obvious. Unlike unit tests which check executable code (mostly at compile or build/deploy time), data tests are called pipeline tests and executed like batches."
},
{
"code": null,
"e": 3198,
"s": 3030,
"text": "Python has established itself as a development language in the area of machine learning. The Great Expectations tool is a Python package, installable via pip or conda."
},
{
"code": null,
"e": 3274,
"s": 3198,
"text": "pip install great-expectationsconda install conda-forge::great-expectations"
},
{
"code": null,
"e": 3652,
"s": 3274,
"text": "Because its scope of application is highly complex, the tool has a very abstract and generic structure. Though this might initially result in a steep learning curve, it flattens as soon as the first use case is dealt with. The developers of Great Expectations have set up a discussion forum providing lucid introductory examples. There is also a slack channel for conversation."
},
{
"code": null,
"e": 3726,
"s": 3652,
"text": "After installation of the Python package, each new project is started by:"
},
{
"code": null,
"e": 3750,
"s": 3726,
"text": "great-expectations init"
},
{
"code": null,
"e": 3901,
"s": 3750,
"text": "This command creates the basic folder of a Great Expectations (GE) project (also called DataContext in GE jargon); it can be followed immediately by a"
},
{
"code": null,
"e": 3944,
"s": 3901,
"text": "to manage the project’s versions with git."
},
{
"code": null,
"e": 4035,
"s": 3944,
"text": "Example of the folder structure created by Great Expectations after an initialization call"
},
{
"code": null,
"e": 4065,
"s": 4035,
"text": "Column “ID” must not be null."
},
{
"code": null,
"e": 4106,
"s": 4065,
"text": "Column “ID” must increase monotonically."
},
{
"code": null,
"e": 4143,
"s": 4106,
"text": "Column “ID” must be of type integer."
},
{
"code": null,
"e": 4194,
"s": 4143,
"text": "Column “A” must always be greater than column “B”."
},
{
"code": null,
"e": 4234,
"s": 4194,
"text": "Column “B” must lie between 0 and 1000."
},
{
"code": null,
"e": 4239,
"s": 4234,
"text": "...."
},
{
"code": null,
"e": 4533,
"s": 4239,
"text": "During the initialization process, you are asked about the location of your data sources; this step may be skipped and carried out manually. Diverse data sources are recognized here, ranging from local CSV through SQLAlchemy Connector to Spark and Hadoop (a partitioned parquet on HDFS, e.g.)."
},
{
"code": null,
"e": 4790,
"s": 4533,
"text": "The basic principle of GE are expectations and validations. Once a project has been initialized and data sources have been selected, you can immediately start loading a batch (data excerpt) and defining expectations. Here are some examples of expectations:"
},
{
"code": null,
"e": 5080,
"s": 4790,
"text": "A large number of expectation templates are available, including statistical (distribution) tests. For exploratory development of expectations in a new data set, examples of notebooks for the various connectors (csv, SQL, pySpark) are available in the folder great_expectations/notebooks/."
},
{
"code": null,
"e": 5245,
"s": 5080,
"text": "Once a set of expectations has been defined, the expectations need to be validated with a new data batch (for example, after arrival of new data from the last day)."
},
{
"code": null,
"e": 5622,
"s": 5245,
"text": "During the validation process it is also possible to parameterize expectation variables. Suppose you have a streaming data source containing a time column with unixtime values. The data is persisted and once a day a batch of the previous day is to be validated. The fact that the time stamps should lie within the day bounds can be easily validated by setting the expectations"
},
{
"code": null,
"e": 5741,
"s": 5622,
"text": "batch.expect_column_values_to_be_between('timestamp', {'$PARAMETER': 'start_time'}, {'$PARAMETER': 'end_time'})"
},
{
"code": null,
"e": 5775,
"s": 5741,
"text": "and during the validation process"
},
{
"code": null,
"e": 5870,
"s": 5775,
"text": "batch.validate(evaluation_parameters={'start_time': unixtime_start, 'end_time': unixtime_end})"
},
{
"code": null,
"e": 6374,
"s": 5870,
"text": "A nice feature of this tool is the DataDocs which are created and then maintained in the course of pipeline tests. There, a catalogue of data sources, expectations and validations tracked by the GE project is stored in a transparent website format (also in the GE folder, under great_expectations/uncommitted/data_docs) and versioned. This way, we can always find out which data sources are being monitored, which tests (expectations) are defined, and whether the tests had positive or negative results."
},
{
"code": null,
"e": 6565,
"s": 6374,
"text": "Configuration keys which we don’t want to commit to a GitHub repository can be easily saved in a yml-file in the uncommitted folder, so that passwords and access keys remain securely stored."
},
{
"code": null,
"e": 6845,
"s": 6565,
"text": "Once we have obtained a set of expectations with which data sources are to be validated in future, we save our expectation suite. It is stored as a JSON file in the project folder. Now is a good time to trigger a git commit to save the expectation suite under version management."
},
{
"code": null,
"e": 7052,
"s": 6845,
"text": "Great Expectations is not intended to be a pipeline automation tool (pipeline execution), but can be integrated into one ( Airflow, Oozie, ...) in order to perform validations in a timed manner, e.g. daily."
},
{
"code": null,
"e": 7407,
"s": 7052,
"text": "Once the pattern according to which GE operates has been understood, it can be extended very easily. Additional expectations can be defined, or new data sources can be integrated. It also makes sense to monitor the same data source repeatedly on its way through the processing pipeline, in order to identify any intermediate steps affecting data quality."
},
{
"code": null,
"e": 7663,
"s": 7407,
"text": "An end-to-end example of loading a database with a data source can be studied in this following GitHub repository . There, a CSV generated newly every day is first validated as raw data, and then validated again after loading into a MySQL database."
},
{
"code": null,
"e": 8249,
"s": 7663,
"text": "Great Expectations is a fast growing tool allowing comprehensive use to ensure data quality for the operation of a machine-learning model. The tool has been developed with special importance attached to providing the most generic possible framework and offering users many interfaces which allow them to adapt Great Expectations to their own project and extend it according to their own needs. Available, for example, is an action operator which can automatically generate slack notification after validation. This and other templates can be used to design interfaces to other systems."
},
{
"code": null,
"e": 8711,
"s": 8249,
"text": "The development rate and the major players like Databricks promoting the tool at conferences denote the importance and quality of this tool. At the same time, there is a great need to take data quality testing into the world of modern data sources and development approaches with the help of a modern tool. It is therefore worth getting to know Great Expectations and integrating it into your own data pipelines; the tool will certainly accompany us for longer."
}
]
|
Can we define an interface inside a Java class? | Yes, you can define an interface inside a class and it is known as a nested interface. You can’t access a nested interface directly; you need to access (implement) the nested interface using the inner class or by using the name of the class holding this nested interface.
Live Demo
public class Sample {
interface myInterface {
void demo();
}
class Inner implements myInterface {
public void demo() {
System.out.println("Welcome to Tutorialspoint");
}
}
public static void main(String args[]) {
Inner obj = new Sample().new Inner();
obj.demo();
}
}
Welcome to Tutorialspoint
You can also access the nested interface using the class name as −
class Test {
interface myInterface {
void demo();
}
}
public class Sample implements Test.myInterface {
public void demo() {
System.out.println("Hello welcome to tutorialspoint");
}
public static void main(String args[]) {
Sample obj = new Sample();
obj.demo();
}
} | [
{
"code": null,
"e": 1334,
"s": 1062,
"text": "Yes, you can define an interface inside a class and it is known as a nested interface. You can’t access a nested interface directly; you need to access (implement) the nested interface using the inner class or by using the name of the class holding this nested interface."
},
{
"code": null,
"e": 1344,
"s": 1334,
"text": "Live Demo"
},
{
"code": null,
"e": 1668,
"s": 1344,
"text": "public class Sample {\n interface myInterface {\n void demo();\n }\n class Inner implements myInterface {\n public void demo() {\n System.out.println(\"Welcome to Tutorialspoint\");\n }\n }\n public static void main(String args[]) {\n Inner obj = new Sample().new Inner();\n obj.demo();\n }\n}"
},
{
"code": null,
"e": 1694,
"s": 1668,
"text": "Welcome to Tutorialspoint"
},
{
"code": null,
"e": 1761,
"s": 1694,
"text": "You can also access the nested interface using the class name as −"
},
{
"code": null,
"e": 2069,
"s": 1761,
"text": "class Test {\n interface myInterface {\n void demo();\n }\n}\npublic class Sample implements Test.myInterface {\n public void demo() {\n System.out.println(\"Hello welcome to tutorialspoint\");\n }\n public static void main(String args[]) {\n Sample obj = new Sample();\n obj.demo();\n }\n}"
}
]
|
What is the difference between 'isset()' and '!empty()' in PHP? | ISSET checks the variable to see if it has been set. In other words, it checks to see if the variable is any value except NULL or not assigned a value. ISSET returns TRUE if the variable exists and has a value other than NULL. That means variables assigned a "", 0, "0", or FALSE are set, and therefore are TRUE for ISSET.
Live Demo
<?php
$val = '0';
if( isset($val)) {
print_r(" $val is set with isset function <br>");
}
$my_array = array();
echo isset($my_array['New_value']) ?
'array is set.' : 'array is not set.';
?>
This will produce the following output −
0 is set with isset function
array is not set.
EMPTY checks to see if a variable is empty. Empty is interpreted as: "" (an empty string), 0 (integer), 0.0 (float)`, "0" (string), NULL, FALSE, array() (an empty array), and "$var;" (a variable declared, but without a value in a class.
Live Demo
<?php
$temp_val = 0;
if (empty($temp_val)) {
echo $temp_val . ' is considered empty';
}
echo "nn";
$new_val = 1;
if (!empty($new_val)) {
echo $new_val . ' is considered set';
}
?>
This will produce the following output −
0 is considered empty 1 is considered set | [
{
"code": null,
"e": 1385,
"s": 1062,
"text": "ISSET checks the variable to see if it has been set. In other words, it checks to see if the variable is any value except NULL or not assigned a value. ISSET returns TRUE if the variable exists and has a value other than NULL. That means variables assigned a \"\", 0, \"0\", or FALSE are set, and therefore are TRUE for ISSET."
},
{
"code": null,
"e": 1396,
"s": 1385,
"text": " Live Demo"
},
{
"code": null,
"e": 1610,
"s": 1396,
"text": "<?php\n $val = '0';\n if( isset($val)) {\n print_r(\" $val is set with isset function <br>\");\n }\n $my_array = array();\n echo isset($my_array['New_value']) ?\n 'array is set.' : 'array is not set.';\n?>"
},
{
"code": null,
"e": 1651,
"s": 1610,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1698,
"s": 1651,
"text": "0 is set with isset function\narray is not set."
},
{
"code": null,
"e": 1935,
"s": 1698,
"text": "EMPTY checks to see if a variable is empty. Empty is interpreted as: \"\" (an empty string), 0 (integer), 0.0 (float)`, \"0\" (string), NULL, FALSE, array() (an empty array), and \"$var;\" (a variable declared, but without a value in a class."
},
{
"code": null,
"e": 1946,
"s": 1935,
"text": " Live Demo"
},
{
"code": null,
"e": 2159,
"s": 1946,
"text": "<?php\n $temp_val = 0;\n if (empty($temp_val)) {\n echo $temp_val . ' is considered empty';\n }\n echo \"nn\";\n $new_val = 1;\n if (!empty($new_val)) {\n echo $new_val . ' is considered set';\n }\n?>"
},
{
"code": null,
"e": 2200,
"s": 2159,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2242,
"s": 2200,
"text": "0 is considered empty 1 is considered set"
}
]
|
Creating a Graph in Javascript | We'll be creating a graph class that supports weights and both directed and undirected types. This will be implemented using an adjacency list. As we move to more advanced concepts, both weights and directed nature of the graphs will come in handy.
An adjacency list is an array A of separate lists. Each element of the array Ai is a list, which contains all the vertices that are adjacent to vertex i. We're defining it using 2 members, nodes and edges.
Let's set up the graph class by defining our class and some methods that we'll use to add nodes and edges to our graph.
We'll initially define the following methods −
addNode: Adds a node to the graph
addEdge: Adds an undirected edge to the graph
addDirectedEdge: Adds a directed edge
class Graph {
constructor() {
this.edges = {};
this.nodes = [];
}
addNode(node) {
this.nodes.push(node);
this.edges[node] = [];
}
addEdge(node1, node2) {
this.edges[node1].push(node2);
this.edges[node2].push(node1);
}
addDirectedEdge(node1, node2) {
this.edges[node1].push(node2);
}
display() {
let graph = ""; this.nodes.forEach(node => {
graph += node + "->" + this.edges[node].join(", ") + "\n";
});
console.log(graph);
}
}
You can test these methods and our class using −
let g = new Graph();
g.addNode("A");
g.addNode("B");
g.addNode("C");
g.addNode("D");
g.addNode("E");
g.addEdge("A", "C");
g.addEdge("A", "B");
g.addDirectedEdge("A", "D");
g.addEdge("D", "E");
g.display();
This will give the output −
A->C, B, D
B->A
C->A
D->E
E->D | [
{
"code": null,
"e": 1311,
"s": 1062,
"text": "We'll be creating a graph class that supports weights and both directed and undirected types. This will be implemented using an adjacency list. As we move to more advanced concepts, both weights and directed nature of the graphs will come in handy."
},
{
"code": null,
"e": 1517,
"s": 1311,
"text": "An adjacency list is an array A of separate lists. Each element of the array Ai is a list, which contains all the vertices that are adjacent to vertex i. We're defining it using 2 members, nodes and edges."
},
{
"code": null,
"e": 1637,
"s": 1517,
"text": "Let's set up the graph class by defining our class and some methods that we'll use to add nodes and edges to our graph."
},
{
"code": null,
"e": 1684,
"s": 1637,
"text": "We'll initially define the following methods −"
},
{
"code": null,
"e": 1718,
"s": 1684,
"text": "addNode: Adds a node to the graph"
},
{
"code": null,
"e": 1764,
"s": 1718,
"text": "addEdge: Adds an undirected edge to the graph"
},
{
"code": null,
"e": 1802,
"s": 1764,
"text": "addDirectedEdge: Adds a directed edge"
},
{
"code": null,
"e": 2328,
"s": 1802,
"text": "class Graph {\n constructor() {\n this.edges = {};\n this.nodes = [];\n }\n addNode(node) {\n this.nodes.push(node);\n this.edges[node] = [];\n }\n addEdge(node1, node2) {\n this.edges[node1].push(node2);\n this.edges[node2].push(node1);\n }\n addDirectedEdge(node1, node2) {\n this.edges[node1].push(node2);\n }\n display() {\n let graph = \"\"; this.nodes.forEach(node => {\n graph += node + \"->\" + this.edges[node].join(\", \") + \"\\n\";\n });\n console.log(graph);\n }\n}"
},
{
"code": null,
"e": 2378,
"s": 2328,
"text": "You can test these methods and our class using − "
},
{
"code": null,
"e": 2587,
"s": 2378,
"text": "let g = new Graph();\ng.addNode(\"A\");\ng.addNode(\"B\");\ng.addNode(\"C\");\ng.addNode(\"D\");\ng.addNode(\"E\");\n \ng.addEdge(\"A\", \"C\");\ng.addEdge(\"A\", \"B\");\ng.addDirectedEdge(\"A\", \"D\");\ng.addEdge(\"D\", \"E\");\n\ng.display();"
},
{
"code": null,
"e": 2615,
"s": 2587,
"text": "This will give the output −"
},
{
"code": null,
"e": 2646,
"s": 2615,
"text": "A->C, B, D\nB->A\nC->A\nD->E\nE->D"
}
]
|
Incremental join using AWS Glue Bookmarks | by Hamish Lamotte | Towards Data Science | I was recently presented the challenge to join two timeseries datasets together on their timestamps without requiring the corresponding data from either dataset to arrive at the same time as the other. For example, data from one day last month from one dataset may have landed on S3 a week ago, and the corresponding data from the other dataset for that day last month may have landed yesterday. This is an incremental join problem.
It may be possible to get around this problem by holding off from joining the data until it was queried, however I wanted to pre-process the join so that the joined data could be queried directly at any scale.
You could re-process the entire dataset every pipeline run. This was not an for a dataset that is constantly larger every day.
It would also be possible to manually implement a system that does not process data from either tables until both have landed. This would in-effect be re-implementing a feature that is already available with AWS Glue: Bookmarks which we are going to leverage below.
AWS Glue Bookmarks allows you to only process the new data that has landed in a data pipeline since the pipeline was previously run. In the incremental join problem described above, where corresponding data that needs processed may have landed and have been processed in different runs of the pipeline, this does not fully solve the problem as corresponding data will be fed by the bookmarks to be processed in different jobs so would not be joined.
The solution we came up with leveraged another feature of AWS Glue, the ability to load a subset of a table using a predicate pushdown. We ended up with the following ETL steps in the Glue ETL job:
# setup Glue ETL environmentimport sysfrom awsglue.transforms import *from awsglue.utils import getResolvedOptionsfrom pyspark.context import SparkContextfrom awsglue.context import GlueContextfrom awsglue.job import Jobfrom pyspark.sql.functions import split, colfrom awsglue.dynamicframe import DynamicFrame## @params: [JOB_NAME]args = getResolvedOptions(sys.argv, ['JOB_NAME'])sc = SparkContext()glueContext = GlueContext(sc)spark = glueContext.spark_sessionjob = Job(glueContext)job.init(args['JOB_NAME'], args)
Load the new data that has landed since the last pipeline run using Glue Bookmarks from the AWS Glue catalog.
table1_new = glueContext.create_dynamic_frame.from_catalog(database="db", table_name="table1", transformation_ctx='table1_new')table2_new = glueContext.create_dynamic_frame.from_catalog(database="db", table_name="table1", transformation_ctx='table2_new')
Find the partitions that are being affected by in your new data. As this was timeseries data, it made sense to partition by datetime. Write these partitions into a pushdown predicate that can be queried on the entire dataset.
Having built the predicate string which lists every partition for which there is new data in either one or both of the tables, we can now load ‘unlock’ just that data from the source data tables.
we use the predicate string we previously built and load the table without using bookmarkstable1_unlock = glueContext.create_dynamic_frame.from_catalog(database="db", table_name="table1", push_down_predicate=table1_predicate)table2_unlock = glueContext.create_dynamic_frame.from_catalog(database="db", table_name="table2", push_down_predicate=table2_predicate)
We can now run whatever join transformations we want using these two tables.
We can then write the tables to a database, in our case S3. Depending on the type of join transformations you are doing, we found it best to use the Spark API writer in “overwrite” mode rather than the Glue DynamicFrame writers as we wanted to delete any old data that was written in a partition in a previous run and write only the newly processed data.
# set the overwrite mode to dynamicspark.conf.set("spark.sql.sources.partitionOverwriteMode","dynamic")final_df.write.partitionBy(["partition1", "partition2"]).saveAsTable("db.output", format='parquet', mode='overwrite', path='s3://your-s3-path')
Note that the PySpark API mode of writing to the Glue Catalog seems to occasionally cause the table to become unavailable when it is being written to.
Using AWS Glue Bookmarks in combination with predicate pushdown enables incremental joins of data in your ETL pipelines without reprocessing of all data every time. Good choice of a partitioning schema can ensure that your incremental join jobs process close to the minimum amount of data required.
Originally published at https://datamunch.tech. | [
{
"code": null,
"e": 605,
"s": 172,
"text": "I was recently presented the challenge to join two timeseries datasets together on their timestamps without requiring the corresponding data from either dataset to arrive at the same time as the other. For example, data from one day last month from one dataset may have landed on S3 a week ago, and the corresponding data from the other dataset for that day last month may have landed yesterday. This is an incremental join problem."
},
{
"code": null,
"e": 815,
"s": 605,
"text": "It may be possible to get around this problem by holding off from joining the data until it was queried, however I wanted to pre-process the join so that the joined data could be queried directly at any scale."
},
{
"code": null,
"e": 942,
"s": 815,
"text": "You could re-process the entire dataset every pipeline run. This was not an for a dataset that is constantly larger every day."
},
{
"code": null,
"e": 1208,
"s": 942,
"text": "It would also be possible to manually implement a system that does not process data from either tables until both have landed. This would in-effect be re-implementing a feature that is already available with AWS Glue: Bookmarks which we are going to leverage below."
},
{
"code": null,
"e": 1658,
"s": 1208,
"text": "AWS Glue Bookmarks allows you to only process the new data that has landed in a data pipeline since the pipeline was previously run. In the incremental join problem described above, where corresponding data that needs processed may have landed and have been processed in different runs of the pipeline, this does not fully solve the problem as corresponding data will be fed by the bookmarks to be processed in different jobs so would not be joined."
},
{
"code": null,
"e": 1856,
"s": 1658,
"text": "The solution we came up with leveraged another feature of AWS Glue, the ability to load a subset of a table using a predicate pushdown. We ended up with the following ETL steps in the Glue ETL job:"
},
{
"code": null,
"e": 2372,
"s": 1856,
"text": "# setup Glue ETL environmentimport sysfrom awsglue.transforms import *from awsglue.utils import getResolvedOptionsfrom pyspark.context import SparkContextfrom awsglue.context import GlueContextfrom awsglue.job import Jobfrom pyspark.sql.functions import split, colfrom awsglue.dynamicframe import DynamicFrame## @params: [JOB_NAME]args = getResolvedOptions(sys.argv, ['JOB_NAME'])sc = SparkContext()glueContext = GlueContext(sc)spark = glueContext.spark_sessionjob = Job(glueContext)job.init(args['JOB_NAME'], args)"
},
{
"code": null,
"e": 2482,
"s": 2372,
"text": "Load the new data that has landed since the last pipeline run using Glue Bookmarks from the AWS Glue catalog."
},
{
"code": null,
"e": 2737,
"s": 2482,
"text": "table1_new = glueContext.create_dynamic_frame.from_catalog(database=\"db\", table_name=\"table1\", transformation_ctx='table1_new')table2_new = glueContext.create_dynamic_frame.from_catalog(database=\"db\", table_name=\"table1\", transformation_ctx='table2_new')"
},
{
"code": null,
"e": 2963,
"s": 2737,
"text": "Find the partitions that are being affected by in your new data. As this was timeseries data, it made sense to partition by datetime. Write these partitions into a pushdown predicate that can be queried on the entire dataset."
},
{
"code": null,
"e": 3159,
"s": 2963,
"text": "Having built the predicate string which lists every partition for which there is new data in either one or both of the tables, we can now load ‘unlock’ just that data from the source data tables."
},
{
"code": null,
"e": 3520,
"s": 3159,
"text": "we use the predicate string we previously built and load the table without using bookmarkstable1_unlock = glueContext.create_dynamic_frame.from_catalog(database=\"db\", table_name=\"table1\", push_down_predicate=table1_predicate)table2_unlock = glueContext.create_dynamic_frame.from_catalog(database=\"db\", table_name=\"table2\", push_down_predicate=table2_predicate)"
},
{
"code": null,
"e": 3597,
"s": 3520,
"text": "We can now run whatever join transformations we want using these two tables."
},
{
"code": null,
"e": 3952,
"s": 3597,
"text": "We can then write the tables to a database, in our case S3. Depending on the type of join transformations you are doing, we found it best to use the Spark API writer in “overwrite” mode rather than the Glue DynamicFrame writers as we wanted to delete any old data that was written in a partition in a previous run and write only the newly processed data."
},
{
"code": null,
"e": 4199,
"s": 3952,
"text": "# set the overwrite mode to dynamicspark.conf.set(\"spark.sql.sources.partitionOverwriteMode\",\"dynamic\")final_df.write.partitionBy([\"partition1\", \"partition2\"]).saveAsTable(\"db.output\", format='parquet', mode='overwrite', path='s3://your-s3-path')"
},
{
"code": null,
"e": 4350,
"s": 4199,
"text": "Note that the PySpark API mode of writing to the Glue Catalog seems to occasionally cause the table to become unavailable when it is being written to."
},
{
"code": null,
"e": 4649,
"s": 4350,
"text": "Using AWS Glue Bookmarks in combination with predicate pushdown enables incremental joins of data in your ETL pipelines without reprocessing of all data every time. Good choice of a partitioning schema can ensure that your incremental join jobs process close to the minimum amount of data required."
}
]
|
Python Program for nth Catalan Number | In this article, we will learn about calculating the nth Catalan number.
Catalan numbers are a sequence of natural numbers that are defined by the recursive formula −
C0=1andCn+1=∑i=0nCiCn−iforn≥0;
The first few Catalan numbers for n = 0, 1, 2, 3, ... are 1, 1, 2, 5, 14, 42, 132,429,...................
Catalan numbers can be obtained both by recursion and dynamic programming.
So let’s see their implementation.
Live Demo
# A recursive solution
def catalan(n):
#negative value
if n <=1 :
return 1
# Catalan(n) = catalan(i)*catalan(n-i-1)
res = 0
for i in range(n):
res += catalan(i) * catalan(n-i-1)
return res
# main
for i in range(6):
print (catalan(i))
1
1
2
5
14
42
The scope of all the variables and recursive calls are shown below.
Live Demo
# using dynamic programming
def catalan(n):
if (n == 0 or n == 1):
return 1
# divide table
catalan = [0 for i in range(n + 1)]
# Initialization
catalan[0] = 1
catalan[1] = 1
# recursion
for i in range(2, n + 1):
catalan[i] = 0
for j in range(i):
catalan[i] = catalan[i] + catalan[j] * catalan[i-j-1]
return catalan[n]
# main
for i in range (6):
print (catalan(i),end=" ")
1
1
2
5
14
42
The scope of all the variables and recursive calls are shown below.
In this article, we learned about the method of generating the nth Catalan number. | [
{
"code": null,
"e": 1135,
"s": 1062,
"text": "In this article, we will learn about calculating the nth Catalan number."
},
{
"code": null,
"e": 1229,
"s": 1135,
"text": "Catalan numbers are a sequence of natural numbers that are defined by the recursive formula −"
},
{
"code": null,
"e": 1260,
"s": 1229,
"text": "C0=1andCn+1=∑i=0nCiCn−iforn≥0;"
},
{
"code": null,
"e": 1366,
"s": 1260,
"text": "The first few Catalan numbers for n = 0, 1, 2, 3, ... are 1, 1, 2, 5, 14, 42, 132,429,..................."
},
{
"code": null,
"e": 1476,
"s": 1366,
"text": "Catalan numbers can be obtained both by recursion and dynamic programming.\nSo let’s see their implementation."
},
{
"code": null,
"e": 1487,
"s": 1476,
"text": " Live Demo"
},
{
"code": null,
"e": 1754,
"s": 1487,
"text": "# A recursive solution\ndef catalan(n):\n #negative value\n if n <=1 :\n return 1\n # Catalan(n) = catalan(i)*catalan(n-i-1)\n res = 0\n for i in range(n):\n res += catalan(i) * catalan(n-i-1)\n return res\n# main\nfor i in range(6):\n print (catalan(i))"
},
{
"code": null,
"e": 1768,
"s": 1754,
"text": "1\n1\n2\n5\n14\n42"
},
{
"code": null,
"e": 1836,
"s": 1768,
"text": "The scope of all the variables and recursive calls are shown below."
},
{
"code": null,
"e": 1847,
"s": 1836,
"text": " Live Demo"
},
{
"code": null,
"e": 2276,
"s": 1847,
"text": "# using dynamic programming\ndef catalan(n):\n if (n == 0 or n == 1):\n return 1\n # divide table\n catalan = [0 for i in range(n + 1)]\n # Initialization\n catalan[0] = 1\n catalan[1] = 1\n # recursion\n for i in range(2, n + 1):\n catalan[i] = 0\n for j in range(i):\n catalan[i] = catalan[i] + catalan[j] * catalan[i-j-1]\n return catalan[n]\n# main\nfor i in range (6):\n print (catalan(i),end=\" \")"
},
{
"code": null,
"e": 2290,
"s": 2276,
"text": "1\n1\n2\n5\n14\n42"
},
{
"code": null,
"e": 2358,
"s": 2290,
"text": "The scope of all the variables and recursive calls are shown below."
},
{
"code": null,
"e": 2441,
"s": 2358,
"text": "In this article, we learned about the method of generating the nth Catalan number."
}
]
|
Distributed DBMS - Database Control | Database control refers to the task of enforcing regulations so as to provide correct data to authentic users and applications of a database. In order that correct data is available to users, all data should conform to the integrity constraints defined in the database. Besides, data should be screened away from unauthorized users so as to maintain security and privacy of the database. Database control is one of the primary tasks of the database administrator (DBA).
The three dimensions of database control are −
Authentication
Access rights
Integrity constraints
In a distributed database system, authentication is the process through which only legitimate users can gain access to the data resources.
Authentication can be enforced in two levels −
Controlling Access to Client Computer − At this level, user access is restricted while login to the client computer that provides user-interface to the database server. The most common method is a username/password combination. However, more sophisticated methods like biometric authentication may be used for high security data.
Controlling Access to Client Computer − At this level, user access is restricted while login to the client computer that provides user-interface to the database server. The most common method is a username/password combination. However, more sophisticated methods like biometric authentication may be used for high security data.
Controlling Access to the Database Software − At this level, the database software/administrator assigns some credentials to the user. The user gains access to the database using these credentials. One of the methods is to create a login account within the database server.
Controlling Access to the Database Software − At this level, the database software/administrator assigns some credentials to the user. The user gains access to the database using these credentials. One of the methods is to create a login account within the database server.
A user’s access rights refers to the privileges that the user is given regarding DBMS operations such as the rights to create a table, drop a table, add/delete/update tuples in a table or query upon the table.
In distributed environments, since there are large number of tables and yet larger number of users, it is not feasible to assign individual access rights to users. So, DDBMS defines certain roles. A role is a construct with certain privileges within a database system. Once the different roles are defined, the individual users are assigned one of these roles. Often a hierarchy of roles are defined according to the organization’s hierarchy of authority and responsibility.
For example, the following SQL statements create a role "Accountant" and then assigns this role to user "ABC".
CREATE ROLE ACCOUNTANT;
GRANT SELECT, INSERT, UPDATE ON EMP_SAL TO ACCOUNTANT;
GRANT INSERT, UPDATE, DELETE ON TENDER TO ACCOUNTANT;
GRANT INSERT, SELECT ON EXPENSE TO ACCOUNTANT;
COMMIT;
GRANT ACCOUNTANT TO ABC;
COMMIT;
Semantic integrity control defines and enforces the integrity constraints of the database system.
The integrity constraints are as follows −
Data type integrity constraint
Entity integrity constraint
Referential integrity constraint
A data type constraint restricts the range of values and the type of operations that can be applied to the field with the specified data type.
For example, let us consider that a table "HOSTEL" has three fields - the hostel number, hostel name and capacity. The hostel number should start with capital letter "H" and cannot be NULL, and the capacity should not be more than 150. The following SQL command can be used for data definition −
CREATE TABLE HOSTEL (
H_NO VARCHAR2(5) NOT NULL,
H_NAME VARCHAR2(15),
CAPACITY INTEGER,
CHECK ( H_NO LIKE 'H%'),
CHECK ( CAPACITY <= 150)
);
Entity integrity control enforces the rules so that each tuple can be uniquely identified from other tuples. For this a primary key is defined. A primary key is a set of minimal fields that can uniquely identify a tuple. Entity integrity constraint states that no two tuples in a table can have identical values for primary keys and that no field which is a part of the primary key can have NULL value.
For example, in the above hostel table, the hostel number can be assigned as the primary key through the following SQL statement (ignoring the checks) −
CREATE TABLE HOSTEL (
H_NO VARCHAR2(5) PRIMARY KEY,
H_NAME VARCHAR2(15),
CAPACITY INTEGER
);
Referential integrity constraint lays down the rules of foreign keys. A foreign key is a field in a data table that is the primary key of a related table. The referential integrity constraint lays down the rule that the value of the foreign key field should either be among the values of the primary key of the referenced table or be entirely NULL.
For example, let us consider a student table where a student may opt to live in a hostel. To include this, the primary key of hostel table should be included as a foreign key in the student table. The following SQL statement incorporates this −
CREATE TABLE STUDENT (
S_ROLL INTEGER PRIMARY KEY,
S_NAME VARCHAR2(25) NOT NULL,
S_COURSE VARCHAR2(10),
S_HOSTEL VARCHAR2(5) REFERENCES HOSTEL
);
49 Lectures
11 hours
Hussein Rashad
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2693,
"s": 2223,
"text": "Database control refers to the task of enforcing regulations so as to provide correct data to authentic users and applications of a database. In order that correct data is available to users, all data should conform to the integrity constraints defined in the database. Besides, data should be screened away from unauthorized users so as to maintain security and privacy of the database. Database control is one of the primary tasks of the database administrator (DBA)."
},
{
"code": null,
"e": 2740,
"s": 2693,
"text": "The three dimensions of database control are −"
},
{
"code": null,
"e": 2755,
"s": 2740,
"text": "Authentication"
},
{
"code": null,
"e": 2769,
"s": 2755,
"text": "Access rights"
},
{
"code": null,
"e": 2791,
"s": 2769,
"text": "Integrity constraints"
},
{
"code": null,
"e": 2930,
"s": 2791,
"text": "In a distributed database system, authentication is the process through which only legitimate users can gain access to the data resources."
},
{
"code": null,
"e": 2977,
"s": 2930,
"text": "Authentication can be enforced in two levels −"
},
{
"code": null,
"e": 3307,
"s": 2977,
"text": "Controlling Access to Client Computer − At this level, user access is restricted while login to the client computer that provides user-interface to the database server. The most common method is a username/password combination. However, more sophisticated methods like biometric authentication may be used for high security data."
},
{
"code": null,
"e": 3637,
"s": 3307,
"text": "Controlling Access to Client Computer − At this level, user access is restricted while login to the client computer that provides user-interface to the database server. The most common method is a username/password combination. However, more sophisticated methods like biometric authentication may be used for high security data."
},
{
"code": null,
"e": 3911,
"s": 3637,
"text": "Controlling Access to the Database Software − At this level, the database software/administrator assigns some credentials to the user. The user gains access to the database using these credentials. One of the methods is to create a login account within the database server."
},
{
"code": null,
"e": 4185,
"s": 3911,
"text": "Controlling Access to the Database Software − At this level, the database software/administrator assigns some credentials to the user. The user gains access to the database using these credentials. One of the methods is to create a login account within the database server."
},
{
"code": null,
"e": 4395,
"s": 4185,
"text": "A user’s access rights refers to the privileges that the user is given regarding DBMS operations such as the rights to create a table, drop a table, add/delete/update tuples in a table or query upon the table."
},
{
"code": null,
"e": 4870,
"s": 4395,
"text": "In distributed environments, since there are large number of tables and yet larger number of users, it is not feasible to assign individual access rights to users. So, DDBMS defines certain roles. A role is a construct with certain privileges within a database system. Once the different roles are defined, the individual users are assigned one of these roles. Often a hierarchy of roles are defined according to the organization’s hierarchy of authority and responsibility."
},
{
"code": null,
"e": 4981,
"s": 4870,
"text": "For example, the following SQL statements create a role \"Accountant\" and then assigns this role to user \"ABC\"."
},
{
"code": null,
"e": 5208,
"s": 4981,
"text": "CREATE ROLE ACCOUNTANT; \nGRANT SELECT, INSERT, UPDATE ON EMP_SAL TO ACCOUNTANT; \nGRANT INSERT, UPDATE, DELETE ON TENDER TO ACCOUNTANT; \nGRANT INSERT, SELECT ON EXPENSE TO ACCOUNTANT; \nCOMMIT; \nGRANT ACCOUNTANT TO ABC; \nCOMMIT;"
},
{
"code": null,
"e": 5306,
"s": 5208,
"text": "Semantic integrity control defines and enforces the integrity constraints of the database system."
},
{
"code": null,
"e": 5349,
"s": 5306,
"text": "The integrity constraints are as follows −"
},
{
"code": null,
"e": 5380,
"s": 5349,
"text": "Data type integrity constraint"
},
{
"code": null,
"e": 5408,
"s": 5380,
"text": "Entity integrity constraint"
},
{
"code": null,
"e": 5441,
"s": 5408,
"text": "Referential integrity constraint"
},
{
"code": null,
"e": 5584,
"s": 5441,
"text": "A data type constraint restricts the range of values and the type of operations that can be applied to the field with the specified data type."
},
{
"code": null,
"e": 5880,
"s": 5584,
"text": "For example, let us consider that a table \"HOSTEL\" has three fields - the hostel number, hostel name and capacity. The hostel number should start with capital letter \"H\" and cannot be NULL, and the capacity should not be more than 150. The following SQL command can be used for data definition −"
},
{
"code": null,
"e": 6043,
"s": 5880,
"text": "CREATE TABLE HOSTEL ( \n H_NO VARCHAR2(5) NOT NULL, \n H_NAME VARCHAR2(15), \n CAPACITY INTEGER, \n CHECK ( H_NO LIKE 'H%'), \n CHECK ( CAPACITY <= 150) \n); "
},
{
"code": null,
"e": 6446,
"s": 6043,
"text": "Entity integrity control enforces the rules so that each tuple can be uniquely identified from other tuples. For this a primary key is defined. A primary key is a set of minimal fields that can uniquely identify a tuple. Entity integrity constraint states that no two tuples in a table can have identical values for primary keys and that no field which is a part of the primary key can have NULL value."
},
{
"code": null,
"e": 6599,
"s": 6446,
"text": "For example, in the above hostel table, the hostel number can be assigned as the primary key through the following SQL statement (ignoring the checks) −"
},
{
"code": null,
"e": 6706,
"s": 6599,
"text": "CREATE TABLE HOSTEL ( \n H_NO VARCHAR2(5) PRIMARY KEY, \n H_NAME VARCHAR2(15), \n CAPACITY INTEGER \n); "
},
{
"code": null,
"e": 7055,
"s": 6706,
"text": "Referential integrity constraint lays down the rules of foreign keys. A foreign key is a field in a data table that is the primary key of a related table. The referential integrity constraint lays down the rule that the value of the foreign key field should either be among the values of the primary key of the referenced table or be entirely NULL."
},
{
"code": null,
"e": 7300,
"s": 7055,
"text": "For example, let us consider a student table where a student may opt to live in a hostel. To include this, the primary key of hostel table should be included as a foreign key in the student table. The following SQL statement incorporates this −"
},
{
"code": null,
"e": 7465,
"s": 7300,
"text": "CREATE TABLE STUDENT ( \n S_ROLL INTEGER PRIMARY KEY, \n S_NAME VARCHAR2(25) NOT NULL, \n S_COURSE VARCHAR2(10), \n S_HOSTEL VARCHAR2(5) REFERENCES HOSTEL \n); "
},
{
"code": null,
"e": 7499,
"s": 7465,
"text": "\n 49 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 7515,
"s": 7499,
"text": " Hussein Rashad"
},
{
"code": null,
"e": 7522,
"s": 7515,
"text": " Print"
},
{
"code": null,
"e": 7533,
"s": 7522,
"text": " Add Notes"
}
]
|
Count The Repetitions in C++ | Suppose we have two non-empty strings s1 and s2 (maximum 100 characters) and two numbers n1 and n2 both are in range 0 to 106. Now suppose the strings S1 and S2, where S1=[s1,n1] and S2=[s2,n2].
S = [s,n] defines the string S which consists of n connected strings s. As an exdample, ["ab", 4] ="abababab".
On the other hand, we cal also define that string s1 can be obtained from string s2 if we remove some characters from s2 such that it becomes s1. So, "abc" can be obtained from "abdbec" based on the definition, but it can not be obtained from “acbbe”.
We have to find the maximum integer M such that [S2,M] can be obtained from S1.
So, if the input is like s1="acb", n1=4, s2="ab", n2=2, then the output will be 2
To solve this, we will follow these steps −
for each character c in s2if c is not in s1 , then −return 0
for each character c in s2
if c is not in s1 , then −return 0
if c is not in s1 , then −
return 0
return 0
p1 := 0, p2 := 0, mark := 0
p1 := 0, p2 := 0, mark := 0
while p1 < size of s1, do −c := s2[p2 mod size of s2]while (s1[p1 mod size of s1] is not equal to c and p1 < size of s1 *n1), do −(increase p1 by 1)(increase p2 by 1)(increase p1 by 1)if p2 mod size of s2 is same as 0, then −if p2 is same as size of s2, then −mark := p1otherwise when p1 mod size of s1 is same as mark mod size of s1, then −round := (size of s1 * n1 - p1) / (p1 - mark)p1 := p1 + round * (p1 - mark)p2 := p2 + round * (p2 - size of s2)
while p1 < size of s1, do −
c := s2[p2 mod size of s2]
c := s2[p2 mod size of s2]
while (s1[p1 mod size of s1] is not equal to c and p1 < size of s1 *n1), do −(increase p1 by 1)
while (s1[p1 mod size of s1] is not equal to c and p1 < size of s1 *n1), do −
(increase p1 by 1)
(increase p1 by 1)
(increase p2 by 1)
(increase p2 by 1)
(increase p1 by 1)
(increase p1 by 1)
if p2 mod size of s2 is same as 0, then −if p2 is same as size of s2, then −mark := p1otherwise when p1 mod size of s1 is same as mark mod size of s1, then −round := (size of s1 * n1 - p1) / (p1 - mark)p1 := p1 + round * (p1 - mark)p2 := p2 + round * (p2 - size of s2)
if p2 mod size of s2 is same as 0, then −
if p2 is same as size of s2, then −mark := p1
if p2 is same as size of s2, then −
mark := p1
mark := p1
otherwise when p1 mod size of s1 is same as mark mod size of s1, then −round := (size of s1 * n1 - p1) / (p1 - mark)p1 := p1 + round * (p1 - mark)p2 := p2 + round * (p2 - size of s2)
otherwise when p1 mod size of s1 is same as mark mod size of s1, then −
round := (size of s1 * n1 - p1) / (p1 - mark)
round := (size of s1 * n1 - p1) / (p1 - mark)
p1 := p1 + round * (p1 - mark)
p1 := p1 + round * (p1 - mark)
p2 := p2 + round * (p2 - size of s2)
p2 := p2 + round * (p2 - size of s2)
return p2 / size of s2 / n2
return p2 / size of s2 / n2
Let us see the following implementation to get better understanding −
Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int getMaxRepetitions(string s1, int n1, string s2, int n2) {
for (auto c : s2) {
if (s1.find(c) == string::npos)
return 0;
}
int p1 = 0, p2 = 0, mark = 0;
while (p1 < s1.length() * n1) {
char c = s2[p2 % s2.length()];
while (s1[p1 % s1.length()] != c && p1 <s1.length() * n1)
p1++;
p2++;
p1++;
if (p2 % s2.length() == 0) {
if (p2 == s2.length()) {
mark = p1;
}
else if (p1 % s1.length() == mark % s1.length()) {
int round = (s1.length() * n1 - p1) / (p1 - mark);
p1 += round * (p1 - mark);
p2 += round * (p2 - s2.length());
}
}
}
return p2 / s2.length() / n2;
}
};
main() {
Solution ob;
cout << (ob.getMaxRepetitions("acb",4,"ab",2));
}
"acb",4,"ab",2
2 | [
{
"code": null,
"e": 1257,
"s": 1062,
"text": "Suppose we have two non-empty strings s1 and s2 (maximum 100 characters) and two numbers n1 and n2 both are in range 0 to 106. Now suppose the strings S1 and S2, where S1=[s1,n1] and S2=[s2,n2]."
},
{
"code": null,
"e": 1368,
"s": 1257,
"text": "S = [s,n] defines the string S which consists of n connected strings s. As an exdample, [\"ab\", 4] =\"abababab\"."
},
{
"code": null,
"e": 1620,
"s": 1368,
"text": "On the other hand, we cal also define that string s1 can be obtained from string s2 if we remove some characters from s2 such that it becomes s1. So, \"abc\" can be obtained from \"abdbec\" based on the definition, but it can not be obtained from “acbbe”."
},
{
"code": null,
"e": 1700,
"s": 1620,
"text": "We have to find the maximum integer M such that [S2,M] can be obtained from S1."
},
{
"code": null,
"e": 1782,
"s": 1700,
"text": "So, if the input is like s1=\"acb\", n1=4, s2=\"ab\", n2=2, then the output will be 2"
},
{
"code": null,
"e": 1826,
"s": 1782,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1887,
"s": 1826,
"text": "for each character c in s2if c is not in s1 , then −return 0"
},
{
"code": null,
"e": 1914,
"s": 1887,
"text": "for each character c in s2"
},
{
"code": null,
"e": 1949,
"s": 1914,
"text": "if c is not in s1 , then −return 0"
},
{
"code": null,
"e": 1976,
"s": 1949,
"text": "if c is not in s1 , then −"
},
{
"code": null,
"e": 1985,
"s": 1976,
"text": "return 0"
},
{
"code": null,
"e": 1994,
"s": 1985,
"text": "return 0"
},
{
"code": null,
"e": 2022,
"s": 1994,
"text": "p1 := 0, p2 := 0, mark := 0"
},
{
"code": null,
"e": 2050,
"s": 2022,
"text": "p1 := 0, p2 := 0, mark := 0"
},
{
"code": null,
"e": 2503,
"s": 2050,
"text": "while p1 < size of s1, do −c := s2[p2 mod size of s2]while (s1[p1 mod size of s1] is not equal to c and p1 < size of s1 *n1), do −(increase p1 by 1)(increase p2 by 1)(increase p1 by 1)if p2 mod size of s2 is same as 0, then −if p2 is same as size of s2, then −mark := p1otherwise when p1 mod size of s1 is same as mark mod size of s1, then −round := (size of s1 * n1 - p1) / (p1 - mark)p1 := p1 + round * (p1 - mark)p2 := p2 + round * (p2 - size of s2)"
},
{
"code": null,
"e": 2531,
"s": 2503,
"text": "while p1 < size of s1, do −"
},
{
"code": null,
"e": 2558,
"s": 2531,
"text": "c := s2[p2 mod size of s2]"
},
{
"code": null,
"e": 2585,
"s": 2558,
"text": "c := s2[p2 mod size of s2]"
},
{
"code": null,
"e": 2681,
"s": 2585,
"text": "while (s1[p1 mod size of s1] is not equal to c and p1 < size of s1 *n1), do −(increase p1 by 1)"
},
{
"code": null,
"e": 2759,
"s": 2681,
"text": "while (s1[p1 mod size of s1] is not equal to c and p1 < size of s1 *n1), do −"
},
{
"code": null,
"e": 2778,
"s": 2759,
"text": "(increase p1 by 1)"
},
{
"code": null,
"e": 2797,
"s": 2778,
"text": "(increase p1 by 1)"
},
{
"code": null,
"e": 2816,
"s": 2797,
"text": "(increase p2 by 1)"
},
{
"code": null,
"e": 2835,
"s": 2816,
"text": "(increase p2 by 1)"
},
{
"code": null,
"e": 2854,
"s": 2835,
"text": "(increase p1 by 1)"
},
{
"code": null,
"e": 2873,
"s": 2854,
"text": "(increase p1 by 1)"
},
{
"code": null,
"e": 3142,
"s": 2873,
"text": "if p2 mod size of s2 is same as 0, then −if p2 is same as size of s2, then −mark := p1otherwise when p1 mod size of s1 is same as mark mod size of s1, then −round := (size of s1 * n1 - p1) / (p1 - mark)p1 := p1 + round * (p1 - mark)p2 := p2 + round * (p2 - size of s2)"
},
{
"code": null,
"e": 3184,
"s": 3142,
"text": "if p2 mod size of s2 is same as 0, then −"
},
{
"code": null,
"e": 3230,
"s": 3184,
"text": "if p2 is same as size of s2, then −mark := p1"
},
{
"code": null,
"e": 3266,
"s": 3230,
"text": "if p2 is same as size of s2, then −"
},
{
"code": null,
"e": 3277,
"s": 3266,
"text": "mark := p1"
},
{
"code": null,
"e": 3288,
"s": 3277,
"text": "mark := p1"
},
{
"code": null,
"e": 3471,
"s": 3288,
"text": "otherwise when p1 mod size of s1 is same as mark mod size of s1, then −round := (size of s1 * n1 - p1) / (p1 - mark)p1 := p1 + round * (p1 - mark)p2 := p2 + round * (p2 - size of s2)"
},
{
"code": null,
"e": 3543,
"s": 3471,
"text": "otherwise when p1 mod size of s1 is same as mark mod size of s1, then −"
},
{
"code": null,
"e": 3589,
"s": 3543,
"text": "round := (size of s1 * n1 - p1) / (p1 - mark)"
},
{
"code": null,
"e": 3635,
"s": 3589,
"text": "round := (size of s1 * n1 - p1) / (p1 - mark)"
},
{
"code": null,
"e": 3666,
"s": 3635,
"text": "p1 := p1 + round * (p1 - mark)"
},
{
"code": null,
"e": 3697,
"s": 3666,
"text": "p1 := p1 + round * (p1 - mark)"
},
{
"code": null,
"e": 3734,
"s": 3697,
"text": "p2 := p2 + round * (p2 - size of s2)"
},
{
"code": null,
"e": 3771,
"s": 3734,
"text": "p2 := p2 + round * (p2 - size of s2)"
},
{
"code": null,
"e": 3799,
"s": 3771,
"text": "return p2 / size of s2 / n2"
},
{
"code": null,
"e": 3827,
"s": 3799,
"text": "return p2 / size of s2 / n2"
},
{
"code": null,
"e": 3897,
"s": 3827,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 3908,
"s": 3897,
"text": " Live Demo"
},
{
"code": null,
"e": 4857,
"s": 3908,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\npublic:\n int getMaxRepetitions(string s1, int n1, string s2, int n2) {\n for (auto c : s2) {\n if (s1.find(c) == string::npos)\n return 0;\n }\n int p1 = 0, p2 = 0, mark = 0;\n while (p1 < s1.length() * n1) {\n char c = s2[p2 % s2.length()];\n while (s1[p1 % s1.length()] != c && p1 <s1.length() * n1)\n p1++;\n p2++;\n p1++;\n if (p2 % s2.length() == 0) {\n if (p2 == s2.length()) {\n mark = p1;\n }\n else if (p1 % s1.length() == mark % s1.length()) {\n int round = (s1.length() * n1 - p1) / (p1 - mark);\n p1 += round * (p1 - mark);\n p2 += round * (p2 - s2.length());\n }\n }\n }\n return p2 / s2.length() / n2;\n }\n};\nmain() {\n Solution ob;\n cout << (ob.getMaxRepetitions(\"acb\",4,\"ab\",2));\n}"
},
{
"code": null,
"e": 4872,
"s": 4857,
"text": "\"acb\",4,\"ab\",2"
},
{
"code": null,
"e": 4874,
"s": 4872,
"text": "2"
}
]
|
Makefile - Example | This is an example of the Makefile for compiling the hello program. This program consists of three files main.cpp, factorial.cpp and hello.cpp.
# Define required macros here
SHELL = /bin/sh
OBJS = main.o factorial.o hello.o
CFLAG = -Wall -g
CC = gcc
INCLUDE =
LIBS = -lm
hello:${OBJ}
${CC} ${CFLAGS} ${INCLUDES} -o $@ ${OBJS} ${LIBS}
clean:
-rm -f *.o core *.core
.cpp.o:
${CC} ${CFLAGS} ${INCLUDES} -c $<
Now you can build your program hello using the make. If you will issue a command make clean then it removes all the object files and core files available in the current directory.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 1929,
"s": 1784,
"text": "This is an example of the Makefile for compiling the hello program. This program consists of three files main.cpp, factorial.cpp and hello.cpp."
},
{
"code": null,
"e": 2205,
"s": 1929,
"text": "# Define required macros here\nSHELL = /bin/sh\n\nOBJS = main.o factorial.o hello.o\nCFLAG = -Wall -g\nCC = gcc\nINCLUDE =\nLIBS = -lm\n\nhello:${OBJ}\n ${CC} ${CFLAGS} ${INCLUDES} -o $@ ${OBJS} ${LIBS}\n\nclean:\n -rm -f *.o core *.core\n\n.cpp.o:\n ${CC} ${CFLAGS} ${INCLUDES} -c $<"
},
{
"code": null,
"e": 2385,
"s": 2205,
"text": "Now you can build your program hello using the make. If you will issue a command make clean then it removes all the object files and core files available in the current directory."
},
{
"code": null,
"e": 2392,
"s": 2385,
"text": " Print"
},
{
"code": null,
"e": 2403,
"s": 2392,
"text": " Add Notes"
}
]
|
How to write "Hello World" Program in C++? | To run the hello world program, you'll have to follow the following steps −
Now that you have a compiler installed, its time to write a C++ program. Let's start with the epitome of programming example's, it, the Hello world program. We'll print hello world to the screen using C++ in this example. Create a new file called hello.cpp and write the following code to it −
#include<iostream>
int main() {
std::cout << "Hello World\n";
}
Let's dissect this program.
Line 1 − We start with the #include<iostream> line which essentially tells the compiler to copy the code from the iostream file(used for managing input and output streams) and paste it in our source file. Header iostream, that allows to perform standard input and output operations, such as writing the output of this program (Hello World) to the screen. Lines beginning with a hash sign (#) are directives read and interpreted by what is known as the preprocessor.
Line 2 − A blank line: Blank lines have no effect on a program.
Line 3 − We then declare a function called main with the return type of int. main() is the entry point of our program. Whenever we run a C++ program, we start with the main function and begin execution from the first line within this function and keep executing each line till we reach the end. We start a block using the curly brace({) here. This marks the beginning of main's function definition, and the closing brace (}) at line 5, marks its end. All statements between these braces are the function's body that defines what happens when main is called.
Line 4 −
std::cout << "Hello World\n";
This line is a C++ statement. This statement has three parts: First, std::cout, which identifies the standard console output device. Second the insertion operator << which indicates that what follows is inserted into std::cout. Last, we have a sentence within quotes that we'd like printed on the screen. This will become more clear to you as we proceed in learning C++.
In short, we provide cout object with a string "Hello world\n" to be printed to the standard output device.
Note that the statement ends with a semicolon (;). This character marks the end of the statement
Now that we've written the program, we need to translate it to a language that the processor understands, ie, in binary machine code. We do this using a compiler we installed in the first step. You need to open your terminal/cmd and navigate to the location of the hello.cpp file using the cd command. Assuming you installed the GCC, you can use the following command to compile the program −
$ g++ -o hello hello.cpp
This command means that you want the g++ compiler to create an output file, hello using the source file hello.cpp.
Now that we've written our program and compiled it, time to run it! You can run the program using −
$ ./hello
You will get the output −
Hello world | [
{
"code": null,
"e": 1138,
"s": 1062,
"text": "To run the hello world program, you'll have to follow the following steps −"
},
{
"code": null,
"e": 1432,
"s": 1138,
"text": "Now that you have a compiler installed, its time to write a C++ program. Let's start with the epitome of programming example's, it, the Hello world program. We'll print hello world to the screen using C++ in this example. Create a new file called hello.cpp and write the following code to it −"
},
{
"code": null,
"e": 1499,
"s": 1432,
"text": "#include<iostream>\nint main() {\n std::cout << \"Hello World\\n\";\n}"
},
{
"code": null,
"e": 1527,
"s": 1499,
"text": "Let's dissect this program."
},
{
"code": null,
"e": 1994,
"s": 1527,
"text": "Line 1 − We start with the #include<iostream> line which essentially tells the compiler to copy the code from the iostream file(used for managing input and output streams) and paste it in our source file. Header iostream, that allows to perform standard input and output operations, such as writing the output of this program (Hello World) to the screen. Lines beginning with a hash sign (#) are directives read and interpreted by what is known as the preprocessor."
},
{
"code": null,
"e": 2058,
"s": 1994,
"text": "Line 2 − A blank line: Blank lines have no effect on a program."
},
{
"code": null,
"e": 2616,
"s": 2058,
"text": "Line 3 − We then declare a function called main with the return type of int. main() is the entry point of our program. Whenever we run a C++ program, we start with the main function and begin execution from the first line within this function and keep executing each line till we reach the end. We start a block using the curly brace({) here. This marks the beginning of main's function definition, and the closing brace (}) at line 5, marks its end. All statements between these braces are the function's body that defines what happens when main is called."
},
{
"code": null,
"e": 2625,
"s": 2616,
"text": "Line 4 −"
},
{
"code": null,
"e": 2655,
"s": 2625,
"text": "std::cout << \"Hello World\\n\";"
},
{
"code": null,
"e": 3026,
"s": 2655,
"text": "This line is a C++ statement. This statement has three parts: First, std::cout, which identifies the standard console output device. Second the insertion operator << which indicates that what follows is inserted into std::cout. Last, we have a sentence within quotes that we'd like printed on the screen. This will become more clear to you as we proceed in learning C++."
},
{
"code": null,
"e": 3134,
"s": 3026,
"text": "In short, we provide cout object with a string \"Hello world\\n\" to be printed to the standard output device."
},
{
"code": null,
"e": 3231,
"s": 3134,
"text": "Note that the statement ends with a semicolon (;). This character marks the end of the statement"
},
{
"code": null,
"e": 3624,
"s": 3231,
"text": "Now that we've written the program, we need to translate it to a language that the processor understands, ie, in binary machine code. We do this using a compiler we installed in the first step. You need to open your terminal/cmd and navigate to the location of the hello.cpp file using the cd command. Assuming you installed the GCC, you can use the following command to compile the program −"
},
{
"code": null,
"e": 3649,
"s": 3624,
"text": "$ g++ -o hello hello.cpp"
},
{
"code": null,
"e": 3764,
"s": 3649,
"text": "This command means that you want the g++ compiler to create an output file, hello using the source file hello.cpp."
},
{
"code": null,
"e": 3864,
"s": 3764,
"text": "Now that we've written our program and compiled it, time to run it! You can run the program using −"
},
{
"code": null,
"e": 3874,
"s": 3864,
"text": "$ ./hello"
},
{
"code": null,
"e": 3900,
"s": 3874,
"text": "You will get the output −"
},
{
"code": null,
"e": 3912,
"s": 3900,
"text": "Hello world"
}
]
|
Ext.js - Ext.tab.Panel Container | Ext.tab.Panel − Tab panel is like a normal panel but has support for card tab panel layout.
Following is a simple syntax to create Ext.tab.Panel container.
Ext.create('Ext.tab.Panel', {
items: [child1, child2]
// this way we can add different child elements to the container as container items.
});
Following is a simple example showing Ext.tab.Panel container.
<!DOCTYPE html>
<html>
<head>
<link href = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-classic/resources/theme-classic-all.css"
rel = "stylesheet" />
<script type = "text/javascript"
src = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js"></script>
<script type = "text/javascript">
Ext.onReady(function () {
Ext.create('Ext.tab.Panel', {
renderTo: Ext.getBody(),
height: 100,
width: 200,
items: [{
xtype: 'panel',
title: 'Tab One',
html: 'The first tab',
listeners: {
render: function() {
Ext.MessageBox.alert('Tab one', 'Tab One was clicked.');
}
}
},{
// xtype for all Component configurations in a Container
title: 'Tab Two',
html: 'The second tab',
listeners: {
render: function() {
Ext.MessageBox.alert('Tab two', 'Tab Two was clicked.');
}
}
}]
});
});
</script>
</head>
<body>
</body>
</html>
The above program will produce the following result −
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2115,
"s": 2023,
"text": "Ext.tab.Panel − Tab panel is like a normal panel but has support for card tab panel layout."
},
{
"code": null,
"e": 2179,
"s": 2115,
"text": "Following is a simple syntax to create Ext.tab.Panel container."
},
{
"code": null,
"e": 2331,
"s": 2179,
"text": "Ext.create('Ext.tab.Panel', {\n items: [child1, child2] \n // this way we can add different child elements to the container as container items.\n});\n"
},
{
"code": null,
"e": 2394,
"s": 2331,
"text": "Following is a simple example showing Ext.tab.Panel container."
},
{
"code": null,
"e": 3758,
"s": 2394,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <link href = \"https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-classic/resources/theme-classic-all.css\" \n rel = \"stylesheet\" />\n <script type = \"text/javascript\" \n src = \"https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js\"></script>\n \n <script type = \"text/javascript\">\n Ext.onReady(function () {\n Ext.create('Ext.tab.Panel', {\n renderTo: Ext.getBody(),\n height: 100,\n width: 200,\n \n items: [{\n xtype: 'panel',\n title: 'Tab One',\n html: 'The first tab',\n listeners: {\n render: function() {\n Ext.MessageBox.alert('Tab one', 'Tab One was clicked.');\n }\n }\n },{\n // xtype for all Component configurations in a Container\n title: 'Tab Two',\n html: 'The second tab',\n listeners: {\n render: function() {\n Ext.MessageBox.alert('Tab two', 'Tab Two was clicked.');\n }\n }\n }]\n });\n });\n </script>\n </head>\n \n <body>\n </body>\n</html>"
},
{
"code": null,
"e": 3812,
"s": 3758,
"text": "The above program will produce the following result −"
},
{
"code": null,
"e": 3819,
"s": 3812,
"text": " Print"
},
{
"code": null,
"e": 3830,
"s": 3819,
"text": " Add Notes"
}
]
|
How to replace a word inside a string in PHP ? - GeeksforGeeks | 31 May, 2020
Given a string containing some words and the task is to replace all the occurrences of a word within the given string str in PHP. In order to do this task, we have the following methods in PHP:
Method 1: Using str_replace() Method: The str_replace() method is used to replace all the occurrences of the word W1 by replacing word W2 in the given string str.
Syntax:
str_replace( $searchVal, $replaceVal, $subjectVal, $count )
Example:
PHP
<?php// PHP program to replace all occurence// of a word inside a string // Given string$str = "geeks for Geeks"; // Word to be replaced$w1 = "geeks"; // Replaced by$w2 = "GEEKS"; // Using str_replace() function // to replace the word $str = str_replace($w1, $w2, $str); // Printing the resultecho $str; ?>
GEEKS for Geeks
Method 2: Using str_ireplace() Method: The str_ireplace() method is used to replace all the occurrences of the word W1 by replacing word W2 in the given string str. The difference between str_replace() and str_ireplace() is that str_ireplace() is a case-insensitive.
Syntax:
str_ireplace( $searchVal, $replaceVal, $subjectVal, $count )
Example:
PHP
<?php// PHP program to replace // a word inside a string // Given string$str = "geeks for Geeks"; // Word to be replaced$w1 = "geeks"; // Replaced by$w2 = "GEEKS"; // Using str_ireplace() function // replace the word $str = str_ireplace($w1, $w2, $str); // Printing the resultecho $str; ?>
GEEKS for GEEKS
Method 3: Using preg_replace() Method: The preg_replace() method is used to perform a regular expression for search and replace the content.
Syntax:
preg_replace( $pattern, $replacement, $subject, $limit, $count )
Example:
PHP
<?php// PHP program to replace // a word inside a string // Given string$str = "geeks for Geeks"; // Word to be replaced$w1 = "geeks"; // Replaced by$w2 = "GEEKS"; // Using preg_replace() function // to replace the word $str = preg_replace('/bgeeksb/',$w2, $str); // Printing the resultecho $str; ?>
geeks for Geeks
PHP-string
PHP
PHP Programs
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to fetch data from localserver database and display on HTML table using PHP ?
Different ways for passing data to view in Laravel
How to create admin login page using PHP?
Create a drop-down list that options fetched from a MySQL database in PHP
How to pass form variables from one page to other page in PHP ?
How to call PHP function on the click of a Button ?
How to fetch data from localserver database and display on HTML table using PHP ?
How to create admin login page using PHP?
How to calculate the difference between two dates in PHP ?
How to pass form variables from one page to other page in PHP ? | [
{
"code": null,
"e": 24581,
"s": 24553,
"text": "\n31 May, 2020"
},
{
"code": null,
"e": 24775,
"s": 24581,
"text": "Given a string containing some words and the task is to replace all the occurrences of a word within the given string str in PHP. In order to do this task, we have the following methods in PHP:"
},
{
"code": null,
"e": 24938,
"s": 24775,
"text": "Method 1: Using str_replace() Method: The str_replace() method is used to replace all the occurrences of the word W1 by replacing word W2 in the given string str."
},
{
"code": null,
"e": 24946,
"s": 24938,
"text": "Syntax:"
},
{
"code": null,
"e": 25007,
"s": 24946,
"text": "str_replace( $searchVal, $replaceVal, $subjectVal, $count )\n"
},
{
"code": null,
"e": 25016,
"s": 25007,
"text": "Example:"
},
{
"code": null,
"e": 25020,
"s": 25016,
"text": "PHP"
},
{
"code": "<?php// PHP program to replace all occurence// of a word inside a string // Given string$str = \"geeks for Geeks\"; // Word to be replaced$w1 = \"geeks\"; // Replaced by$w2 = \"GEEKS\"; // Using str_replace() function // to replace the word $str = str_replace($w1, $w2, $str); // Printing the resultecho $str; ?>",
"e": 25338,
"s": 25020,
"text": null
},
{
"code": null,
"e": 25354,
"s": 25338,
"text": "GEEKS for Geeks"
},
{
"code": null,
"e": 25621,
"s": 25354,
"text": "Method 2: Using str_ireplace() Method: The str_ireplace() method is used to replace all the occurrences of the word W1 by replacing word W2 in the given string str. The difference between str_replace() and str_ireplace() is that str_ireplace() is a case-insensitive."
},
{
"code": null,
"e": 25629,
"s": 25621,
"text": "Syntax:"
},
{
"code": null,
"e": 25691,
"s": 25629,
"text": "str_ireplace( $searchVal, $replaceVal, $subjectVal, $count )\n"
},
{
"code": null,
"e": 25700,
"s": 25691,
"text": "Example:"
},
{
"code": null,
"e": 25704,
"s": 25700,
"text": "PHP"
},
{
"code": "<?php// PHP program to replace // a word inside a string // Given string$str = \"geeks for Geeks\"; // Word to be replaced$w1 = \"geeks\"; // Replaced by$w2 = \"GEEKS\"; // Using str_ireplace() function // replace the word $str = str_ireplace($w1, $w2, $str); // Printing the resultecho $str; ?>",
"e": 26005,
"s": 25704,
"text": null
},
{
"code": null,
"e": 26021,
"s": 26005,
"text": "GEEKS for GEEKS"
},
{
"code": null,
"e": 26162,
"s": 26021,
"text": "Method 3: Using preg_replace() Method: The preg_replace() method is used to perform a regular expression for search and replace the content."
},
{
"code": null,
"e": 26170,
"s": 26162,
"text": "Syntax:"
},
{
"code": null,
"e": 26236,
"s": 26170,
"text": "preg_replace( $pattern, $replacement, $subject, $limit, $count )\n"
},
{
"code": null,
"e": 26245,
"s": 26236,
"text": "Example:"
},
{
"code": null,
"e": 26249,
"s": 26245,
"text": "PHP"
},
{
"code": "<?php// PHP program to replace // a word inside a string // Given string$str = \"geeks for Geeks\"; // Word to be replaced$w1 = \"geeks\"; // Replaced by$w2 = \"GEEKS\"; // Using preg_replace() function // to replace the word $str = preg_replace('/bgeeksb/',$w2, $str); // Printing the resultecho $str; ?>",
"e": 26562,
"s": 26249,
"text": null
},
{
"code": null,
"e": 26578,
"s": 26562,
"text": "geeks for Geeks"
},
{
"code": null,
"e": 26589,
"s": 26578,
"text": "PHP-string"
},
{
"code": null,
"e": 26593,
"s": 26589,
"text": "PHP"
},
{
"code": null,
"e": 26606,
"s": 26593,
"text": "PHP Programs"
},
{
"code": null,
"e": 26623,
"s": 26606,
"text": "Web Technologies"
},
{
"code": null,
"e": 26650,
"s": 26623,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 26654,
"s": 26650,
"text": "PHP"
},
{
"code": null,
"e": 26752,
"s": 26654,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26761,
"s": 26752,
"text": "Comments"
},
{
"code": null,
"e": 26774,
"s": 26761,
"text": "Old Comments"
},
{
"code": null,
"e": 26856,
"s": 26774,
"text": "How to fetch data from localserver database and display on HTML table using PHP ?"
},
{
"code": null,
"e": 26907,
"s": 26856,
"text": "Different ways for passing data to view in Laravel"
},
{
"code": null,
"e": 26949,
"s": 26907,
"text": "How to create admin login page using PHP?"
},
{
"code": null,
"e": 27023,
"s": 26949,
"text": "Create a drop-down list that options fetched from a MySQL database in PHP"
},
{
"code": null,
"e": 27087,
"s": 27023,
"text": "How to pass form variables from one page to other page in PHP ?"
},
{
"code": null,
"e": 27139,
"s": 27087,
"text": "How to call PHP function on the click of a Button ?"
},
{
"code": null,
"e": 27221,
"s": 27139,
"text": "How to fetch data from localserver database and display on HTML table using PHP ?"
},
{
"code": null,
"e": 27263,
"s": 27221,
"text": "How to create admin login page using PHP?"
},
{
"code": null,
"e": 27322,
"s": 27263,
"text": "How to calculate the difference between two dates in PHP ?"
}
]
|
Java Math random() method with Examples | 08 Jun, 2022
The java.lang.Math.random() method returns a pseudorandom double type number greater than or equal to 0.0 and less than 1.0. . When this method is first called, it creates a single new pseudorandom-number generator, exactly as if by the expression new java.util.Random.
Syntax:
public static double random()
Return Type: This method returns a pseudorandom double greater than or equal to 0.0 and less than 1.0.
Example 1:To show the working of java.lang.Math.random() method.
java
// Java program to demonstrate working// of java.lang.Math.random() methodimport java.lang.Math; class Gfg1 { // driver code public static void main(String args[]) { // Generate random number double rand = Math.random(); // Output is different everytime this code is executed System.out.println("Random Number:" + rand); }}
Output:
0.5568515217910215
Example 2:To show the working of java.lang.Math.random() method.
Now to get random integer numbers from a given fixed range, we take a min and max variable to define the range for our random numbers, both min and max are inclusive in the range.
java
// Java program to demonstrate working// of java.lang.Math.random() methodimport java.lang.Math; class Gfg2 { // driver code public static void main(String args[]) { // define the range int max = 10; int min = 1; int range = max - min + 1; // generate random numbers within 1 to 10 for (int i = 0; i < 10; i++) { int rand = (int)(Math.random() * range) + min; // Output is different everytime this code is executed System.out.println(rand); } }}
Output:
6
8
10
10
5
3
6
10
4
2
ashutosh44
Java-lang package
java-math
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
Stream In Java
ArrayList in Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n08 Jun, 2022"
},
{
"code": null,
"e": 323,
"s": 52,
"text": "The java.lang.Math.random() method returns a pseudorandom double type number greater than or equal to 0.0 and less than 1.0. . When this method is first called, it creates a single new pseudorandom-number generator, exactly as if by the expression new java.util.Random. "
},
{
"code": null,
"e": 331,
"s": 323,
"text": "Syntax:"
},
{
"code": null,
"e": 361,
"s": 331,
"text": "public static double random()"
},
{
"code": null,
"e": 464,
"s": 361,
"text": "Return Type: This method returns a pseudorandom double greater than or equal to 0.0 and less than 1.0."
},
{
"code": null,
"e": 530,
"s": 464,
"text": "Example 1:To show the working of java.lang.Math.random() method. "
},
{
"code": null,
"e": 535,
"s": 530,
"text": "java"
},
{
"code": "// Java program to demonstrate working// of java.lang.Math.random() methodimport java.lang.Math; class Gfg1 { // driver code public static void main(String args[]) { // Generate random number double rand = Math.random(); // Output is different everytime this code is executed System.out.println(\"Random Number:\" + rand); }}",
"e": 901,
"s": 535,
"text": null
},
{
"code": null,
"e": 909,
"s": 901,
"text": "Output:"
},
{
"code": null,
"e": 928,
"s": 909,
"text": "0.5568515217910215"
},
{
"code": null,
"e": 994,
"s": 928,
"text": "Example 2:To show the working of java.lang.Math.random() method. "
},
{
"code": null,
"e": 1174,
"s": 994,
"text": "Now to get random integer numbers from a given fixed range, we take a min and max variable to define the range for our random numbers, both min and max are inclusive in the range."
},
{
"code": null,
"e": 1179,
"s": 1174,
"text": "java"
},
{
"code": "// Java program to demonstrate working// of java.lang.Math.random() methodimport java.lang.Math; class Gfg2 { // driver code public static void main(String args[]) { // define the range int max = 10; int min = 1; int range = max - min + 1; // generate random numbers within 1 to 10 for (int i = 0; i < 10; i++) { int rand = (int)(Math.random() * range) + min; // Output is different everytime this code is executed System.out.println(rand); } }}",
"e": 1722,
"s": 1179,
"text": null
},
{
"code": null,
"e": 1730,
"s": 1722,
"text": "Output:"
},
{
"code": null,
"e": 1753,
"s": 1730,
"text": "6\n8\n10\n10\n5\n3\n6\n10\n4\n2"
},
{
"code": null,
"e": 1764,
"s": 1753,
"text": "ashutosh44"
},
{
"code": null,
"e": 1782,
"s": 1764,
"text": "Java-lang package"
},
{
"code": null,
"e": 1792,
"s": 1782,
"text": "java-math"
},
{
"code": null,
"e": 1797,
"s": 1792,
"text": "Java"
},
{
"code": null,
"e": 1802,
"s": 1797,
"text": "Java"
},
{
"code": null,
"e": 1900,
"s": 1802,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1951,
"s": 1900,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 1982,
"s": 1951,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 2001,
"s": 1982,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 2031,
"s": 2001,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 2046,
"s": 2031,
"text": "Stream In Java"
},
{
"code": null,
"e": 2064,
"s": 2046,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 2084,
"s": 2064,
"text": "Collections in Java"
},
{
"code": null,
"e": 2108,
"s": 2084,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 2140,
"s": 2108,
"text": "Multidimensional Arrays in Java"
}
]
|
CSS | linear-gradient() Function | 01 Jul, 2022
The linear-gradient() function is an inbuilt function in CSS which is used to set the linear gradient as the background image.Syntax:
background-image: linear-gradient( direction, color1, color2, ... )
Parameters: This function accepts one direction parameter and many color parameters which are listed below:
direction: This parameter is used to define the starting point and direction along with the gradient effect.
color1, color2, ...: This parameter is used to hold the color value followed by its optional stop position.
Below examples illustrate the linear-gradient() function in CSS: Example 1:
html
<!DOCTYPE html><html> <head> <title>linear-gradient function</title> <style> .gradient { height: 100px; background-image: linear-gradient(green, yellow, blue); Text-align:center; padding-top:40px; font-size:40px; color:white; font-weight:bold; } h2 { text-align:center; } </style> </head> <body> <h2>linear-gradient: Top to Bottom property</h1> <div class="gradient">GeeksforGeeks</div> </body></html>
Output:
Example 2:
html
<!DOCTYPE html><html> <head> <title>linear-gradient function</title> <style> .gradient { height: 100px; background-image: linear-gradient(to left, green, yellow, blue); Text-align:center; padding-top:40px; font-size:40px; color:white; font-weight:bold; } h2 { text-align:center; } </style> </head> <body> <h2>linear-gradient: Right to Left property</h1> <div class="gradient">GeeksforGeeks</div> </body></html>
Output:
Supported Browser:
Google Chrome 26
Edge 12
Internet Explorer 10
Firefox 16
Opera 12.1
Safari 7
ysachin2314
geeksr3ap
CSS-Functions
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": "\n01 Jul, 2022"
},
{
"code": null,
"e": 164,
"s": 28,
"text": "The linear-gradient() function is an inbuilt function in CSS which is used to set the linear gradient as the background image.Syntax: "
},
{
"code": null,
"e": 232,
"s": 164,
"text": "background-image: linear-gradient( direction, color1, color2, ... )"
},
{
"code": null,
"e": 342,
"s": 232,
"text": "Parameters: This function accepts one direction parameter and many color parameters which are listed below: "
},
{
"code": null,
"e": 451,
"s": 342,
"text": "direction: This parameter is used to define the starting point and direction along with the gradient effect."
},
{
"code": null,
"e": 559,
"s": 451,
"text": "color1, color2, ...: This parameter is used to hold the color value followed by its optional stop position."
},
{
"code": null,
"e": 637,
"s": 559,
"text": "Below examples illustrate the linear-gradient() function in CSS: Example 1: "
},
{
"code": null,
"e": 642,
"s": 637,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>linear-gradient function</title> <style> .gradient { height: 100px; background-image: linear-gradient(green, yellow, blue); Text-align:center; padding-top:40px; font-size:40px; color:white; font-weight:bold; } h2 { text-align:center; } </style> </head> <body> <h2>linear-gradient: Top to Bottom property</h1> <div class=\"gradient\">GeeksforGeeks</div> </body></html>",
"e": 1207,
"s": 642,
"text": null
},
{
"code": null,
"e": 1217,
"s": 1207,
"text": "Output: "
},
{
"code": null,
"e": 1230,
"s": 1217,
"text": "Example 2: "
},
{
"code": null,
"e": 1235,
"s": 1230,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>linear-gradient function</title> <style> .gradient { height: 100px; background-image: linear-gradient(to left, green, yellow, blue); Text-align:center; padding-top:40px; font-size:40px; color:white; font-weight:bold; } h2 { text-align:center; } </style> </head> <body> <h2>linear-gradient: Right to Left property</h1> <div class=\"gradient\">GeeksforGeeks</div> </body></html>",
"e": 1809,
"s": 1235,
"text": null
},
{
"code": null,
"e": 1819,
"s": 1809,
"text": "Output: "
},
{
"code": null,
"e": 1838,
"s": 1819,
"text": "Supported Browser:"
},
{
"code": null,
"e": 1855,
"s": 1838,
"text": "Google Chrome 26"
},
{
"code": null,
"e": 1863,
"s": 1855,
"text": "Edge 12"
},
{
"code": null,
"e": 1884,
"s": 1863,
"text": "Internet Explorer 10"
},
{
"code": null,
"e": 1895,
"s": 1884,
"text": "Firefox 16"
},
{
"code": null,
"e": 1906,
"s": 1895,
"text": "Opera 12.1"
},
{
"code": null,
"e": 1916,
"s": 1906,
"text": "Safari 7 "
},
{
"code": null,
"e": 1928,
"s": 1916,
"text": "ysachin2314"
},
{
"code": null,
"e": 1938,
"s": 1928,
"text": "geeksr3ap"
},
{
"code": null,
"e": 1952,
"s": 1938,
"text": "CSS-Functions"
},
{
"code": null,
"e": 1956,
"s": 1952,
"text": "CSS"
},
{
"code": null,
"e": 1961,
"s": 1956,
"text": "HTML"
},
{
"code": null,
"e": 1978,
"s": 1961,
"text": "Web Technologies"
},
{
"code": null,
"e": 1983,
"s": 1978,
"text": "HTML"
}
]
|
Find value of (1^n + 2^n + 3^n + 4^n ) mod 5 | 07 Apr, 2021
You are given an positive integer n. You have to find the value of (1n +2n + 3n + 4n ) mod 5. Note : Value of n may be very large of order 1015. Examples:
Input : n = 4
Output : 4
Explanation : (14 + 24 + 34 + 44)mod 5 = (1+16+81+256)mod 5 = 354 mod 5 = 4
Input : n = 2
Output : 0
Explanation : (12 + 22 + 32 + 42)mod 5 = (1+4+9+16)mod 5 = 30 mod 5 = 0
Basic Approach : If you will solve this question with a very basic approach of finding value of (1n +2n + 3n + 4n ) and then finding its modulo value for 5, you will certainly get your answer but for the larger value of n we must got wrong answer as you will be unable to store value of (1n +2n + 3n + 4n ) properly. Better and Proper Approach : Before proceeding to solution lets go through some of periodical properties of power of 2, 3 & 4.
f(n) = 2n is periodical for n = 4 in terms of last digit. i.e. last digit of 2n always repeat for next 4th value of n. (ex: 2, 4, 8, 16, 32, 64...)
f(n) = 3n is periodical for n = 4 in terms of last digit. i.e. last digit of 3n always repeat for next 4th value of n.(ex: 3, 9, 27, 81, 243, 729...)
f(n) = 4n is periodical for n = 2 in terms of last digit. i.e. last digit of 4n always repeat for next 2nd value of n.(ex: 4, 16, 64, 256..)
1n is going to be 1 always, independent of n.
So, If we will have a close look for periodicity of f(n) = (1n +2n + 3n + 4n ) we will get that its periodicity is also 4 and its last digits occurs as :
for n = 1, f(n) = 10
for n = 2, f(n) = 30
for n = 3, f(n) = 100
for n = 4, f(n) = 354
for n = 5, f(n) = 1300
Observing above periodicity we can see that if (n%4==0) result of f(n)%5 is going to be 4 other wise result = 0. So, rather than calculating actual value of f(n) and then obtaining its value with mod 5 we can easily get result only be examine value of n.
C++
Java
Python
C#
PHP
Javascript
// Program to find value of f(n)%5#include <bits/stdc++.h>using namespace std; // function for obtaining remainderint fnMod(int n){ // calculate res based on value of n return (n % 4) ? 0 : 4;} // driver programint main(){ int n = 43; cout << fnMod(n) << endl; n = 44; cout << fnMod(n); return 0;}
// Program to find value of f(n)% 5 class GFG{ // function for obtaining remainder static int fnMod(int n) { // calculate res based on value of n return (n % 4 != 0) ? 0 : 4; } // Driver code public static void main (String[] args) { int n = 43; System.out.println(fnMod(n)); n = 44; System.out.print(fnMod(n)); }} // This code is contributed by Anant Agarwal.
# program to find f(n) mod 5def fnMod (n): res = 4 if (n % 4 == 0) else 0 return res # driver sectionn = 43print (fnMod(n))n = 44print (fnMod(n))
// C# Program to find value of f(n) % 5using System; class GFG { // function for obtaining remainder static int fnMod(int n) { // calculate res based on value of n return (n % 4 != 0) ? 0 : 4; } // Driver code public static void Main () { int n = 43; Console.WriteLine(fnMod(n)); n = 44; Console.Write(fnMod(n)); }} // This code is contributed by nitin mittal.
<?php// PHP Program to find value of f(n)%5 // function for obtaining remainderfunction fnMod($n){ // calculate res based // on value of n return ($n % 4) ? 0 : 4;} // Driver Code{ $n = 43; echo fnMod($n),"\n" ; $n = 44; echo fnMod($n); return 0;} // This code is contributed by nitin mittal.?>
<script>// JavaScript program to find value of f(n)% 5 // function for obtaining remainder function fnMod(n) { // calculate res based on value of n return (n % 4 != 0) ? 0 : 4; } // Driver Code let n = 43; document.write(fnMod(n) + "<br/>"); n = 44; document.write(fnMod(n) + "<br/>"); // This code is contributed by splevel62.</script>
0
4
nitin mittal
splevel62
series
Mathematical
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Operators in C / C++
Prime Numbers
Find minimum number of coins that make a given value
Minimum number of jumps to reach end
Algorithm to solve Rubik's Cube
Modulo 10^9+7 (1000000007)
The Knight's tour problem | Backtracking-1
Program for Decimal to Binary Conversion
Modulo Operator (%) in C/C++ with Examples | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Apr, 2021"
},
{
"code": null,
"e": 185,
"s": 28,
"text": "You are given an positive integer n. You have to find the value of (1n +2n + 3n + 4n ) mod 5. Note : Value of n may be very large of order 1015. Examples: "
},
{
"code": null,
"e": 384,
"s": 185,
"text": "Input : n = 4\nOutput : 4\nExplanation : (14 + 24 + 34 + 44)mod 5 = (1+16+81+256)mod 5 = 354 mod 5 = 4\n\nInput : n = 2\nOutput : 0\nExplanation : (12 + 22 + 32 + 42)mod 5 = (1+4+9+16)mod 5 = 30 mod 5 = 0"
},
{
"code": null,
"e": 832,
"s": 386,
"text": "Basic Approach : If you will solve this question with a very basic approach of finding value of (1n +2n + 3n + 4n ) and then finding its modulo value for 5, you will certainly get your answer but for the larger value of n we must got wrong answer as you will be unable to store value of (1n +2n + 3n + 4n ) properly. Better and Proper Approach : Before proceeding to solution lets go through some of periodical properties of power of 2, 3 & 4. "
},
{
"code": null,
"e": 980,
"s": 832,
"text": "f(n) = 2n is periodical for n = 4 in terms of last digit. i.e. last digit of 2n always repeat for next 4th value of n. (ex: 2, 4, 8, 16, 32, 64...)"
},
{
"code": null,
"e": 1130,
"s": 980,
"text": "f(n) = 3n is periodical for n = 4 in terms of last digit. i.e. last digit of 3n always repeat for next 4th value of n.(ex: 3, 9, 27, 81, 243, 729...)"
},
{
"code": null,
"e": 1271,
"s": 1130,
"text": "f(n) = 4n is periodical for n = 2 in terms of last digit. i.e. last digit of 4n always repeat for next 2nd value of n.(ex: 4, 16, 64, 256..)"
},
{
"code": null,
"e": 1317,
"s": 1271,
"text": "1n is going to be 1 always, independent of n."
},
{
"code": null,
"e": 1473,
"s": 1317,
"text": "So, If we will have a close look for periodicity of f(n) = (1n +2n + 3n + 4n ) we will get that its periodicity is also 4 and its last digits occurs as : "
},
{
"code": null,
"e": 1494,
"s": 1473,
"text": "for n = 1, f(n) = 10"
},
{
"code": null,
"e": 1515,
"s": 1494,
"text": "for n = 2, f(n) = 30"
},
{
"code": null,
"e": 1537,
"s": 1515,
"text": "for n = 3, f(n) = 100"
},
{
"code": null,
"e": 1559,
"s": 1537,
"text": "for n = 4, f(n) = 354"
},
{
"code": null,
"e": 1582,
"s": 1559,
"text": "for n = 5, f(n) = 1300"
},
{
"code": null,
"e": 1839,
"s": 1582,
"text": "Observing above periodicity we can see that if (n%4==0) result of f(n)%5 is going to be 4 other wise result = 0. So, rather than calculating actual value of f(n) and then obtaining its value with mod 5 we can easily get result only be examine value of n. "
},
{
"code": null,
"e": 1843,
"s": 1839,
"text": "C++"
},
{
"code": null,
"e": 1848,
"s": 1843,
"text": "Java"
},
{
"code": null,
"e": 1855,
"s": 1848,
"text": "Python"
},
{
"code": null,
"e": 1858,
"s": 1855,
"text": "C#"
},
{
"code": null,
"e": 1862,
"s": 1858,
"text": "PHP"
},
{
"code": null,
"e": 1873,
"s": 1862,
"text": "Javascript"
},
{
"code": "// Program to find value of f(n)%5#include <bits/stdc++.h>using namespace std; // function for obtaining remainderint fnMod(int n){ // calculate res based on value of n return (n % 4) ? 0 : 4;} // driver programint main(){ int n = 43; cout << fnMod(n) << endl; n = 44; cout << fnMod(n); return 0;}",
"e": 2192,
"s": 1873,
"text": null
},
{
"code": "// Program to find value of f(n)% 5 class GFG{ // function for obtaining remainder static int fnMod(int n) { // calculate res based on value of n return (n % 4 != 0) ? 0 : 4; } // Driver code public static void main (String[] args) { int n = 43; System.out.println(fnMod(n)); n = 44; System.out.print(fnMod(n)); }} // This code is contributed by Anant Agarwal.",
"e": 2624,
"s": 2192,
"text": null
},
{
"code": "# program to find f(n) mod 5def fnMod (n): res = 4 if (n % 4 == 0) else 0 return res # driver sectionn = 43print (fnMod(n))n = 44print (fnMod(n))",
"e": 2776,
"s": 2624,
"text": null
},
{
"code": "// C# Program to find value of f(n) % 5using System; class GFG { // function for obtaining remainder static int fnMod(int n) { // calculate res based on value of n return (n % 4 != 0) ? 0 : 4; } // Driver code public static void Main () { int n = 43; Console.WriteLine(fnMod(n)); n = 44; Console.Write(fnMod(n)); }} // This code is contributed by nitin mittal.",
"e": 3213,
"s": 2776,
"text": null
},
{
"code": "<?php// PHP Program to find value of f(n)%5 // function for obtaining remainderfunction fnMod($n){ // calculate res based // on value of n return ($n % 4) ? 0 : 4;} // Driver Code{ $n = 43; echo fnMod($n),\"\\n\" ; $n = 44; echo fnMod($n); return 0;} // This code is contributed by nitin mittal.?>",
"e": 3537,
"s": 3213,
"text": null
},
{
"code": "<script>// JavaScript program to find value of f(n)% 5 // function for obtaining remainder function fnMod(n) { // calculate res based on value of n return (n % 4 != 0) ? 0 : 4; } // Driver Code let n = 43; document.write(fnMod(n) + \"<br/>\"); n = 44; document.write(fnMod(n) + \"<br/>\"); // This code is contributed by splevel62.</script>",
"e": 3930,
"s": 3537,
"text": null
},
{
"code": null,
"e": 3934,
"s": 3930,
"text": "0\n4"
},
{
"code": null,
"e": 3949,
"s": 3936,
"text": "nitin mittal"
},
{
"code": null,
"e": 3959,
"s": 3949,
"text": "splevel62"
},
{
"code": null,
"e": 3966,
"s": 3959,
"text": "series"
},
{
"code": null,
"e": 3979,
"s": 3966,
"text": "Mathematical"
},
{
"code": null,
"e": 3992,
"s": 3979,
"text": "Mathematical"
},
{
"code": null,
"e": 3999,
"s": 3992,
"text": "series"
},
{
"code": null,
"e": 4097,
"s": 3999,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4121,
"s": 4097,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 4142,
"s": 4121,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 4156,
"s": 4142,
"text": "Prime Numbers"
},
{
"code": null,
"e": 4209,
"s": 4156,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 4246,
"s": 4209,
"text": "Minimum number of jumps to reach end"
},
{
"code": null,
"e": 4278,
"s": 4246,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 4305,
"s": 4278,
"text": "Modulo 10^9+7 (1000000007)"
},
{
"code": null,
"e": 4348,
"s": 4305,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 4389,
"s": 4348,
"text": "Program for Decimal to Binary Conversion"
}
]
|
Constructor Overloading in C++ | 28 Jun, 2021
Prerequisites: Constructors in C++ In C++, We can have more than one constructor in a class with same name, as long as each has a different list of arguments.This concept is known as Constructor Overloading and is quite similar to function overloading.
Overloaded constructors essentially have the same name (exact name of the class) and differ by number and type of arguments.
A constructor is called depending upon the number and type of arguments passed.
While creating the object, arguments must be passed to let compiler know, which constructor needs to be called.
CPP
// C++ program to illustrate// Constructor overloading#include <iostream>using namespace std; class construct{ public: float area; // Constructor with no parameters construct() { area = 0; } // Constructor with two parameters construct(int a, int b) { area = a * b; } void disp() { cout<< area<< endl; }}; int main(){ // Constructor Overloading // with two different constructors // of class name construct o; construct o2( 10, 20); o.disp(); o2.disp(); return 1;}
Output:
0
200
Related Articles :
Destructors in C++
quiz on constructors in C++
Output of C++ programs | Set 26 (Constructors)
Output of C++ programs | Set 27(Constructors and Destructors)
This article is contributed by I.HARISH 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 [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
utkarshgupta04092003
cpp-constructor
cpp-overloading
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Set in C++ Standard Template Library (STL)
Priority Queue in C++ Standard Template Library (STL)
vector erase() and clear() in C++
Substring in C++
unordered_map in C++ STL
C++ Classes and Objects
Sorting a vector in C++
2D Vector In C++ With User Defined Size
C++ Data Types
Templates in C++ with Examples | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 308,
"s": 53,
"text": "Prerequisites: Constructors in C++ In C++, We can have more than one constructor in a class with same name, as long as each has a different list of arguments.This concept is known as Constructor Overloading and is quite similar to function overloading. "
},
{
"code": null,
"e": 433,
"s": 308,
"text": "Overloaded constructors essentially have the same name (exact name of the class) and differ by number and type of arguments."
},
{
"code": null,
"e": 513,
"s": 433,
"text": "A constructor is called depending upon the number and type of arguments passed."
},
{
"code": null,
"e": 627,
"s": 513,
"text": "While creating the object, arguments must be passed to let compiler know, which constructor needs to be called. "
},
{
"code": null,
"e": 633,
"s": 629,
"text": "CPP"
},
{
"code": "// C++ program to illustrate// Constructor overloading#include <iostream>using namespace std; class construct{ public: float area; // Constructor with no parameters construct() { area = 0; } // Constructor with two parameters construct(int a, int b) { area = a * b; } void disp() { cout<< area<< endl; }}; int main(){ // Constructor Overloading // with two different constructors // of class name construct o; construct o2( 10, 20); o.disp(); o2.disp(); return 1;}",
"e": 1199,
"s": 633,
"text": null
},
{
"code": null,
"e": 1208,
"s": 1199,
"text": "Output: "
},
{
"code": null,
"e": 1216,
"s": 1208,
"text": "0\n200\n "
},
{
"code": null,
"e": 1237,
"s": 1216,
"text": "Related Articles : "
},
{
"code": null,
"e": 1256,
"s": 1237,
"text": "Destructors in C++"
},
{
"code": null,
"e": 1284,
"s": 1256,
"text": "quiz on constructors in C++"
},
{
"code": null,
"e": 1331,
"s": 1284,
"text": "Output of C++ programs | Set 26 (Constructors)"
},
{
"code": null,
"e": 1393,
"s": 1331,
"text": "Output of C++ programs | Set 27(Constructors and Destructors)"
},
{
"code": null,
"e": 1816,
"s": 1393,
"text": "This article is contributed by I.HARISH 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 [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 1837,
"s": 1816,
"text": "utkarshgupta04092003"
},
{
"code": null,
"e": 1853,
"s": 1837,
"text": "cpp-constructor"
},
{
"code": null,
"e": 1869,
"s": 1853,
"text": "cpp-overloading"
},
{
"code": null,
"e": 1873,
"s": 1869,
"text": "C++"
},
{
"code": null,
"e": 1877,
"s": 1873,
"text": "CPP"
},
{
"code": null,
"e": 1975,
"s": 1877,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2018,
"s": 1975,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 2072,
"s": 2018,
"text": "Priority Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 2106,
"s": 2072,
"text": "vector erase() and clear() in C++"
},
{
"code": null,
"e": 2123,
"s": 2106,
"text": "Substring in C++"
},
{
"code": null,
"e": 2148,
"s": 2123,
"text": "unordered_map in C++ STL"
},
{
"code": null,
"e": 2172,
"s": 2148,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 2196,
"s": 2172,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 2236,
"s": 2196,
"text": "2D Vector In C++ With User Defined Size"
},
{
"code": null,
"e": 2251,
"s": 2236,
"text": "C++ Data Types"
}
]
|
EditText in Android using Jetpack Compose | 25 Feb, 2021
EditText is one of the most important widget which is seen in most of the apps. This widget is generally use to get the data from users. Users can directly communicate with the app using this widget. This widget is used to get the data from user in the form of numbers, text or any other text. In this article we will take a look at the implementation of the EditText widget in Android using Jetpack Compose.
Attributes
Description
if the text field is empty we are displaying a hint to the user what he
has to enter in the text field.
keyboardOptions is used to add capitalization in the data which is entered by
user in text field, we can also specify auto correction option in this. We can specify
the type of keyboard which we have to display such as (phone, text) and to display
actions which can be performed from the keyboard itself.
active color is use to when user has click on edit text or the text field is focused and
entering some data in the text field.
This method is use to add leading icon to our text input field. With this method
we can also specify color(tint) for our icon.
This method is use to add trailing icon to our text input field. With this method
we can also specify color(tint) for our icon.
Step 1: Create a New Project
To create a new project in the Android Studio Canary Version please refer to How to Create a new Project in Android Studio Canary Version with Jetpack Compose.
Step 2: Adding EditText in MainActivity.kt file
Navigate to the app > java > your app’s package name and open the MainActivity.kt file. Inside that file add the below code to it. Comments are added inside the code to understand the code in more detail.
Kotlin
package com.example.gfgapp import android.graphics.drawable.shapes.Shapeimport android.media.Imageimport android.os.Bundleimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivityimport androidx.compose.foundation.BorderStrokeimport androidx.compose.foundation.Imageimport androidx.compose.foundation.Textimport androidx.compose.foundation.layout.*import androidx.compose.foundation.shape.RoundedCornerShapeimport androidx.compose.foundation.text.KeyboardOptionsimport androidx.compose.material.*import androidx.compose.material.icons.Iconsimport androidx.compose.material.icons.filled.AccountCircleimport androidx.compose.material.icons.filled.Infoimport androidx.compose.material.icons.filled.Phoneimport androidx.compose.runtime.*import androidx.compose.runtime.savedinstancestate.savedInstanceStateimport androidx.compose.ui.Alignmentimport androidx.compose.ui.layout.ContentScaleimport androidx.compose.ui.platform.setContentimport androidx.compose.ui.res.imageResourceimport androidx.compose.ui.tooling.preview.Previewimport androidx.compose.ui.unit.dpimport com.example.gfgapp.ui.GFGAppThemeimport androidx.compose.ui.Modifierimport androidx.compose.ui.draw.clipimport androidx.compose.ui.graphics.Colorimport androidx.compose.ui.graphics.SolidColorimport androidx.compose.ui.platform.ContextAmbientimport androidx.compose.ui.res.colorResourceimport androidx.compose.ui.text.TextStyleimport androidx.compose.ui.text.font.FontFamilyimport androidx.compose.ui.text.input.*import androidx.compose.ui.unit.Dpimport androidx.compose.ui.unit.TextUnit class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { GFGAppTheme { // A surface container using the // 'background' color from the theme Surface(color = MaterialTheme.colors.background) { // at below line we are calling // our function for text field. TxtField(); } } } }} @Composablefun TxtField() { // we are creating a variable for // getting a value of our text field. val inputvalue = remember { mutableStateOf(TextFieldValue()) } Column( // we are using column to align our // imageview to center of the screen. modifier = Modifier.fillMaxWidth().fillMaxHeight(), // below line is used for specifying // vertical arrangement. verticalArrangement = Arrangement.Center, // below line is used for specifying // horizontal arrangement. horizontalAlignment = Alignment.CenterHorizontally, ) { TextField( // below line is used to get // value of text field, value = inputvalue.value, // below line is used to get value in text field // on value change in text field. onValueChange = { inputvalue.value = it }, // below line is used to add placeholder // for our text field. placeholder = { Text(text = "Enter user name") }, // modifier is use to add padding // to our text field. modifier = Modifier.padding(all = 16.dp).fillMaxWidth(), // keyboard options is used to modify // the keyboard for text field. keyboardOptions = KeyboardOptions( // below line is use for capitalization // inside our text field. capitalization = KeyboardCapitalization.None, // below line is to enable auto // correct in our keyboard. autoCorrect = true, // below line is used to specify our // type of keyboard such as text, number, phone. keyboardType = KeyboardType.Text, ), // below line is use to specify // styling for our text field value. textStyle = TextStyle(color = Color.Black, // below line is used to add font // size for our text field fontSize = TextUnit.Companion.Sp(value = 15), // below line is use to change font family. fontFamily = FontFamily.SansSerif), // below line is use to give // max lines for our text field. maxLines = 2, // active color is use to change // color when text field is focused. activeColor = colorResource(id = R.color.purple_200), // single line boolean is use to avoid // textfield entering in multiple lines. singleLine = true, // inactive color is use to change // color when text field is not focused. inactiveColor = Color.Gray, // below line is use to specify background // color for our text field. backgroundColor = Color.LightGray, // leading icon is use to add icon // at the start of text field. leadingIcon = { // In this method we are specifying // our leading icon and its color. Icon(Icons.Filled.AccountCircle, tint = colorResource(id = R.color.purple_200)) }, // trailing icons is use to add // icon to the end of tet field. trailingIcon = { Icon(Icons.Filled.Info, tint = colorResource(id = R.color.purple_200)) }, ) }} // @Preview function is use to see preview// for our composable function in preview section@Preview(showBackground = true)@Composablefun DefaultPreview() { GFGAppTheme { TxtField() }}
Android-Jetpack
Technical Scripter 2020
Android
Kotlin
Technical Scripter
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 RecyclerView in Kotlin
Broadcast Receiver in Android With Example
Android SDK and it's Components
Flutter - Custom Bottom Navigation Bar
How to Add Views Dynamically and Store Data in Arraylist in Android?
Android UI Layouts
Android RecyclerView in Kotlin
Broadcast Receiver in Android With Example | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 Feb, 2021"
},
{
"code": null,
"e": 438,
"s": 28,
"text": "EditText is one of the most important widget which is seen in most of the apps. This widget is generally use to get the data from users. Users can directly communicate with the app using this widget. This widget is used to get the data from user in the form of numbers, text or any other text. In this article we will take a look at the implementation of the EditText widget in Android using Jetpack Compose. "
},
{
"code": null,
"e": 450,
"s": 438,
"text": "Attributes "
},
{
"code": null,
"e": 462,
"s": 450,
"text": "Description"
},
{
"code": null,
"e": 535,
"s": 462,
"text": "if the text field is empty we are displaying a hint to the user what he "
},
{
"code": null,
"e": 568,
"s": 535,
"text": "has to enter in the text field. "
},
{
"code": null,
"e": 647,
"s": 568,
"text": "keyboardOptions is used to add capitalization in the data which is entered by "
},
{
"code": null,
"e": 735,
"s": 647,
"text": "user in text field, we can also specify auto correction option in this. We can specify "
},
{
"code": null,
"e": 818,
"s": 735,
"text": "the type of keyboard which we have to display such as (phone, text) and to display"
},
{
"code": null,
"e": 876,
"s": 818,
"text": "actions which can be performed from the keyboard itself. "
},
{
"code": null,
"e": 966,
"s": 876,
"text": "active color is use to when user has click on edit text or the text field is focused and "
},
{
"code": null,
"e": 1005,
"s": 966,
"text": "entering some data in the text field. "
},
{
"code": null,
"e": 1086,
"s": 1005,
"text": "This method is use to add leading icon to our text input field. With this method"
},
{
"code": null,
"e": 1132,
"s": 1086,
"text": "we can also specify color(tint) for our icon."
},
{
"code": null,
"e": 1215,
"s": 1132,
"text": "This method is use to add trailing icon to our text input field. With this method "
},
{
"code": null,
"e": 1261,
"s": 1215,
"text": "we can also specify color(tint) for our icon."
},
{
"code": null,
"e": 1290,
"s": 1261,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 1450,
"s": 1290,
"text": "To create a new project in the Android Studio Canary Version please refer to How to Create a new Project in Android Studio Canary Version with Jetpack Compose."
},
{
"code": null,
"e": 1498,
"s": 1450,
"text": "Step 2: Adding EditText in MainActivity.kt file"
},
{
"code": null,
"e": 1703,
"s": 1498,
"text": "Navigate to the app > java > your app’s package name and open the MainActivity.kt file. Inside that file add the below code to it. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 1710,
"s": 1703,
"text": "Kotlin"
},
{
"code": "package com.example.gfgapp import android.graphics.drawable.shapes.Shapeimport android.media.Imageimport android.os.Bundleimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivityimport androidx.compose.foundation.BorderStrokeimport androidx.compose.foundation.Imageimport androidx.compose.foundation.Textimport androidx.compose.foundation.layout.*import androidx.compose.foundation.shape.RoundedCornerShapeimport androidx.compose.foundation.text.KeyboardOptionsimport androidx.compose.material.*import androidx.compose.material.icons.Iconsimport androidx.compose.material.icons.filled.AccountCircleimport androidx.compose.material.icons.filled.Infoimport androidx.compose.material.icons.filled.Phoneimport androidx.compose.runtime.*import androidx.compose.runtime.savedinstancestate.savedInstanceStateimport androidx.compose.ui.Alignmentimport androidx.compose.ui.layout.ContentScaleimport androidx.compose.ui.platform.setContentimport androidx.compose.ui.res.imageResourceimport androidx.compose.ui.tooling.preview.Previewimport androidx.compose.ui.unit.dpimport com.example.gfgapp.ui.GFGAppThemeimport androidx.compose.ui.Modifierimport androidx.compose.ui.draw.clipimport androidx.compose.ui.graphics.Colorimport androidx.compose.ui.graphics.SolidColorimport androidx.compose.ui.platform.ContextAmbientimport androidx.compose.ui.res.colorResourceimport androidx.compose.ui.text.TextStyleimport androidx.compose.ui.text.font.FontFamilyimport androidx.compose.ui.text.input.*import androidx.compose.ui.unit.Dpimport androidx.compose.ui.unit.TextUnit class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { GFGAppTheme { // A surface container using the // 'background' color from the theme Surface(color = MaterialTheme.colors.background) { // at below line we are calling // our function for text field. TxtField(); } } } }} @Composablefun TxtField() { // we are creating a variable for // getting a value of our text field. val inputvalue = remember { mutableStateOf(TextFieldValue()) } Column( // we are using column to align our // imageview to center of the screen. modifier = Modifier.fillMaxWidth().fillMaxHeight(), // below line is used for specifying // vertical arrangement. verticalArrangement = Arrangement.Center, // below line is used for specifying // horizontal arrangement. horizontalAlignment = Alignment.CenterHorizontally, ) { TextField( // below line is used to get // value of text field, value = inputvalue.value, // below line is used to get value in text field // on value change in text field. onValueChange = { inputvalue.value = it }, // below line is used to add placeholder // for our text field. placeholder = { Text(text = \"Enter user name\") }, // modifier is use to add padding // to our text field. modifier = Modifier.padding(all = 16.dp).fillMaxWidth(), // keyboard options is used to modify // the keyboard for text field. keyboardOptions = KeyboardOptions( // below line is use for capitalization // inside our text field. capitalization = KeyboardCapitalization.None, // below line is to enable auto // correct in our keyboard. autoCorrect = true, // below line is used to specify our // type of keyboard such as text, number, phone. keyboardType = KeyboardType.Text, ), // below line is use to specify // styling for our text field value. textStyle = TextStyle(color = Color.Black, // below line is used to add font // size for our text field fontSize = TextUnit.Companion.Sp(value = 15), // below line is use to change font family. fontFamily = FontFamily.SansSerif), // below line is use to give // max lines for our text field. maxLines = 2, // active color is use to change // color when text field is focused. activeColor = colorResource(id = R.color.purple_200), // single line boolean is use to avoid // textfield entering in multiple lines. singleLine = true, // inactive color is use to change // color when text field is not focused. inactiveColor = Color.Gray, // below line is use to specify background // color for our text field. backgroundColor = Color.LightGray, // leading icon is use to add icon // at the start of text field. leadingIcon = { // In this method we are specifying // our leading icon and its color. Icon(Icons.Filled.AccountCircle, tint = colorResource(id = R.color.purple_200)) }, // trailing icons is use to add // icon to the end of tet field. trailingIcon = { Icon(Icons.Filled.Info, tint = colorResource(id = R.color.purple_200)) }, ) }} // @Preview function is use to see preview// for our composable function in preview section@Preview(showBackground = true)@Composablefun DefaultPreview() { GFGAppTheme { TxtField() }}",
"e": 8081,
"s": 1710,
"text": null
},
{
"code": null,
"e": 8097,
"s": 8081,
"text": "Android-Jetpack"
},
{
"code": null,
"e": 8121,
"s": 8097,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 8129,
"s": 8121,
"text": "Android"
},
{
"code": null,
"e": 8136,
"s": 8129,
"text": "Kotlin"
},
{
"code": null,
"e": 8155,
"s": 8136,
"text": "Technical Scripter"
},
{
"code": null,
"e": 8163,
"s": 8155,
"text": "Android"
},
{
"code": null,
"e": 8261,
"s": 8163,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8330,
"s": 8261,
"text": "How to Add Views Dynamically and Store Data in Arraylist in Android?"
},
{
"code": null,
"e": 8361,
"s": 8330,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 8404,
"s": 8361,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 8436,
"s": 8404,
"text": "Android SDK and it's Components"
},
{
"code": null,
"e": 8475,
"s": 8436,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 8544,
"s": 8475,
"text": "How to Add Views Dynamically and Store Data in Arraylist in Android?"
},
{
"code": null,
"e": 8563,
"s": 8544,
"text": "Android UI Layouts"
},
{
"code": null,
"e": 8594,
"s": 8563,
"text": "Android RecyclerView in Kotlin"
}
]
|
C++ Program to Check the Connectivity of Directed Graph Using DFS | To check connectivity of a graph, we will try to traverse all nodes using any traversal algorithm. After completing the traversal, if there is any node, which is not visited, then the graph is not connected.
For the directed graph, we will start traversing from all nodes to check connectivity. Sometimes one edge can have only outward edge but no inward edge, so that node will be unvisited from any other starting node.
In this case the traversal algorithm is recursive DFS traversal.
Input: Adjacency matrix of a graph
Output: The Graph is connected.
Input: The start node u and the visited node to mark which node is visited.
Output: Traverse all connected vertices.
Begin
mark u as visited
for all vertex v, if it is adjacent with u, do
if v is not visited, then
traverse(v, visited)
done
End
Input: The graph.
Output: True if the graph is connected.
Begin
define visited array
for all vertices u in the graph, do
make all nodes unvisited
traverse(u, visited)
if any unvisited node is still remaining, then
return false
done
return true
End
#include<iostream>
#define NODE 5
using namespace std;
int graph[NODE][NODE] = {{0, 1, 0, 0, 0},
{0, 0, 1, 0, 0},
{0, 0, 0, 1, 1},
{1, 0, 0, 0, 0},
{0, 1, 0, 0, 0}};
void traverse(int u, bool visited[]) {
visited[u] = true; //mark v as visited
for(int v = 0; v<NODE; v++) {
if(graph[u][v]) {
if(!visited[v])
traverse(v, visited);
}
}
}
bool isConnected() {
bool *vis = new bool[NODE];
//for all vertex u as start point, check whether all nodes are visible or not
for(int u; u < NODE; u++) {
for(int i = 0; i<NODE; i++)
vis[i] = false; //initialize as no node is visited
traverse(u, vis);
for(int i = 0; i<NODE; i++) {
if(!vis[i]) //if there is a node, not visited by traversal, graph is not connected
return false;
}
}
return true;
}
int main() {
if(isConnected())
cout << "The Graph is connected.";
else
cout << "The Graph is not connected.";
}
The Graph is connected. | [
{
"code": null,
"e": 1270,
"s": 1062,
"text": "To check connectivity of a graph, we will try to traverse all nodes using any traversal algorithm. After completing the traversal, if there is any node, which is not visited, then the graph is not connected."
},
{
"code": null,
"e": 1484,
"s": 1270,
"text": "For the directed graph, we will start traversing from all nodes to check connectivity. Sometimes one edge can have only outward edge but no inward edge, so that node will be unvisited from any other starting node."
},
{
"code": null,
"e": 1549,
"s": 1484,
"text": "In this case the traversal algorithm is recursive DFS traversal."
},
{
"code": null,
"e": 1584,
"s": 1549,
"text": "Input: Adjacency matrix of a graph"
},
{
"code": null,
"e": 1616,
"s": 1584,
"text": "Output: The Graph is connected."
},
{
"code": null,
"e": 1692,
"s": 1616,
"text": "Input: The start node u and the visited node to mark which node is visited."
},
{
"code": null,
"e": 1733,
"s": 1692,
"text": "Output: Traverse all connected vertices."
},
{
"code": null,
"e": 1884,
"s": 1733,
"text": "Begin\n mark u as visited\n for all vertex v, if it is adjacent with u, do\n if v is not visited, then\n traverse(v, visited)\n done\nEnd"
},
{
"code": null,
"e": 1902,
"s": 1884,
"text": "Input: The graph."
},
{
"code": null,
"e": 1942,
"s": 1902,
"text": "Output: True if the graph is connected."
},
{
"code": null,
"e": 2171,
"s": 1942,
"text": "Begin\n define visited array\n for all vertices u in the graph, do\n make all nodes unvisited\n traverse(u, visited)\n if any unvisited node is still remaining, then\n return false\n done\n return true\nEnd"
},
{
"code": null,
"e": 3189,
"s": 2171,
"text": "#include<iostream>\n#define NODE 5\nusing namespace std;\nint graph[NODE][NODE] = {{0, 1, 0, 0, 0},\n {0, 0, 1, 0, 0},\n {0, 0, 0, 1, 1},\n {1, 0, 0, 0, 0},\n {0, 1, 0, 0, 0}};\nvoid traverse(int u, bool visited[]) {\n visited[u] = true; //mark v as visited\n for(int v = 0; v<NODE; v++) {\n if(graph[u][v]) {\n if(!visited[v])\n traverse(v, visited);\n }\n }\n}\nbool isConnected() {\n bool *vis = new bool[NODE];\n //for all vertex u as start point, check whether all nodes are visible or not\n for(int u; u < NODE; u++) {\n for(int i = 0; i<NODE; i++)\n vis[i] = false; //initialize as no node is visited\n traverse(u, vis);\n for(int i = 0; i<NODE; i++) {\n if(!vis[i]) //if there is a node, not visited by traversal, graph is not connected\n return false;\n }\n }\n return true;\n}\nint main() {\n if(isConnected())\n cout << \"The Graph is connected.\";\n else\n cout << \"The Graph is not connected.\";\n}"
},
{
"code": null,
"e": 3213,
"s": 3189,
"text": "The Graph is connected."
}
]
|
jQuery - contents( ) Method | The contents( ) method finds all the child nodes inside the matched elements (including text nodes), or the content document, if the element is an iframe.
Here is the simple syntax to use this method −
selector.contents( )
Here is the description of all the parameters used by this method −
NA
NA
Consider you have an html file index.htm which we would use in an iframe.
Try the following example which shows how you can access the objects in an iframe from a parent window. This operation has become possible just because of contents() method.
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script>
$(document).ready(function(){
var $content = $("iframe").contents();
$content.find("body").append("I'm in an iframe!");
});
</script>
</head>
<body>
<iframe src = "/jquery/index.htm" width = "300" height = "100"></iframe>
</body>
</html>
This will produce following result −
27 Lectures
1 hours
Mahesh Kumar
27 Lectures
1.5 hours
Pratik Singh
72 Lectures
4.5 hours
Frahaan Hussain
60 Lectures
9 hours
Eduonix Learning Solutions
17 Lectures
2 hours
Sandip Bhattacharya
12 Lectures
53 mins
Laurence Svekis
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2477,
"s": 2322,
"text": "The contents( ) method finds all the child nodes inside the matched elements (including text nodes), or the content document, if the element is an iframe."
},
{
"code": null,
"e": 2524,
"s": 2477,
"text": "Here is the simple syntax to use this method −"
},
{
"code": null,
"e": 2546,
"s": 2524,
"text": "selector.contents( )\n"
},
{
"code": null,
"e": 2614,
"s": 2546,
"text": "Here is the description of all the parameters used by this method −"
},
{
"code": null,
"e": 2617,
"s": 2614,
"text": "NA"
},
{
"code": null,
"e": 2620,
"s": 2617,
"text": "NA"
},
{
"code": null,
"e": 2694,
"s": 2620,
"text": "Consider you have an html file index.htm which we would use in an iframe."
},
{
"code": null,
"e": 2868,
"s": 2694,
"text": "Try the following example which shows how you can access the objects in an iframe from a parent window. This operation has become possible just because of contents() method."
},
{
"code": null,
"e": 3385,
"s": 2868,
"text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n\t\t\n <script>\n $(document).ready(function(){\n var $content = $(\"iframe\").contents();\n $content.find(\"body\").append(\"I'm in an iframe!\");\n });\n </script>\n </head>\n\t\n <body>\n <iframe src = \"/jquery/index.htm\" width = \"300\" height = \"100\"></iframe>\n </body>\n</html>"
},
{
"code": null,
"e": 3422,
"s": 3385,
"text": "This will produce following result −"
},
{
"code": null,
"e": 3455,
"s": 3422,
"text": "\n 27 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3469,
"s": 3455,
"text": " Mahesh Kumar"
},
{
"code": null,
"e": 3504,
"s": 3469,
"text": "\n 27 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3518,
"s": 3504,
"text": " Pratik Singh"
},
{
"code": null,
"e": 3553,
"s": 3518,
"text": "\n 72 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3570,
"s": 3553,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3603,
"s": 3570,
"text": "\n 60 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 3631,
"s": 3603,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3664,
"s": 3631,
"text": "\n 17 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3685,
"s": 3664,
"text": " Sandip Bhattacharya"
},
{
"code": null,
"e": 3717,
"s": 3685,
"text": "\n 12 Lectures \n 53 mins\n"
},
{
"code": null,
"e": 3734,
"s": 3717,
"text": " Laurence Svekis"
},
{
"code": null,
"e": 3741,
"s": 3734,
"text": " Print"
},
{
"code": null,
"e": 3752,
"s": 3741,
"text": " Add Notes"
}
]
|
How to use ArrayAdapter in android to create a simple listview in Kotlin? | This example demonstrates how to use ArrayAdapter in android to create a simple listview in Kotlin.
Step 1 − Create a new project in Android Studio, go to File ⇒New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="4dp"
tools:context=".MainActivity">
<ListView
android:id="@+id/simpleListView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:divider="#000"
android:dividerHeight="4dp" />
</RelativeLayout>
Step 3 − Add the following code to MainActivity.kt
import android.os.Bundle
import android.widget.ArrayAdapter
import android.widget.ListView
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
val arrayAdapter: ArrayAdapter<*>
val list = arrayOf(
"Cristiano Ronaldo",
"Messi",
"Neymar",
"Isco",
"Hazard",
"Mbappe",
"Hazard",
"Ziyech",
"Suarez"
)
// access the listView from xml file
val listView = findViewById<ListView>(R.id.listView)
arrayAdapter = ArrayAdapter(
this,
android.R.layout.simple_list_item_1, list
)
listView.adapter = arrayAdapter
}
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="app.com.q36">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code. | [
{
"code": null,
"e": 1162,
"s": 1062,
"text": "This example demonstrates how to use ArrayAdapter in android to create a simple listview in Kotlin."
},
{
"code": null,
"e": 1290,
"s": 1162,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1355,
"s": 1290,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1878,
"s": 1355,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:padding=\"4dp\"\n tools:context=\".MainActivity\">\n <ListView\n android:id=\"@+id/simpleListView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:divider=\"#000\"\n android:dividerHeight=\"4dp\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 1929,
"s": 1878,
"text": "Step 3 − Add the following code to MainActivity.kt"
},
{
"code": null,
"e": 2787,
"s": 1929,
"text": "import android.os.Bundle\nimport android.widget.ArrayAdapter\nimport android.widget.ListView\nimport androidx.appcompat.app.AppCompatActivity\nclass MainActivity : AppCompatActivity() {\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n val arrayAdapter: ArrayAdapter<*>\n val list = arrayOf(\n \"Cristiano Ronaldo\",\n \"Messi\",\n \"Neymar\",\n \"Isco\",\n \"Hazard\",\n \"Mbappe\",\n \"Hazard\",\n \"Ziyech\",\n \"Suarez\"\n )\n // access the listView from xml file\n val listView = findViewById<ListView>(R.id.listView)\n arrayAdapter = ArrayAdapter(\n this,\n android.R.layout.simple_list_item_1, list\n )\n listView.adapter = arrayAdapter\n }\n}"
},
{
"code": null,
"e": 2842,
"s": 2787,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 3527,
"s": 2842,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.q36\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 3878,
"s": 3527,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −"
},
{
"code": null,
"e": 3919,
"s": 3878,
"text": "Click here to download the project code."
}
]
|
A short introduction to NLP in Python with spaCy | by Conor Mc. | Towards Data Science | Natural Language Processing (NLP) is one of the most interesting sub-fields of data science, and data scientists are increasingly expected to be able to whip up solutions that involve the exploitation of unstructured text data. Despite this, many applied data scientists (both from STEM and social science backgrounds) lack NLP experience.
In this post I explore some fundamental NLP concepts and show how they can be implemented using the increasingly popular spaCy package in Python. This post is for the absolute NLP beginner, but knowledge of Python is assumed.
spaCy, you say?
spaCy is a relatively new package for “Industrial strength NLP in Python” developed by Matt Honnibal at Explosion AI. It is designed with the applied data scientist in mind, meaning it does not weigh the user down with decisions over what esoteric algorithms to use for common tasks and it’s fast. Incredibly fast (it’s implemented in Cython). If you are familiar with the Python data science stack, spaCy is your numpy for NLP – it’s reasonably low-level, but very intuitive and performant.
So, what can it do?
spacy provides a one-stop-shop for tasks commonly used in any NLP project, including:
Tokenisation
Lemmatisation
Part-of-speech tagging
Entity recognition
Dependency parsing
Sentence recognition
Word-to-vector transformations
Many convenience methods for cleaning and normalising text
I’ll provide a high level overview of some of these features and show how to access them using spaCy.
Let’s get started!
First, we load spaCy’s pipeline, which by convention is stored in a variable named nlp. declaring this variable will take a couple of seconds as spaCy loads its models and data to it up-front to save time later. In effect, this gets some heavy lifting out of the way early, so that the cost is not incurred upon each application of the nlp parser to your data. Note that here I am using the English language model, but there is also a fully featured German model, with tokenisation (discussed below) implemented across several languages.
We invoke nlp on the sample text to create a Doc object. The Doc object is now a vessel for NLP tasks on the text itself, slices of the text (Span objects) and elements (Token objects) of the text. It is worth noting that Token and Span objects actually hold no data. Instead they contain pointers to data contained in the Doc object and are evaluated lazily (i.e. upon request). Much of spaCy’s core functionality is accessed through the methods on Doc (n=33), Span (n=29) and Token (n=78) objects.
In[1]: import spacy ...: nlp = spacy.load("en") ...: doc = nlp("The big grey dog ate all of the chocolate, but fortunately he wasn't sick!")
Tokenization
Tokenisation is a foundational step in many NLP tasks. Tokenising text is the process of splitting a piece of text into words, symbols, punctuation, spaces and other elements, thereby creating “tokens”. A naive way to do this is to simply split the string on white space:
In[2]: doc.text.split() ...: Out[2]: ['The', 'big', 'grey', 'dog', 'ate', 'all', 'of', 'the', 'chocolate,', 'but', 'fortunately', 'he', "wasn't", 'sick!']
On the surface, this looks fine. But, note that a) it disregards the punctuation and, b) it does not split the verb and adverb (“was”, “n’t”). Put differently, it is naive, it fails to recognise elements of the text that help us (and a machine) to understand its structure and meaning. Let’s see how SpaCy handles this:
In[3]: [token.orth_ for token in doc] ...: Out[3]: ['The', 'big', 'grey', 'dog', 'ate', 'all', 'of', 'the', 'chocolate', ',', 'but', 'fortunately', 'he', 'was', "n't", ' ', 'sick', '!']
Here we access the each token’s .orth_ method, which returns a string representation of the token rather than a SpaCy token object, this might not always be desirable, but worth noting. SpaCy recognises punctuation and is able to split these punctuation tokens from word tokens. Many of SpaCy’s token method offer both string and integer representations of processed text – methods with an underscore suffix return strings, methods without an underscore suffix return integers. For example:
In[4]: [(token, token.orth_, token.orth) for token in doc] ...: Out[4]: [(The, 'The', 517), (big, 'big', 742), (grey, 'grey', 4623), (dog, 'dog', 1175), (ate, 'ate', 3469), (all, 'all', 516), (of, 'of', 471), (the, 'the', 466), (chocolate, 'chocolate', 3593), (,, ',', 416), (but, 'but', 494), (fortunately, 'fortunately', 15520), (he, 'he', 514), (was, 'was', 491), (n't, "n't", 479), ( , ' ', 483), (sick, 'sick', 1698), (!, '!', 495)]
Here, we return the SpaCy token, the string representation of the token and the integer representation of the token in a list of tuples.
If you want to avoid returning tokens that are punctuation or white space, SpaCy provides convienence methods for this (as well as many other common text cleaning tasks — for example, to remove stop words you can call the .is_stopmethod.
In[5]: [token.orth_ for token in doc if not token.is_punct | token.is_space] ...: Out[5]: ['The', 'big', 'grey', 'dog', 'ate', 'all', 'of', 'the', 'chocolate', 'but', 'fortunately', 'he', 'was', "n't", 'sick']
Cool, right?
Lemmatization
A related task to tokenisation is lemmatisation. Lemmatisation is the process of reducing a word to its base form, its mother word if you like. Different uses of a word often have the same root meaning. For example, practice, practised and practising all essentially refer to the same thing. It is often desirable to standardise words with similar meaning to their base form. With SpaCy we can access each word’s base form with a token’s .lemma_ method:
In[6]: practice = "practice practiced practicing" ...: nlp_practice = nlp(practice) ...: [word.lemma_ for word in nlp_practice] ...: Out[6]: ['practice', 'practice', 'practice']
Why is this useful? An immediate use case is in machine learning, specifically text classification. Lemmatising the text prior to, for example, creating a “bag-of-words” avoids word duplication and, therefore, allows for the model to build a clearer picture of patterns of word usage across multiple documents.
POS Tagging
Part-of-speech tagging is the process of assigning grammatical properties (e.g. noun, verb, adverb, adjective etc.) to words. Words that share the same POS tag tend to follow a similar syntactic structure and are useful in rule-based processes.
For example, in a given description of an event we may wish to determine who owns what. By exploiting possessives, we can do this (providing the text is grammatically sound!). SpaCy uses the popular Penn Treebank POS tags, see https://www.ling.upenn.edu/courses/Fall_2003/ling001/penn_treebank_pos.html. With SpaCy you can access coarse and fine-grained POS tags with the .pos_ and .tag_ methods, respectively. Here, I access the fine grained POS tag:
In[7]: doc2 = nlp("Conor's dog's toy was hidden under the man's sofa in the woman's house") ...: pos_tags = [(i, i.tag_) for i in doc2] ...: pos_tags ...: Out[7]: [(Conor, 'NNP'), ('s, 'POS'), (dog, 'NN'), ('s, 'POS'), (toy, 'NN'), (was, 'VBD'), (hidden, 'VBN'), (under, 'IN'), (the, 'DT'), (man, 'NN'), ('s, 'POS'), (sofa, 'NN'), (in, 'IN'), (the, 'DT'), (woman, 'NN'), ('s, 'POS'), (house, 'NN')]
We can see that the “ ’s ” tokens are labelled as POS. We can exploit this tag to extract the owner and the thing that they own:
In[8]: owners_possessions = [] ...: for i in pos_tags: ...: if i[1] == "POS": ...: owner = i[0].nbor(-1) ...: possession = i[0].nbor(1) ...: owners_possessions.append((owner, possession)) ...: ...: owners_possessions ...: Out[8]: [(Conor, dog), (dog, toy), (man, sofa), (woman, house)]
This returns a list of owner-possession tuples. If you want to be super Pythonic about it, you can do this in a list comprehenion (which, I think is preferable!):
In[9]: [(i[0].nbor(-1), i[0].nbor(+1)) for i in pos_tags if i[1] == "POS"] ...: Out[9]: [(Conor, dog), (dog, toy), (man, sofa), (woman, house)]
Here we are using each token’s .nbor method which returns a token’s neighbouring tokens.
Entity recognition
Entity recognition is the process of classifying named entities found in a text into pre-defined categories, such as persons, places, organizations, dates, etc. spaCy uses a statistical model to classify a broad range of entities, including persons, events, works-of-art and nationalities / religions (see the documentation for the full list https://spacy.io/docs/usage/entity-recognition).
For example, let’s take the first two sentences from Barack Obama’s wikipedia entry. We will parse this text, then access the identified entities using the Doc object’s .ents method. With this method called on the Doc we can access additional Token methods, specifically .label_ and .label:
In[10]: wiki_obama = """Barack Obama is an American politician who served as ...: the 44th President of the United States from 2009 to 2017. He is the first ...: African American to have served as president, ...: as well as the first born outside the contiguous United States.""" ...: ...: nlp_obama = nlp(wiki_obama) ...: [(i, i.label_, i.label) for i in nlp_obama.ents] ...: Out[10]: [(Barack Obama, 'PERSON', 346), (American, 'NORP', 347), (the United States, 'GPE', 350), (2009 to 2017, 'DATE', 356), (first, 'ORDINAL', 361), (African, 'NORP', 347), (American, 'NORP', 347), (first, 'ORDINAL', 361), (United States, 'GPE', 350)]
You can see the entities that the model has identified and how accurate they are (in this instance). PERSON is self explanatory, NORP is natianalities or religuos groups, GPE identifies locations (cities, countries, etc.), DATE recognises a specific date or date-range and ORDINAL identifies a word or number representing some type of order.
While we are on the topic of Doc methods, it is worth mentioning spaCy’s sentence identifier. It is not uncommon in NLP tasks to want to split a document into sentences. It is simple to do this with SpaCy by accessing a Doc's .sents method:
In[11]: for ix, sent in enumerate(nlp_obama.sents, 1): ...: print("Sentence number {}: {}".format(ix, sent)) ...: Sentence number 1: Barack Obama is an American politician who served as the 44th President of the United States from 2009 to 2017. Sentence number 2: He is the first African American to have served as president, as well as the first born outside the contiguous United States.
Originally published at dataflume.wordpress.com on March 17, 2017. | [
{
"code": null,
"e": 512,
"s": 172,
"text": "Natural Language Processing (NLP) is one of the most interesting sub-fields of data science, and data scientists are increasingly expected to be able to whip up solutions that involve the exploitation of unstructured text data. Despite this, many applied data scientists (both from STEM and social science backgrounds) lack NLP experience."
},
{
"code": null,
"e": 738,
"s": 512,
"text": "In this post I explore some fundamental NLP concepts and show how they can be implemented using the increasingly popular spaCy package in Python. This post is for the absolute NLP beginner, but knowledge of Python is assumed."
},
{
"code": null,
"e": 754,
"s": 738,
"text": "spaCy, you say?"
},
{
"code": null,
"e": 1246,
"s": 754,
"text": "spaCy is a relatively new package for “Industrial strength NLP in Python” developed by Matt Honnibal at Explosion AI. It is designed with the applied data scientist in mind, meaning it does not weigh the user down with decisions over what esoteric algorithms to use for common tasks and it’s fast. Incredibly fast (it’s implemented in Cython). If you are familiar with the Python data science stack, spaCy is your numpy for NLP – it’s reasonably low-level, but very intuitive and performant."
},
{
"code": null,
"e": 1266,
"s": 1246,
"text": "So, what can it do?"
},
{
"code": null,
"e": 1352,
"s": 1266,
"text": "spacy provides a one-stop-shop for tasks commonly used in any NLP project, including:"
},
{
"code": null,
"e": 1365,
"s": 1352,
"text": "Tokenisation"
},
{
"code": null,
"e": 1379,
"s": 1365,
"text": "Lemmatisation"
},
{
"code": null,
"e": 1402,
"s": 1379,
"text": "Part-of-speech tagging"
},
{
"code": null,
"e": 1421,
"s": 1402,
"text": "Entity recognition"
},
{
"code": null,
"e": 1440,
"s": 1421,
"text": "Dependency parsing"
},
{
"code": null,
"e": 1461,
"s": 1440,
"text": "Sentence recognition"
},
{
"code": null,
"e": 1492,
"s": 1461,
"text": "Word-to-vector transformations"
},
{
"code": null,
"e": 1551,
"s": 1492,
"text": "Many convenience methods for cleaning and normalising text"
},
{
"code": null,
"e": 1653,
"s": 1551,
"text": "I’ll provide a high level overview of some of these features and show how to access them using spaCy."
},
{
"code": null,
"e": 1672,
"s": 1653,
"text": "Let’s get started!"
},
{
"code": null,
"e": 2210,
"s": 1672,
"text": "First, we load spaCy’s pipeline, which by convention is stored in a variable named nlp. declaring this variable will take a couple of seconds as spaCy loads its models and data to it up-front to save time later. In effect, this gets some heavy lifting out of the way early, so that the cost is not incurred upon each application of the nlp parser to your data. Note that here I am using the English language model, but there is also a fully featured German model, with tokenisation (discussed below) implemented across several languages."
},
{
"code": null,
"e": 2710,
"s": 2210,
"text": "We invoke nlp on the sample text to create a Doc object. The Doc object is now a vessel for NLP tasks on the text itself, slices of the text (Span objects) and elements (Token objects) of the text. It is worth noting that Token and Span objects actually hold no data. Instead they contain pointers to data contained in the Doc object and are evaluated lazily (i.e. upon request). Much of spaCy’s core functionality is accessed through the methods on Doc (n=33), Span (n=29) and Token (n=78) objects."
},
{
"code": null,
"e": 2851,
"s": 2710,
"text": "In[1]: import spacy ...: nlp = spacy.load(\"en\") ...: doc = nlp(\"The big grey dog ate all of the chocolate, but fortunately he wasn't sick!\")"
},
{
"code": null,
"e": 2864,
"s": 2851,
"text": "Tokenization"
},
{
"code": null,
"e": 3136,
"s": 2864,
"text": "Tokenisation is a foundational step in many NLP tasks. Tokenising text is the process of splitting a piece of text into words, symbols, punctuation, spaces and other elements, thereby creating “tokens”. A naive way to do this is to simply split the string on white space:"
},
{
"code": null,
"e": 3291,
"s": 3136,
"text": "In[2]: doc.text.split() ...: Out[2]: ['The', 'big', 'grey', 'dog', 'ate', 'all', 'of', 'the', 'chocolate,', 'but', 'fortunately', 'he', \"wasn't\", 'sick!']"
},
{
"code": null,
"e": 3611,
"s": 3291,
"text": "On the surface, this looks fine. But, note that a) it disregards the punctuation and, b) it does not split the verb and adverb (“was”, “n’t”). Put differently, it is naive, it fails to recognise elements of the text that help us (and a machine) to understand its structure and meaning. Let’s see how SpaCy handles this:"
},
{
"code": null,
"e": 3797,
"s": 3611,
"text": "In[3]: [token.orth_ for token in doc] ...: Out[3]: ['The', 'big', 'grey', 'dog', 'ate', 'all', 'of', 'the', 'chocolate', ',', 'but', 'fortunately', 'he', 'was', \"n't\", ' ', 'sick', '!']"
},
{
"code": null,
"e": 4288,
"s": 3797,
"text": "Here we access the each token’s .orth_ method, which returns a string representation of the token rather than a SpaCy token object, this might not always be desirable, but worth noting. SpaCy recognises punctuation and is able to split these punctuation tokens from word tokens. Many of SpaCy’s token method offer both string and integer representations of processed text – methods with an underscore suffix return strings, methods without an underscore suffix return integers. For example:"
},
{
"code": null,
"e": 4726,
"s": 4288,
"text": "In[4]: [(token, token.orth_, token.orth) for token in doc] ...: Out[4]: [(The, 'The', 517), (big, 'big', 742), (grey, 'grey', 4623), (dog, 'dog', 1175), (ate, 'ate', 3469), (all, 'all', 516), (of, 'of', 471), (the, 'the', 466), (chocolate, 'chocolate', 3593), (,, ',', 416), (but, 'but', 494), (fortunately, 'fortunately', 15520), (he, 'he', 514), (was, 'was', 491), (n't, \"n't\", 479), ( , ' ', 483), (sick, 'sick', 1698), (!, '!', 495)]"
},
{
"code": null,
"e": 4863,
"s": 4726,
"text": "Here, we return the SpaCy token, the string representation of the token and the integer representation of the token in a list of tuples."
},
{
"code": null,
"e": 5101,
"s": 4863,
"text": "If you want to avoid returning tokens that are punctuation or white space, SpaCy provides convienence methods for this (as well as many other common text cleaning tasks — for example, to remove stop words you can call the .is_stopmethod."
},
{
"code": null,
"e": 5311,
"s": 5101,
"text": "In[5]: [token.orth_ for token in doc if not token.is_punct | token.is_space] ...: Out[5]: ['The', 'big', 'grey', 'dog', 'ate', 'all', 'of', 'the', 'chocolate', 'but', 'fortunately', 'he', 'was', \"n't\", 'sick']"
},
{
"code": null,
"e": 5324,
"s": 5311,
"text": "Cool, right?"
},
{
"code": null,
"e": 5338,
"s": 5324,
"text": "Lemmatization"
},
{
"code": null,
"e": 5792,
"s": 5338,
"text": "A related task to tokenisation is lemmatisation. Lemmatisation is the process of reducing a word to its base form, its mother word if you like. Different uses of a word often have the same root meaning. For example, practice, practised and practising all essentially refer to the same thing. It is often desirable to standardise words with similar meaning to their base form. With SpaCy we can access each word’s base form with a token’s .lemma_ method:"
},
{
"code": null,
"e": 5970,
"s": 5792,
"text": "In[6]: practice = \"practice practiced practicing\" ...: nlp_practice = nlp(practice) ...: [word.lemma_ for word in nlp_practice] ...: Out[6]: ['practice', 'practice', 'practice']"
},
{
"code": null,
"e": 6281,
"s": 5970,
"text": "Why is this useful? An immediate use case is in machine learning, specifically text classification. Lemmatising the text prior to, for example, creating a “bag-of-words” avoids word duplication and, therefore, allows for the model to build a clearer picture of patterns of word usage across multiple documents."
},
{
"code": null,
"e": 6293,
"s": 6281,
"text": "POS Tagging"
},
{
"code": null,
"e": 6538,
"s": 6293,
"text": "Part-of-speech tagging is the process of assigning grammatical properties (e.g. noun, verb, adverb, adjective etc.) to words. Words that share the same POS tag tend to follow a similar syntactic structure and are useful in rule-based processes."
},
{
"code": null,
"e": 6990,
"s": 6538,
"text": "For example, in a given description of an event we may wish to determine who owns what. By exploiting possessives, we can do this (providing the text is grammatically sound!). SpaCy uses the popular Penn Treebank POS tags, see https://www.ling.upenn.edu/courses/Fall_2003/ling001/penn_treebank_pos.html. With SpaCy you can access coarse and fine-grained POS tags with the .pos_ and .tag_ methods, respectively. Here, I access the fine grained POS tag:"
},
{
"code": null,
"e": 7389,
"s": 6990,
"text": "In[7]: doc2 = nlp(\"Conor's dog's toy was hidden under the man's sofa in the woman's house\") ...: pos_tags = [(i, i.tag_) for i in doc2] ...: pos_tags ...: Out[7]: [(Conor, 'NNP'), ('s, 'POS'), (dog, 'NN'), ('s, 'POS'), (toy, 'NN'), (was, 'VBD'), (hidden, 'VBN'), (under, 'IN'), (the, 'DT'), (man, 'NN'), ('s, 'POS'), (sofa, 'NN'), (in, 'IN'), (the, 'DT'), (woman, 'NN'), ('s, 'POS'), (house, 'NN')]"
},
{
"code": null,
"e": 7518,
"s": 7389,
"text": "We can see that the “ ’s ” tokens are labelled as POS. We can exploit this tag to extract the owner and the thing that they own:"
},
{
"code": null,
"e": 7832,
"s": 7518,
"text": "In[8]: owners_possessions = [] ...: for i in pos_tags: ...: if i[1] == \"POS\": ...: owner = i[0].nbor(-1) ...: possession = i[0].nbor(1) ...: owners_possessions.append((owner, possession)) ...: ...: owners_possessions ...: Out[8]: [(Conor, dog), (dog, toy), (man, sofa), (woman, house)]"
},
{
"code": null,
"e": 7995,
"s": 7832,
"text": "This returns a list of owner-possession tuples. If you want to be super Pythonic about it, you can do this in a list comprehenion (which, I think is preferable!):"
},
{
"code": null,
"e": 8139,
"s": 7995,
"text": "In[9]: [(i[0].nbor(-1), i[0].nbor(+1)) for i in pos_tags if i[1] == \"POS\"] ...: Out[9]: [(Conor, dog), (dog, toy), (man, sofa), (woman, house)]"
},
{
"code": null,
"e": 8228,
"s": 8139,
"text": "Here we are using each token’s .nbor method which returns a token’s neighbouring tokens."
},
{
"code": null,
"e": 8247,
"s": 8228,
"text": "Entity recognition"
},
{
"code": null,
"e": 8638,
"s": 8247,
"text": "Entity recognition is the process of classifying named entities found in a text into pre-defined categories, such as persons, places, organizations, dates, etc. spaCy uses a statistical model to classify a broad range of entities, including persons, events, works-of-art and nationalities / religions (see the documentation for the full list https://spacy.io/docs/usage/entity-recognition)."
},
{
"code": null,
"e": 8929,
"s": 8638,
"text": "For example, let’s take the first two sentences from Barack Obama’s wikipedia entry. We will parse this text, then access the identified entities using the Doc object’s .ents method. With this method called on the Doc we can access additional Token methods, specifically .label_ and .label:"
},
{
"code": null,
"e": 9562,
"s": 8929,
"text": "In[10]: wiki_obama = \"\"\"Barack Obama is an American politician who served as ...: the 44th President of the United States from 2009 to 2017. He is the first ...: African American to have served as president, ...: as well as the first born outside the contiguous United States.\"\"\" ...: ...: nlp_obama = nlp(wiki_obama) ...: [(i, i.label_, i.label) for i in nlp_obama.ents] ...: Out[10]: [(Barack Obama, 'PERSON', 346), (American, 'NORP', 347), (the United States, 'GPE', 350), (2009 to 2017, 'DATE', 356), (first, 'ORDINAL', 361), (African, 'NORP', 347), (American, 'NORP', 347), (first, 'ORDINAL', 361), (United States, 'GPE', 350)]"
},
{
"code": null,
"e": 9904,
"s": 9562,
"text": "You can see the entities that the model has identified and how accurate they are (in this instance). PERSON is self explanatory, NORP is natianalities or religuos groups, GPE identifies locations (cities, countries, etc.), DATE recognises a specific date or date-range and ORDINAL identifies a word or number representing some type of order."
},
{
"code": null,
"e": 10145,
"s": 9904,
"text": "While we are on the topic of Doc methods, it is worth mentioning spaCy’s sentence identifier. It is not uncommon in NLP tasks to want to split a document into sentences. It is simple to do this with SpaCy by accessing a Doc's .sents method:"
},
{
"code": null,
"e": 10535,
"s": 10145,
"text": "In[11]: for ix, sent in enumerate(nlp_obama.sents, 1): ...: print(\"Sentence number {}: {}\".format(ix, sent)) ...: Sentence number 1: Barack Obama is an American politician who served as the 44th President of the United States from 2009 to 2017. Sentence number 2: He is the first African American to have served as president, as well as the first born outside the contiguous United States."
}
]
|
Implementing K-means clustering of Diabetes dataset with SciPy library | The Pima Indian Diabetes dataset, which we will be using here, is originally from the National Institute of Diabetes and Digestive and Kidney Diseases. Based on the following diagnostic factors, this dataset can be used to place a patient in ether diabetic cluster or non-diabetic cluster −
Pregnancies
Pregnancies
Glucose
Glucose
Blood Pressure
Blood Pressure
Skin Thickness
Skin Thickness
Insulin
Insulin
BMI
BMI
Diabetes Pedigree Function
Diabetes Pedigree Function
Age
Age
You can get this dataset in .CSV format from Kaggle website.
The example below will use SciPy library to create two clusters namely diabetic and non-diabetic from the Pima Indian diabetes dataset.
#importing the required Python libraries:
import matplotlib.pyplot as plt
import numpy as np
from scipy.cluster.vq import whiten, kmeans, vq
#Loading the dataset:
dataset = np.loadtxt(r"{your path}\pima-indians-diabetes.csv", delimiter=",")
# Printing the data after excluding the outcome column
dataset = dataset[:, 0:8]
print("Data :\n", dataset, "\n")
#Normalizing the data:
dataset = whiten(dataset)
# generating code book by computing K-Means with K = 2 (2 clusters i.e., diabetic, and non-diabetic clusters)
centroids, mean_dist = kmeans(dataset, 2)
print("Code book :\n", centroids, "\n")
clusters, dist = vq(dataset, centroids)
print("Clusters :\n", clusters, "\n")
# forming cluster of non-diabetic patients
non_diabetic = list(clusters).count(0)
# forming cluster of diabetic patients
diabetic = list(clusters).count(1)
#Plotting the pie chart having clusters
x_axis = []
x_axis.append(diabetic)
x_axis.append(non_diabetic)
colors = ['red', 'green']
print("Total number of diabetic patients : " + str(x_axis[0]) + "\nTotal number non-diabetic patients : " + str(x_axis[1]))
y = ['diabetic', 'non-diabetic']
plt.pie(x_axis, labels=y, colors=colors, shadow='false')
plt.show()
Data :
[[ 6. 148. 72. ... 33.6 0.627 50. ]
[ 1. 85. 66. ... 26.6 0.351 31. ]
[ 8. 183. 64. ... 23.3 0.672 32. ]
...
[ 5. 121. 72. ... 26.2 0.245 30. ]
[ 1. 126. 60. ... 30.1 0.349 47. ]
[ 1. 93. 70. ... 30.4 0.315 23. ]]
Code book :
[[2.08198148 4.17698255 3.96280983 1.04984582 0.56968574 4.13266474
1.40143319 3.86427413]
[0.6114727 3.56175537 3.35245694 1.42268776 0.76239717 4.01974705
1.43848683 2.24399453]]
Clusters :
[0 1 0 1 1 1 1 1 0 0 0 0 0 0 0 1 1 0 1 1 1 0 0 0 0 0 0 1 0 0 0 1 1 0 0 1
0
0 1 0 1 0 0 0 0 1 1 1 1 1 1 1 1 0 0 1 0 1 0 1 1 0 1 1 0 1 1 0 1 1 1 1 0 1
1 1 0 1 1 1 1 1 0 1 0 1 0 1 0 1 1 1 0 0 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
0 1 1 0 0 0 1 1 1 1 1 1 0 1 1 1 1 1 0 0 0 1 0 1 1 1 1 1 1 0 0 1 0 1 1 0 1
0 1 1 1 0 1 0 0 1 1 1 0 0 0 1 1 1 0 1 1 1 1 0 1 1 1 1 0 0 1 0 0 0 1 1 1 0
0 0 1 0 1 1 0 0 0 0 1 1 1 1 1 1 1 1 1 0 1 0 0 1 0 1 1 0 1 0 0 1 1 1 0 1 0
1 0 1 1 1 1 1 1 1 0 1 1 1 0 0 1 0 1 1 1 1 1 1 0 0 1 0 1 0 1 1 1 0 1 1 1 1
0 0 1 1 0 1 0 1 1 1 1 0 1 0 1 0 1 1 1 0 1 1 0 0 0 0 0 1 1 1 1 1 1 1 1 0 1
1 1 0 0 1 1 1 0 0 1 0 1 1 1 0 1 1 1 0 1 1 0 1 0 1 1 1 0 1 1 1 0 1 0 0 1 1
0 1 1 1 0 0 0 1 1 1 0 0 0 1 1 1 1 1 0 1 1 1 0 1 0 0 1 1 0 0 0 1 1 0 1 1 0
1 1 1 1 1 0 1 1 0 1 1 1 1 1 1 1 1 0 0 1 1 0 1 1 0 1 1 1 1 1 1 0 0 0 0 1 0
1 0 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 0 0 1 0 0 1 1 0
1 1 1 1 1 1 1 1 1 0 1 0 0 1 0 0 0 1 0 1 0 1 1 1 0 1 1 1 1 0 1 0 1 0 0 0 1
1 1 1 1 1 1 0 1 0 1 1 1 0 1 0 1 1 0 0 1 1 1 0 1 0 1 1 1 0 0 1 0 1 1 1 0 0
0 0 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 0 0 1 1 0 1 0 1 1 0 0 1 0 0 1 1 0 1 1
0 1 0 0 0 0 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 1 1 0 0 1 1 0 0 0 1 0 1 0 1 0 1
0 1 1 1 1 1 0 1 1 1 1 0 1 1 1 1 1 1 1 1 0 1 0 1 0 1 0 1 1 1 0 1 1 1 1 1 0
1 0 1 1 1 0 0 0 1 1 1 1 1 0 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 0 1 0 1 0 0 0 1
0 0 0 0 0 1 0 1 0 0 0 1 1 1 1 1 1 1 0 1 1 1 1 0 0 0 1 0 1 0 1 1 1 1 1 0 0
1 1 1 1 1 0 1 1 0 0 1 1 0 1 0 1 0 1 1 1 0 0 1 1 1 1 1 1 0 1 1 0 1 1 0 1 1
0 1 1 0 0 0 1 1 0 0 1 1 1 1 0 1 0 0 1 0 1 0 0 0 1 1 0 1]
Total number of diabetic patients : 492
Total number non-diabetic patients : 276 | [
{
"code": null,
"e": 1353,
"s": 1062,
"text": "The Pima Indian Diabetes dataset, which we will be using here, is originally from the National Institute of Diabetes and Digestive and Kidney Diseases. Based on the following diagnostic factors, this dataset can be used to place a patient in ether diabetic cluster or non-diabetic cluster −"
},
{
"code": null,
"e": 1365,
"s": 1353,
"text": "Pregnancies"
},
{
"code": null,
"e": 1377,
"s": 1365,
"text": "Pregnancies"
},
{
"code": null,
"e": 1385,
"s": 1377,
"text": "Glucose"
},
{
"code": null,
"e": 1393,
"s": 1385,
"text": "Glucose"
},
{
"code": null,
"e": 1408,
"s": 1393,
"text": "Blood Pressure"
},
{
"code": null,
"e": 1423,
"s": 1408,
"text": "Blood Pressure"
},
{
"code": null,
"e": 1438,
"s": 1423,
"text": "Skin Thickness"
},
{
"code": null,
"e": 1453,
"s": 1438,
"text": "Skin Thickness"
},
{
"code": null,
"e": 1461,
"s": 1453,
"text": "Insulin"
},
{
"code": null,
"e": 1469,
"s": 1461,
"text": "Insulin"
},
{
"code": null,
"e": 1473,
"s": 1469,
"text": "BMI"
},
{
"code": null,
"e": 1477,
"s": 1473,
"text": "BMI"
},
{
"code": null,
"e": 1504,
"s": 1477,
"text": "Diabetes Pedigree Function"
},
{
"code": null,
"e": 1531,
"s": 1504,
"text": "Diabetes Pedigree Function"
},
{
"code": null,
"e": 1535,
"s": 1531,
"text": "Age"
},
{
"code": null,
"e": 1539,
"s": 1535,
"text": "Age"
},
{
"code": null,
"e": 1600,
"s": 1539,
"text": "You can get this dataset in .CSV format from Kaggle website."
},
{
"code": null,
"e": 1736,
"s": 1600,
"text": "The example below will use SciPy library to create two clusters namely diabetic and non-diabetic from the Pima Indian diabetes dataset."
},
{
"code": null,
"e": 2927,
"s": 1736,
"text": "#importing the required Python libraries:\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy.cluster.vq import whiten, kmeans, vq\n\n#Loading the dataset:\ndataset = np.loadtxt(r\"{your path}\\pima-indians-diabetes.csv\", delimiter=\",\")\n\n# Printing the data after excluding the outcome column\ndataset = dataset[:, 0:8]\nprint(\"Data :\\n\", dataset, \"\\n\")\n\n#Normalizing the data:\ndataset = whiten(dataset)\n\n# generating code book by computing K-Means with K = 2 (2 clusters i.e., diabetic, and non-diabetic clusters)\ncentroids, mean_dist = kmeans(dataset, 2)\nprint(\"Code book :\\n\", centroids, \"\\n\")\n\nclusters, dist = vq(dataset, centroids)\nprint(\"Clusters :\\n\", clusters, \"\\n\")\n\n# forming cluster of non-diabetic patients\nnon_diabetic = list(clusters).count(0)\n# forming cluster of diabetic patients\ndiabetic = list(clusters).count(1)\n#Plotting the pie chart having clusters\nx_axis = []\nx_axis.append(diabetic)\nx_axis.append(non_diabetic)\ncolors = ['red', 'green']\nprint(\"Total number of diabetic patients : \" + str(x_axis[0]) + \"\\nTotal number non-diabetic patients : \" + str(x_axis[1]))\ny = ['diabetic', 'non-diabetic']\nplt.pie(x_axis, labels=y, colors=colors, shadow='false')\nplt.show()"
},
{
"code": null,
"e": 4974,
"s": 2927,
"text": "Data :\n[[ 6. 148. 72. ... 33.6 0.627 50. ]\n[ 1. 85. 66. ... 26.6 0.351 31. ]\n[ 8. 183. 64. ... 23.3 0.672 32. ]\n...\n[ 5. 121. 72. ... 26.2 0.245 30. ]\n[ 1. 126. 60. ... 30.1 0.349 47. ]\n[ 1. 93. 70. ... 30.4 0.315 23. ]]\n\nCode book :\n[[2.08198148 4.17698255 3.96280983 1.04984582 0.56968574 4.13266474\n1.40143319 3.86427413]\n[0.6114727 3.56175537 3.35245694 1.42268776 0.76239717 4.01974705\n1.43848683 2.24399453]]\n\nClusters :\n[0 1 0 1 1 1 1 1 0 0 0 0 0 0 0 1 1 0 1 1 1 0 0 0 0 0 0 1 0 0 0 1 1 0 0 1\n0\n0 1 0 1 0 0 0 0 1 1 1 1 1 1 1 1 0 0 1 0 1 0 1 1 0 1 1 0 1 1 0 1 1 1 1 0 1\n1 1 0 1 1 1 1 1 0 1 0 1 0 1 0 1 1 1 0 0 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n0 1 1 0 0 0 1 1 1 1 1 1 0 1 1 1 1 1 0 0 0 1 0 1 1 1 1 1 1 0 0 1 0 1 1 0 1\n0 1 1 1 0 1 0 0 1 1 1 0 0 0 1 1 1 0 1 1 1 1 0 1 1 1 1 0 0 1 0 0 0 1 1 1 0\n0 0 1 0 1 1 0 0 0 0 1 1 1 1 1 1 1 1 1 0 1 0 0 1 0 1 1 0 1 0 0 1 1 1 0 1 0\n1 0 1 1 1 1 1 1 1 0 1 1 1 0 0 1 0 1 1 1 1 1 1 0 0 1 0 1 0 1 1 1 0 1 1 1 1\n0 0 1 1 0 1 0 1 1 1 1 0 1 0 1 0 1 1 1 0 1 1 0 0 0 0 0 1 1 1 1 1 1 1 1 0 1\n1 1 0 0 1 1 1 0 0 1 0 1 1 1 0 1 1 1 0 1 1 0 1 0 1 1 1 0 1 1 1 0 1 0 0 1 1\n0 1 1 1 0 0 0 1 1 1 0 0 0 1 1 1 1 1 0 1 1 1 0 1 0 0 1 1 0 0 0 1 1 0 1 1 0\n1 1 1 1 1 0 1 1 0 1 1 1 1 1 1 1 1 0 0 1 1 0 1 1 0 1 1 1 1 1 1 0 0 0 0 1 0\n1 0 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 0 0 1 0 0 1 1 0\n1 1 1 1 1 1 1 1 1 0 1 0 0 1 0 0 0 1 0 1 0 1 1 1 0 1 1 1 1 0 1 0 1 0 0 0 1\n1 1 1 1 1 1 0 1 0 1 1 1 0 1 0 1 1 0 0 1 1 1 0 1 0 1 1 1 0 0 1 0 1 1 1 0 0\n0 0 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 0 0 1 1 0 1 0 1 1 0 0 1 0 0 1 1 0 1 1\n0 1 0 0 0 0 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 1 1 0 0 1 1 0 0 0 1 0 1 0 1 0 1\n0 1 1 1 1 1 0 1 1 1 1 0 1 1 1 1 1 1 1 1 0 1 0 1 0 1 0 1 1 1 0 1 1 1 1 1 0\n1 0 1 1 1 0 0 0 1 1 1 1 1 0 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 0 1 0 1 0 0 0 1\n0 0 0 0 0 1 0 1 0 0 0 1 1 1 1 1 1 1 0 1 1 1 1 0 0 0 1 0 1 0 1 1 1 1 1 0 0\n1 1 1 1 1 0 1 1 0 0 1 1 0 1 0 1 0 1 1 1 0 0 1 1 1 1 1 1 0 1 1 0 1 1 0 1 1\n0 1 1 0 0 0 1 1 0 0 1 1 1 1 0 1 0 0 1 0 1 0 0 0 1 1 0 1]\n\nTotal number of diabetic patients : 492\nTotal number non-diabetic patients : 276"
}
]
|
Find the XOR of first N Prime Numbers - GeeksforGeeks | 18 Mar, 2022
Given a positive integer N, the task is to find the XOR of the first N prime numbers.Examples:
Input: N = 3 Output: 4 First 3 prime numbers are 2, 3 and 5. And 2 ^ 3 ^ 5 = 4Input: N = 5 Output: 8
Approach:
Create Sieve of Eratosthenes to identify if a number is prime or not in O(1) time.Run a loop starting from 1 until and unless we find N prime numbers.XOR all the prime numbers and neglect those which are not prime.Finally, print the XOR of the 1st N prime numbers.
Create Sieve of Eratosthenes to identify if a number is prime or not in O(1) time.
Run a loop starting from 1 until and unless we find N prime numbers.
XOR all the prime numbers and neglect those which are not prime.
Finally, print the XOR of the 1st N prime numbers.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;#define MAX 10000 // 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[MAX + 1];void SieveOfEratosthenes(){ memset(prime, true, sizeof(prime)); prime[1] = false; for (int p = 2; p * p <= MAX; p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == true) { // Set all multiples of p to non-prime for (int i = p * 2; i <= MAX; i += p) prime[i] = false; } }} // Function to return the xor of 1st N prime numbersint xorFirstNPrime(int n){ // Count of prime numbers int count = 0, num = 1; // XOR of prime numbers int xorVal = 0; while (count < n) { // If the number is prime xor it if (prime[num]) { xorVal ^= num; // Increment the count count++; } // Get to the next number num++; } return xorVal;} // Driver codeint main(){ // Create the sieve SieveOfEratosthenes(); int n = 4; // Find the xor of 1st n prime numbers cout << xorFirstNPrime(n); return 0;}
// Java implementation of the approachclass GFG{static final int MAX = 10000; // 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.static boolean prime[] = new boolean [MAX + 1]; static void SieveOfEratosthenes(){ int i ; for (i = 0; i < MAX + 1; i++) { prime[i] = true; } prime[1] = false; for (int p = 2; p * p <= MAX; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Set all multiples of p to non-prime for (i = p * 2; i <= MAX; i += p) prime[i] = false; } }} // Function to return the xor of// 1st N prime numbersstatic int xorFirstNPrime(int n){ // Count of prime numbers int count = 0, num = 1; // XOR of prime numbers int xorVal = 0; while (count < n) { // If the number is prime xor it if (prime[num]) { xorVal ^= num; // Increment the count count++; } // Get to the next number num++; } return xorVal;} // Driver codepublic static void main (String[] args){ // Create the sieve SieveOfEratosthenes(); int n = 4; // Find the xor of 1st n prime numbers System.out.println(xorFirstNPrime(n)); }} // This code is contributed by AnkitRai01
# Python3 implementation of the approachMAX = 10000 # 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(MAX + 1)] def SieveOfEratosthenes(): prime[1] = False for p in range(2, MAX + 1): # If prime[p] is not changed, # then it is a prime if (prime[p] == True): # Set all multiples of p to non-prime for i in range(2 * p, MAX + 1, p): prime[i] = False # Function to return the xor of# 1st N prime numbersdef xorFirstNPrime(n): # Count of prime numbers count = 0 num = 1 # XOR of prime numbers xorVal = 0 while (count < n): # If the number is prime xor it if (prime[num]): xorVal ^= num # Increment the count count += 1 # Get to the next number num += 1 return xorVal # Driver code # Create the sieveSieveOfEratosthenes() n = 4 # Find the xor of 1st n prime numbersprint(xorFirstNPrime(n)) # This code is contributed by Mohit Kumar
// C# implementation of the approachusing System; class GFG{ static int MAX = 10000; // 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.static bool []prime = new bool [MAX + 1]; static void SieveOfEratosthenes(){ int i ; for (i = 0; i < MAX + 1; i++) { prime[i] = true; } prime[1] = false; for (int p = 2; p * p <= MAX; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Set all multiples of p to non-prime for (i = p * 2; i <= MAX; i += p) prime[i] = false; } }} // Function to return the xor of// 1st N prime numbersstatic int xorFirstNPrime(int n){ // Count of prime numbers int count = 0, num = 1; // XOR of prime numbers int xorVal = 0; while (count < n) { // If the number is prime xor it if (prime[num]) { xorVal ^= num; // Increment the count count++; } // Get to the next number num++; } return xorVal;} // Driver codestatic public void Main (){ // Create the sieve SieveOfEratosthenes(); int n = 4; // Find the xor of 1st n prime numbers Console.Write(xorFirstNPrime(n));}} // This code is contributed by Sachin
<script> // Javascript implementation of the approach let MAX = 10000; // 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 = new Array(MAX + 1); function SieveOfEratosthenes() { let i; for (i = 0; i < MAX + 1; i++) { prime[i] = true; } prime[1] = false; for (let p = 2; p * p <= MAX; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Set all multiples of p to non-prime for (i = p * 2; i <= MAX; i += p) prime[i] = false; } } } // Function to return the xor of // 1st N prime numbers function xorFirstNPrime(n) { // Count of prime numbers let count = 0, num = 1; // XOR of prime numbers let xorVal = 0; while (count < n) { // If the number is prime xor it if (prime[num]) { xorVal ^= num; // Increment the count count++; } // Get to the next number num++; } return xorVal; } // Create the sieve SieveOfEratosthenes(); let n = 4; // Find the xor of 1st n prime numbers document.write(xorFirstNPrime(n)); </script>
3
Time Complexity: O(n + MAX*log(log(MAX)))
Auxiliary Space: O(MAX)
mohit kumar 29
ankthon
Sach_Code
divyeshrabadiya07
subhamkumarm348
Bitwise-XOR
Prime Number
sieve
Arrays
Mathematical
Arrays
Mathematical
Prime Number
sieve
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Window Sliding Technique
Program to find sum of elements in a given array
Reversal algorithm for array rotation
Find duplicates in O(n) time and O(1) extra space | Set 1
Trapping Rain Water
Program for Fibonacci numbers
C++ Data Types
Write a program to print all permutations of a given string
Set in C++ Standard Template Library (STL)
Coin Change | DP-7 | [
{
"code": null,
"e": 24716,
"s": 24688,
"text": "\n18 Mar, 2022"
},
{
"code": null,
"e": 24813,
"s": 24716,
"text": "Given a positive integer N, the task is to find the XOR of the first N prime numbers.Examples: "
},
{
"code": null,
"e": 24916,
"s": 24813,
"text": "Input: N = 3 Output: 4 First 3 prime numbers are 2, 3 and 5. And 2 ^ 3 ^ 5 = 4Input: N = 5 Output: 8 "
},
{
"code": null,
"e": 24928,
"s": 24916,
"text": "Approach: "
},
{
"code": null,
"e": 25193,
"s": 24928,
"text": "Create Sieve of Eratosthenes to identify if a number is prime or not in O(1) time.Run a loop starting from 1 until and unless we find N prime numbers.XOR all the prime numbers and neglect those which are not prime.Finally, print the XOR of the 1st N prime numbers."
},
{
"code": null,
"e": 25276,
"s": 25193,
"text": "Create Sieve of Eratosthenes to identify if a number is prime or not in O(1) time."
},
{
"code": null,
"e": 25345,
"s": 25276,
"text": "Run a loop starting from 1 until and unless we find N prime numbers."
},
{
"code": null,
"e": 25410,
"s": 25345,
"text": "XOR all the prime numbers and neglect those which are not prime."
},
{
"code": null,
"e": 25461,
"s": 25410,
"text": "Finally, print the XOR of the 1st N prime numbers."
},
{
"code": null,
"e": 25513,
"s": 25461,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25517,
"s": 25513,
"text": "C++"
},
{
"code": null,
"e": 25522,
"s": 25517,
"text": "Java"
},
{
"code": null,
"e": 25530,
"s": 25522,
"text": "Python3"
},
{
"code": null,
"e": 25533,
"s": 25530,
"text": "C#"
},
{
"code": null,
"e": 25544,
"s": 25533,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;#define MAX 10000 // 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[MAX + 1];void SieveOfEratosthenes(){ memset(prime, true, sizeof(prime)); prime[1] = false; for (int p = 2; p * p <= MAX; p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == true) { // Set all multiples of p to non-prime for (int i = p * 2; i <= MAX; i += p) prime[i] = false; } }} // Function to return the xor of 1st N prime numbersint xorFirstNPrime(int n){ // Count of prime numbers int count = 0, num = 1; // XOR of prime numbers int xorVal = 0; while (count < n) { // If the number is prime xor it if (prime[num]) { xorVal ^= num; // Increment the count count++; } // Get to the next number num++; } return xorVal;} // Driver codeint main(){ // Create the sieve SieveOfEratosthenes(); int n = 4; // Find the xor of 1st n prime numbers cout << xorFirstNPrime(n); return 0;}",
"e": 26798,
"s": 25544,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG{static final int MAX = 10000; // 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.static boolean prime[] = new boolean [MAX + 1]; static void SieveOfEratosthenes(){ int i ; for (i = 0; i < MAX + 1; i++) { prime[i] = true; } prime[1] = false; for (int p = 2; p * p <= MAX; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Set all multiples of p to non-prime for (i = p * 2; i <= MAX; i += p) prime[i] = false; } }} // Function to return the xor of// 1st N prime numbersstatic int xorFirstNPrime(int n){ // Count of prime numbers int count = 0, num = 1; // XOR of prime numbers int xorVal = 0; while (count < n) { // If the number is prime xor it if (prime[num]) { xorVal ^= num; // Increment the count count++; } // Get to the next number num++; } return xorVal;} // Driver codepublic static void main (String[] args){ // Create the sieve SieveOfEratosthenes(); int n = 4; // Find the xor of 1st n prime numbers System.out.println(xorFirstNPrime(n)); }} // This code is contributed by AnkitRai01",
"e": 28213,
"s": 26798,
"text": null
},
{
"code": "# Python3 implementation of the approachMAX = 10000 # 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(MAX + 1)] def SieveOfEratosthenes(): prime[1] = False for p in range(2, MAX + 1): # If prime[p] is not changed, # then it is a prime if (prime[p] == True): # Set all multiples of p to non-prime for i in range(2 * p, MAX + 1, p): prime[i] = False # Function to return the xor of# 1st N prime numbersdef xorFirstNPrime(n): # Count of prime numbers count = 0 num = 1 # XOR of prime numbers xorVal = 0 while (count < n): # If the number is prime xor it if (prime[num]): xorVal ^= num # Increment the count count += 1 # Get to the next number num += 1 return xorVal # Driver code # Create the sieveSieveOfEratosthenes() n = 4 # Find the xor of 1st n prime numbersprint(xorFirstNPrime(n)) # This code is contributed by Mohit Kumar",
"e": 29336,
"s": 28213,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ static int MAX = 10000; // 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.static bool []prime = new bool [MAX + 1]; static void SieveOfEratosthenes(){ int i ; for (i = 0; i < MAX + 1; i++) { prime[i] = true; } prime[1] = false; for (int p = 2; p * p <= MAX; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Set all multiples of p to non-prime for (i = p * 2; i <= MAX; i += p) prime[i] = false; } }} // Function to return the xor of// 1st N prime numbersstatic int xorFirstNPrime(int n){ // Count of prime numbers int count = 0, num = 1; // XOR of prime numbers int xorVal = 0; while (count < n) { // If the number is prime xor it if (prime[num]) { xorVal ^= num; // Increment the count count++; } // Get to the next number num++; } return xorVal;} // Driver codestatic public void Main (){ // Create the sieve SieveOfEratosthenes(); int n = 4; // Find the xor of 1st n prime numbers Console.Write(xorFirstNPrime(n));}} // This code is contributed by Sachin",
"e": 30737,
"s": 29336,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach let MAX = 10000; // 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 = new Array(MAX + 1); function SieveOfEratosthenes() { let i; for (i = 0; i < MAX + 1; i++) { prime[i] = true; } prime[1] = false; for (let p = 2; p * p <= MAX; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Set all multiples of p to non-prime for (i = p * 2; i <= MAX; i += p) prime[i] = false; } } } // Function to return the xor of // 1st N prime numbers function xorFirstNPrime(n) { // Count of prime numbers let count = 0, num = 1; // XOR of prime numbers let xorVal = 0; while (count < n) { // If the number is prime xor it if (prime[num]) { xorVal ^= num; // Increment the count count++; } // Get to the next number num++; } return xorVal; } // Create the sieve SieveOfEratosthenes(); let n = 4; // Find the xor of 1st n prime numbers document.write(xorFirstNPrime(n)); </script>",
"e": 32347,
"s": 30737,
"text": null
},
{
"code": null,
"e": 32349,
"s": 32347,
"text": "3"
},
{
"code": null,
"e": 32393,
"s": 32351,
"text": "Time Complexity: O(n + MAX*log(log(MAX)))"
},
{
"code": null,
"e": 32417,
"s": 32393,
"text": "Auxiliary Space: O(MAX)"
},
{
"code": null,
"e": 32432,
"s": 32417,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 32440,
"s": 32432,
"text": "ankthon"
},
{
"code": null,
"e": 32450,
"s": 32440,
"text": "Sach_Code"
},
{
"code": null,
"e": 32468,
"s": 32450,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 32484,
"s": 32468,
"text": "subhamkumarm348"
},
{
"code": null,
"e": 32496,
"s": 32484,
"text": "Bitwise-XOR"
},
{
"code": null,
"e": 32509,
"s": 32496,
"text": "Prime Number"
},
{
"code": null,
"e": 32515,
"s": 32509,
"text": "sieve"
},
{
"code": null,
"e": 32522,
"s": 32515,
"text": "Arrays"
},
{
"code": null,
"e": 32535,
"s": 32522,
"text": "Mathematical"
},
{
"code": null,
"e": 32542,
"s": 32535,
"text": "Arrays"
},
{
"code": null,
"e": 32555,
"s": 32542,
"text": "Mathematical"
},
{
"code": null,
"e": 32568,
"s": 32555,
"text": "Prime Number"
},
{
"code": null,
"e": 32574,
"s": 32568,
"text": "sieve"
},
{
"code": null,
"e": 32672,
"s": 32574,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32681,
"s": 32672,
"text": "Comments"
},
{
"code": null,
"e": 32694,
"s": 32681,
"text": "Old Comments"
},
{
"code": null,
"e": 32719,
"s": 32694,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 32768,
"s": 32719,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 32806,
"s": 32768,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 32864,
"s": 32806,
"text": "Find duplicates in O(n) time and O(1) extra space | Set 1"
},
{
"code": null,
"e": 32884,
"s": 32864,
"text": "Trapping Rain Water"
},
{
"code": null,
"e": 32914,
"s": 32884,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 32929,
"s": 32914,
"text": "C++ Data Types"
},
{
"code": null,
"e": 32989,
"s": 32929,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 33032,
"s": 32989,
"text": "Set in C++ Standard Template Library (STL)"
}
]
|
Collaborative Filtering and Embeddings — Part 2 | by Shikhar Gupta | Towards Data Science | In Part 1, I’ve covered the basic idea behind collaborative filtering and the concept of embeddings and bias. It is recommended that you go through that post before going ahead.
Collaborative Filtering and Embeddings — Part 1
In this part I’ll talk about how we can implement collaborative filtering using a library called fastai developed by Jeremy Howard et al. This library is built on top of pytorch and is focused on easier implementation of machine learning and deep learning models.
Also, we’ll get to know how we can interpret and visualise embeddings using t-SNE, Plotly and Bokeh (Python interactive visualisation library that targets modern web browsers for presentation).
Most of the ideas presented in this post are derived from the Deep learning MOOC -v2 conducted by Jeremy Howard as part of the Data Institute. This post is just my attempt to share some amazing stuff that I’m learning during this course.
I have used Movielens [1] dataset (ml-latest-small). This dataset describes 5-star rating and free-text tagging activity from MovieLens, a movie recommendation service. It contains 100004 ratings and 1296 tag applications across 9125 movies. These data were created by 671 users between January 09, 1995 and October 16, 2016.
We’ll be using 2 files: ratings.csv and movies.csv
Before we get started we need 2 things:
A GPU enabled machine (local or AWS)
Install fastai library on your machine: pip install fastai
Note: At the end of the post I have explained in detail as to how to setup your system for fastai
Below is a step by step code walkthrough of the implementation using fastai. The underlying algorithm is the same as what we have discussed in Part 1.
We are looking at 2 files: ratings and movies
Ratings contain ratings by different users for different movies.
Movies contains metadata about movies. movieid is the key to join the 2 datasets.
#fastai functionval_idxs = get_cv_idxs(len(ratings)) #get validation indices
We’ll divide our data into train and validation set. Our validation is 20% of our original dataset.
wd=2e-4 #weight decayn_factors = 50 #dimension of embedding vector
We’ll use weight decay to reduce overfitting. Also we have to define the dimension of our embedding vector.
#fastai functioncf = CollabFilterDataset.from_csv(path, 'ratings.csv', 'userId', 'movieId', 'rating') #creating a custom data loader
Now we have to create a data object for collaborative filtering. Think of it as something which will transform your raw data and prepare it in the form that is required by the model. from_csv implies that the input should be a csv file.
Parameters of the function:
path: path to the location of the csv file
ratings.csv : name of the csv file. It should be in the long format shown in figure 1
userID/movieID : column names of the 2 entities
rating : column name of the dependent variable that you want to predict
#create a learner (model) and specify the batch size and optimizer learn = cf.get_learner(n_factors, val_idxs, 64, opt_fn=optim.Adam) #fastai function
Next step is to create a model object which is a function of the data object that we have created. learner in fastai library is synonymous to model. This function takes the following parameters:
n_factors : Dimension of the embedding vector (50 in our case)
val_idxs : Row Indices from the ratings.csv file which have to be considered in validation
batch size : Number of rows that will be passed to the optimiser for each step of gradient descent. In our case 64 rows will be passed per iteration
opt_fn : Optimiser that we want to use. In our case we are using Adam. You have access to different optimisers in this library
#training with learning rate as 1e-2 learn.fit(1e-2, 2, wds=wd, cycle_len=1, cycle_mult=2, use_wd_sched=True) #fastai function
The final step of training is to actually train the model. Calling fit on the learner object trains the model and learn the right values in the embedding and bias matrix.
Parameters of the function:
learning rate : 1e-2 is the learning rate that we use for optimisation
wd : passing the weight decay
cycle_len/cycle_mult : These are fastai goodies that incorporate the state of the art methods for learning rate scheduling. The end of the post contains links to useful articles related to this.
use_wd_sched : Whether to use schedule for weight decay
When you run the above code, model will start training as shown below. You can observe training (left) and validation (right) loss after each epoch. Our loss function for optimisation is MSE (Mean squared error) .
preds = learn.predict() #prediction on validationmath.sqrt(metrics.mean_squared_error(y,preds)) #calculating RMSE
We’ll use the trained model to predict on validation and compute RMSE. We get an RMSE of ~.90 which is at par with the current benchmarks for this dataset.
y=learn.data.val_y #actual ratings for validationsns.jointplot(preds, y, kind='hex', stat_func=None);
We can also see that our predictions from the model are in tally with the actual ratings.
Now we’ll try to interpret the embeddings and bias and see if they capture some meaningful information.
We’ll focus on embeddings and bias for movies as we have actual titles for movies.
We know that our embedding vectors are of dimension 50. Visualising such high-dimensional vector is difficult and next to impossible.
t-distributed stochastic neighbour embedding (t-SNE) is a effective way to visualise them in lower dimensions while maintaining the spatial relationship between these vectors.
Using the above code I have reduced the dimensionality of embedding vectors to 2 (t-SNE components). Below we can visualise the 2 t-SNE components of embeddings for 3000 movies. Each point represents a movie.
You can play with this plot here: http://tsne.getforge.io/
Zooming in further we can see that movies from the same franchise are very close in the embedding space (almost overlapping). This shows that embeddings are not just some numbers optimised for reducing loss.
We expect that movies in the same franchise are more or less similar in characteristics like genre, director, cast among many other things. Closeness in embedding space reflects that embeddings are capturing these characteristics
Movie bias can be considered as a measure of actual goodness of the movie adjusting for the different rating patterns of different users.
Bias can be considered as a proxy for how good/popular the movie actually is
Let’s see whether this is reflected in the bias from our model
Looking at the list, I guess most of you’ll agree that this list seems more or less appropriate and closer to most of our expectations.
Ranking movies based on bias makes much more sense then just averaging the ratings given by all users. Opposed to the name, it’s actually making the rankings unbiased
For me this is the most interesting section. Below I have picked a user (userID:547) which has rated the maximum number of movies. Now I’m trying to see if there is any visible relationship between the ratings given by the user and the embedding vectors of different movies.
And guess what...
It’s quite evident that movies which are highly rated (black and red) are concentrated in one portion of the embedding space. Similarly, movies which are low rated (green and blue) are concentrated in another portion of the space.
Link to the html file of the plot. Download and open in browser: https://github.com/shik3519/collaborative-filtering/blob/master/t-SNE_cluster_rating.html
On similar lines I have tried to cluster movie embeddings based on the movie bias. The expectation is that movies with similar bias (measure of unbiased popularity as discussed) should be close in embedding space.
And we can see that in the below plot.
Movies which are good (or bad) have some characteristics in common which are getting captured by the embeddings
Link to the html file of the plot. Download and open in browser: https://github.com/shik3519/collaborative-filtering/blob/master/t-SNE_emb_cluster_bias.html
I was feeling fancy so I tried visualising 3 t-SNE components of movie embeddings clustered by bias. Each point represents a movie and the size and colour of the point is dependent on bias.
Here is the link to the actual plot: https://plot.ly/~shik1470/2/
Link to the data used for this plot: https://github.com/shik3519/collaborative-filtering/blob/master/t-sne1.csv
By now I guess you’ll be somewhat convinced that the idea of embeddings is quite powerful. This concept can be extended to any problem with structured data where you have a lot of categorical variables.
Each level of a categorical variable can be represented as a high dimensional vector which can capture relationships which label or one-hot encoding fails to capture. Label or one hot encoding assumes that every entity is independent of each other which is definitely not the case if you think about it.
Here is another cool post on usage of embeddings in structural settings that you should definitely checkout.
towardsdatascience.com
Learning rate selection and scheduling:
Learning rate selection and scheduling:
techburst.io
towardsdatascience.com
medium.com
2. t-SNE:
distill.pub
medium.com
www.kaggle.com
3. fastai:
Github repo of the library: https://github.com/fastai/fastai
fastai notebook on collaborative filtering
Instructions for setting up fastai:
4. GitHub repo for this post : This repo contains the notebook and plots shown in this post
[1] F. Maxwell Harper and Joseph A. Konstan. 2015. The MovieLens Datasets: History and Context. ACM Transactions on Interactive Intelligent Systems (TiiS) 5, 4, Article 19 (December 2015), 19 pages. DOI=http://dx.doi.org/10.1145/2827872 | [
{
"code": null,
"e": 350,
"s": 172,
"text": "In Part 1, I’ve covered the basic idea behind collaborative filtering and the concept of embeddings and bias. It is recommended that you go through that post before going ahead."
},
{
"code": null,
"e": 398,
"s": 350,
"text": "Collaborative Filtering and Embeddings — Part 1"
},
{
"code": null,
"e": 662,
"s": 398,
"text": "In this part I’ll talk about how we can implement collaborative filtering using a library called fastai developed by Jeremy Howard et al. This library is built on top of pytorch and is focused on easier implementation of machine learning and deep learning models."
},
{
"code": null,
"e": 856,
"s": 662,
"text": "Also, we’ll get to know how we can interpret and visualise embeddings using t-SNE, Plotly and Bokeh (Python interactive visualisation library that targets modern web browsers for presentation)."
},
{
"code": null,
"e": 1094,
"s": 856,
"text": "Most of the ideas presented in this post are derived from the Deep learning MOOC -v2 conducted by Jeremy Howard as part of the Data Institute. This post is just my attempt to share some amazing stuff that I’m learning during this course."
},
{
"code": null,
"e": 1420,
"s": 1094,
"text": "I have used Movielens [1] dataset (ml-latest-small). This dataset describes 5-star rating and free-text tagging activity from MovieLens, a movie recommendation service. It contains 100004 ratings and 1296 tag applications across 9125 movies. These data were created by 671 users between January 09, 1995 and October 16, 2016."
},
{
"code": null,
"e": 1471,
"s": 1420,
"text": "We’ll be using 2 files: ratings.csv and movies.csv"
},
{
"code": null,
"e": 1511,
"s": 1471,
"text": "Before we get started we need 2 things:"
},
{
"code": null,
"e": 1548,
"s": 1511,
"text": "A GPU enabled machine (local or AWS)"
},
{
"code": null,
"e": 1607,
"s": 1548,
"text": "Install fastai library on your machine: pip install fastai"
},
{
"code": null,
"e": 1705,
"s": 1607,
"text": "Note: At the end of the post I have explained in detail as to how to setup your system for fastai"
},
{
"code": null,
"e": 1856,
"s": 1705,
"text": "Below is a step by step code walkthrough of the implementation using fastai. The underlying algorithm is the same as what we have discussed in Part 1."
},
{
"code": null,
"e": 1902,
"s": 1856,
"text": "We are looking at 2 files: ratings and movies"
},
{
"code": null,
"e": 1967,
"s": 1902,
"text": "Ratings contain ratings by different users for different movies."
},
{
"code": null,
"e": 2049,
"s": 1967,
"text": "Movies contains metadata about movies. movieid is the key to join the 2 datasets."
},
{
"code": null,
"e": 2127,
"s": 2049,
"text": "#fastai functionval_idxs = get_cv_idxs(len(ratings)) #get validation indices "
},
{
"code": null,
"e": 2227,
"s": 2127,
"text": "We’ll divide our data into train and validation set. Our validation is 20% of our original dataset."
},
{
"code": null,
"e": 2294,
"s": 2227,
"text": "wd=2e-4 #weight decayn_factors = 50 #dimension of embedding vector"
},
{
"code": null,
"e": 2402,
"s": 2294,
"text": "We’ll use weight decay to reduce overfitting. Also we have to define the dimension of our embedding vector."
},
{
"code": null,
"e": 2535,
"s": 2402,
"text": "#fastai functioncf = CollabFilterDataset.from_csv(path, 'ratings.csv', 'userId', 'movieId', 'rating') #creating a custom data loader"
},
{
"code": null,
"e": 2772,
"s": 2535,
"text": "Now we have to create a data object for collaborative filtering. Think of it as something which will transform your raw data and prepare it in the form that is required by the model. from_csv implies that the input should be a csv file."
},
{
"code": null,
"e": 2800,
"s": 2772,
"text": "Parameters of the function:"
},
{
"code": null,
"e": 2843,
"s": 2800,
"text": "path: path to the location of the csv file"
},
{
"code": null,
"e": 2929,
"s": 2843,
"text": "ratings.csv : name of the csv file. It should be in the long format shown in figure 1"
},
{
"code": null,
"e": 2977,
"s": 2929,
"text": "userID/movieID : column names of the 2 entities"
},
{
"code": null,
"e": 3049,
"s": 2977,
"text": "rating : column name of the dependent variable that you want to predict"
},
{
"code": null,
"e": 3200,
"s": 3049,
"text": "#create a learner (model) and specify the batch size and optimizer learn = cf.get_learner(n_factors, val_idxs, 64, opt_fn=optim.Adam) #fastai function"
},
{
"code": null,
"e": 3395,
"s": 3200,
"text": "Next step is to create a model object which is a function of the data object that we have created. learner in fastai library is synonymous to model. This function takes the following parameters:"
},
{
"code": null,
"e": 3458,
"s": 3395,
"text": "n_factors : Dimension of the embedding vector (50 in our case)"
},
{
"code": null,
"e": 3549,
"s": 3458,
"text": "val_idxs : Row Indices from the ratings.csv file which have to be considered in validation"
},
{
"code": null,
"e": 3698,
"s": 3549,
"text": "batch size : Number of rows that will be passed to the optimiser for each step of gradient descent. In our case 64 rows will be passed per iteration"
},
{
"code": null,
"e": 3825,
"s": 3698,
"text": "opt_fn : Optimiser that we want to use. In our case we are using Adam. You have access to different optimisers in this library"
},
{
"code": null,
"e": 3952,
"s": 3825,
"text": "#training with learning rate as 1e-2 learn.fit(1e-2, 2, wds=wd, cycle_len=1, cycle_mult=2, use_wd_sched=True) #fastai function"
},
{
"code": null,
"e": 4123,
"s": 3952,
"text": "The final step of training is to actually train the model. Calling fit on the learner object trains the model and learn the right values in the embedding and bias matrix."
},
{
"code": null,
"e": 4151,
"s": 4123,
"text": "Parameters of the function:"
},
{
"code": null,
"e": 4222,
"s": 4151,
"text": "learning rate : 1e-2 is the learning rate that we use for optimisation"
},
{
"code": null,
"e": 4252,
"s": 4222,
"text": "wd : passing the weight decay"
},
{
"code": null,
"e": 4447,
"s": 4252,
"text": "cycle_len/cycle_mult : These are fastai goodies that incorporate the state of the art methods for learning rate scheduling. The end of the post contains links to useful articles related to this."
},
{
"code": null,
"e": 4503,
"s": 4447,
"text": "use_wd_sched : Whether to use schedule for weight decay"
},
{
"code": null,
"e": 4717,
"s": 4503,
"text": "When you run the above code, model will start training as shown below. You can observe training (left) and validation (right) loss after each epoch. Our loss function for optimisation is MSE (Mean squared error) ."
},
{
"code": null,
"e": 4831,
"s": 4717,
"text": "preds = learn.predict() #prediction on validationmath.sqrt(metrics.mean_squared_error(y,preds)) #calculating RMSE"
},
{
"code": null,
"e": 4987,
"s": 4831,
"text": "We’ll use the trained model to predict on validation and compute RMSE. We get an RMSE of ~.90 which is at par with the current benchmarks for this dataset."
},
{
"code": null,
"e": 5089,
"s": 4987,
"text": "y=learn.data.val_y #actual ratings for validationsns.jointplot(preds, y, kind='hex', stat_func=None);"
},
{
"code": null,
"e": 5179,
"s": 5089,
"text": "We can also see that our predictions from the model are in tally with the actual ratings."
},
{
"code": null,
"e": 5283,
"s": 5179,
"text": "Now we’ll try to interpret the embeddings and bias and see if they capture some meaningful information."
},
{
"code": null,
"e": 5366,
"s": 5283,
"text": "We’ll focus on embeddings and bias for movies as we have actual titles for movies."
},
{
"code": null,
"e": 5500,
"s": 5366,
"text": "We know that our embedding vectors are of dimension 50. Visualising such high-dimensional vector is difficult and next to impossible."
},
{
"code": null,
"e": 5676,
"s": 5500,
"text": "t-distributed stochastic neighbour embedding (t-SNE) is a effective way to visualise them in lower dimensions while maintaining the spatial relationship between these vectors."
},
{
"code": null,
"e": 5885,
"s": 5676,
"text": "Using the above code I have reduced the dimensionality of embedding vectors to 2 (t-SNE components). Below we can visualise the 2 t-SNE components of embeddings for 3000 movies. Each point represents a movie."
},
{
"code": null,
"e": 5944,
"s": 5885,
"text": "You can play with this plot here: http://tsne.getforge.io/"
},
{
"code": null,
"e": 6152,
"s": 5944,
"text": "Zooming in further we can see that movies from the same franchise are very close in the embedding space (almost overlapping). This shows that embeddings are not just some numbers optimised for reducing loss."
},
{
"code": null,
"e": 6382,
"s": 6152,
"text": "We expect that movies in the same franchise are more or less similar in characteristics like genre, director, cast among many other things. Closeness in embedding space reflects that embeddings are capturing these characteristics"
},
{
"code": null,
"e": 6520,
"s": 6382,
"text": "Movie bias can be considered as a measure of actual goodness of the movie adjusting for the different rating patterns of different users."
},
{
"code": null,
"e": 6597,
"s": 6520,
"text": "Bias can be considered as a proxy for how good/popular the movie actually is"
},
{
"code": null,
"e": 6660,
"s": 6597,
"text": "Let’s see whether this is reflected in the bias from our model"
},
{
"code": null,
"e": 6796,
"s": 6660,
"text": "Looking at the list, I guess most of you’ll agree that this list seems more or less appropriate and closer to most of our expectations."
},
{
"code": null,
"e": 6963,
"s": 6796,
"text": "Ranking movies based on bias makes much more sense then just averaging the ratings given by all users. Opposed to the name, it’s actually making the rankings unbiased"
},
{
"code": null,
"e": 7238,
"s": 6963,
"text": "For me this is the most interesting section. Below I have picked a user (userID:547) which has rated the maximum number of movies. Now I’m trying to see if there is any visible relationship between the ratings given by the user and the embedding vectors of different movies."
},
{
"code": null,
"e": 7256,
"s": 7238,
"text": "And guess what..."
},
{
"code": null,
"e": 7487,
"s": 7256,
"text": "It’s quite evident that movies which are highly rated (black and red) are concentrated in one portion of the embedding space. Similarly, movies which are low rated (green and blue) are concentrated in another portion of the space."
},
{
"code": null,
"e": 7642,
"s": 7487,
"text": "Link to the html file of the plot. Download and open in browser: https://github.com/shik3519/collaborative-filtering/blob/master/t-SNE_cluster_rating.html"
},
{
"code": null,
"e": 7856,
"s": 7642,
"text": "On similar lines I have tried to cluster movie embeddings based on the movie bias. The expectation is that movies with similar bias (measure of unbiased popularity as discussed) should be close in embedding space."
},
{
"code": null,
"e": 7895,
"s": 7856,
"text": "And we can see that in the below plot."
},
{
"code": null,
"e": 8007,
"s": 7895,
"text": "Movies which are good (or bad) have some characteristics in common which are getting captured by the embeddings"
},
{
"code": null,
"e": 8164,
"s": 8007,
"text": "Link to the html file of the plot. Download and open in browser: https://github.com/shik3519/collaborative-filtering/blob/master/t-SNE_emb_cluster_bias.html"
},
{
"code": null,
"e": 8354,
"s": 8164,
"text": "I was feeling fancy so I tried visualising 3 t-SNE components of movie embeddings clustered by bias. Each point represents a movie and the size and colour of the point is dependent on bias."
},
{
"code": null,
"e": 8420,
"s": 8354,
"text": "Here is the link to the actual plot: https://plot.ly/~shik1470/2/"
},
{
"code": null,
"e": 8532,
"s": 8420,
"text": "Link to the data used for this plot: https://github.com/shik3519/collaborative-filtering/blob/master/t-sne1.csv"
},
{
"code": null,
"e": 8735,
"s": 8532,
"text": "By now I guess you’ll be somewhat convinced that the idea of embeddings is quite powerful. This concept can be extended to any problem with structured data where you have a lot of categorical variables."
},
{
"code": null,
"e": 9039,
"s": 8735,
"text": "Each level of a categorical variable can be represented as a high dimensional vector which can capture relationships which label or one-hot encoding fails to capture. Label or one hot encoding assumes that every entity is independent of each other which is definitely not the case if you think about it."
},
{
"code": null,
"e": 9148,
"s": 9039,
"text": "Here is another cool post on usage of embeddings in structural settings that you should definitely checkout."
},
{
"code": null,
"e": 9171,
"s": 9148,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 9211,
"s": 9171,
"text": "Learning rate selection and scheduling:"
},
{
"code": null,
"e": 9251,
"s": 9211,
"text": "Learning rate selection and scheduling:"
},
{
"code": null,
"e": 9264,
"s": 9251,
"text": "techburst.io"
},
{
"code": null,
"e": 9287,
"s": 9264,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 9298,
"s": 9287,
"text": "medium.com"
},
{
"code": null,
"e": 9308,
"s": 9298,
"text": "2. t-SNE:"
},
{
"code": null,
"e": 9320,
"s": 9308,
"text": "distill.pub"
},
{
"code": null,
"e": 9331,
"s": 9320,
"text": "medium.com"
},
{
"code": null,
"e": 9346,
"s": 9331,
"text": "www.kaggle.com"
},
{
"code": null,
"e": 9357,
"s": 9346,
"text": "3. fastai:"
},
{
"code": null,
"e": 9418,
"s": 9357,
"text": "Github repo of the library: https://github.com/fastai/fastai"
},
{
"code": null,
"e": 9461,
"s": 9418,
"text": "fastai notebook on collaborative filtering"
},
{
"code": null,
"e": 9497,
"s": 9461,
"text": "Instructions for setting up fastai:"
},
{
"code": null,
"e": 9589,
"s": 9497,
"text": "4. GitHub repo for this post : This repo contains the notebook and plots shown in this post"
}
]
|
How to Transpose a DataFrame in R? - GeeksforGeeks | 19 Dec, 2021
In this article, we will discuss how to transpose dataframe in R Programming Language. Transposing means converting rows to columns and columns to rows
R
# create a dataframedata = data.frame(col1=c(1:5), col2=c(6:10), col3=c(11:15), col4=c(16:20)) # assign row names to dataframerow.names(data) = c("r1","r2","r3","r4","r5") # displaydata
Output:
col1 col2 col3 col4
r1 1 6 11 16
r2 2 7 12 17
r3 3 8 13 18
r4 4 9 14 19
r5 5 10 15 20
Here we are using t() function which stands for transpose to transpose a dataframe
Syntax: t(dataframe)
where dataframe is the input dataframe
Example:
R
# create a dataframedata = data.frame(col1 = c(1:5), col2 = c(6:10), col3 = c(11:15), col4 = c(16:20)) # assign row names to dataframerow.names(data) = c("r1","r2","r3", "r4","r5") # display transposed dataframet(data)
Output:
r1 r2 r3 r4 r5
col1 1 2 3 4 5
col2 6 7 8 9 10
col3 11 12 13 14 15
col4 16 17 18 19 20
Here we are using data.table data structure to transpose the dataframe, we are using transpose() method to do this
Syntax: transpose(dataframe)
Example:
R
# load modulelibrary(data.table) # create a dataframedata = data.frame(col1=c(1:5), col2=c(6:10), col3=c(11:15), col4=c(16:20)) # assign row names to dataframerow.names(data) = c("r1","r2","r3","r4","r5") # display transposed dataframe# using data.tabletranspose(data)
Output:
V1 V2 V3 V4 V5
1 1 2 3 4 5
2 6 7 8 9 10
3 11 12 13 14 15
4 16 17 18 19 20
Picked
R DataFrame-Programs
R-DataFrame
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to Change Axis Scales in R Plots?
Replace Specific Characters in String in R
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to filter R dataframe by multiple conditions?
Convert Matrix to Dataframe in R | [
{
"code": null,
"e": 26597,
"s": 26569,
"text": "\n19 Dec, 2021"
},
{
"code": null,
"e": 26749,
"s": 26597,
"text": "In this article, we will discuss how to transpose dataframe in R Programming Language. Transposing means converting rows to columns and columns to rows"
},
{
"code": null,
"e": 26751,
"s": 26749,
"text": "R"
},
{
"code": "# create a dataframedata = data.frame(col1=c(1:5), col2=c(6:10), col3=c(11:15), col4=c(16:20)) # assign row names to dataframerow.names(data) = c(\"r1\",\"r2\",\"r3\",\"r4\",\"r5\") # displaydata",
"e": 26990,
"s": 26751,
"text": null
},
{
"code": null,
"e": 26998,
"s": 26990,
"text": "Output:"
},
{
"code": null,
"e": 27136,
"s": 26998,
"text": " col1 col2 col3 col4\nr1 1 6 11 16\nr2 2 7 12 17\nr3 3 8 13 18\nr4 4 9 14 19\nr5 5 10 15 20"
},
{
"code": null,
"e": 27219,
"s": 27136,
"text": "Here we are using t() function which stands for transpose to transpose a dataframe"
},
{
"code": null,
"e": 27240,
"s": 27219,
"text": "Syntax: t(dataframe)"
},
{
"code": null,
"e": 27279,
"s": 27240,
"text": "where dataframe is the input dataframe"
},
{
"code": null,
"e": 27288,
"s": 27279,
"text": "Example:"
},
{
"code": null,
"e": 27290,
"s": 27288,
"text": "R"
},
{
"code": "# create a dataframedata = data.frame(col1 = c(1:5), col2 = c(6:10), col3 = c(11:15), col4 = c(16:20)) # assign row names to dataframerow.names(data) = c(\"r1\",\"r2\",\"r3\", \"r4\",\"r5\") # display transposed dataframet(data)",
"e": 27582,
"s": 27290,
"text": null
},
{
"code": null,
"e": 27590,
"s": 27582,
"text": "Output:"
},
{
"code": null,
"e": 27689,
"s": 27590,
"text": " r1 r2 r3 r4 r5\ncol1 1 2 3 4 5\ncol2 6 7 8 9 10\ncol3 11 12 13 14 15\ncol4 16 17 18 19 20"
},
{
"code": null,
"e": 27804,
"s": 27689,
"text": "Here we are using data.table data structure to transpose the dataframe, we are using transpose() method to do this"
},
{
"code": null,
"e": 27833,
"s": 27804,
"text": "Syntax: transpose(dataframe)"
},
{
"code": null,
"e": 27842,
"s": 27833,
"text": "Example:"
},
{
"code": null,
"e": 27844,
"s": 27842,
"text": "R"
},
{
"code": "# load modulelibrary(data.table) # create a dataframedata = data.frame(col1=c(1:5), col2=c(6:10), col3=c(11:15), col4=c(16:20)) # assign row names to dataframerow.names(data) = c(\"r1\",\"r2\",\"r3\",\"r4\",\"r5\") # display transposed dataframe# using data.tabletranspose(data)",
"e": 28167,
"s": 27844,
"text": null
},
{
"code": null,
"e": 28175,
"s": 28167,
"text": "Output:"
},
{
"code": null,
"e": 28259,
"s": 28175,
"text": " V1 V2 V3 V4 V5\n1 1 2 3 4 5\n2 6 7 8 9 10\n3 11 12 13 14 15\n4 16 17 18 19 20"
},
{
"code": null,
"e": 28266,
"s": 28259,
"text": "Picked"
},
{
"code": null,
"e": 28287,
"s": 28266,
"text": "R DataFrame-Programs"
},
{
"code": null,
"e": 28299,
"s": 28287,
"text": "R-DataFrame"
},
{
"code": null,
"e": 28310,
"s": 28299,
"text": "R Language"
},
{
"code": null,
"e": 28321,
"s": 28310,
"text": "R Programs"
},
{
"code": null,
"e": 28419,
"s": 28321,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28471,
"s": 28419,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 28506,
"s": 28471,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 28564,
"s": 28506,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 28602,
"s": 28564,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 28645,
"s": 28602,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 28703,
"s": 28645,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 28746,
"s": 28703,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 28795,
"s": 28746,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 28845,
"s": 28795,
"text": "How to filter R dataframe by multiple conditions?"
}
]
|
HTML - Phrase Elements | Phrase elements add structural information to text fragments. The usual meanings of phrase elements are following −
NONE
<abbr>pvt. or inc.</abbr><br />
<acronym>HTML</acronym><br />
<cite>Citation</cite><br />
<em>Emphasized text</em><br />
<strong>Strong text</strong><br />
<dfn>Definition term</dfn><br />
<code>Computer code text</code><br />
<samp>Sample computer code text</samp><br />
<kbd>Keyboard text</kbd><br />
<var>Variable</var><br />
This will produce following result −
Document wide identifier
Specifies the direction of the text
Document wide identifier
Specifies a title to associate with the element.
Helps to include inline casecadubf style sheet.
Sets the language code.
Script runs when a mouse click
Script runs when a mouse double-click
Script runs when mouse button is pressed
Script runs when mouse button is released
Script runs when mouse pointer moves over an element
Script runs when mouse pointer moves
Script runs when mouse pointer moves out of an element
Script runs when key is pressed and released
Script runs when key is pressed
Script runs when key is released
19 Lectures
2 hours
Anadi Sharma
16 Lectures
1.5 hours
Anadi Sharma
18 Lectures
1.5 hours
Frahaan Hussain
57 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
54 Lectures
6 hours
DigiFisk (Programming Is Fun)
45 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2490,
"s": 2374,
"text": "Phrase elements add structural information to text fragments. The usual meanings of phrase elements are following −"
},
{
"code": null,
"e": 2495,
"s": 2490,
"text": "NONE"
},
{
"code": null,
"e": 2824,
"s": 2495,
"text": "<abbr>pvt. or inc.</abbr><br />\n<acronym>HTML</acronym><br />\n<cite>Citation</cite><br />\n<em>Emphasized text</em><br />\n<strong>Strong text</strong><br />\n<dfn>Definition term</dfn><br />\n<code>Computer code text</code><br />\n<samp>Sample computer code text</samp><br />\n<kbd>Keyboard text</kbd><br />\n<var>Variable</var><br />"
},
{
"code": null,
"e": 2861,
"s": 2824,
"text": "This will produce following result −"
},
{
"code": null,
"e": 2886,
"s": 2861,
"text": "Document wide identifier"
},
{
"code": null,
"e": 2922,
"s": 2886,
"text": "Specifies the direction of the text"
},
{
"code": null,
"e": 2947,
"s": 2922,
"text": "Document wide identifier"
},
{
"code": null,
"e": 2996,
"s": 2947,
"text": "Specifies a title to associate with the element."
},
{
"code": null,
"e": 3044,
"s": 2996,
"text": "Helps to include inline casecadubf style sheet."
},
{
"code": null,
"e": 3068,
"s": 3044,
"text": "Sets the language code."
},
{
"code": null,
"e": 3099,
"s": 3068,
"text": "Script runs when a mouse click"
},
{
"code": null,
"e": 3137,
"s": 3099,
"text": "Script runs when a mouse double-click"
},
{
"code": null,
"e": 3178,
"s": 3137,
"text": "Script runs when mouse button is pressed"
},
{
"code": null,
"e": 3220,
"s": 3178,
"text": "Script runs when mouse button is released"
},
{
"code": null,
"e": 3273,
"s": 3220,
"text": "Script runs when mouse pointer moves over an element"
},
{
"code": null,
"e": 3310,
"s": 3273,
"text": "Script runs when mouse pointer moves"
},
{
"code": null,
"e": 3365,
"s": 3310,
"text": "Script runs when mouse pointer moves out of an element"
},
{
"code": null,
"e": 3410,
"s": 3365,
"text": "Script runs when key is pressed and released"
},
{
"code": null,
"e": 3442,
"s": 3410,
"text": "Script runs when key is pressed"
},
{
"code": null,
"e": 3475,
"s": 3442,
"text": "Script runs when key is released"
},
{
"code": null,
"e": 3508,
"s": 3475,
"text": "\n 19 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3522,
"s": 3508,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3557,
"s": 3522,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3571,
"s": 3557,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3606,
"s": 3571,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3623,
"s": 3606,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3658,
"s": 3623,
"text": "\n 57 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3689,
"s": 3658,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3722,
"s": 3689,
"text": "\n 54 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3753,
"s": 3722,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3788,
"s": 3753,
"text": "\n 45 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3819,
"s": 3788,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3826,
"s": 3819,
"text": " Print"
},
{
"code": null,
"e": 3837,
"s": 3826,
"text": " Add Notes"
}
]
|
Check if a number is Palindrome - GeeksforGeeks | 27 Apr, 2022
Given an integer, write a function that returns true if the given number is palindrome, else false. For example, 12321 is palindrome, but 1451 is not palindrome.
Let the given number be num. A simple method for this problem is to first reverse digits of num, then compare the reverse of num with num. If both are same, then return true, else false.
Following is an interesting method inspired from method#2 of this post. The idea is to create a copy of num and recursively pass the copy by reference, and pass num by value. In the recursive calls, divide num by 10 while moving down the recursion tree. While moving up the recursion tree, divide the copy by 10. When they meet in a function for which all child calls are over, the last digit of num will be ith digit from the beginning and the last digit of copy will be ith digit from the end.
C++
C
Java
Python3
C#
PHP
Javascript
// A recursive C++ program to check// whether a given number// is palindrome or not#include <iostream>using namespace std; // A function that returns true only// if num contains one// digitint oneDigit(int num){ // Comparison operation is faster // than division // operation. So using following // instead of "return num // / 10 == 0;" return (num >= 0 && num < 10);} // A recursive function to find// out whether num is// palindrome or not. Initially, dupNum// contains address of// a copy of num.bool isPalUtil(int num, int* dupNum){ // Base case (needed for recursion // termination): This // statement mainly compares the // first digit with the // last digit if (oneDigit(num)) return (num == (*dupNum) % 10); // This is the key line in this // method. Note that all // recursive calls have a separate // copy of num, but they // all share same copy of *dupNum. // We divide num while // moving up the recursion tree if (!isPalUtil(num / 10, dupNum)) return false; // The following statements are // executed when we move up // the recursion call tree *dupNum /= 10; // At this point, if num%10 contains // i'th digit from // beginning, then (*dupNum)%10 // contains i'th digit // from end return (num % 10 == (*dupNum) % 10);} // The main function that uses// recursive function// isPalUtil() to find out whether// num is palindrome or notint isPal(int num){ // Check if num is negative, // make it positive if (num < 0) num = -num; // Create a separate copy of num, // so that modifications // made to address dupNum don't // change the input number. // *dupNum = num int* dupNum = new int(num); return isPalUtil(num, dupNum);} // Driver program to test// above functionsint main(){ int n = 12321; isPal(n) ? cout <<"Yes\n": cout <<"No" << endl; n = 12; isPal(n) ? cout <<"Yes\n": cout <<"No" << endl; n = 88; isPal(n) ? cout <<"Yes\n": cout <<"No" << endl; n = 8999; isPal(n) ? cout <<"Yes\n": cout <<"No"; return 0;} // this code is contributed by shivanisinghss2110
// A recursive C program to check// whether a given number// is palindrome or not#include <stdio.h> // A function that returns true only// if num contains one// digitint oneDigit(int num){ // Comparison operation is faster // than division // operation. So using following // instead of "return num // / 10 == 0;" return (num >= 0 && num < 10);} // A recursive function to find// out whether num is// palindrome or not. Initially, dupNum// contains address of// a copy of num.bool isPalUtil(int num, int* dupNum){ // Base case (needed for recursion // termination): This // statement mainly compares the // first digit with the // last digit if (oneDigit(num)) return (num == (*dupNum) % 10); // This is the key line in this // method. Note that all // recursive calls have a separate // copy of num, but they // all share same copy of *dupNum. // We divide num while // moving up the recursion tree if (!isPalUtil(num / 10, dupNum)) return false; // The following statements are // executed when we move up // the recursion call tree *dupNum /= 10; // At this point, if num%10 contains // i'th digit from // beginning, then (*dupNum)%10 // contains i'th digit // from end return (num % 10 == (*dupNum) % 10);} // The main function that uses// recursive function// isPalUtil() to find out whether// num is palindrome or notint isPal(int num){ // Check if num is negative, // make it positive if (num < 0) num = -num; // Create a separate copy of num, // so that modifications // made to address dupNum don't // change the input number. // *dupNum = num int* dupNum = new int(num); return isPalUtil(num, dupNum);} // Driver program to test// above functionsint main(){ int n = 12321; isPal(n) ? printf("Yes\n") : printf("No\n"); n = 12; isPal(n) ? printf("Yes\n") : printf("No\n"); n = 88; isPal(n) ? printf("Yes\n") : printf("No\n"); n = 8999; isPal(n) ? printf("Yes\n") : printf("No\n"); return 0;}
// A recursive Java program to// check whether a given number// is palindrome or notimport java.io.*;import java.util.*; public class CheckPallindromNumberRecursion { // A function that returns true // only if num contains one digit public static int oneDigit(int num) { if ((num >= 0) && (num < 10)) return 1; else return 0; } public static int isPalUtil (int num, int dupNum) throws Exception { // base condition to return once we // move past first digit if (num == 0) { return dupNum; } else { dupNum = isPalUtil(num / 10, dupNum); } // Check for equality of first digit of // num and dupNum if (num % 10 == dupNum % 10) { // if first digit values of num and // dupNum are equal divide dupNum // value by 10 to keep moving in sync // with num. return dupNum / 10; } else { // At position values are not // matching throw exception and exit. // no need to proceed further. throw new Exception(); } } public static int isPal(int num) throws Exception { if (num < 0) num = (-num); int dupNum = (num); return isPalUtil(num, dupNum); } public static void main(String args[]) { int n = 1242; try { isPal(n); System.out.println("Yes"); } catch (Exception e) { System.out.println("No"); } n = 1231; try { isPal(n); System.out.println("Yes"); } catch (Exception e) { System.out.println("No"); } n = 12; try { isPal(n); System.out.println("Yes"); } catch (Exception e) { System.out.println("No"); } n = 88; try { isPal(n); System.out.println("Yes"); } catch (Exception e) { System.out.println("No"); } n = 8999; try { isPal(n); System.out.println("Yes"); } catch (Exception e) { System.out.println("No"); } }} // This code is contributed// by Nasir J
# A recursive Python3 program to check# whether a given number is palindrome or not # A function that returns true# only if num contains one digitdef oneDigit(num): # comparison operation is faster # than division operation. So # using following instead of # "return num / 10 == 0;" return ((num >= 0) and (num < 10)) # A recursive function to find# out whether num is palindrome# or not. Initially, dupNum# contains address of a copy of num.def isPalUtil(num, dupNum): # Base case (needed for recursion # termination): This statement # mainly compares the first digit # with the last digit if oneDigit(num): return (num == (dupNum[0]) % 10) # This is the key line in this # method. Note that all recursive # calls have a separate copy of # num, but they all share same # copy of *dupNum. We divide num # while moving up the recursion tree if not isPalUtil(num //10, dupNum): return False # The following statements are # executed when we move up the # recursion call tree dupNum[0] = dupNum[0] //10 # At this point, if num%10 # contains i'th digit from # beginning, then (*dupNum)%10 # contains i'th digit from end return (num % 10 == (dupNum[0]) % 10) # The main function that uses# recursive function isPalUtil()# to find out whether num is# palindrome or notdef isPal(num): # If num is negative, # make it positive if (num < 0): num = (-num) # Create a separate copy of # num, so that modifications # made to address dupNum # don't change the input number. dupNum = [num] # *dupNum = num return isPalUtil(num, dupNum) # Driver Coden = 12321if isPal(n): print("Yes")else: print("No") n = 12if isPal(n) : print("Yes")else: print("No") n = 88if isPal(n) : print("Yes")else: print("No") n = 8999if isPal(n) : print("Yes")else: print("No") # This code is contributed by mits
// A recursive C# program to// check whether a given number// is palindrome or notusing System; class GFG{ // A function that returns true// only if num contains one digitpublic static int oneDigit(int num){ // comparison operation is // faster than division // operation. So using // following instead of // "return num / 10 == 0;" if((num >= 0) &&(num < 10)) return 1; else return 0;} // A recursive function to// find out whether num is// palindrome or not.// Initially, dupNum contains// address of a copy of num.public static int isPalUtil(int num, int dupNum){ // Base case (needed for recursion // termination): This statement // mainly compares the first digit // with the last digit if (oneDigit(num) == 1) if(num == (dupNum) % 10) return 1; else return 0; // This is the key line in // this method. Note that // all recursive calls have // a separate copy of num, // but they all share same // copy of *dupNum. We divide // num while moving up the // recursion tree if (isPalUtil((int)(num / 10), dupNum) == 0) return -1; // The following statements // are executed when we move // up the recursion call tree dupNum = (int)(dupNum / 10); // At this point, if num%10 // contains i'th digit from // beginning, then (*dupNum)%10 // contains i'th digit from end if(num % 10 == (dupNum) % 10) return 1; else return 0;} // The main function that uses// recursive function isPalUtil()// to find out whether num is// palindrome or notpublic static int isPal(int num){ // If num is negative, // make it positive if (num < 0) num = (-num); // Create a separate copy // of num, so that modifications // made to address dupNum // don't change the input number. int dupNum = (num); // *dupNum = num return isPalUtil(num, dupNum);} // Driver Codepublic static void Main(){int n = 12321;if(isPal(n) == 0) Console.WriteLine("Yes");else Console.WriteLine("No"); n = 12;if(isPal(n) == 0) Console.WriteLine("Yes");else Console.WriteLine( "No"); n = 88;if(isPal(n) == 1) Console.WriteLine("Yes");else Console.WriteLine("No"); n = 8999;if(isPal(n) == 0) Console.WriteLine("Yes");else Console.WriteLine("No");}} // This code is contributed by mits
<?php// A recursive PHP program to// check whether a given number// is palindrome or not // A function that returns true// only if num contains one digitfunction oneDigit($num){ // comparison operation is faster // than division operation. So // using following instead of // "return num / 10 == 0;" return (($num >= 0) && ($num < 10));} // A recursive function to find// out whether num is palindrome// or not. Initially, dupNum// contains address of a copy of num.function isPalUtil($num, $dupNum){ // Base case (needed for recursion // termination): This statement // mainly compares the first digit // with the last digit if (oneDigit($num)) return ($num == ($dupNum) % 10); // This is the key line in this // method. Note that all recursive // calls have a separate copy of // num, but they all share same // copy of *dupNum. We divide num // while moving up the recursion tree if (!isPalUtil((int)($num / 10), $dupNum)) return -1; // The following statements are // executed when we move up the // recursion call tree $dupNum = (int)($dupNum / 10); // At this point, if num%10 // contains i'th digit from // beginning, then (*dupNum)%10 // contains i'th digit from end return ($num % 10 == ($dupNum) % 10);} // The main function that uses// recursive function isPalUtil()// to find out whether num is// palindrome or notfunction isPal($num){ // If num is negative, // make it positive if ($num < 0) $num = (-$num); // Create a separate copy of // num, so that modifications // made to address dupNum // don't change the input number. $dupNum = ($num); // *dupNum = num return isPalUtil($num, $dupNum);} // Driver Code$n = 12321;if(isPal($n) == 0) echo "Yes\n";else echo "No\n"; $n = 12;if(isPal($n) == 0) echo "Yes\n";else echo "No\n"; $n = 88;if(isPal($n) == 1) echo "Yes\n";else echo "No\n"; $n = 8999;if(isPal($n) == 0) echo "Yes\n";else echo "No\n"; // This code is contributed by m_kit?>
<script>// A recursive javascript program to// check whether a given number// is palindrome or not // A function that returns true // only if num contains one digit function oneDigit(num) { if ((num >= 0) && (num < 10)) return 1; else return 0; } function isPalUtil (num , dupNum) { // base condition to return once we // move past first digit if (num == 0) { return dupNum; } else { dupNum = isPalUtil(parseInt(num / 10), dupNum); } // Check for equality of first digit of // num and dupNum if (num % 10 == dupNum % 10) { // if first digit values of num and // dupNum are equal divide dupNum // value by 10 to keep moving in sync // with num. return parseInt(dupNum / 10); } else { // At position values are not // matching throw exception and exit. // no need to proceed further. throw e; } } function isPal(num) { if (num < 0) num = (-num); var dupNum = (num); return isPalUtil(num, dupNum); } var n = 1242; try { isPal(n); document.write("<br>Yes"); } catch (e) { document.write("<br>No"); } n = 1231; try { isPal(n); document.write("<br>Yes"); } catch (e) { document.write("<br>No"); } n = 12; try { isPal(n); document.write("<br>Yes"); } catch (e) { document.write("<br>No"); } n = 88; try { isPal(n); document.write("<br>Yes"); } catch (e) { document.write("<br>No"); } n = 8999; try { isPal(n); document.write("<br>Yes"); } catch (e) { document.write("<br>No"); } // This code is contributed by Amit Katiyar</script>
Output:
Yes
No
Yes
No
To check a number is palindrome or not without using any extra spaceMethod #2:Using string() method
When the number of digits of that number exceeds 1018, we can’t take that number as an integer since the range of long long int doesn’t satisfy the given number.So take input as a string, Run a loop from starting to length/2 and check the first character(numeric) to the last character of the string and second to second last one, and so on ....If any character mismatches, the string wouldn’t be a palindrome.
When the number of digits of that number exceeds 1018, we can’t take that number as an integer since the range of long long int doesn’t satisfy the given number.
So take input as a string, Run a loop from starting to length/2 and check the first character(numeric) to the last character of the string and second to second last one, and so on ....If any character mismatches, the string wouldn’t be a palindrome.
Below is the implementation of the above approach
C++14
Java
Python3
C#
Javascript
// C++ implementation of the above approach#include <iostream>using namespace std; // Function to check palindromeint checkPalindrome(string str){ // Calculating string length int len = str.length(); // Traversing through the string // upto half its length for (int i = 0; i < len / 2; i++) { // Comparing i th character // from starting and len-i // th character from end if (str[i] != str[len - i - 1]) return false; } // If the above loop doesn't return then it is // palindrome return true;} // Driver Codeint main(){ // taking number as string string st = "112233445566778899000000998877665544332211"; if (checkPalindrome(st) == true) cout << "Yes"; else cout << "No"; return 0;}// this code is written by vikkycirus
// Java implementation of the above approachimport java.io.*; class GFG{ // Function to check palindromestatic boolean checkPalindrome(String str){ // Calculating string length int len = str.length(); // Traversing through the string // upto half its length for(int i = 0; i < len / 2; i++) { // Comparing i th character // from starting and len-i // th character from end if (str.charAt(i) != str.charAt(len - i - 1)) return false; } // If the above loop doesn't return then // it is palindrome return true;} // Driver Codepublic static void main(String[] args){ // Taking number as string String st = "112233445566778899000000998877665544332211"; if (checkPalindrome(st) == true) System.out.print("Yes"); else System.out.print("No");}} // This code is contributed by subhammahato348
# Python3 implementation of the above approach # function to check palindromedef checkPalindrome(str): # Run loop from 0 to len/2 for i in range(0, len(str)//2): if str[i] != str[len(str)-i-1]: return False # If the above loop doesn't #return then it is palindrome return True # Driver codest = "112233445566778899000000998877665544332211"if(checkPalindrome(st) == True): print("it is a palindrome")else: print("It is not a palindrome")
// C# implementation of the above approachusing System; class GFG{ // Function to check palindromestatic bool checkPalindrome(string str){ // Calculating string length int len = str.Length; // Traversing through the string // upto half its length for(int i = 0; i < len / 2; i++) { // Comparing i th character // from starting and len-i // th character from end if (str[i] != str[len - i - 1]) return false; } // If the above loop doesn't return then // it is palindrome return true;} // Driver Codepublic static void Main(){ // Taking number as string string st = "112233445566778899000000998877665544332211"; if (checkPalindrome(st) == true) Console.Write("Yes"); else Console.Write("No");}} // This code is contributed by subhammahato348
<script> // Javascript implementation of the above approach // Function to check palindromefunction checkPalindrome(str){ // Calculating string length var len = str.length; // Traversing through the string // upto half its length for (var i = 0; i < len / 2; i++) { // Comparing ith character // from starting and len-ith // character from end if (str[i] != str[len - i - 1]) return false; } // If the above loop doesn't return then it is // palindrome return true;} // Driver Code // taking number as string let st = "112233445566778899000000998877665544332211"; if (checkPalindrome(st) == true) document.write("Yes"); else document.write("No"); // This code is contributed by Mayank Tyagi </script>
Yes
Time Complexity: O(|str|)
Method #3:Using split(), reverse() and join() methods simultaneously
When user inputs an integer, it is further passed inside a method which will evaluate the result or the actual logic part.Logic part inside the method focuses on using several important JavaScript methods simultaneously.First task is to convert the integer passed in into the string using toString() method.Then split(), reverse() and join() method will be applied to obtain the reverse of that string.Thereafter using the triple equality operator (“===”), reverse string and original string will be compared and based on that result will be printed on the console.
When user inputs an integer, it is further passed inside a method which will evaluate the result or the actual logic part.
Logic part inside the method focuses on using several important JavaScript methods simultaneously.
First task is to convert the integer passed in into the string using toString() method.
Then split(), reverse() and join() method will be applied to obtain the reverse of that string.
Thereafter using the triple equality operator (“===”), reverse string and original string will be compared and based on that result will be printed on the console.
Below is the implementation of the above approach
Python3
Javascript
def checkPalindrome(x): convertedNumber = str(x) reverseString = convertedNumber[::-1] return "Yes" if reverseString == convertedNumber else "No" # Some Testcases...num = 12321print(checkPalindrome(num)) # Yes number = 456print(checkPalindrome(number)) # No # This code is contributed by shinjanpatra
function checkPalindrome(x) { let convertedNumber = x.toString(); let reverseString = convertedNumber.split("").reverse().join(""); return reverseString === convertedNumber ? "Yes" : "No";} // Some Testcases...let num = 12321;console.log(checkPalindrome(num)); // Yes let number = 456;console.log(checkPalindrome(number)); // No // This code is contributed by Aman Singla....
Output
Yes
No
This article is compiled by Aashish Barnwal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
jit_t
Mithun Kumar
Akanksha_Rai
NasirJamal
pansaripulkit13
vikkycirus
mayanktyagi1709
subhammahato348
amit143katiyar
akshaysingh98088
ruhelaa48
shivanisinghss2110
sagartomar9927
rishavmahato348
amansingla
simmytarika5
shinjanpatra
Adobe
Oracle
palindrome
Samsung
Zoho
Mathematical
Recursion
Zoho
Samsung
Oracle
Adobe
Mathematical
Recursion
palindrome
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Prime Numbers
Program to find GCD or HCF of two numbers
Print all possible combinations of r elements in a given array of size n
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Recursion
Program for Tower of Hanoi
Backtracking | Introduction
Print all possible combinations of r elements in a given array of size n | [
{
"code": null,
"e": 26668,
"s": 26640,
"text": "\n27 Apr, 2022"
},
{
"code": null,
"e": 26831,
"s": 26668,
"text": "Given an integer, write a function that returns true if the given number is palindrome, else false. For example, 12321 is palindrome, but 1451 is not palindrome. "
},
{
"code": null,
"e": 27019,
"s": 26831,
"text": "Let the given number be num. A simple method for this problem is to first reverse digits of num, then compare the reverse of num with num. If both are same, then return true, else false. "
},
{
"code": null,
"e": 27515,
"s": 27019,
"text": "Following is an interesting method inspired from method#2 of this post. The idea is to create a copy of num and recursively pass the copy by reference, and pass num by value. In the recursive calls, divide num by 10 while moving down the recursion tree. While moving up the recursion tree, divide the copy by 10. When they meet in a function for which all child calls are over, the last digit of num will be ith digit from the beginning and the last digit of copy will be ith digit from the end."
},
{
"code": null,
"e": 27519,
"s": 27515,
"text": "C++"
},
{
"code": null,
"e": 27521,
"s": 27519,
"text": "C"
},
{
"code": null,
"e": 27526,
"s": 27521,
"text": "Java"
},
{
"code": null,
"e": 27534,
"s": 27526,
"text": "Python3"
},
{
"code": null,
"e": 27537,
"s": 27534,
"text": "C#"
},
{
"code": null,
"e": 27541,
"s": 27537,
"text": "PHP"
},
{
"code": null,
"e": 27552,
"s": 27541,
"text": "Javascript"
},
{
"code": "// A recursive C++ program to check// whether a given number// is palindrome or not#include <iostream>using namespace std; // A function that returns true only// if num contains one// digitint oneDigit(int num){ // Comparison operation is faster // than division // operation. So using following // instead of \"return num // / 10 == 0;\" return (num >= 0 && num < 10);} // A recursive function to find// out whether num is// palindrome or not. Initially, dupNum// contains address of// a copy of num.bool isPalUtil(int num, int* dupNum){ // Base case (needed for recursion // termination): This // statement mainly compares the // first digit with the // last digit if (oneDigit(num)) return (num == (*dupNum) % 10); // This is the key line in this // method. Note that all // recursive calls have a separate // copy of num, but they // all share same copy of *dupNum. // We divide num while // moving up the recursion tree if (!isPalUtil(num / 10, dupNum)) return false; // The following statements are // executed when we move up // the recursion call tree *dupNum /= 10; // At this point, if num%10 contains // i'th digit from // beginning, then (*dupNum)%10 // contains i'th digit // from end return (num % 10 == (*dupNum) % 10);} // The main function that uses// recursive function// isPalUtil() to find out whether// num is palindrome or notint isPal(int num){ // Check if num is negative, // make it positive if (num < 0) num = -num; // Create a separate copy of num, // so that modifications // made to address dupNum don't // change the input number. // *dupNum = num int* dupNum = new int(num); return isPalUtil(num, dupNum);} // Driver program to test// above functionsint main(){ int n = 12321; isPal(n) ? cout <<\"Yes\\n\": cout <<\"No\" << endl; n = 12; isPal(n) ? cout <<\"Yes\\n\": cout <<\"No\" << endl; n = 88; isPal(n) ? cout <<\"Yes\\n\": cout <<\"No\" << endl; n = 8999; isPal(n) ? cout <<\"Yes\\n\": cout <<\"No\"; return 0;} // this code is contributed by shivanisinghss2110",
"e": 29721,
"s": 27552,
"text": null
},
{
"code": "// A recursive C program to check// whether a given number// is palindrome or not#include <stdio.h> // A function that returns true only// if num contains one// digitint oneDigit(int num){ // Comparison operation is faster // than division // operation. So using following // instead of \"return num // / 10 == 0;\" return (num >= 0 && num < 10);} // A recursive function to find// out whether num is// palindrome or not. Initially, dupNum// contains address of// a copy of num.bool isPalUtil(int num, int* dupNum){ // Base case (needed for recursion // termination): This // statement mainly compares the // first digit with the // last digit if (oneDigit(num)) return (num == (*dupNum) % 10); // This is the key line in this // method. Note that all // recursive calls have a separate // copy of num, but they // all share same copy of *dupNum. // We divide num while // moving up the recursion tree if (!isPalUtil(num / 10, dupNum)) return false; // The following statements are // executed when we move up // the recursion call tree *dupNum /= 10; // At this point, if num%10 contains // i'th digit from // beginning, then (*dupNum)%10 // contains i'th digit // from end return (num % 10 == (*dupNum) % 10);} // The main function that uses// recursive function// isPalUtil() to find out whether// num is palindrome or notint isPal(int num){ // Check if num is negative, // make it positive if (num < 0) num = -num; // Create a separate copy of num, // so that modifications // made to address dupNum don't // change the input number. // *dupNum = num int* dupNum = new int(num); return isPalUtil(num, dupNum);} // Driver program to test// above functionsint main(){ int n = 12321; isPal(n) ? printf(\"Yes\\n\") : printf(\"No\\n\"); n = 12; isPal(n) ? printf(\"Yes\\n\") : printf(\"No\\n\"); n = 88; isPal(n) ? printf(\"Yes\\n\") : printf(\"No\\n\"); n = 8999; isPal(n) ? printf(\"Yes\\n\") : printf(\"No\\n\"); return 0;}",
"e": 31812,
"s": 29721,
"text": null
},
{
"code": "// A recursive Java program to// check whether a given number// is palindrome or notimport java.io.*;import java.util.*; public class CheckPallindromNumberRecursion { // A function that returns true // only if num contains one digit public static int oneDigit(int num) { if ((num >= 0) && (num < 10)) return 1; else return 0; } public static int isPalUtil (int num, int dupNum) throws Exception { // base condition to return once we // move past first digit if (num == 0) { return dupNum; } else { dupNum = isPalUtil(num / 10, dupNum); } // Check for equality of first digit of // num and dupNum if (num % 10 == dupNum % 10) { // if first digit values of num and // dupNum are equal divide dupNum // value by 10 to keep moving in sync // with num. return dupNum / 10; } else { // At position values are not // matching throw exception and exit. // no need to proceed further. throw new Exception(); } } public static int isPal(int num) throws Exception { if (num < 0) num = (-num); int dupNum = (num); return isPalUtil(num, dupNum); } public static void main(String args[]) { int n = 1242; try { isPal(n); System.out.println(\"Yes\"); } catch (Exception e) { System.out.println(\"No\"); } n = 1231; try { isPal(n); System.out.println(\"Yes\"); } catch (Exception e) { System.out.println(\"No\"); } n = 12; try { isPal(n); System.out.println(\"Yes\"); } catch (Exception e) { System.out.println(\"No\"); } n = 88; try { isPal(n); System.out.println(\"Yes\"); } catch (Exception e) { System.out.println(\"No\"); } n = 8999; try { isPal(n); System.out.println(\"Yes\"); } catch (Exception e) { System.out.println(\"No\"); } }} // This code is contributed// by Nasir J",
"e": 34089,
"s": 31812,
"text": null
},
{
"code": "# A recursive Python3 program to check# whether a given number is palindrome or not # A function that returns true# only if num contains one digitdef oneDigit(num): # comparison operation is faster # than division operation. So # using following instead of # \"return num / 10 == 0;\" return ((num >= 0) and (num < 10)) # A recursive function to find# out whether num is palindrome# or not. Initially, dupNum# contains address of a copy of num.def isPalUtil(num, dupNum): # Base case (needed for recursion # termination): This statement # mainly compares the first digit # with the last digit if oneDigit(num): return (num == (dupNum[0]) % 10) # This is the key line in this # method. Note that all recursive # calls have a separate copy of # num, but they all share same # copy of *dupNum. We divide num # while moving up the recursion tree if not isPalUtil(num //10, dupNum): return False # The following statements are # executed when we move up the # recursion call tree dupNum[0] = dupNum[0] //10 # At this point, if num%10 # contains i'th digit from # beginning, then (*dupNum)%10 # contains i'th digit from end return (num % 10 == (dupNum[0]) % 10) # The main function that uses# recursive function isPalUtil()# to find out whether num is# palindrome or notdef isPal(num): # If num is negative, # make it positive if (num < 0): num = (-num) # Create a separate copy of # num, so that modifications # made to address dupNum # don't change the input number. dupNum = [num] # *dupNum = num return isPalUtil(num, dupNum) # Driver Coden = 12321if isPal(n): print(\"Yes\")else: print(\"No\") n = 12if isPal(n) : print(\"Yes\")else: print(\"No\") n = 88if isPal(n) : print(\"Yes\")else: print(\"No\") n = 8999if isPal(n) : print(\"Yes\")else: print(\"No\") # This code is contributed by mits",
"e": 36039,
"s": 34089,
"text": null
},
{
"code": "// A recursive C# program to// check whether a given number// is palindrome or notusing System; class GFG{ // A function that returns true// only if num contains one digitpublic static int oneDigit(int num){ // comparison operation is // faster than division // operation. So using // following instead of // \"return num / 10 == 0;\" if((num >= 0) &&(num < 10)) return 1; else return 0;} // A recursive function to// find out whether num is// palindrome or not.// Initially, dupNum contains// address of a copy of num.public static int isPalUtil(int num, int dupNum){ // Base case (needed for recursion // termination): This statement // mainly compares the first digit // with the last digit if (oneDigit(num) == 1) if(num == (dupNum) % 10) return 1; else return 0; // This is the key line in // this method. Note that // all recursive calls have // a separate copy of num, // but they all share same // copy of *dupNum. We divide // num while moving up the // recursion tree if (isPalUtil((int)(num / 10), dupNum) == 0) return -1; // The following statements // are executed when we move // up the recursion call tree dupNum = (int)(dupNum / 10); // At this point, if num%10 // contains i'th digit from // beginning, then (*dupNum)%10 // contains i'th digit from end if(num % 10 == (dupNum) % 10) return 1; else return 0;} // The main function that uses// recursive function isPalUtil()// to find out whether num is// palindrome or notpublic static int isPal(int num){ // If num is negative, // make it positive if (num < 0) num = (-num); // Create a separate copy // of num, so that modifications // made to address dupNum // don't change the input number. int dupNum = (num); // *dupNum = num return isPalUtil(num, dupNum);} // Driver Codepublic static void Main(){int n = 12321;if(isPal(n) == 0) Console.WriteLine(\"Yes\");else Console.WriteLine(\"No\"); n = 12;if(isPal(n) == 0) Console.WriteLine(\"Yes\");else Console.WriteLine( \"No\"); n = 88;if(isPal(n) == 1) Console.WriteLine(\"Yes\");else Console.WriteLine(\"No\"); n = 8999;if(isPal(n) == 0) Console.WriteLine(\"Yes\");else Console.WriteLine(\"No\");}} // This code is contributed by mits",
"e": 38413,
"s": 36039,
"text": null
},
{
"code": "<?php// A recursive PHP program to// check whether a given number// is palindrome or not // A function that returns true// only if num contains one digitfunction oneDigit($num){ // comparison operation is faster // than division operation. So // using following instead of // \"return num / 10 == 0;\" return (($num >= 0) && ($num < 10));} // A recursive function to find// out whether num is palindrome// or not. Initially, dupNum// contains address of a copy of num.function isPalUtil($num, $dupNum){ // Base case (needed for recursion // termination): This statement // mainly compares the first digit // with the last digit if (oneDigit($num)) return ($num == ($dupNum) % 10); // This is the key line in this // method. Note that all recursive // calls have a separate copy of // num, but they all share same // copy of *dupNum. We divide num // while moving up the recursion tree if (!isPalUtil((int)($num / 10), $dupNum)) return -1; // The following statements are // executed when we move up the // recursion call tree $dupNum = (int)($dupNum / 10); // At this point, if num%10 // contains i'th digit from // beginning, then (*dupNum)%10 // contains i'th digit from end return ($num % 10 == ($dupNum) % 10);} // The main function that uses// recursive function isPalUtil()// to find out whether num is// palindrome or notfunction isPal($num){ // If num is negative, // make it positive if ($num < 0) $num = (-$num); // Create a separate copy of // num, so that modifications // made to address dupNum // don't change the input number. $dupNum = ($num); // *dupNum = num return isPalUtil($num, $dupNum);} // Driver Code$n = 12321;if(isPal($n) == 0) echo \"Yes\\n\";else echo \"No\\n\"; $n = 12;if(isPal($n) == 0) echo \"Yes\\n\";else echo \"No\\n\"; $n = 88;if(isPal($n) == 1) echo \"Yes\\n\";else echo \"No\\n\"; $n = 8999;if(isPal($n) == 0) echo \"Yes\\n\";else echo \"No\\n\"; // This code is contributed by m_kit?>",
"e": 40499,
"s": 38413,
"text": null
},
{
"code": "<script>// A recursive javascript program to// check whether a given number// is palindrome or not // A function that returns true // only if num contains one digit function oneDigit(num) { if ((num >= 0) && (num < 10)) return 1; else return 0; } function isPalUtil (num , dupNum) { // base condition to return once we // move past first digit if (num == 0) { return dupNum; } else { dupNum = isPalUtil(parseInt(num / 10), dupNum); } // Check for equality of first digit of // num and dupNum if (num % 10 == dupNum % 10) { // if first digit values of num and // dupNum are equal divide dupNum // value by 10 to keep moving in sync // with num. return parseInt(dupNum / 10); } else { // At position values are not // matching throw exception and exit. // no need to proceed further. throw e; } } function isPal(num) { if (num < 0) num = (-num); var dupNum = (num); return isPalUtil(num, dupNum); } var n = 1242; try { isPal(n); document.write(\"<br>Yes\"); } catch (e) { document.write(\"<br>No\"); } n = 1231; try { isPal(n); document.write(\"<br>Yes\"); } catch (e) { document.write(\"<br>No\"); } n = 12; try { isPal(n); document.write(\"<br>Yes\"); } catch (e) { document.write(\"<br>No\"); } n = 88; try { isPal(n); document.write(\"<br>Yes\"); } catch (e) { document.write(\"<br>No\"); } n = 8999; try { isPal(n); document.write(\"<br>Yes\"); } catch (e) { document.write(\"<br>No\"); } // This code is contributed by Amit Katiyar</script>",
"e": 42472,
"s": 40499,
"text": null
},
{
"code": null,
"e": 42481,
"s": 42472,
"text": "Output: "
},
{
"code": null,
"e": 42496,
"s": 42481,
"text": "Yes\nNo\nYes\nNo "
},
{
"code": null,
"e": 42596,
"s": 42496,
"text": "To check a number is palindrome or not without using any extra spaceMethod #2:Using string() method"
},
{
"code": null,
"e": 43007,
"s": 42596,
"text": "When the number of digits of that number exceeds 1018, we can’t take that number as an integer since the range of long long int doesn’t satisfy the given number.So take input as a string, Run a loop from starting to length/2 and check the first character(numeric) to the last character of the string and second to second last one, and so on ....If any character mismatches, the string wouldn’t be a palindrome."
},
{
"code": null,
"e": 43169,
"s": 43007,
"text": "When the number of digits of that number exceeds 1018, we can’t take that number as an integer since the range of long long int doesn’t satisfy the given number."
},
{
"code": null,
"e": 43419,
"s": 43169,
"text": "So take input as a string, Run a loop from starting to length/2 and check the first character(numeric) to the last character of the string and second to second last one, and so on ....If any character mismatches, the string wouldn’t be a palindrome."
},
{
"code": null,
"e": 43469,
"s": 43419,
"text": "Below is the implementation of the above approach"
},
{
"code": null,
"e": 43475,
"s": 43469,
"text": "C++14"
},
{
"code": null,
"e": 43480,
"s": 43475,
"text": "Java"
},
{
"code": null,
"e": 43488,
"s": 43480,
"text": "Python3"
},
{
"code": null,
"e": 43491,
"s": 43488,
"text": "C#"
},
{
"code": null,
"e": 43502,
"s": 43491,
"text": "Javascript"
},
{
"code": "// C++ implementation of the above approach#include <iostream>using namespace std; // Function to check palindromeint checkPalindrome(string str){ // Calculating string length int len = str.length(); // Traversing through the string // upto half its length for (int i = 0; i < len / 2; i++) { // Comparing i th character // from starting and len-i // th character from end if (str[i] != str[len - i - 1]) return false; } // If the above loop doesn't return then it is // palindrome return true;} // Driver Codeint main(){ // taking number as string string st = \"112233445566778899000000998877665544332211\"; if (checkPalindrome(st) == true) cout << \"Yes\"; else cout << \"No\"; return 0;}// this code is written by vikkycirus",
"e": 44336,
"s": 43502,
"text": null
},
{
"code": "// Java implementation of the above approachimport java.io.*; class GFG{ // Function to check palindromestatic boolean checkPalindrome(String str){ // Calculating string length int len = str.length(); // Traversing through the string // upto half its length for(int i = 0; i < len / 2; i++) { // Comparing i th character // from starting and len-i // th character from end if (str.charAt(i) != str.charAt(len - i - 1)) return false; } // If the above loop doesn't return then // it is palindrome return true;} // Driver Codepublic static void main(String[] args){ // Taking number as string String st = \"112233445566778899000000998877665544332211\"; if (checkPalindrome(st) == true) System.out.print(\"Yes\"); else System.out.print(\"No\");}} // This code is contributed by subhammahato348",
"e": 45253,
"s": 44336,
"text": null
},
{
"code": "# Python3 implementation of the above approach # function to check palindromedef checkPalindrome(str): # Run loop from 0 to len/2 for i in range(0, len(str)//2): if str[i] != str[len(str)-i-1]: return False # If the above loop doesn't #return then it is palindrome return True # Driver codest = \"112233445566778899000000998877665544332211\"if(checkPalindrome(st) == True): print(\"it is a palindrome\")else: print(\"It is not a palindrome\")",
"e": 45744,
"s": 45253,
"text": null
},
{
"code": "// C# implementation of the above approachusing System; class GFG{ // Function to check palindromestatic bool checkPalindrome(string str){ // Calculating string length int len = str.Length; // Traversing through the string // upto half its length for(int i = 0; i < len / 2; i++) { // Comparing i th character // from starting and len-i // th character from end if (str[i] != str[len - i - 1]) return false; } // If the above loop doesn't return then // it is palindrome return true;} // Driver Codepublic static void Main(){ // Taking number as string string st = \"112233445566778899000000998877665544332211\"; if (checkPalindrome(st) == true) Console.Write(\"Yes\"); else Console.Write(\"No\");}} // This code is contributed by subhammahato348",
"e": 46602,
"s": 45744,
"text": null
},
{
"code": "<script> // Javascript implementation of the above approach // Function to check palindromefunction checkPalindrome(str){ // Calculating string length var len = str.length; // Traversing through the string // upto half its length for (var i = 0; i < len / 2; i++) { // Comparing ith character // from starting and len-ith // character from end if (str[i] != str[len - i - 1]) return false; } // If the above loop doesn't return then it is // palindrome return true;} // Driver Code // taking number as string let st = \"112233445566778899000000998877665544332211\"; if (checkPalindrome(st) == true) document.write(\"Yes\"); else document.write(\"No\"); // This code is contributed by Mayank Tyagi </script>",
"e": 47424,
"s": 46602,
"text": null
},
{
"code": null,
"e": 47428,
"s": 47424,
"text": "Yes"
},
{
"code": null,
"e": 47454,
"s": 47428,
"text": "Time Complexity: O(|str|)"
},
{
"code": null,
"e": 47524,
"s": 47454,
"text": "Method #3:Using split(), reverse() and join() methods simultaneously "
},
{
"code": null,
"e": 48090,
"s": 47524,
"text": "When user inputs an integer, it is further passed inside a method which will evaluate the result or the actual logic part.Logic part inside the method focuses on using several important JavaScript methods simultaneously.First task is to convert the integer passed in into the string using toString() method.Then split(), reverse() and join() method will be applied to obtain the reverse of that string.Thereafter using the triple equality operator (“===”), reverse string and original string will be compared and based on that result will be printed on the console."
},
{
"code": null,
"e": 48213,
"s": 48090,
"text": "When user inputs an integer, it is further passed inside a method which will evaluate the result or the actual logic part."
},
{
"code": null,
"e": 48312,
"s": 48213,
"text": "Logic part inside the method focuses on using several important JavaScript methods simultaneously."
},
{
"code": null,
"e": 48400,
"s": 48312,
"text": "First task is to convert the integer passed in into the string using toString() method."
},
{
"code": null,
"e": 48496,
"s": 48400,
"text": "Then split(), reverse() and join() method will be applied to obtain the reverse of that string."
},
{
"code": null,
"e": 48660,
"s": 48496,
"text": "Thereafter using the triple equality operator (“===”), reverse string and original string will be compared and based on that result will be printed on the console."
},
{
"code": null,
"e": 48711,
"s": 48660,
"text": " Below is the implementation of the above approach"
},
{
"code": null,
"e": 48719,
"s": 48711,
"text": "Python3"
},
{
"code": null,
"e": 48730,
"s": 48719,
"text": "Javascript"
},
{
"code": "def checkPalindrome(x): convertedNumber = str(x) reverseString = convertedNumber[::-1] return \"Yes\" if reverseString == convertedNumber else \"No\" # Some Testcases...num = 12321print(checkPalindrome(num)) # Yes number = 456print(checkPalindrome(number)) # No # This code is contributed by shinjanpatra",
"e": 49040,
"s": 48730,
"text": null
},
{
"code": "function checkPalindrome(x) { let convertedNumber = x.toString(); let reverseString = convertedNumber.split(\"\").reverse().join(\"\"); return reverseString === convertedNumber ? \"Yes\" : \"No\";} // Some Testcases...let num = 12321;console.log(checkPalindrome(num)); // Yes let number = 456;console.log(checkPalindrome(number)); // No // This code is contributed by Aman Singla....",
"e": 49425,
"s": 49040,
"text": null
},
{
"code": null,
"e": 49432,
"s": 49425,
"text": "Output"
},
{
"code": null,
"e": 49439,
"s": 49432,
"text": "Yes\nNo"
},
{
"code": null,
"e": 49610,
"s": 49439,
"text": "This article is compiled by Aashish Barnwal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 49616,
"s": 49610,
"text": "jit_t"
},
{
"code": null,
"e": 49629,
"s": 49616,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 49642,
"s": 49629,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 49653,
"s": 49642,
"text": "NasirJamal"
},
{
"code": null,
"e": 49669,
"s": 49653,
"text": "pansaripulkit13"
},
{
"code": null,
"e": 49680,
"s": 49669,
"text": "vikkycirus"
},
{
"code": null,
"e": 49696,
"s": 49680,
"text": "mayanktyagi1709"
},
{
"code": null,
"e": 49712,
"s": 49696,
"text": "subhammahato348"
},
{
"code": null,
"e": 49727,
"s": 49712,
"text": "amit143katiyar"
},
{
"code": null,
"e": 49744,
"s": 49727,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 49754,
"s": 49744,
"text": "ruhelaa48"
},
{
"code": null,
"e": 49773,
"s": 49754,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 49788,
"s": 49773,
"text": "sagartomar9927"
},
{
"code": null,
"e": 49804,
"s": 49788,
"text": "rishavmahato348"
},
{
"code": null,
"e": 49815,
"s": 49804,
"text": "amansingla"
},
{
"code": null,
"e": 49828,
"s": 49815,
"text": "simmytarika5"
},
{
"code": null,
"e": 49841,
"s": 49828,
"text": "shinjanpatra"
},
{
"code": null,
"e": 49847,
"s": 49841,
"text": "Adobe"
},
{
"code": null,
"e": 49854,
"s": 49847,
"text": "Oracle"
},
{
"code": null,
"e": 49865,
"s": 49854,
"text": "palindrome"
},
{
"code": null,
"e": 49873,
"s": 49865,
"text": "Samsung"
},
{
"code": null,
"e": 49878,
"s": 49873,
"text": "Zoho"
},
{
"code": null,
"e": 49891,
"s": 49878,
"text": "Mathematical"
},
{
"code": null,
"e": 49901,
"s": 49891,
"text": "Recursion"
},
{
"code": null,
"e": 49906,
"s": 49901,
"text": "Zoho"
},
{
"code": null,
"e": 49914,
"s": 49906,
"text": "Samsung"
},
{
"code": null,
"e": 49921,
"s": 49914,
"text": "Oracle"
},
{
"code": null,
"e": 49927,
"s": 49921,
"text": "Adobe"
},
{
"code": null,
"e": 49940,
"s": 49927,
"text": "Mathematical"
},
{
"code": null,
"e": 49950,
"s": 49940,
"text": "Recursion"
},
{
"code": null,
"e": 49961,
"s": 49950,
"text": "palindrome"
},
{
"code": null,
"e": 50059,
"s": 49961,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 50083,
"s": 50059,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 50126,
"s": 50083,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 50140,
"s": 50126,
"text": "Prime Numbers"
},
{
"code": null,
"e": 50182,
"s": 50140,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 50255,
"s": 50182,
"text": "Print all possible combinations of r elements in a given array of size n"
},
{
"code": null,
"e": 50340,
"s": 50255,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 50350,
"s": 50340,
"text": "Recursion"
},
{
"code": null,
"e": 50377,
"s": 50350,
"text": "Program for Tower of Hanoi"
},
{
"code": null,
"e": 50405,
"s": 50377,
"text": "Backtracking | Introduction"
}
]
|
Difference Between ConcurrentHashMap and SynchronizedHashMap - GeeksforGeeks | 14 Aug, 2021
The ConcurrentHashMap and SynchronizedHashMap both are the Collection classes which are thread-safe and can be used in multithreaded and concurrent java application. But there are few differences that exists between them. In this article, we have tried to cover all these differences between them.
1. ConcurrentHashMap: ConcurrentHashMap is a class which implements the ConcurrentMap interface. It uses Hashtable, underlined data structure. As we know, while dealing with thread in our application HashMap is not a good choice because of the performance issue. To resolve this issue, we use ConcurrentHashMap in our application. ConcurrentHashMap is thread-safe therefore multiple threads can operate on a single object without any problem. In ConcurrentHashMap, the Object is divided into a number of segments according to the concurrency level. By default, it allows 16 thread to read and write from the Map without any synchronization. In ConcurrentHashMap, at a time any number of threads can perform retrieval operation but for updating in the object, the thread must lock the particular segment in which the thread wants to operate. This type of locking mechanism is known as Segment locking or bucket locking. Hence, at a time16 update operations can be performed by threads.
ConcurrentHashMap Demo:
Java
// Java Program to demonstrate the// working of ConcurrentHashMap import java.util.*;import java.util.concurrent.*; public class TraversingConcurrentHashMap { public static void main(String[] args) { // create an instance of ConcurrentHashMap ConcurrentHashMap<Integer, String> chmap = new ConcurrentHashMap<Integer, String>(); // Add elements using put() chmap.put(10, "Geeks"); chmap.put(20, "for"); chmap.put(30, "Geeks"); chmap.put(40, "Welcome"); chmap.put(50, "you"); // Create an Iterator over the // ConcurrentHashMap Iterator<ConcurrentHashMap.Entry<Integer, String> > itr = chmap.entrySet().iterator(); // The hasNext() method is used to check if there is // a next element and the next() method is used to // retrieve the next element while (itr.hasNext()) { ConcurrentHashMap.Entry<Integer, String> entry = itr.next(); System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); } }}
Key = 50, Value = you
Key = 20, Value = for
Key = 40, Value = Welcome
Key = 10, Value = Geeks
Key = 30, Value = Geeks
2. Synchronized HashMap: Java HashMap is a non-synchronized collection class. If we need to perform thread-safe operations on it then we must need to synchronize it explicitly. The synchronizedMap() method of java.util.Collections class is used to synchronize it. It returns a synchronized (thread-safe) map backed by the specified map.
Synchronized HashMap Demo:
Java
// Java program to demonstrate the// working of Synchronized HashMap import java.util.Collections;import java.util.HashMap;import java.util.Iterator;import java.util.Map;import java.util.Set; public class SynchronizedHashMap { public static void main(String args[]) { // Creating a HashMap HashMap<Integer, String> hmap = new HashMap<Integer, String>(); // Adding the elements using put method hmap.put(10, "Geeks"); hmap.put(20, "for"); hmap.put(30, "Geeks"); hmap.put(25, "Welcome"); hmap.put(40, "you"); // Creating a synchronized map Map map = Collections.synchronizedMap(hmap); Set set = map.entrySet(); // Synchronize on HashMap, not on set synchronized (map) { Iterator i = set.iterator(); // Printing the elements while (i.hasNext()) { Map.Entry me = (Map.Entry)i.next(); System.out.print(me.getKey() + ": "); System.out.println(me.getValue()); } } }}
20: for
40: you
25: Welcome
10: Geeks
30: Geeks
Difference between ConcurrentHashMap and Synchronized HashMap:
ConcurrentHashMap
Synchronized HashMap
simmytarika5
Java-Collections
Java-ConcurrentHashMap
Technical Scripter 2020
Difference Between
Java
Technical Scripter
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference between Process and Thread
Difference Between Method Overloading and Method Overriding in Java
Difference between Clustered and Non-clustered index
Differences between IPv4 and IPv6
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Reverse a string in Java
Arrays.sort() in Java with examples | [
{
"code": null,
"e": 24093,
"s": 24065,
"text": "\n14 Aug, 2021"
},
{
"code": null,
"e": 24391,
"s": 24093,
"text": "The ConcurrentHashMap and SynchronizedHashMap both are the Collection classes which are thread-safe and can be used in multithreaded and concurrent java application. But there are few differences that exists between them. In this article, we have tried to cover all these differences between them."
},
{
"code": null,
"e": 25377,
"s": 24391,
"text": "1. ConcurrentHashMap: ConcurrentHashMap is a class which implements the ConcurrentMap interface. It uses Hashtable, underlined data structure. As we know, while dealing with thread in our application HashMap is not a good choice because of the performance issue. To resolve this issue, we use ConcurrentHashMap in our application. ConcurrentHashMap is thread-safe therefore multiple threads can operate on a single object without any problem. In ConcurrentHashMap, the Object is divided into a number of segments according to the concurrency level. By default, it allows 16 thread to read and write from the Map without any synchronization. In ConcurrentHashMap, at a time any number of threads can perform retrieval operation but for updating in the object, the thread must lock the particular segment in which the thread wants to operate. This type of locking mechanism is known as Segment locking or bucket locking. Hence, at a time16 update operations can be performed by threads."
},
{
"code": null,
"e": 25401,
"s": 25377,
"text": "ConcurrentHashMap Demo:"
},
{
"code": null,
"e": 25406,
"s": 25401,
"text": "Java"
},
{
"code": "// Java Program to demonstrate the// working of ConcurrentHashMap import java.util.*;import java.util.concurrent.*; public class TraversingConcurrentHashMap { public static void main(String[] args) { // create an instance of ConcurrentHashMap ConcurrentHashMap<Integer, String> chmap = new ConcurrentHashMap<Integer, String>(); // Add elements using put() chmap.put(10, \"Geeks\"); chmap.put(20, \"for\"); chmap.put(30, \"Geeks\"); chmap.put(40, \"Welcome\"); chmap.put(50, \"you\"); // Create an Iterator over the // ConcurrentHashMap Iterator<ConcurrentHashMap.Entry<Integer, String> > itr = chmap.entrySet().iterator(); // The hasNext() method is used to check if there is // a next element and the next() method is used to // retrieve the next element while (itr.hasNext()) { ConcurrentHashMap.Entry<Integer, String> entry = itr.next(); System.out.println(\"Key = \" + entry.getKey() + \", Value = \" + entry.getValue()); } }}",
"e": 26568,
"s": 25406,
"text": null
},
{
"code": null,
"e": 26689,
"s": 26571,
"text": "Key = 50, Value = you\nKey = 20, Value = for\nKey = 40, Value = Welcome\nKey = 10, Value = Geeks\nKey = 30, Value = Geeks"
},
{
"code": null,
"e": 27029,
"s": 26691,
"text": "2. Synchronized HashMap: Java HashMap is a non-synchronized collection class. If we need to perform thread-safe operations on it then we must need to synchronize it explicitly. The synchronizedMap() method of java.util.Collections class is used to synchronize it. It returns a synchronized (thread-safe) map backed by the specified map. "
},
{
"code": null,
"e": 27057,
"s": 27029,
"text": "Synchronized HashMap Demo: "
},
{
"code": null,
"e": 27062,
"s": 27057,
"text": "Java"
},
{
"code": "// Java program to demonstrate the// working of Synchronized HashMap import java.util.Collections;import java.util.HashMap;import java.util.Iterator;import java.util.Map;import java.util.Set; public class SynchronizedHashMap { public static void main(String args[]) { // Creating a HashMap HashMap<Integer, String> hmap = new HashMap<Integer, String>(); // Adding the elements using put method hmap.put(10, \"Geeks\"); hmap.put(20, \"for\"); hmap.put(30, \"Geeks\"); hmap.put(25, \"Welcome\"); hmap.put(40, \"you\"); // Creating a synchronized map Map map = Collections.synchronizedMap(hmap); Set set = map.entrySet(); // Synchronize on HashMap, not on set synchronized (map) { Iterator i = set.iterator(); // Printing the elements while (i.hasNext()) { Map.Entry me = (Map.Entry)i.next(); System.out.print(me.getKey() + \": \"); System.out.println(me.getValue()); } } }}",
"e": 28140,
"s": 27062,
"text": null
},
{
"code": null,
"e": 28188,
"s": 28140,
"text": "20: for\n40: you\n25: Welcome\n10: Geeks\n30: Geeks"
},
{
"code": null,
"e": 28251,
"s": 28188,
"text": "Difference between ConcurrentHashMap and Synchronized HashMap:"
},
{
"code": null,
"e": 28287,
"s": 28251,
"text": " ConcurrentHashMap"
},
{
"code": null,
"e": 28330,
"s": 28287,
"text": " Synchronized HashMap"
},
{
"code": null,
"e": 28343,
"s": 28330,
"text": "simmytarika5"
},
{
"code": null,
"e": 28360,
"s": 28343,
"text": "Java-Collections"
},
{
"code": null,
"e": 28383,
"s": 28360,
"text": "Java-ConcurrentHashMap"
},
{
"code": null,
"e": 28407,
"s": 28383,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 28426,
"s": 28407,
"text": "Difference Between"
},
{
"code": null,
"e": 28431,
"s": 28426,
"text": "Java"
},
{
"code": null,
"e": 28450,
"s": 28431,
"text": "Technical Scripter"
},
{
"code": null,
"e": 28455,
"s": 28450,
"text": "Java"
},
{
"code": null,
"e": 28472,
"s": 28455,
"text": "Java-Collections"
},
{
"code": null,
"e": 28570,
"s": 28472,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28579,
"s": 28570,
"text": "Comments"
},
{
"code": null,
"e": 28592,
"s": 28579,
"text": "Old Comments"
},
{
"code": null,
"e": 28653,
"s": 28592,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28691,
"s": 28653,
"text": "Difference between Process and Thread"
},
{
"code": null,
"e": 28759,
"s": 28691,
"text": "Difference Between Method Overloading and Method Overriding in Java"
},
{
"code": null,
"e": 28812,
"s": 28759,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 28846,
"s": 28812,
"text": "Differences between IPv4 and IPv6"
},
{
"code": null,
"e": 28861,
"s": 28846,
"text": "Arrays in Java"
},
{
"code": null,
"e": 28905,
"s": 28861,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 28927,
"s": 28905,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 28952,
"s": 28927,
"text": "Reverse a string in Java"
}
]
|
How to change background color of TableView items on iOS? | Changing the background color of table view items is different from changing the background color of the table view. New programmers may often confuse between these two things, In this post, we will be seeing how to change the background color of TableView items i.e. cells.
So let’s get started.
For changing the background color of the table view cell, you should change the contentView.backgroundColor property of the cell.
Add the below code in your cellForRowAt indexPath method,
cell.contentView.backgroundColor = UIColor.cyan
Your method should look like something below,
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell
cell.contentView.backgroundColor = UIColor.cyan
return cell
}
Now run the project to see the effect. | [
{
"code": null,
"e": 1337,
"s": 1062,
"text": "Changing the background color of table view items is different from changing the background color of the table view. New programmers may often confuse between these two things, In this post, we will be seeing how to change the background color of TableView items i.e. cells."
},
{
"code": null,
"e": 1359,
"s": 1337,
"text": "So let’s get started."
},
{
"code": null,
"e": 1489,
"s": 1359,
"text": "For changing the background color of the table view cell, you should change the contentView.backgroundColor property of the cell."
},
{
"code": null,
"e": 1595,
"s": 1489,
"text": "Add the below code in your cellForRowAt indexPath method,\ncell.contentView.backgroundColor = UIColor.cyan"
},
{
"code": null,
"e": 1641,
"s": 1595,
"text": "Your method should look like something below,"
},
{
"code": null,
"e": 1925,
"s": 1641,
"text": "func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {\n let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: \"cell\", for: indexPath) as! TableViewCell\n cell.contentView.backgroundColor = UIColor.cyan\n return cell\n}"
},
{
"code": null,
"e": 1964,
"s": 1925,
"text": "Now run the project to see the effect."
}
]
|
What is NaN in JavaScript? | NaN is a JavaScript property, which is "Not-a-Number" value. This shows it is not a legal number.
Here’s the syntax −
Number.NaN
To find out whether value is NaN, use the Number.isNaN() or isNan() method. Here’s an example to check −
Live Demo
<!DOCTYPE html>
<html>
<body>
<button onclick="display()">Check</button>
<p id="test"></p>
<script>
function display() {
var a = "";
a = a + isNaN(6234) + ": 6234<br>";
a = a + isNaN(-52.1) + ": -52.1<br>";
a = a + isNaN('Hello') + ": 'Hello'<br>";
a = a + isNaN(NaN) + ": NaN<br>";
a = a + isNaN('') + ": ''<br>";
a = a + isNaN(0) + ": 0<br>";
a = a + isNaN(false) + ": false<br>";
document.getElementById("test").innerHTML = a;
}
</script>
</body>
</html> | [
{
"code": null,
"e": 1160,
"s": 1062,
"text": "NaN is a JavaScript property, which is \"Not-a-Number\" value. This shows it is not a legal number."
},
{
"code": null,
"e": 1180,
"s": 1160,
"text": "Here’s the syntax −"
},
{
"code": null,
"e": 1191,
"s": 1180,
"text": "Number.NaN"
},
{
"code": null,
"e": 1296,
"s": 1191,
"text": "To find out whether value is NaN, use the Number.isNaN() or isNan() method. Here’s an example to check −"
},
{
"code": null,
"e": 1306,
"s": 1296,
"text": "Live Demo"
},
{
"code": null,
"e": 1920,
"s": 1306,
"text": "<!DOCTYPE html>\n<html>\n <body>\n <button onclick=\"display()\">Check</button>\n <p id=\"test\"></p>\n <script>\n function display() {\n var a = \"\";\n a = a + isNaN(6234) + \": 6234<br>\";\n a = a + isNaN(-52.1) + \": -52.1<br>\";\n a = a + isNaN('Hello') + \": 'Hello'<br>\";\n a = a + isNaN(NaN) + \": NaN<br>\";\n a = a + isNaN('') + \": ''<br>\";\n a = a + isNaN(0) + \": 0<br>\";\n a = a + isNaN(false) + \": false<br>\";\n document.getElementById(\"test\").innerHTML = a;\n }\n </script>\n </body>\n</html>"
}
]
|
Python 3 - Date & Time | A Python program can handle date and time in several ways. Converting between date formats is a common chore for computers. Python's time and calendar modules help track dates and times.
Time intervals are floating-point numbers in units of seconds. Particular instants in time are expressed in seconds since 12:00am, January 1, 1970(epoch).
There is a popular time module available in Python which provides functions for working with times, and for converting between representations. The function time.time() returns the current system time in ticks since 12:00am, January 1, 1970(epoch).
#!/usr/bin/python3
import time; # This is required to include time module.
ticks = time.time()
print ("Number of ticks since 12:00am, January 1, 1970:", ticks)
This would produce a result something as follows −
Number of ticks since 12:00am, January 1, 1970: 1455508609.34375
Date arithmetic is easy to do with ticks. However, dates before the epoch cannot be represented in this form. Dates in the far future also cannot be represented this way - the cutoff point is sometime in 2038 for UNIX and Windows.
Many of the Python's time functions handle time as a tuple of 9 numbers, as shown below −
For Example −
import time
print (time.localtime());
This would produce a result as follows −
time.struct_time(tm_year = 2016, tm_mon = 2, tm_mday = 15, tm_hour = 9,
tm_min = 29, tm_sec = 2, tm_wday = 0, tm_yday = 46, tm_isdst = 0)
The above tuple is equivalent to struct_time structure. This structure has following attributes −
To translate a time instant from seconds since the epoch floating-point value into a timetuple, pass the floating-point value to a function (e.g., localtime) that returns a time-tuple with all valid nine items.
#!/usr/bin/python3
import time
localtime = time.localtime(time.time())
print ("Local current time :", localtime)
This would produce the following result, which could be formatted in any other presentable form −
Local current time : time.struct_time(tm_year = 2016, tm_mon = 2, tm_mday = 15,
tm_hour = 9, tm_min = 29, tm_sec = 2, tm_wday = 0, tm_yday = 46, tm_isdst = 0)
You can format any time as per your requirement, but a simple method to get time in a readable format is asctime() −
#!/usr/bin/python3
import time
localtime = time.asctime( time.localtime(time.time()) )
print ("Local current time :", localtime)
This would produce the following result −
Local current time : Mon Feb 15 09:34:03 2016
The calendar module gives a wide range of methods to play with yearly and monthly calendars. Here, we print a calendar for a given month ( Jan 2008 ) −
#!/usr/bin/python3
import calendar
cal = calendar.month(2016, 2)
print ("Here is the calendar:")
print (cal)
This would produce the following result −
Here is the calendar:
February 2016
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
There is a popular time module available in Python, which provides functions for working with times and for converting between representations. Here is the list of all available methods.
The offset of the local DST timezone, in seconds west of UTC, if one is defined. This is negative if the local DST timezone is east of UTC (as in Western Europe, including the UK). Use this if the daylight is nonzero.
Accepts a time-tuple and returns a readable 24-character string such as 'Tue Dec 11 18:07:14 2008'.
Returns the current CPU time as a floating-point number of seconds. To measure computational costs of different approaches, the value of time.clock is more useful than that of time.time().
Like asctime(localtime(secs)) and without arguments is like asctime( )
Accepts an instant expressed in seconds since the epoch and returns a time-tuple t with the UTC time. Note − t.tm_isdst is always 0
Accepts an instant expressed in seconds since the epoch and returns a time-tuple t with the local time (t.tm_isdst is 0 or 1, depending on whether DST applies to instant secs by local rules).
Accepts an instant expressed as a time-tuple in local time and returns a floating-point value with the instant expressed in seconds since the epoch.
Suspends the calling thread for secs seconds.
Accepts an instant expressed as a time-tuple in local time and returns a string representing the instant as specified by string fmt.
Parses str according to format string fmt and returns the instant in time-tuple format.
Returns the current time instant, a floating-point number of seconds since the epoch.
Resets the time conversion rules used by the library routines. The environment variable TZ specifies how this is done.
There are two important attributes available with time module. They are −
time.timezone
Attribute time.timezone is the offset in seconds of the local time zone (without DST) from UTC (>0 in the Americas; <=0 in most of Europe, Asia, Africa).
time.tzname
Attribute time.tzname is a pair of locale-dependent strings, which are the names of the local time zone without and with DST, respectively.
The calendar module supplies calendar-related functions, including functions to print a text calendar for a given month or year.
By default, calendar takes Monday as the first day of the week and Sunday as the last one. To change this, call the calendar.setfirstweekday() function.
Here is a list of functions available with the calendar module −
calendar.calendar(year,w = 2,l = 1,c = 6)
Returns a multiline string with a calendar for year year formatted into three columns separated by c spaces. w is the width in characters of each date; each line has length 21*w+18+2*c. l is the number of lines for each week.
calendar.firstweekday( )
Returns the current setting for the weekday that starts each week. By default, when calendar is first imported, this is 0, meaning Monday.
calendar.isleap(year)
Returns True if year is a leap year; otherwise, False.
calendar.leapdays(y1,y2)
Returns the total number of leap days in the years within range(y1,y2).
calendar.month(year,month,w = 2,l = 1)
Returns a multiline string with a calendar for month month of year year, one line per week plus two header lines. w is the width in characters of each date; each line has length 7*w+6. l is the number of lines for each week.
calendar.monthcalendar(year,month)
Returns a list of lists of ints. Each sublist denotes a week. Days outside month month of year year are set to 0; days within the month are set to their day-of-month, 1 and up.
calendar.monthrange(year,month)
Returns two integers. The first one is the code of the weekday for the first day of the month month in year year; the second one is the number of days in the month. Weekday codes are 0 (Monday) to 6 (Sunday); month numbers are 1 to 12.
calendar.prcal(year,w = 2,l = 1,c = 6)
Like print calendar.calendar(year,w,l,c).
calendar.prmonth(year,month,w = 2,l = 1)
Like print calendar.month(year,month,w,l).
calendar.setfirstweekday(weekday)
Sets the first day of each week to weekday code weekday. Weekday codes are 0 (Monday) to 6 (Sunday).
calendar.timegm(tupletime)
The inverse of time.gmtime: accepts a time instant in time-tuple form and returns the same instant as a floating-point number of seconds since the epoch.
calendar.weekday(year,month,day)
Returns the weekday code for the given date. Weekday codes are 0 (Monday) to 6 (Sunday); month numbers are 1 (January) to 12 (December).
If you are interested, then here you would find a list of other important modules and functions to play with date & time in Python −
The datetime Module
The pytz Module
The dateutil Module
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2527,
"s": 2340,
"text": "A Python program can handle date and time in several ways. Converting between date formats is a common chore for computers. Python's time and calendar modules help track dates and times."
},
{
"code": null,
"e": 2682,
"s": 2527,
"text": "Time intervals are floating-point numbers in units of seconds. Particular instants in time are expressed in seconds since 12:00am, January 1, 1970(epoch)."
},
{
"code": null,
"e": 2931,
"s": 2682,
"text": "There is a popular time module available in Python which provides functions for working with times, and for converting between representations. The function time.time() returns the current system time in ticks since 12:00am, January 1, 1970(epoch)."
},
{
"code": null,
"e": 3097,
"s": 2931,
"text": "#!/usr/bin/python3\nimport time; # This is required to include time module.\n\nticks = time.time()\nprint (\"Number of ticks since 12:00am, January 1, 1970:\", ticks)"
},
{
"code": null,
"e": 3148,
"s": 3097,
"text": "This would produce a result something as follows −"
},
{
"code": null,
"e": 3214,
"s": 3148,
"text": "Number of ticks since 12:00am, January 1, 1970: 1455508609.34375\n"
},
{
"code": null,
"e": 3445,
"s": 3214,
"text": "Date arithmetic is easy to do with ticks. However, dates before the epoch cannot be represented in this form. Dates in the far future also cannot be represented this way - the cutoff point is sometime in 2038 for UNIX and Windows."
},
{
"code": null,
"e": 3535,
"s": 3445,
"text": "Many of the Python's time functions handle time as a tuple of 9 numbers, as shown below −"
},
{
"code": null,
"e": 3549,
"s": 3535,
"text": "For Example −"
},
{
"code": null,
"e": 3588,
"s": 3549,
"text": "import time\n\nprint (time.localtime());"
},
{
"code": null,
"e": 3629,
"s": 3588,
"text": "This would produce a result as follows −"
},
{
"code": null,
"e": 3772,
"s": 3629,
"text": "time.struct_time(tm_year = 2016, tm_mon = 2, tm_mday = 15, tm_hour = 9, \n tm_min = 29, tm_sec = 2, tm_wday = 0, tm_yday = 46, tm_isdst = 0)\n"
},
{
"code": null,
"e": 3870,
"s": 3772,
"text": "The above tuple is equivalent to struct_time structure. This structure has following attributes −"
},
{
"code": null,
"e": 4081,
"s": 3870,
"text": "To translate a time instant from seconds since the epoch floating-point value into a timetuple, pass the floating-point value to a function (e.g., localtime) that returns a time-tuple with all valid nine items."
},
{
"code": null,
"e": 4195,
"s": 4081,
"text": "#!/usr/bin/python3\nimport time\n\nlocaltime = time.localtime(time.time())\nprint (\"Local current time :\", localtime)"
},
{
"code": null,
"e": 4293,
"s": 4195,
"text": "This would produce the following result, which could be formatted in any other presentable form −"
},
{
"code": null,
"e": 4457,
"s": 4293,
"text": "Local current time : time.struct_time(tm_year = 2016, tm_mon = 2, tm_mday = 15, \n tm_hour = 9, tm_min = 29, tm_sec = 2, tm_wday = 0, tm_yday = 46, tm_isdst = 0)\n"
},
{
"code": null,
"e": 4574,
"s": 4457,
"text": "You can format any time as per your requirement, but a simple method to get time in a readable format is asctime() −"
},
{
"code": null,
"e": 4704,
"s": 4574,
"text": "#!/usr/bin/python3\nimport time\n\nlocaltime = time.asctime( time.localtime(time.time()) )\nprint (\"Local current time :\", localtime)"
},
{
"code": null,
"e": 4746,
"s": 4704,
"text": "This would produce the following result −"
},
{
"code": null,
"e": 4793,
"s": 4746,
"text": "Local current time : Mon Feb 15 09:34:03 2016\n"
},
{
"code": null,
"e": 4945,
"s": 4793,
"text": "The calendar module gives a wide range of methods to play with yearly and monthly calendars. Here, we print a calendar for a given month ( Jan 2008 ) −"
},
{
"code": null,
"e": 5055,
"s": 4945,
"text": "#!/usr/bin/python3\nimport calendar\n\ncal = calendar.month(2016, 2)\nprint (\"Here is the calendar:\")\nprint (cal)"
},
{
"code": null,
"e": 5097,
"s": 5055,
"text": "This would produce the following result −"
},
{
"code": null,
"e": 5245,
"s": 5097,
"text": "Here is the calendar:\n February 2016\nMo Tu We Th Fr Sa Su\n 1 2 3 4 5 6 7\n 8 9 10 11 12 13 14\n15 16 17 18 19 20 21\n22 23 24 25 26 27 28\n29\n"
},
{
"code": null,
"e": 5432,
"s": 5245,
"text": "There is a popular time module available in Python, which provides functions for working with times and for converting between representations. Here is the list of all available methods."
},
{
"code": null,
"e": 5650,
"s": 5432,
"text": "The offset of the local DST timezone, in seconds west of UTC, if one is defined. This is negative if the local DST timezone is east of UTC (as in Western Europe, including the UK). Use this if the daylight is nonzero."
},
{
"code": null,
"e": 5750,
"s": 5650,
"text": "Accepts a time-tuple and returns a readable 24-character string such as 'Tue Dec 11 18:07:14 2008'."
},
{
"code": null,
"e": 5939,
"s": 5750,
"text": "Returns the current CPU time as a floating-point number of seconds. To measure computational costs of different approaches, the value of time.clock is more useful than that of time.time()."
},
{
"code": null,
"e": 6010,
"s": 5939,
"text": "Like asctime(localtime(secs)) and without arguments is like asctime( )"
},
{
"code": null,
"e": 6142,
"s": 6010,
"text": "Accepts an instant expressed in seconds since the epoch and returns a time-tuple t with the UTC time. Note − t.tm_isdst is always 0"
},
{
"code": null,
"e": 6334,
"s": 6142,
"text": "Accepts an instant expressed in seconds since the epoch and returns a time-tuple t with the local time (t.tm_isdst is 0 or 1, depending on whether DST applies to instant secs by local rules)."
},
{
"code": null,
"e": 6483,
"s": 6334,
"text": "Accepts an instant expressed as a time-tuple in local time and returns a floating-point value with the instant expressed in seconds since the epoch."
},
{
"code": null,
"e": 6529,
"s": 6483,
"text": "Suspends the calling thread for secs seconds."
},
{
"code": null,
"e": 6662,
"s": 6529,
"text": "Accepts an instant expressed as a time-tuple in local time and returns a string representing the instant as specified by string fmt."
},
{
"code": null,
"e": 6750,
"s": 6662,
"text": "Parses str according to format string fmt and returns the instant in time-tuple format."
},
{
"code": null,
"e": 6836,
"s": 6750,
"text": "Returns the current time instant, a floating-point number of seconds since the epoch."
},
{
"code": null,
"e": 6955,
"s": 6836,
"text": "Resets the time conversion rules used by the library routines. The environment variable TZ specifies how this is done."
},
{
"code": null,
"e": 7029,
"s": 6955,
"text": "There are two important attributes available with time module. They are −"
},
{
"code": null,
"e": 7043,
"s": 7029,
"text": "time.timezone"
},
{
"code": null,
"e": 7197,
"s": 7043,
"text": "Attribute time.timezone is the offset in seconds of the local time zone (without DST) from UTC (>0 in the Americas; <=0 in most of Europe, Asia, Africa)."
},
{
"code": null,
"e": 7209,
"s": 7197,
"text": "time.tzname"
},
{
"code": null,
"e": 7349,
"s": 7209,
"text": "Attribute time.tzname is a pair of locale-dependent strings, which are the names of the local time zone without and with DST, respectively."
},
{
"code": null,
"e": 7478,
"s": 7349,
"text": "The calendar module supplies calendar-related functions, including functions to print a text calendar for a given month or year."
},
{
"code": null,
"e": 7632,
"s": 7478,
"text": " By default, calendar takes Monday as the first day of the week and Sunday as the last one. To change this, call the calendar.setfirstweekday() function."
},
{
"code": null,
"e": 7697,
"s": 7632,
"text": "Here is a list of functions available with the calendar module −"
},
{
"code": null,
"e": 7739,
"s": 7697,
"text": "calendar.calendar(year,w = 2,l = 1,c = 6)"
},
{
"code": null,
"e": 7965,
"s": 7739,
"text": "Returns a multiline string with a calendar for year year formatted into three columns separated by c spaces. w is the width in characters of each date; each line has length 21*w+18+2*c. l is the number of lines for each week."
},
{
"code": null,
"e": 7990,
"s": 7965,
"text": "calendar.firstweekday( )"
},
{
"code": null,
"e": 8129,
"s": 7990,
"text": "Returns the current setting for the weekday that starts each week. By default, when calendar is first imported, this is 0, meaning Monday."
},
{
"code": null,
"e": 8151,
"s": 8129,
"text": "calendar.isleap(year)"
},
{
"code": null,
"e": 8206,
"s": 8151,
"text": "Returns True if year is a leap year; otherwise, False."
},
{
"code": null,
"e": 8231,
"s": 8206,
"text": "calendar.leapdays(y1,y2)"
},
{
"code": null,
"e": 8303,
"s": 8231,
"text": "Returns the total number of leap days in the years within range(y1,y2)."
},
{
"code": null,
"e": 8342,
"s": 8303,
"text": "calendar.month(year,month,w = 2,l = 1)"
},
{
"code": null,
"e": 8567,
"s": 8342,
"text": "Returns a multiline string with a calendar for month month of year year, one line per week plus two header lines. w is the width in characters of each date; each line has length 7*w+6. l is the number of lines for each week."
},
{
"code": null,
"e": 8602,
"s": 8567,
"text": "calendar.monthcalendar(year,month)"
},
{
"code": null,
"e": 8779,
"s": 8602,
"text": "Returns a list of lists of ints. Each sublist denotes a week. Days outside month month of year year are set to 0; days within the month are set to their day-of-month, 1 and up."
},
{
"code": null,
"e": 8811,
"s": 8779,
"text": "calendar.monthrange(year,month)"
},
{
"code": null,
"e": 9047,
"s": 8811,
"text": "Returns two integers. The first one is the code of the weekday for the first day of the month month in year year; the second one is the number of days in the month. Weekday codes are 0 (Monday) to 6 (Sunday); month numbers are 1 to 12."
},
{
"code": null,
"e": 9086,
"s": 9047,
"text": "calendar.prcal(year,w = 2,l = 1,c = 6)"
},
{
"code": null,
"e": 9128,
"s": 9086,
"text": "Like print calendar.calendar(year,w,l,c)."
},
{
"code": null,
"e": 9169,
"s": 9128,
"text": "calendar.prmonth(year,month,w = 2,l = 1)"
},
{
"code": null,
"e": 9212,
"s": 9169,
"text": "Like print calendar.month(year,month,w,l)."
},
{
"code": null,
"e": 9246,
"s": 9212,
"text": "calendar.setfirstweekday(weekday)"
},
{
"code": null,
"e": 9347,
"s": 9246,
"text": "Sets the first day of each week to weekday code weekday. Weekday codes are 0 (Monday) to 6 (Sunday)."
},
{
"code": null,
"e": 9374,
"s": 9347,
"text": "calendar.timegm(tupletime)"
},
{
"code": null,
"e": 9528,
"s": 9374,
"text": "The inverse of time.gmtime: accepts a time instant in time-tuple form and returns the same instant as a floating-point number of seconds since the epoch."
},
{
"code": null,
"e": 9561,
"s": 9528,
"text": "calendar.weekday(year,month,day)"
},
{
"code": null,
"e": 9698,
"s": 9561,
"text": "Returns the weekday code for the given date. Weekday codes are 0 (Monday) to 6 (Sunday); month numbers are 1 (January) to 12 (December)."
},
{
"code": null,
"e": 9831,
"s": 9698,
"text": "If you are interested, then here you would find a list of other important modules and functions to play with date & time in Python −"
},
{
"code": null,
"e": 9851,
"s": 9831,
"text": "The datetime Module"
},
{
"code": null,
"e": 9867,
"s": 9851,
"text": "The pytz Module"
},
{
"code": null,
"e": 9887,
"s": 9867,
"text": "The dateutil Module"
},
{
"code": null,
"e": 9924,
"s": 9887,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 9940,
"s": 9924,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 9973,
"s": 9940,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 9992,
"s": 9973,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 10027,
"s": 9992,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 10049,
"s": 10027,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 10083,
"s": 10049,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 10111,
"s": 10083,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 10146,
"s": 10111,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 10160,
"s": 10146,
"text": " Lets Kode It"
},
{
"code": null,
"e": 10193,
"s": 10160,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 10210,
"s": 10193,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 10217,
"s": 10210,
"text": " Print"
},
{
"code": null,
"e": 10228,
"s": 10217,
"text": " Add Notes"
}
]
|
Python os.fstat() Method | Python method fstat() returns information about a file associated with the fd. Here is the structure returned by fstat method −
st_dev − ID of device containing file
st_dev − ID of device containing file
st_ino − inode number
st_ino − inode number
st_mode − protection
st_mode − protection
st_nlink − number of hard links
st_nlink − number of hard links
st_uid − user ID of owner
st_uid − user ID of owner
st_gid − group ID of owner
st_gid − group ID of owner
st_rdev − device ID (if special file)
st_rdev − device ID (if special file)
st_size − total size, in bytes
st_size − total size, in bytes
st_blksize − blocksize for filesystem I/O
st_blksize − blocksize for filesystem I/O
st_blocks − number of blocks allocated
st_blocks − number of blocks allocated
st_atime − time of last access
st_atime − time of last access
st_mtime − time of last modification
st_mtime − time of last modification
st_ctime − time of last status change
st_ctime − time of last status change
Following is the syntax for fstat() method −
os.fstat(fd)
fd − This is the file descriptor for which system information is to be returned.
fd − This is the file descriptor for which system information is to be returned.
This method returns information about a file associated with the fd.
The following example shows the usage of chdir() method.
#!/usr/bin/python
import os, sys
# Open a file
fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT )
# Now get the touple
info = os.fstat(fd)
print "File Info :", info
# Now get uid of the file
print "UID of the file :%d" % info.st_uid
# Now get gid of the file
print "GID of the file :%d" % info.st_gid
# Close opened file
os.close( fd)
When we run above program, it produces following result −
File Info : (33261, 3753776L, 103L, 1, 0, 0,
102L, 1238783197, 1238786767, 1238786767)
UID of the file :0
GID of the file :0
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2372,
"s": 2244,
"text": "Python method fstat() returns information about a file associated with the fd. Here is the structure returned by fstat method −"
},
{
"code": null,
"e": 2410,
"s": 2372,
"text": "st_dev − ID of device containing file"
},
{
"code": null,
"e": 2448,
"s": 2410,
"text": "st_dev − ID of device containing file"
},
{
"code": null,
"e": 2470,
"s": 2448,
"text": "st_ino − inode number"
},
{
"code": null,
"e": 2492,
"s": 2470,
"text": "st_ino − inode number"
},
{
"code": null,
"e": 2513,
"s": 2492,
"text": "st_mode − protection"
},
{
"code": null,
"e": 2534,
"s": 2513,
"text": "st_mode − protection"
},
{
"code": null,
"e": 2566,
"s": 2534,
"text": "st_nlink − number of hard links"
},
{
"code": null,
"e": 2598,
"s": 2566,
"text": "st_nlink − number of hard links"
},
{
"code": null,
"e": 2624,
"s": 2598,
"text": "st_uid − user ID of owner"
},
{
"code": null,
"e": 2650,
"s": 2624,
"text": "st_uid − user ID of owner"
},
{
"code": null,
"e": 2677,
"s": 2650,
"text": "st_gid − group ID of owner"
},
{
"code": null,
"e": 2704,
"s": 2677,
"text": "st_gid − group ID of owner"
},
{
"code": null,
"e": 2742,
"s": 2704,
"text": "st_rdev − device ID (if special file)"
},
{
"code": null,
"e": 2780,
"s": 2742,
"text": "st_rdev − device ID (if special file)"
},
{
"code": null,
"e": 2811,
"s": 2780,
"text": "st_size − total size, in bytes"
},
{
"code": null,
"e": 2842,
"s": 2811,
"text": "st_size − total size, in bytes"
},
{
"code": null,
"e": 2884,
"s": 2842,
"text": "st_blksize − blocksize for filesystem I/O"
},
{
"code": null,
"e": 2926,
"s": 2884,
"text": "st_blksize − blocksize for filesystem I/O"
},
{
"code": null,
"e": 2965,
"s": 2926,
"text": "st_blocks − number of blocks allocated"
},
{
"code": null,
"e": 3004,
"s": 2965,
"text": "st_blocks − number of blocks allocated"
},
{
"code": null,
"e": 3035,
"s": 3004,
"text": "st_atime − time of last access"
},
{
"code": null,
"e": 3066,
"s": 3035,
"text": "st_atime − time of last access"
},
{
"code": null,
"e": 3103,
"s": 3066,
"text": "st_mtime − time of last modification"
},
{
"code": null,
"e": 3140,
"s": 3103,
"text": "st_mtime − time of last modification"
},
{
"code": null,
"e": 3178,
"s": 3140,
"text": "st_ctime − time of last status change"
},
{
"code": null,
"e": 3216,
"s": 3178,
"text": "st_ctime − time of last status change"
},
{
"code": null,
"e": 3261,
"s": 3216,
"text": "Following is the syntax for fstat() method −"
},
{
"code": null,
"e": 3275,
"s": 3261,
"text": "os.fstat(fd)\n"
},
{
"code": null,
"e": 3356,
"s": 3275,
"text": "fd − This is the file descriptor for which system information is to be returned."
},
{
"code": null,
"e": 3437,
"s": 3356,
"text": "fd − This is the file descriptor for which system information is to be returned."
},
{
"code": null,
"e": 3506,
"s": 3437,
"text": "This method returns information about a file associated with the fd."
},
{
"code": null,
"e": 3563,
"s": 3506,
"text": "The following example shows the usage of chdir() method."
},
{
"code": null,
"e": 3903,
"s": 3563,
"text": "#!/usr/bin/python\n\nimport os, sys\n\n# Open a file\nfd = os.open( \"foo.txt\", os.O_RDWR|os.O_CREAT )\n\n# Now get the touple\ninfo = os.fstat(fd)\n\nprint \"File Info :\", info\n\n# Now get uid of the file\nprint \"UID of the file :%d\" % info.st_uid\n\n# Now get gid of the file\nprint \"GID of the file :%d\" % info.st_gid\n\n# Close opened file\nos.close( fd)"
},
{
"code": null,
"e": 3961,
"s": 3903,
"text": "When we run above program, it produces following result −"
},
{
"code": null,
"e": 4100,
"s": 3961,
"text": "File Info : (33261, 3753776L, 103L, 1, 0, 0, \n 102L, 1238783197, 1238786767, 1238786767)\nUID of the file :0\nGID of the file :0\n"
},
{
"code": null,
"e": 4137,
"s": 4100,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 4153,
"s": 4137,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 4186,
"s": 4153,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 4205,
"s": 4186,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4240,
"s": 4205,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 4262,
"s": 4240,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 4296,
"s": 4262,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 4324,
"s": 4296,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4359,
"s": 4324,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 4373,
"s": 4359,
"text": " Lets Kode It"
},
{
"code": null,
"e": 4406,
"s": 4373,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 4423,
"s": 4406,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 4430,
"s": 4423,
"text": " Print"
},
{
"code": null,
"e": 4441,
"s": 4430,
"text": " Add Notes"
}
]
|
Database operations in Java | This article provides an example of how to create a simple JDBC application. This will show you how to open a database connection, execute a SQL query, and display the results.
There are following six steps involved in building a JDBC application −
Import the packages: Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice.
Import the packages: Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice.
Register the JDBC driver: Requires that you initialize a driver so you can open a communication channel with the database.
Register the JDBC driver: Requires that you initialize a driver so you can open a communication channel with the database.
Open a connection: Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with the database.
Open a connection: Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with the database.
Execute a query: Requires using an object of type Statement for building and submitting an SQL statement to the database.
Execute a query: Requires using an object of type Statement for building and submitting an SQL statement to the database.
Extract data from result set: Requires that you use the appropriate ResultSet.getXXX() method to retrieve the data from the result set.
Extract data from result set: Requires that you use the appropriate ResultSet.getXXX() method to retrieve the data from the result set.
Clean up the environment: Requires explicitly closing all database resources versus relying on the JVM's garbage collection.
Clean up the environment: Requires explicitly closing all database resources versus relying on the JVM's garbage collection.
This simple example can serve as a template when you need to create your own JDBC application in the future.
This sample code has been written based on the environment and database setup done in the previous chapter.
Copy and paste the following example in FirstExample.java, compile and run as follows −
//STEP 1. Import required packages
import java.sql.*;
public class FirstExample {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/EMP";
// Database credentials
static final String USER = "username";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()) {
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
//STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException se) {
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e) {
//Handle errors for Class.forName
e.printStackTrace();
}finally {
//finally block used to close resources
try {
if(stmt!=null)
stmt.close();
}catch(SQLException se2) {}
// nothing we can do
try {
if(conn!=null)
conn.close();
}catch(SQLException se) {
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end FirstExample
Now let us compile the above example as follows −
C:\>javac FirstExample.java
C:\>
When you run FirstExample, it produces the following result −
C:\>java FirstExample
Connecting to database...
Creating statement...
ID: 100, Age: 18, First: Zara, Last: Ali
ID: 101, Age: 25, First: Mahnaz, Last: Fatma
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal
C:\> | [
{
"code": null,
"e": 1239,
"s": 1062,
"text": "This article provides an example of how to create a simple JDBC application. This will show you how to open a database connection, execute a SQL query, and display the results."
},
{
"code": null,
"e": 1311,
"s": 1239,
"text": "There are following six steps involved in building a JDBC application −"
},
{
"code": null,
"e": 1482,
"s": 1311,
"text": "Import the packages: Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice."
},
{
"code": null,
"e": 1653,
"s": 1482,
"text": "Import the packages: Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice."
},
{
"code": null,
"e": 1776,
"s": 1653,
"text": "Register the JDBC driver: Requires that you initialize a driver so you can open a communication channel with the database."
},
{
"code": null,
"e": 1899,
"s": 1776,
"text": "Register the JDBC driver: Requires that you initialize a driver so you can open a communication channel with the database."
},
{
"code": null,
"e": 2063,
"s": 1899,
"text": "Open a connection: Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with the database."
},
{
"code": null,
"e": 2227,
"s": 2063,
"text": "Open a connection: Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with the database."
},
{
"code": null,
"e": 2349,
"s": 2227,
"text": "Execute a query: Requires using an object of type Statement for building and submitting an SQL statement to the database."
},
{
"code": null,
"e": 2471,
"s": 2349,
"text": "Execute a query: Requires using an object of type Statement for building and submitting an SQL statement to the database."
},
{
"code": null,
"e": 2607,
"s": 2471,
"text": "Extract data from result set: Requires that you use the appropriate ResultSet.getXXX() method to retrieve the data from the result set."
},
{
"code": null,
"e": 2743,
"s": 2607,
"text": "Extract data from result set: Requires that you use the appropriate ResultSet.getXXX() method to retrieve the data from the result set."
},
{
"code": null,
"e": 2868,
"s": 2743,
"text": "Clean up the environment: Requires explicitly closing all database resources versus relying on the JVM's garbage collection."
},
{
"code": null,
"e": 2993,
"s": 2868,
"text": "Clean up the environment: Requires explicitly closing all database resources versus relying on the JVM's garbage collection."
},
{
"code": null,
"e": 3102,
"s": 2993,
"text": "This simple example can serve as a template when you need to create your own JDBC application in the future."
},
{
"code": null,
"e": 3210,
"s": 3102,
"text": "This sample code has been written based on the environment and database setup done in the previous chapter."
},
{
"code": null,
"e": 3298,
"s": 3210,
"text": "Copy and paste the following example in FirstExample.java, compile and run as follows −"
},
{
"code": null,
"e": 5579,
"s": 3298,
"text": "//STEP 1. Import required packages\nimport java.sql.*;\n\npublic class FirstExample {\n // JDBC driver name and database URL\n static final String JDBC_DRIVER = \"com.mysql.jdbc.Driver\"; \n static final String DB_URL = \"jdbc:mysql://localhost/EMP\";\n\n // Database credentials\n static final String USER = \"username\";\n static final String PASS = \"password\";\n\n public static void main(String[] args) {\n Connection conn = null;\n Statement stmt = null;\n try{\n //STEP 2: Register JDBC driver\n Class.forName(\"com.mysql.jdbc.Driver\");\n\n //STEP 3: Open a connection\n System.out.println(\"Connecting to database...\");\n conn = DriverManager.getConnection(DB_URL,USER,PASS);\n\n //STEP 4: Execute a query\n System.out.println(\"Creating statement...\");\n stmt = conn.createStatement();\n String sql;\n sql = \"SELECT id, first, last, age FROM Employees\";\n ResultSet rs = stmt.executeQuery(sql);\n\n //STEP 5: Extract data from result set\n while(rs.next()) {\n //Retrieve by column name\n int id = rs.getInt(\"id\");\n int age = rs.getInt(\"age\");\n String first = rs.getString(\"first\");\n String last = rs.getString(\"last\");\n\n //Display values\n System.out.print(\"ID: \" + id);\n System.out.print(\", Age: \" + age);\n System.out.print(\", First: \" + first);\n System.out.println(\", Last: \" + last);\n }\n //STEP 6: Clean-up environment\n rs.close();\n stmt.close();\n conn.close();\n }catch(SQLException se) {\n //Handle errors for JDBC\n se.printStackTrace();\n }catch(Exception e) {\n //Handle errors for Class.forName\n e.printStackTrace();\n }finally {\n //finally block used to close resources\n try {\n if(stmt!=null)\n stmt.close();\n }catch(SQLException se2) {}\n // nothing we can do\n try {\n if(conn!=null)\n conn.close();\n }catch(SQLException se) {\n se.printStackTrace();\n }//end finally try\n }//end try\n System.out.println(\"Goodbye!\");\n }//end main\n}//end FirstExample"
},
{
"code": null,
"e": 5629,
"s": 5579,
"text": "Now let us compile the above example as follows −"
},
{
"code": null,
"e": 5662,
"s": 5629,
"text": "C:\\>javac FirstExample.java\nC:\\>"
},
{
"code": null,
"e": 5724,
"s": 5662,
"text": "When you run FirstExample, it produces the following result −"
},
{
"code": null,
"e": 5972,
"s": 5724,
"text": "C:\\>java FirstExample\nConnecting to database...\nCreating statement...\nID: 100, Age: 18, First: Zara, Last: Ali\nID: 101, Age: 25, First: Mahnaz, Last: Fatma\nID: 102, Age: 30, First: Zaid, Last: Khan\nID: 103, Age: 28, First: Sumit, Last: Mittal\nC:\\>"
}
]
|
InterpretML: Another Way to Explain Your Model | by Noga Gershon Barak | Towards Data Science | Interpretability can be crucial when implementing ML models. By interpreting models , customers can gain trust in the model and facilitate adoption. It may also be helpful in debugging your model, and in some situations, you will be required to provide explanations for predictions generated by the model. In my previous blog post, I discussed two methods: LIME and SHAP, that I used in one of our projects at Dell.
In this blog post, I’ll provide an overview of the InterpretML package, which holds a new developed interpretable model (Explainable Boosting Machine) that can explain your model in both a global and local context, alongside existing methods like LIME, SHAP, and more with great visualizations that can take your model’s explanations to the next level.
This blog will cover the following:
InterpretML overviewExplainable Boosting Machine (EBM)ExamplesSummaryFurther reading
InterpretML overview
Explainable Boosting Machine (EBM)
Examples
Summary
Further reading
InterpretML is an open-source Python package that contains different interpretability algorithms which can be used by both practitioners and researchers. The package offers two types of interpretability methods: glassbox and blackbox. The glassbox methods include both interpretable models such as linear regression, logistic regression, decision trees that can be trained as a part of the package, as well as corresponding explainability tools. While the blackbox models only include model-agnostic explainability tools such as LIME, and Kernel SHAP that are compatible with models trained outside the package, the glassbox models provide both global and local explanations, while the blackbox models only support local explanations. Furthermore, InterpretML has a built-in visualization platform that allows users to compare different methods easily. Moreover, as InterpretML is scikit-learn compatible, the hyperparameters of the glassbox models can be tuned as other scikit-learn models. To emphasize the difference, using a glassbox model in your project, will allow you to both train and visualize explanations using InterpretML, while using a different model will only allow you to visualize explanations generated by a blackbox model, after training the model with another package.
Lastly, the package also includes a new interpretable model- Explainable Boosting Machine (EBM) that was developed by Microsoft Researchers and will be discussed in the next section.
EBM is a glassbox model indented to have comparable accuracy to machine learning models such as Random Forest and Boosted Trees as well as interpretability capabilities. EBM is a Generalized Additive Model (GAM) which is very similar to linear models. In linear models, the relation between the observations Y and the dependent variables Xi is formulated as:
Y = β0 + β1X1 + β2X2 + β3X3 + ... + βnXn
while in Generalized additive models, the relation is formalized as:
Y = β0 + f(X1) + f(X2) + f(X3) + ... + f(Xn)
So now each contribution to the predictor is now some function f. EBM offers some improvements to traditional GAMs: each feature function is learned using modern machine learning technique such as bagging and boosting. Training is carried out in many iterations where each iteration consists of constructing a boosting procedure separately for each feature. As this is done with low learning rates, the order of the features does not matter. The high number of iterations aims to mitigate the effects of co-linearity in order to learn best what is the contribution of each feature to the model’s prediction. Furthermore, EBM can automatically detect and include pairwise interaction terms, this increases the accuracy of the model while preserving its explainability. Since EBM is an additive model, the contribution of each feature can be captured and visualized, and therefore enhance explainability.
As a further explanation, for each iteration of the model, small trees are constructed sequentially and each tree can only use a single feature, in a boosting manner the residual is updated and a new tree is constructed using a different feature. This is done for each feature in every iteration. Once training is completed, we can look at all the trees that were constructed by a certain feature, and build a graph based on their predictions that showing the contribution that each feature made to the predictions.
As an example, we will use the heart failure prediction data set from Kaggle. The data set contains 12 features that can be used to predict mortality (DEATH_EVENT- 0/1) by heart failure. Some of the features include: age, sex, whether the patient has anemia/diabetes/high blood pressure and more.We will Examine the following models and corresponding explanations generated by InterpretML:
EBM (glassbox)
EBM (glassbox)
2. Logistic Regression (glassbox)
3. LightGBM using Lime and SHAP (blackbox)
A notebook of the code, including the interactive visualizations can be found here.
Before getting into the examples, it is important to note that unlike the implementations of LIME and SHAP, for classification problems with EBM / logistic regression, the contributions of features are expressed as log odds and not probabilities. In fact, as done in logistic regression, to get the probability, the log odds is passed through a logit link function. Scores are displayed in an additive log odds space because it allows a fair comparison of the contributions from each feature. This is due to the non-linearity of the log odds and the probability. Look into this GitHub issue for more information.
Following that I will share some examples of what else you can do with InterpretML beyond explainability.
Let’s start by looking at the global explanation.
ebm_global = trained_ebm.explain_global()show(ebm_global)
You can look at the overall importance of the features, and also look into each feature/interaction separately.
The overall importance of each feature is the average of the absolute predicted value of each feature in the training set. Essentially, each data point in the training data is scored using one feature at a time. The absolute values of the scores are averaged, this creates each bar in the summary plot.
As mentioned before, you can look into each feature individually and see how the value of the feature affects the score. You will also notice grey markup, these are the error bars. These are estimates of the model’s uncertainty within certain regions of the feature. The broader the bar, the greater the impact of small changes in the training data. Based on that, interpretation of these data points should be addressed with caution. You can access the the error bar sizes with the following code:
trained_ebm.term_standard_deviations_[4]
This will give us the standard deviations of the fourth feature in the data.
Now, let’s look into the local explanation. You can examine several observations together using the following code:
ebm_local = trained_ebm.explain_local(X_test[10:15], y_test[10:15])show(ebm_local)
To generate the local predictions, the model uses the graph created for each feature as a lookup table together with the learned intercept.
Let’s start by looking at the global explanation:
lr_global = trained_lr.explain_global()show(lr_global)
Here, as opposed to EBM the global explanation not only provides the magnitude but also the sign. As before, you can examine each feature separately as well.
Now, let’s examine the local explanations:
Now, you can compare the local explanations provided by the EBM model with the local explanations provided by the logistic regression model.Based on your knowledge or with the help domain experts you can decided which one is a better fit.
Depending on the data, you might want to use a model other than EBM or logistic regression. One example of such reason could be the presence of missing values in the data- while LightGBM is able to handle the presence of missing values, other models may requires filling the missing values prior to training.
As opposed to previous presented methods, using the InterpretML package, you cannot generate global explanations to a non-glassbox model. However, using SHAP directly will allow you to do that. Another important point to note is that using SHAP through InterpretML, only provides KernalSHAP which is model agnostic. Using SHAP directly offers additional explainers such as: TreeSHAP and DeepSHAP.
we will start by looking into SHAP:
from interpret.blackbox import ShapKernelshap = ShapKernel(predict_fn=trained_LGBM.predict_proba, data=X_train)shap_local = shap.explain_local(X_test[10:15], y_test[10:15])show(shap_local)
Now, let’s look into LIME:
lime = LimeTabular(predict_fn=trained_LGBM.predict_proba, data=X_train)lime_local = lime.explain_local(X_test[10:15], y_test[10:15])show(lime_local)
As you can see, the local explanations for both the glassbox and blackbox models have the same format.
Notice that if you have categorical features in the data that were one-hot-encoded, results might not be entirely reliable. This is because LIME creates explanations by permuting data. If the features are one hot encoded, LIME cannot know which columns are a part of the same original feature, and as a result create a data point that is not consistent with the original data.
To know more about SHAP, LIME and how to deal with categorical data, check out my previous blog post.
InterpretML beyond explainability
InterpretML can be used to perform EDA on the data, the package offers some basic EDA capabilities using plotly.
from interpret import showfrom interpret.provider import InlineProviderfrom interpret import set_visualize_providerset_visualize_provider(InlineProvider())from interpret.data import ClassHistogramhist = ClassHistogram().explain_data(X_train, y_train, name="Train Data")show(hist)
You can also perform hypermeter tuning of models in the package. Here as an example, I used RandomizedSearchCV with 3 fold cross validation.
from interpret.glassbox import ExplainableBoostingClassifierfrom sklearn.model_selection import RandomizedSearchCVparam_test = {'learning_rate': [0.001,0.005,0.01,0.03], 'interactions': [5,10,15], 'max_interaction_bins': [10,15,20], 'max_rounds': [5000,10000,15000,20000], 'min_samples_leaf': [2,3,5], 'max_leaves': [3,5,10]}n_HP_points_to_test=10LGBM_clf = LGBMClassifier(random_state=314, n_jobs=-1)LGBM_gs = RandomizedSearchCV( estimator=LGBM_clf, param_distributions=param_test, n_iter=n_HP_points_to_test, scoring="roc_auc", cv=3, refit=True, random_state=314, verbose=False,)LGBM_gs.fit(X_train, y_train)
You can use the following code to further compare the results by plotting the ROC curves for each model:
from interpret import perfroc = perf.ROC(gs.best_estimator_.predict_proba, feature_names=X_train.columns)roc_explanation = roc.explain_perf(X_test, y_test)show(roc_explanation)
Alternatively, you can have a unified view of the results or explanations across the different models by having the objects you wish to view as a list in show.
show([hist, ebm_global, lr_global], share_tables=True)
You should be aware that this is not supported if you’re using a cloud environment.
InterpretML offers different explainability methods under one roof. It also offers EDA tools and great visualizations to support a better understanding of the results, as well as the comparison of different methods. It should definitely be considered as a possible explanation tool for your model. The GitHub page of the package (specifically the issues tab) was extremely helpful and helped me gain a deeper understanding of the package while researching and writing this blog post.
Here are some additional reading & watching recommendations:
1- InterpretML documentation
2- GitHub page
3- You Tube Video- The Science Behind InterpretML: Explainable Boosting Machine
4- Paper- InterpretML: A Unified Framework for Machine Learning Interpretability
Special thanks to Or Herman-Saffar and Rachel Shalom for reviewing, and providing valuable feedback on this blog post. | [
{
"code": null,
"e": 588,
"s": 172,
"text": "Interpretability can be crucial when implementing ML models. By interpreting models , customers can gain trust in the model and facilitate adoption. It may also be helpful in debugging your model, and in some situations, you will be required to provide explanations for predictions generated by the model. In my previous blog post, I discussed two methods: LIME and SHAP, that I used in one of our projects at Dell."
},
{
"code": null,
"e": 941,
"s": 588,
"text": "In this blog post, I’ll provide an overview of the InterpretML package, which holds a new developed interpretable model (Explainable Boosting Machine) that can explain your model in both a global and local context, alongside existing methods like LIME, SHAP, and more with great visualizations that can take your model’s explanations to the next level."
},
{
"code": null,
"e": 977,
"s": 941,
"text": "This blog will cover the following:"
},
{
"code": null,
"e": 1062,
"s": 977,
"text": "InterpretML overviewExplainable Boosting Machine (EBM)ExamplesSummaryFurther reading"
},
{
"code": null,
"e": 1083,
"s": 1062,
"text": "InterpretML overview"
},
{
"code": null,
"e": 1118,
"s": 1083,
"text": "Explainable Boosting Machine (EBM)"
},
{
"code": null,
"e": 1127,
"s": 1118,
"text": "Examples"
},
{
"code": null,
"e": 1135,
"s": 1127,
"text": "Summary"
},
{
"code": null,
"e": 1151,
"s": 1135,
"text": "Further reading"
},
{
"code": null,
"e": 2441,
"s": 1151,
"text": "InterpretML is an open-source Python package that contains different interpretability algorithms which can be used by both practitioners and researchers. The package offers two types of interpretability methods: glassbox and blackbox. The glassbox methods include both interpretable models such as linear regression, logistic regression, decision trees that can be trained as a part of the package, as well as corresponding explainability tools. While the blackbox models only include model-agnostic explainability tools such as LIME, and Kernel SHAP that are compatible with models trained outside the package, the glassbox models provide both global and local explanations, while the blackbox models only support local explanations. Furthermore, InterpretML has a built-in visualization platform that allows users to compare different methods easily. Moreover, as InterpretML is scikit-learn compatible, the hyperparameters of the glassbox models can be tuned as other scikit-learn models. To emphasize the difference, using a glassbox model in your project, will allow you to both train and visualize explanations using InterpretML, while using a different model will only allow you to visualize explanations generated by a blackbox model, after training the model with another package."
},
{
"code": null,
"e": 2624,
"s": 2441,
"text": "Lastly, the package also includes a new interpretable model- Explainable Boosting Machine (EBM) that was developed by Microsoft Researchers and will be discussed in the next section."
},
{
"code": null,
"e": 2983,
"s": 2624,
"text": "EBM is a glassbox model indented to have comparable accuracy to machine learning models such as Random Forest and Boosted Trees as well as interpretability capabilities. EBM is a Generalized Additive Model (GAM) which is very similar to linear models. In linear models, the relation between the observations Y and the dependent variables Xi is formulated as:"
},
{
"code": null,
"e": 3024,
"s": 2983,
"text": "Y = β0 + β1X1 + β2X2 + β3X3 + ... + βnXn"
},
{
"code": null,
"e": 3093,
"s": 3024,
"text": "while in Generalized additive models, the relation is formalized as:"
},
{
"code": null,
"e": 3138,
"s": 3093,
"text": "Y = β0 + f(X1) + f(X2) + f(X3) + ... + f(Xn)"
},
{
"code": null,
"e": 4041,
"s": 3138,
"text": "So now each contribution to the predictor is now some function f. EBM offers some improvements to traditional GAMs: each feature function is learned using modern machine learning technique such as bagging and boosting. Training is carried out in many iterations where each iteration consists of constructing a boosting procedure separately for each feature. As this is done with low learning rates, the order of the features does not matter. The high number of iterations aims to mitigate the effects of co-linearity in order to learn best what is the contribution of each feature to the model’s prediction. Furthermore, EBM can automatically detect and include pairwise interaction terms, this increases the accuracy of the model while preserving its explainability. Since EBM is an additive model, the contribution of each feature can be captured and visualized, and therefore enhance explainability."
},
{
"code": null,
"e": 4557,
"s": 4041,
"text": "As a further explanation, for each iteration of the model, small trees are constructed sequentially and each tree can only use a single feature, in a boosting manner the residual is updated and a new tree is constructed using a different feature. This is done for each feature in every iteration. Once training is completed, we can look at all the trees that were constructed by a certain feature, and build a graph based on their predictions that showing the contribution that each feature made to the predictions."
},
{
"code": null,
"e": 4947,
"s": 4557,
"text": "As an example, we will use the heart failure prediction data set from Kaggle. The data set contains 12 features that can be used to predict mortality (DEATH_EVENT- 0/1) by heart failure. Some of the features include: age, sex, whether the patient has anemia/diabetes/high blood pressure and more.We will Examine the following models and corresponding explanations generated by InterpretML:"
},
{
"code": null,
"e": 4962,
"s": 4947,
"text": "EBM (glassbox)"
},
{
"code": null,
"e": 4977,
"s": 4962,
"text": "EBM (glassbox)"
},
{
"code": null,
"e": 5011,
"s": 4977,
"text": "2. Logistic Regression (glassbox)"
},
{
"code": null,
"e": 5054,
"s": 5011,
"text": "3. LightGBM using Lime and SHAP (blackbox)"
},
{
"code": null,
"e": 5138,
"s": 5054,
"text": "A notebook of the code, including the interactive visualizations can be found here."
},
{
"code": null,
"e": 5751,
"s": 5138,
"text": "Before getting into the examples, it is important to note that unlike the implementations of LIME and SHAP, for classification problems with EBM / logistic regression, the contributions of features are expressed as log odds and not probabilities. In fact, as done in logistic regression, to get the probability, the log odds is passed through a logit link function. Scores are displayed in an additive log odds space because it allows a fair comparison of the contributions from each feature. This is due to the non-linearity of the log odds and the probability. Look into this GitHub issue for more information."
},
{
"code": null,
"e": 5857,
"s": 5751,
"text": "Following that I will share some examples of what else you can do with InterpretML beyond explainability."
},
{
"code": null,
"e": 5907,
"s": 5857,
"text": "Let’s start by looking at the global explanation."
},
{
"code": null,
"e": 5965,
"s": 5907,
"text": "ebm_global = trained_ebm.explain_global()show(ebm_global)"
},
{
"code": null,
"e": 6077,
"s": 5965,
"text": "You can look at the overall importance of the features, and also look into each feature/interaction separately."
},
{
"code": null,
"e": 6380,
"s": 6077,
"text": "The overall importance of each feature is the average of the absolute predicted value of each feature in the training set. Essentially, each data point in the training data is scored using one feature at a time. The absolute values of the scores are averaged, this creates each bar in the summary plot."
},
{
"code": null,
"e": 6879,
"s": 6380,
"text": "As mentioned before, you can look into each feature individually and see how the value of the feature affects the score. You will also notice grey markup, these are the error bars. These are estimates of the model’s uncertainty within certain regions of the feature. The broader the bar, the greater the impact of small changes in the training data. Based on that, interpretation of these data points should be addressed with caution. You can access the the error bar sizes with the following code:"
},
{
"code": null,
"e": 6920,
"s": 6879,
"text": "trained_ebm.term_standard_deviations_[4]"
},
{
"code": null,
"e": 6997,
"s": 6920,
"text": "This will give us the standard deviations of the fourth feature in the data."
},
{
"code": null,
"e": 7113,
"s": 6997,
"text": "Now, let’s look into the local explanation. You can examine several observations together using the following code:"
},
{
"code": null,
"e": 7196,
"s": 7113,
"text": "ebm_local = trained_ebm.explain_local(X_test[10:15], y_test[10:15])show(ebm_local)"
},
{
"code": null,
"e": 7336,
"s": 7196,
"text": "To generate the local predictions, the model uses the graph created for each feature as a lookup table together with the learned intercept."
},
{
"code": null,
"e": 7386,
"s": 7336,
"text": "Let’s start by looking at the global explanation:"
},
{
"code": null,
"e": 7441,
"s": 7386,
"text": "lr_global = trained_lr.explain_global()show(lr_global)"
},
{
"code": null,
"e": 7599,
"s": 7441,
"text": "Here, as opposed to EBM the global explanation not only provides the magnitude but also the sign. As before, you can examine each feature separately as well."
},
{
"code": null,
"e": 7642,
"s": 7599,
"text": "Now, let’s examine the local explanations:"
},
{
"code": null,
"e": 7881,
"s": 7642,
"text": "Now, you can compare the local explanations provided by the EBM model with the local explanations provided by the logistic regression model.Based on your knowledge or with the help domain experts you can decided which one is a better fit."
},
{
"code": null,
"e": 8190,
"s": 7881,
"text": "Depending on the data, you might want to use a model other than EBM or logistic regression. One example of such reason could be the presence of missing values in the data- while LightGBM is able to handle the presence of missing values, other models may requires filling the missing values prior to training."
},
{
"code": null,
"e": 8587,
"s": 8190,
"text": "As opposed to previous presented methods, using the InterpretML package, you cannot generate global explanations to a non-glassbox model. However, using SHAP directly will allow you to do that. Another important point to note is that using SHAP through InterpretML, only provides KernalSHAP which is model agnostic. Using SHAP directly offers additional explainers such as: TreeSHAP and DeepSHAP."
},
{
"code": null,
"e": 8623,
"s": 8587,
"text": "we will start by looking into SHAP:"
},
{
"code": null,
"e": 8812,
"s": 8623,
"text": "from interpret.blackbox import ShapKernelshap = ShapKernel(predict_fn=trained_LGBM.predict_proba, data=X_train)shap_local = shap.explain_local(X_test[10:15], y_test[10:15])show(shap_local)"
},
{
"code": null,
"e": 8839,
"s": 8812,
"text": "Now, let’s look into LIME:"
},
{
"code": null,
"e": 8988,
"s": 8839,
"text": "lime = LimeTabular(predict_fn=trained_LGBM.predict_proba, data=X_train)lime_local = lime.explain_local(X_test[10:15], y_test[10:15])show(lime_local)"
},
{
"code": null,
"e": 9091,
"s": 8988,
"text": "As you can see, the local explanations for both the glassbox and blackbox models have the same format."
},
{
"code": null,
"e": 9468,
"s": 9091,
"text": "Notice that if you have categorical features in the data that were one-hot-encoded, results might not be entirely reliable. This is because LIME creates explanations by permuting data. If the features are one hot encoded, LIME cannot know which columns are a part of the same original feature, and as a result create a data point that is not consistent with the original data."
},
{
"code": null,
"e": 9570,
"s": 9468,
"text": "To know more about SHAP, LIME and how to deal with categorical data, check out my previous blog post."
},
{
"code": null,
"e": 9604,
"s": 9570,
"text": "InterpretML beyond explainability"
},
{
"code": null,
"e": 9717,
"s": 9604,
"text": "InterpretML can be used to perform EDA on the data, the package offers some basic EDA capabilities using plotly."
},
{
"code": null,
"e": 9997,
"s": 9717,
"text": "from interpret import showfrom interpret.provider import InlineProviderfrom interpret import set_visualize_providerset_visualize_provider(InlineProvider())from interpret.data import ClassHistogramhist = ClassHistogram().explain_data(X_train, y_train, name=\"Train Data\")show(hist)"
},
{
"code": null,
"e": 10138,
"s": 9997,
"text": "You can also perform hypermeter tuning of models in the package. Here as an example, I used RandomizedSearchCV with 3 fold cross validation."
},
{
"code": null,
"e": 10838,
"s": 10138,
"text": "from interpret.glassbox import ExplainableBoostingClassifierfrom sklearn.model_selection import RandomizedSearchCVparam_test = {'learning_rate': [0.001,0.005,0.01,0.03], 'interactions': [5,10,15], 'max_interaction_bins': [10,15,20], 'max_rounds': [5000,10000,15000,20000], 'min_samples_leaf': [2,3,5], 'max_leaves': [3,5,10]}n_HP_points_to_test=10LGBM_clf = LGBMClassifier(random_state=314, n_jobs=-1)LGBM_gs = RandomizedSearchCV( estimator=LGBM_clf, param_distributions=param_test, n_iter=n_HP_points_to_test, scoring=\"roc_auc\", cv=3, refit=True, random_state=314, verbose=False,)LGBM_gs.fit(X_train, y_train)"
},
{
"code": null,
"e": 10943,
"s": 10838,
"text": "You can use the following code to further compare the results by plotting the ROC curves for each model:"
},
{
"code": null,
"e": 11120,
"s": 10943,
"text": "from interpret import perfroc = perf.ROC(gs.best_estimator_.predict_proba, feature_names=X_train.columns)roc_explanation = roc.explain_perf(X_test, y_test)show(roc_explanation)"
},
{
"code": null,
"e": 11280,
"s": 11120,
"text": "Alternatively, you can have a unified view of the results or explanations across the different models by having the objects you wish to view as a list in show."
},
{
"code": null,
"e": 11335,
"s": 11280,
"text": "show([hist, ebm_global, lr_global], share_tables=True)"
},
{
"code": null,
"e": 11419,
"s": 11335,
"text": "You should be aware that this is not supported if you’re using a cloud environment."
},
{
"code": null,
"e": 11903,
"s": 11419,
"text": "InterpretML offers different explainability methods under one roof. It also offers EDA tools and great visualizations to support a better understanding of the results, as well as the comparison of different methods. It should definitely be considered as a possible explanation tool for your model. The GitHub page of the package (specifically the issues tab) was extremely helpful and helped me gain a deeper understanding of the package while researching and writing this blog post."
},
{
"code": null,
"e": 11964,
"s": 11903,
"text": "Here are some additional reading & watching recommendations:"
},
{
"code": null,
"e": 11993,
"s": 11964,
"text": "1- InterpretML documentation"
},
{
"code": null,
"e": 12008,
"s": 11993,
"text": "2- GitHub page"
},
{
"code": null,
"e": 12088,
"s": 12008,
"text": "3- You Tube Video- The Science Behind InterpretML: Explainable Boosting Machine"
},
{
"code": null,
"e": 12169,
"s": 12088,
"text": "4- Paper- InterpretML: A Unified Framework for Machine Learning Interpretability"
}
]
|
How to pass Text Area Data to Python CGI script? | TEXTAREA element is used when multiline text has to be passed to the CGI Program.
Here is example HTML code for a form with a TEXTAREA box −
<form action = "/cgi-bin/textarea.py" method = "post" target = "_blank">
<textarea name = "textcontent" cols = "40" rows = "4">
Type your text here...
</textarea>
<input type = "submit" value = "Submit" />
</form>
The result of this code is the following form −
Type your text here...
Submit
Below is textarea.cgi script to handle input given by web browser −
#!/usr/bin/python
# Import modules for CGI handling
import cgi, cgitb
# Create instance of FieldStorage
form = cgi.FieldStorage()
# Get data from fields
if form.getvalue('textcontent'):
text_content = form.getvalue('textcontent')
else:
text_content = "Not entered"
print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>";
print "<title>Text Area - Fifth CGI Program</title>"
print "</head>"
print "<body>"
print "<h2> Entered Text Content is %s</h2>" % text_content
print "</body>" | [
{
"code": null,
"e": 1144,
"s": 1062,
"text": "TEXTAREA element is used when multiline text has to be passed to the CGI Program."
},
{
"code": null,
"e": 1203,
"s": 1144,
"text": "Here is example HTML code for a form with a TEXTAREA box −"
},
{
"code": null,
"e": 1417,
"s": 1203,
"text": "<form action = \"/cgi-bin/textarea.py\" method = \"post\" target = \"_blank\">\n<textarea name = \"textcontent\" cols = \"40\" rows = \"4\">\nType your text here...\n</textarea>\n<input type = \"submit\" value = \"Submit\" />\n</form>"
},
{
"code": null,
"e": 1465,
"s": 1417,
"text": "The result of this code is the following form −"
},
{
"code": null,
"e": 1496,
"s": 1465,
"text": "Type your text here...\n Submit"
},
{
"code": null,
"e": 1564,
"s": 1496,
"text": "Below is textarea.cgi script to handle input given by web browser −"
},
{
"code": null,
"e": 2065,
"s": 1564,
"text": "#!/usr/bin/python\n# Import modules for CGI handling\nimport cgi, cgitb\n# Create instance of FieldStorage\nform = cgi.FieldStorage()\n# Get data from fields\nif form.getvalue('textcontent'):\n text_content = form.getvalue('textcontent')\nelse:\n text_content = \"Not entered\"\nprint \"Content-type:text/html\\r\\n\\r\\n\"\nprint \"<html>\"\nprint \"<head>\";\nprint \"<title>Text Area - Fifth CGI Program</title>\"\nprint \"</head>\"\nprint \"<body>\"\nprint \"<h2> Entered Text Content is %s</h2>\" % text_content\nprint \"</body>\""
}
]
|
Python Program to Find Element Occurring Odd Number of Times in a List | When it is required to find an element that occurs odd number of times in a list, a method can be defined. This method iterates through the list and checks to see if the elements in the nested loops match. If they do, the counter is incremented. If that count is not divisible by 2, the specific element of the list is returned as the result. Otherwise, -1 is returned as the result.
Below is a demonstration of the same −
Live Demo
def odd_occurence(my_list, list_size):
for i in range(0, list_size):
count = 0
for j in range(0, list_size):
if my_list[i] == my_list[j]:
count+= 1
if (count % 2 != 0):
return my_list[i]
return -1
my_list = [34, 56, 78, 99, 23, 34, 34, 56, 78, 99, 99, 99, 99, 34, 34, 56, 56 ]
print("The list is :")
print(my_list)
n = len(my_list)
print("The length is :")
print(n)
print("The method to find the element that occurs odd number of times is called ")
print("The element that occurs odd number of times is :")
print(odd_occurence(my_list, n))
The list is :
[34, 56, 78, 99, 23, 34, 34, 56, 78, 99, 99, 99, 99, 34, 34, 56, 56]
The length is :
17
The method to find the element that occurs odd number of times is called
The element that occurs odd number of times is :
34
A method named ‘odd_occurence’ is defined, which takes the list and its size as parameters.
A method named ‘odd_occurence’ is defined, which takes the list and its size as parameters.
The listed size is taken as the range and the list is iterated over.
The listed size is taken as the range and the list is iterated over.
Two nested loops are iterated, and if the element in the list matches the first and second loop iterations, the ‘count’ variable is incremented.
Two nested loops are iterated, and if the element in the list matches the first and second loop iterations, the ‘count’ variable is incremented.
If the ‘count’ variable is an odd number, the specific element in the list is returned.
If the ‘count’ variable is an odd number, the specific element in the list is returned.
A list of integers is defined and is displayed on the console.
A list of integers is defined and is displayed on the console.
The length of the list is stored in a variable.
The length of the list is stored in a variable.
The method is called by passing relevant parameters.
The method is called by passing relevant parameters.
The output is displayed on the console.
The output is displayed on the console. | [
{
"code": null,
"e": 1446,
"s": 1062,
"text": "When it is required to find an element that occurs odd number of times in a list, a method can be defined. This method iterates through the list and checks to see if the elements in the nested loops match. If they do, the counter is incremented. If that count is not divisible by 2, the specific element of the list is returned as the result. Otherwise, -1 is returned as the result."
},
{
"code": null,
"e": 1485,
"s": 1446,
"text": "Below is a demonstration of the same −"
},
{
"code": null,
"e": 1496,
"s": 1485,
"text": " Live Demo"
},
{
"code": null,
"e": 2093,
"s": 1496,
"text": "def odd_occurence(my_list, list_size):\n\n for i in range(0, list_size):\n count = 0\n for j in range(0, list_size):\n if my_list[i] == my_list[j]:\n count+= 1\n\n if (count % 2 != 0):\n return my_list[i]\n\n return -1\nmy_list = [34, 56, 78, 99, 23, 34, 34, 56, 78, 99, 99, 99, 99, 34, 34, 56, 56 ]\nprint(\"The list is :\")\nprint(my_list)\nn = len(my_list)\nprint(\"The length is :\")\nprint(n)\nprint(\"The method to find the element that occurs odd number of times is called \")\nprint(\"The element that occurs odd number of times is :\")\nprint(odd_occurence(my_list, n))"
},
{
"code": null,
"e": 2320,
"s": 2093,
"text": "The list is :\n[34, 56, 78, 99, 23, 34, 34, 56, 78, 99, 99, 99, 99, 34, 34, 56, 56]\nThe length is :\n17\nThe method to find the element that occurs odd number of times is called\nThe element that occurs odd number of times is :\n34"
},
{
"code": null,
"e": 2412,
"s": 2320,
"text": "A method named ‘odd_occurence’ is defined, which takes the list and its size as parameters."
},
{
"code": null,
"e": 2504,
"s": 2412,
"text": "A method named ‘odd_occurence’ is defined, which takes the list and its size as parameters."
},
{
"code": null,
"e": 2573,
"s": 2504,
"text": "The listed size is taken as the range and the list is iterated over."
},
{
"code": null,
"e": 2642,
"s": 2573,
"text": "The listed size is taken as the range and the list is iterated over."
},
{
"code": null,
"e": 2787,
"s": 2642,
"text": "Two nested loops are iterated, and if the element in the list matches the first and second loop iterations, the ‘count’ variable is incremented."
},
{
"code": null,
"e": 2932,
"s": 2787,
"text": "Two nested loops are iterated, and if the element in the list matches the first and second loop iterations, the ‘count’ variable is incremented."
},
{
"code": null,
"e": 3020,
"s": 2932,
"text": "If the ‘count’ variable is an odd number, the specific element in the list is returned."
},
{
"code": null,
"e": 3108,
"s": 3020,
"text": "If the ‘count’ variable is an odd number, the specific element in the list is returned."
},
{
"code": null,
"e": 3171,
"s": 3108,
"text": "A list of integers is defined and is displayed on the console."
},
{
"code": null,
"e": 3234,
"s": 3171,
"text": "A list of integers is defined and is displayed on the console."
},
{
"code": null,
"e": 3282,
"s": 3234,
"text": "The length of the list is stored in a variable."
},
{
"code": null,
"e": 3330,
"s": 3282,
"text": "The length of the list is stored in a variable."
},
{
"code": null,
"e": 3383,
"s": 3330,
"text": "The method is called by passing relevant parameters."
},
{
"code": null,
"e": 3436,
"s": 3383,
"text": "The method is called by passing relevant parameters."
},
{
"code": null,
"e": 3476,
"s": 3436,
"text": "The output is displayed on the console."
},
{
"code": null,
"e": 3516,
"s": 3476,
"text": "The output is displayed on the console."
}
]
|
C++ Library - <wostringstream> | It is an output stream class to operate on strings of wide characters.
Below is definition of std::wostringstream.
typedef basic_ostringstream<wchar_t> wostringstream;
charT − Character type.
charT − Character type.
traits − Character traits class that defines essential properties of the characters used by stream objects.
traits − Character traits class that defines essential properties of the characters used by stream objects.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2674,
"s": 2603,
"text": "It is an output stream class to operate on strings of wide characters."
},
{
"code": null,
"e": 2718,
"s": 2674,
"text": "Below is definition of std::wostringstream."
},
{
"code": null,
"e": 2771,
"s": 2718,
"text": "typedef basic_ostringstream<wchar_t> wostringstream;"
},
{
"code": null,
"e": 2795,
"s": 2771,
"text": "charT − Character type."
},
{
"code": null,
"e": 2819,
"s": 2795,
"text": "charT − Character type."
},
{
"code": null,
"e": 2927,
"s": 2819,
"text": "traits − Character traits class that defines essential properties of the characters used by stream objects."
},
{
"code": null,
"e": 3035,
"s": 2927,
"text": "traits − Character traits class that defines essential properties of the characters used by stream objects."
},
{
"code": null,
"e": 3042,
"s": 3035,
"text": " Print"
},
{
"code": null,
"e": 3053,
"s": 3042,
"text": " Add Notes"
}
]
|
House Robber II in C++ | Consider, you are a professional robber. And you are planning to rob houses along a street. Each house has a certain amount of money stored. All houses are arranged in a circle. That means the first house is the neighbor of the last house. We have to keep in mind that the adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night. So if we have a list of integers representing the amount of money of each house, determine the maximum amount of money you can rob in one night without alerting the police. So if the array is [1,2,3,1], then the output will be 4.
To solve this, we will follow these steps −
We are using one module called solve(), that will take the array, start and end, that will act like below −
ans := nums[start]
create one table for dynamic programming, that’s name is dp, and size is same as nums size.
dp[start] := nums[start]
for i := start + 1 to endlast := dp[i – 1]lastToLast := 0 when i – 2, otherwise dp[i – 2]dp[i] := maximum of nums[i] + lastToLast and lastans := max of dp[i] and ans
last := dp[i – 1]
lastToLast := 0 when i – 2, otherwise dp[i – 2]
dp[i] := maximum of nums[i] + lastToLast and last
ans := max of dp[i] and ans
return ans
Robbing is done like below −
n := size of nums
if n is zero, then return 0
if n = 1, then return nums[0]
return maximum of solve(nums, 0, n - 2), solve(nums, 1, n – 1)
Let us see the following implementation to get better understanding −
Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int solve(vector <int>& nums, int start, int end){
int ans = nums[start];
vector <int> dp(nums.size());
dp[start] = nums[start];
for(int i = start + 1; i <= end; i++){
int last = dp[i - 1];
int lastToLast = i - 2 < start? 0 : dp[i - 2];
dp[i] = max(nums[i] + lastToLast, last);
ans = max(dp[i], ans);
}
return ans;
}
int rob(vector<int>& nums) {
int n = nums.size();
if(!n)return 0;
if(n == 1)return nums[0];
return max(solve(nums, 0, n - 2), solve(nums, 1, n - 1));
}
};
main(){
vector<int> v = {1,2,3,5};
Solution ob;
cout << ob.rob(v);
}
[1,2,3,5]
7 | [
{
"code": null,
"e": 1716,
"s": 1062,
"text": "Consider, you are a professional robber. And you are planning to rob houses along a street. Each house has a certain amount of money stored. All houses are arranged in a circle. That means the first house is the neighbor of the last house. We have to keep in mind that the adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night. So if we have a list of integers representing the amount of money of each house, determine the maximum amount of money you can rob in one night without alerting the police. So if the array is [1,2,3,1], then the output will be 4."
},
{
"code": null,
"e": 1760,
"s": 1716,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1868,
"s": 1760,
"text": "We are using one module called solve(), that will take the array, start and end, that will act like below −"
},
{
"code": null,
"e": 1887,
"s": 1868,
"text": "ans := nums[start]"
},
{
"code": null,
"e": 1979,
"s": 1887,
"text": "create one table for dynamic programming, that’s name is dp, and size is same as nums size."
},
{
"code": null,
"e": 2004,
"s": 1979,
"text": "dp[start] := nums[start]"
},
{
"code": null,
"e": 2170,
"s": 2004,
"text": "for i := start + 1 to endlast := dp[i – 1]lastToLast := 0 when i – 2, otherwise dp[i – 2]dp[i] := maximum of nums[i] + lastToLast and lastans := max of dp[i] and ans"
},
{
"code": null,
"e": 2188,
"s": 2170,
"text": "last := dp[i – 1]"
},
{
"code": null,
"e": 2236,
"s": 2188,
"text": "lastToLast := 0 when i – 2, otherwise dp[i – 2]"
},
{
"code": null,
"e": 2286,
"s": 2236,
"text": "dp[i] := maximum of nums[i] + lastToLast and last"
},
{
"code": null,
"e": 2314,
"s": 2286,
"text": "ans := max of dp[i] and ans"
},
{
"code": null,
"e": 2325,
"s": 2314,
"text": "return ans"
},
{
"code": null,
"e": 2354,
"s": 2325,
"text": "Robbing is done like below −"
},
{
"code": null,
"e": 2372,
"s": 2354,
"text": "n := size of nums"
},
{
"code": null,
"e": 2400,
"s": 2372,
"text": "if n is zero, then return 0"
},
{
"code": null,
"e": 2430,
"s": 2400,
"text": "if n = 1, then return nums[0]"
},
{
"code": null,
"e": 2493,
"s": 2430,
"text": "return maximum of solve(nums, 0, n - 2), solve(nums, 1, n – 1)"
},
{
"code": null,
"e": 2563,
"s": 2493,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 2574,
"s": 2563,
"text": " Live Demo"
},
{
"code": null,
"e": 3306,
"s": 2574,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\n public:\n int solve(vector <int>& nums, int start, int end){\n int ans = nums[start];\n vector <int> dp(nums.size());\n dp[start] = nums[start];\n for(int i = start + 1; i <= end; i++){\n int last = dp[i - 1];\n int lastToLast = i - 2 < start? 0 : dp[i - 2];\n dp[i] = max(nums[i] + lastToLast, last);\n ans = max(dp[i], ans);\n }\n return ans;\n }\n int rob(vector<int>& nums) {\n int n = nums.size();\n if(!n)return 0;\n if(n == 1)return nums[0];\n return max(solve(nums, 0, n - 2), solve(nums, 1, n - 1));\n }\n};\nmain(){\n vector<int> v = {1,2,3,5};\n Solution ob;\n cout << ob.rob(v);\n}"
},
{
"code": null,
"e": 3316,
"s": 3306,
"text": "[1,2,3,5]"
},
{
"code": null,
"e": 3318,
"s": 3316,
"text": "7"
}
]
|
How to add a Submit button after the end of the tableview using Swift? | To add a submit button at the end of a table view, we can make use of table view footers. Let’s see this with help of an example where we’ll add a footer view to our table, and inside the table, we will add code for adding button at the bottom of the table view.
Create a new project first, then inside the view controller add the following code which will initialize the table, add a section and a few rows to the table.
func initTableView() {
let tableView = UITableView()
tableView.frame = self.view.frame
tableView.dataSource = self
tableView.delegate = self
tableView.backgroundColor = colorLiteral(red: 0.6000000238, green: 0.6000000238, blue: 0.6000000238, alpha: 1)
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
self.view.addSubview(tableView)
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
cell?.layer.backgroundColor = colorLiteral(red: 0.2392156869, green:
0.6745098233, blue: 0.9686274529, alpha: 1)
cell?.textLabel?.text = "cell at \(indexPath.row)"
return cell!
}
Now, call the first function, initTableView() inside the view did a load or viewDidAppear method of your view controller.
Now add the following code which will tell the table to give some height to its rows and footer.
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 60
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 100
}
Make sure you have confirmed your class to UITableViewDataSource and UITableViewDelegate, otherwise these methods above will appear as an error.
Now, let’s add a footer view and a button to the footer view.
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let footerView = UIView()
footerView.backgroundColor = colorLiteral(red: 0.9686274529, green:
0.78039217, blue: 0.3450980484, alpha: 1)
footerView.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height:
100)
let button = UIButton()
button.frame = CGRect(x: 20, y: 10, width: 300, height: 50)
button.setTitle("CustomButton", for: .normal)
button.setTitleColor( colorLiteral(red: 0, green: 0, blue: 0, alpha: 1), for: .normal)
button.backgroundColor = colorLiteral(red: 0.721568644, green:
0.8862745166, blue: 0.5921568871, alpha: 1)
footerView.addSubview(button)
return footerView
}
When we run the above code on our device, below is the result that’s produced. You can add a custom action to the button and customize it according to requirement. | [
{
"code": null,
"e": 1325,
"s": 1062,
"text": "To add a submit button at the end of a table view, we can make use of table view footers. Let’s see this with help of an example where we’ll add a footer view to our table, and inside the table, we will add code for adding button at the bottom of the table view."
},
{
"code": null,
"e": 1484,
"s": 1325,
"text": "Create a new project first, then inside the view controller add the following code which will initialize the table, add a section and a few rows to the table."
},
{
"code": null,
"e": 2392,
"s": 1484,
"text": "func initTableView() {\n let tableView = UITableView()\n tableView.frame = self.view.frame\n tableView.dataSource = self\n tableView.delegate = self\n tableView.backgroundColor = colorLiteral(red: 0.6000000238, green: 0.6000000238, blue: 0.6000000238, alpha: 1)\n tableView.register(UITableViewCell.self, forCellReuseIdentifier: \"cell\")\n self.view.addSubview(tableView)\n}\nfunc numberOfSections(in tableView: UITableView) -> Int {\n return 1\n}\nfunc tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {\n return 2\n}\nfunc tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {\n let cell = tableView.dequeueReusableCell(withIdentifier: \"cell\")\n cell?.layer.backgroundColor = colorLiteral(red: 0.2392156869, green:\n 0.6745098233, blue: 0.9686274529, alpha: 1)\n cell?.textLabel?.text = \"cell at \\(indexPath.row)\"\n return cell!\n}"
},
{
"code": null,
"e": 2514,
"s": 2392,
"text": "Now, call the first function, initTableView() inside the view did a load or viewDidAppear method of your view controller."
},
{
"code": null,
"e": 2611,
"s": 2514,
"text": "Now add the following code which will tell the table to give some height to its rows and footer."
},
{
"code": null,
"e": 2826,
"s": 2611,
"text": "func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {\n return 60\n}\nfunc tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {\n return 100\n}"
},
{
"code": null,
"e": 2971,
"s": 2826,
"text": "Make sure you have confirmed your class to UITableViewDataSource and UITableViewDelegate, otherwise these methods above will appear as an error."
},
{
"code": null,
"e": 3033,
"s": 2971,
"text": "Now, let’s add a footer view and a button to the footer view."
},
{
"code": null,
"e": 3754,
"s": 3033,
"text": "func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {\n let footerView = UIView()\n footerView.backgroundColor = colorLiteral(red: 0.9686274529, green:\n 0.78039217, blue: 0.3450980484, alpha: 1)\n footerView.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height:\n 100)\n let button = UIButton()\n button.frame = CGRect(x: 20, y: 10, width: 300, height: 50)\n button.setTitle(\"CustomButton\", for: .normal)\n button.setTitleColor( colorLiteral(red: 0, green: 0, blue: 0, alpha: 1), for: .normal)\n button.backgroundColor = colorLiteral(red: 0.721568644, green:\n 0.8862745166, blue: 0.5921568871, alpha: 1)\n footerView.addSubview(button)\n return footerView\n}"
},
{
"code": null,
"e": 3918,
"s": 3754,
"text": "When we run the above code on our device, below is the result that’s produced. You can add a custom action to the button and customize it according to requirement."
}
]
|
WebSockets - JavaScript Application | The following program code describes the working of a chat application using JavaScript and Web Socket protocol.
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = utf-8>
<title>HTML5 Chat</title>
<body>
<section id = "wrapper">
<header>
<h1>HTML5 Chat</h1>
</header>
<style>
#chat { width: 97%; }
.message { font-weight: bold; }
.message:before { content: ' '; color: #bbb; font-size: 14px; }
#log {
overflow: auto;
max-height: 300px;
list-style: none;
padding: 0;
}
#log li {
border-top: 1px solid #ccc;
margin: 0;
padding: 10px 0;
}
body {
font: normal 16px/20px "Helvetica Neue", Helvetica, sans-serif;
background: rgb(237, 237, 236);
margin: 0;
margin-top: 40px;
padding: 0;
}
section, header {
display: block;
}
#wrapper {
width: 600px;
margin: 0 auto;
background: #fff;
border-radius: 10px;
border-top: 1px solid #fff;
padding-bottom: 16px;
}
h1 {
padding-top: 10px;
}
h2 {
font-size: 100%;
font-style: italic;
}
header, article > * {
margin: 20px;
}
#status {
padding: 5px;
color: #fff;
background: #ccc;
}
#status.fail {
background: #c00;
}
#status.success {
background: #0c0;
}
#status.offline {
background: #c00;
}
#status.online {
background: #0c0;
}
#html5badge {
margin-left: -30px;
border: 0;
}
#html5badge img {
border: 0;
}
</style>
<article>
<form onsubmit = "addMessage(); return false;">
<input type = "text" id = "chat" placeholder = "type and press
enter to chat" />
</form>
<p id = "status">Not connected</p>
<p>Users connected: <span id = "connected">0
</span></p>
<ul id = "log"></ul>
</article>
<script>
connected = document.getElementById("connected");
log = document.getElementById("log");
chat = document.getElementById("chat");
form = chat.form;
state = document.getElementById("status");
if (window.WebSocket === undefined) {
state.innerHTML = "sockets not supported";
state.className = "fail";
}else {
if (typeof String.prototype.startsWith != "function") {
String.prototype.startsWith = function (str) {
return this.indexOf(str) == 0;
};
}
window.addEventListener("load", onLoad, false);
}
function onLoad() {
var wsUri = "ws://127.0.0.1:7777";
websocket = new WebSocket(wsUri);
websocket.onopen = function(evt) { onOpen(evt) };
websocket.onclose = function(evt) { onClose(evt) };
websocket.onmessage = function(evt) { onMessage(evt) };
websocket.onerror = function(evt) { onError(evt) };
}
function onOpen(evt) {
state.className = "success";
state.innerHTML = "Connected to server";
}
function onClose(evt) {
state.className = "fail";
state.innerHTML = "Not connected";
connected.innerHTML = "0";
}
function onMessage(evt) {
// There are two types of messages:
// 1. a chat participant message itself
// 2. a message with a number of connected chat participants
var message = evt.data;
if (message.startsWith("log:")) {
message = message.slice("log:".length);
log.innerHTML = '<li class = "message">' +
message + "</li>" + log.innerHTML;
}else if (message.startsWith("connected:")) {
message = message.slice("connected:".length);
connected.innerHTML = message;
}
}
function onError(evt) {
state.className = "fail";
state.innerHTML = "Communication error";
}
function addMessage() {
var message = chat.value;
chat.value = "";
websocket.send(message);
}
</script>
</section>
</body>
</head>
</html>
The key features and the output of the chat application are discussed below −
To test, open the two windows with Web Socket support, type a message above and press return. This would enable the feature of chat application.
If the connection is not established, the output is available as shown below.
The output of a successful chat communication is shown below.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2232,
"s": 2119,
"text": "The following program code describes the working of a chat application using JavaScript and Web Socket protocol."
},
{
"code": null,
"e": 7924,
"s": 2232,
"text": "<!DOCTYPE html>\n<html lang = \"en\">\n\n <head>\n <meta charset = utf-8>\n <title>HTML5 Chat</title>\n\t\t\n <body>\n\t\t\n <section id = \"wrapper\">\n\t\t\t\n <header>\n <h1>HTML5 Chat</h1>\n </header>\n\t\t\t\t\n <style>\n #chat { width: 97%; }\n .message { font-weight: bold; }\n .message:before { content: ' '; color: #bbb; font-size: 14px; }\n\t\t\t\t\t\n #log {\n overflow: auto;\n max-height: 300px;\n list-style: none;\n padding: 0;\n }\n\t\t\t\t\t\n #log li {\n border-top: 1px solid #ccc;\n margin: 0;\n padding: 10px 0;\n }\n\t\t\t\t\t\n body {\n font: normal 16px/20px \"Helvetica Neue\", Helvetica, sans-serif;\n background: rgb(237, 237, 236);\n margin: 0;\n margin-top: 40px;\n padding: 0;\n }\n\t\t\t\t\t\n section, header {\n display: block;\n }\n\t\t\t\t\t\n #wrapper {\n width: 600px;\n margin: 0 auto;\n background: #fff;\n border-radius: 10px;\n border-top: 1px solid #fff;\n padding-bottom: 16px;\n }\n\t\t\t\t\t\n h1 {\n padding-top: 10px;\n }\n\t\t\t\t\t\n h2 {\n font-size: 100%;\n font-style: italic;\n }\n\t\t\t\t\t\n header, article > * {\n margin: 20px;\n }\n\t\t\t\t\t\n #status {\n padding: 5px;\n color: #fff;\n background: #ccc;\n }\n\t\t\t\t\t\n #status.fail {\n background: #c00;\n }\n\t\t\t\t\t\n #status.success {\n background: #0c0;\n }\n\t\t\t\t\t\n #status.offline {\n background: #c00;\n }\n\t\t\t\t\t\n #status.online {\n background: #0c0;\n }\n\t\t\t\t\t\n #html5badge {\n margin-left: -30px;\n border: 0;\n }\n\t\t\t\t\t\n #html5badge img {\n border: 0;\n }\n </style>\n\t\t\t\t\n <article>\n\t\t\t\t\n <form onsubmit = \"addMessage(); return false;\">\n <input type = \"text\" id = \"chat\" placeholder = \"type and press \n enter to chat\" />\n </form>\n\t\t\t\t\t\n <p id = \"status\">Not connected</p>\n <p>Users connected: <span id = \"connected\">0\n </span></p>\n <ul id = \"log\"></ul>\n\t\t\t\t\t\n </article>\n\t\t\t\t\n <script>\n connected = document.getElementById(\"connected\");\n log = document.getElementById(\"log\");\n chat = document.getElementById(\"chat\");\n form = chat.form;\n state = document.getElementById(\"status\");\n\t\t\t\t\t\n if (window.WebSocket === undefined) {\n state.innerHTML = \"sockets not supported\";\n state.className = \"fail\";\n }else {\n if (typeof String.prototype.startsWith != \"function\") {\n String.prototype.startsWith = function (str) {\n return this.indexOf(str) == 0;\n };\n }\n\t\t\t\t\t\t\n window.addEventListener(\"load\", onLoad, false);\n }\n\t\t\t\t\t\n function onLoad() {\n var wsUri = \"ws://127.0.0.1:7777\";\n websocket = new WebSocket(wsUri);\n websocket.onopen = function(evt) { onOpen(evt) };\n websocket.onclose = function(evt) { onClose(evt) };\n websocket.onmessage = function(evt) { onMessage(evt) };\n websocket.onerror = function(evt) { onError(evt) };\n }\n\t\t\t\t\t\n function onOpen(evt) {\n state.className = \"success\";\n state.innerHTML = \"Connected to server\";\n }\n\t\t\t\t\t\n function onClose(evt) {\n state.className = \"fail\";\n state.innerHTML = \"Not connected\";\n connected.innerHTML = \"0\";\n }\n\t\t\t\t\t\n function onMessage(evt) {\n // There are two types of messages:\n // 1. a chat participant message itself\n // 2. a message with a number of connected chat participants\n var message = evt.data;\n\t\t\t\t\t\t\n if (message.startsWith(\"log:\")) {\n message = message.slice(\"log:\".length);\n log.innerHTML = '<li class = \"message\">' + \n message + \"</li>\" + log.innerHTML;\n }else if (message.startsWith(\"connected:\")) {\n message = message.slice(\"connected:\".length);\n connected.innerHTML = message;\n }\n }\n\t\t\t\t\t\n function onError(evt) {\n state.className = \"fail\";\n state.innerHTML = \"Communication error\";\n }\n\t\t\t\t\t\n function addMessage() {\n var message = chat.value;\n chat.value = \"\";\n websocket.send(message);\n }\n\t\t\t\t\t\n </script>\n\t\t\t\t\n </section>\n\t\t\t\n </body>\n\t\t\n </head>\t\n\t\n</html>"
},
{
"code": null,
"e": 8002,
"s": 7924,
"text": "The key features and the output of the chat application are discussed below −"
},
{
"code": null,
"e": 8147,
"s": 8002,
"text": "To test, open the two windows with Web Socket support, type a message above and press return. This would enable the feature of chat application."
},
{
"code": null,
"e": 8225,
"s": 8147,
"text": "If the connection is not established, the output is available as shown below."
},
{
"code": null,
"e": 8287,
"s": 8225,
"text": "The output of a successful chat communication is shown below."
},
{
"code": null,
"e": 8294,
"s": 8287,
"text": " Print"
},
{
"code": null,
"e": 8305,
"s": 8294,
"text": " Add Notes"
}
]
|
Java Program for Longest Common Subsequence | Following is the Java program for Longest Common Subsequence −
Live Demo
public class Demo{
int subseq(char[] a, char[] b, int a_len, int b_len){
int my_arr[][] = new int[a_len + 1][b_len + 1];
for (int i = 0; i <= a_len; i++){
for (int j = 0; j <= b_len; j++){
if (i == 0 || j == 0)
my_arr[i][j] = 0;
else if (a[i - 1] == b[j - 1])
my_arr[i][j] = my_arr[i - 1][j - 1] + 1;
else
my_arr[i][j] = max_val(my_arr[i - 1][j], my_arr[i][j - 1]);
}
}
return my_arr[a_len][b_len];
}
int max_val(int val_1, int val_2){
return (val_1 > val_2) ? val_1 : val_2;
}
public static void main(String[] args){
Demo my_inst = new Demo();
String my_str_1 = "MNSQR";
String my_str_2 = "PSQR";
char[] a = my_str_1.toCharArray();
char[] b = my_str_2.toCharArray();
int a_len = a.length;
int b_len = b.length;
System.out.println("The length of the longest common subsequence is"+ " " + my_inst.subseq(a, b, a_len, b_len));
}
}
The length of the longest common subsequence is 3
A class named Demo contains a function called "subseq" which returns the longest common subsequence for the given strings i.e str_1[0 to len(str_1-1) , str_2(0 to len(str_2-1) //2 'for' loops are iterated over the length of both the strings and if both 'i' and 'j' are 0, then, the array's specific indices are assigned to 0. Otherwise, my_arr[length of first string +1][length of second string +1] is built.
The main function defines a new instance of the Demo class and defines two strings my_str_1 and my_str_2. Both the strings are converted to arrays and their lengths are stored in separate variables. The function is called on these values.
This is dynamic programming technique wherein one value is computed and stored in an array, removing the need to compute it again and again as in recursion. Whenever a previously computed element is required, it is fetched from the array. | [
{
"code": null,
"e": 1125,
"s": 1062,
"text": "Following is the Java program for Longest Common Subsequence −"
},
{
"code": null,
"e": 1136,
"s": 1125,
"text": " Live Demo"
},
{
"code": null,
"e": 2157,
"s": 1136,
"text": "public class Demo{\n int subseq(char[] a, char[] b, int a_len, int b_len){\n int my_arr[][] = new int[a_len + 1][b_len + 1];\n for (int i = 0; i <= a_len; i++){\n for (int j = 0; j <= b_len; j++){\n if (i == 0 || j == 0)\n my_arr[i][j] = 0;\n else if (a[i - 1] == b[j - 1])\n my_arr[i][j] = my_arr[i - 1][j - 1] + 1;\n else\n my_arr[i][j] = max_val(my_arr[i - 1][j], my_arr[i][j - 1]);\n }\n }\n return my_arr[a_len][b_len];\n }\n int max_val(int val_1, int val_2){\n return (val_1 > val_2) ? val_1 : val_2;\n }\n public static void main(String[] args){\n Demo my_inst = new Demo();\n String my_str_1 = \"MNSQR\";\n String my_str_2 = \"PSQR\";\n char[] a = my_str_1.toCharArray();\n char[] b = my_str_2.toCharArray();\n int a_len = a.length;\n int b_len = b.length;\n System.out.println(\"The length of the longest common subsequence is\"+ \" \" + my_inst.subseq(a, b, a_len, b_len));\n }\n}"
},
{
"code": null,
"e": 2207,
"s": 2157,
"text": "The length of the longest common subsequence is 3"
},
{
"code": null,
"e": 2616,
"s": 2207,
"text": "A class named Demo contains a function called \"subseq\" which returns the longest common subsequence for the given strings i.e str_1[0 to len(str_1-1) , str_2(0 to len(str_2-1) //2 'for' loops are iterated over the length of both the strings and if both 'i' and 'j' are 0, then, the array's specific indices are assigned to 0. Otherwise, my_arr[length of first string +1][length of second string +1] is built."
},
{
"code": null,
"e": 2855,
"s": 2616,
"text": "The main function defines a new instance of the Demo class and defines two strings my_str_1 and my_str_2. Both the strings are converted to arrays and their lengths are stored in separate variables. The function is called on these values."
},
{
"code": null,
"e": 3094,
"s": 2855,
"text": "This is dynamic programming technique wherein one value is computed and stored in an array, removing the need to compute it again and again as in recursion. Whenever a previously computed element is required, it is fetched from the array."
}
]
|
Python dictionary copy() Method | Python dictionary method copy() returns a shallow copy of the dictionary.
Following is the syntax for copy() method −
dict.copy()
NA
NA
This method returns a shallow copy of the dictionary.
The following example shows the usage of copy() method.
#!/usr/bin/python
dict1 = {'Name': 'Zara', 'Age': 7};
dict2 = dict1.copy()
print "New Dictionary : %s" % str(dict2)
When we run above program, it produces following result −
New Dictionary : {'Age': 7, 'Name': 'Zara'}
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2319,
"s": 2244,
"text": "Python dictionary method copy() returns a shallow copy of the dictionary."
},
{
"code": null,
"e": 2363,
"s": 2319,
"text": "Following is the syntax for copy() method −"
},
{
"code": null,
"e": 2376,
"s": 2363,
"text": "dict.copy()\n"
},
{
"code": null,
"e": 2379,
"s": 2376,
"text": "NA"
},
{
"code": null,
"e": 2382,
"s": 2379,
"text": "NA"
},
{
"code": null,
"e": 2436,
"s": 2382,
"text": "This method returns a shallow copy of the dictionary."
},
{
"code": null,
"e": 2492,
"s": 2436,
"text": "The following example shows the usage of copy() method."
},
{
"code": null,
"e": 2610,
"s": 2492,
"text": "#!/usr/bin/python\n\ndict1 = {'Name': 'Zara', 'Age': 7};\ndict2 = dict1.copy()\nprint \"New Dictionary : %s\" % str(dict2)"
},
{
"code": null,
"e": 2668,
"s": 2610,
"text": "When we run above program, it produces following result −"
},
{
"code": null,
"e": 2713,
"s": 2668,
"text": "New Dictionary : {'Age': 7, 'Name': 'Zara'}\n"
},
{
"code": null,
"e": 2750,
"s": 2713,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 2766,
"s": 2750,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 2799,
"s": 2766,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 2818,
"s": 2799,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 2853,
"s": 2818,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 2875,
"s": 2853,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 2909,
"s": 2875,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 2937,
"s": 2909,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 2972,
"s": 2937,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 2986,
"s": 2972,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3019,
"s": 2986,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3036,
"s": 3019,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3043,
"s": 3036,
"text": " Print"
},
{
"code": null,
"e": 3054,
"s": 3043,
"text": " Add Notes"
}
]
|
OBIEE - Quick Guide | In today’s competitive market, most successful companies respond quickly to market changes and opportunities. The requirement to respond quickly is by effective and efficient use of data and information. “Data Warehouse” is a central repository of data that is organized by category to support the organization’s decision makers. Once data is stored in a data warehouse, it can be accessed for analysis.
The term "Data Warehouse" was first invented by Bill Inmon in 1990. According to him, “Data warehouse is a subject-oriented, integrated, time-variant and non-volatile collection of data in support of management's decision making process.”
Ralph Kimball provided a definition of data warehouse based on its functionality. He said, “Data warehouse is a copy of transaction data specifically structured for query and analysis.”
Data Warehouse (DW or DWH) is a system used for analysis of data and reporting purposes. They are repositories that saves data from one or more heterogeneous data sources. They store both current and historical data and are used for creating analytical reports. DW can be used to create interactive dashboards for the senior management.
For example, analytic reports can contain data for quarterly comparisons or for annual comparison of sales report for a company.
Data in DW comes from multiple operational systems like sales, human resource, marketing, warehouse management, etc. It contains historical data from different transaction systems but it can also include data from other sources. DW is used to separate data processing and analysis workload from transaction workload and enables to consolidate the data from several data sources.
For example − You have a home loan agency, where data comes from multiple SAP/non-SAP applications such as marketing, sales, ERP, HRM, etc. This data is extracted, transformed and loaded into DW. If you have to do quarterly/annual sales comparison of a product, you cannot use an operational database as this will hang the transaction system. This is where the need for using DW arises.
Some of the key characteristics of DW are −
It is used for reporting and data analysis.
It provides a central repository with data integrated from one or more sources.
It stores current and historical data.
Following are few differences between Data Warehouse and Operational Database (Transaction System) −
Transactional system is designed for known workloads and transactions like updating a user record, searching a record, etc. However, DW transactions are more complex and present a general form of data.
Transactional system is designed for known workloads and transactions like updating a user record, searching a record, etc. However, DW transactions are more complex and present a general form of data.
Transactional system contains the current data of an organization whereas DW normally contains historical data.
Transactional system contains the current data of an organization whereas DW normally contains historical data.
Transactional system supports parallel processing of multiple transactions. Concurrency control and recovery mechanisms are required to maintain consistency of the database.
Transactional system supports parallel processing of multiple transactions. Concurrency control and recovery mechanisms are required to maintain consistency of the database.
Operational database query allows to read and modify operations (delete and update), while an OLAP query needs only read-only access of stored data (select statement).
Operational database query allows to read and modify operations (delete and update), while an OLAP query needs only read-only access of stored data (select statement).
DW involves data cleaning, data integration, and data consolidations.
DW involves data cleaning, data integration, and data consolidations.
DW has a three-layer architecture − Data Source Layer, Integration Layer, and Presentation Layer. The following diagram shows the common architecture of a Data Warehouse system.
Following are the types of DW system −
Data Mart
Online Analytical Processing (OLAP)
Online Transaction Processing (OLTP)
Predictive Analysis
Data Mart is the simplest form of DW and it normally focuses on a single functional area, such as sales, finance or marketing. Hence, data mart usually gets data only from few data sources.
Sources could be an internal transaction system, a central data warehouse, or an external data source application. De-normalization is the norm for data modeling techniques in this system.
An OLAP system contains less number of transactions but involves complex calculations like use of Aggregations − Sum, Count, Average, etc.
We save tables with aggregated data like yearly (1 row), quarterly (4 rows), monthly (12 rows) and now we want to compare data, like Yearly only 1 row will be processed. However, in an un-aggregated data, all the rows will be processed.
OLAP system normally stores data in multidimensional schemas like Star Schema, Galaxy schemas (with Fact and Dimensional tables are joined in logical manner).
In an OLAP system, response time to execute a query is an effectiveness measure. OLAP applications are widely used by Data Mining techniques to get data from OLAP systems. OLAP databases store aggregated historical data in multi-dimensional schemas. OLAP systems have data latency of a few hours as compared to Data Marts where latency is normally closer to few days.
An OLTP system is known for large number of short online transactions like insert, update, delete, etc. OLTP systems provide fast query processing and also responsible to provide data integrity in multi-access environment.
For an OLTP systems, effectiveness is measured by the number of transactions processed per second. OLTP systems normally contain only current data. The schema used to store transactional databases is the entity model. Normalization is used for data modeling techniques in OLTP system.
The following illustration shows the key differences between an OLTP and OLAP system.
Indexes − In an OLTP system, there are only few indexes while in an OLAP system there are many indexes for performance optimization.
Joins − In an OLTP system, large number of joins and data is normalized; however, in an OLAP system there are less joins and de-normalized.
Aggregation − In an OLTP system, data is not aggregated while in an OLAP database more aggregations are used.
Dimensional modeling provides set of methods and concepts that are used in DW design. According to DW consultant, Ralph Kimball, dimensional modeling is a design technique for databases intended to support end-user queries in a data warehouse. It is oriented around understandability and performance. According to him, although transaction-oriented ER is very useful for the transaction capture, it should be avoided for end-user delivery.
Dimensional modeling always uses facts and dimension tables. Facts are numerical values which can be aggregated and analyzed on the fact values. Dimensions define hierarchies and description on fact values.
Dimension table stores the attributes that describe objects in a Fact table. A Dimension table has a primary key that uniquely identifies each dimension row. This key is used to associate the Dimension table to a Fact table.
Dimension tables are normally de-normalized as they are not created to execute transactions and only used to analyze data in detail.
In the following dimension table, the customer dimension normally includes the name of customers, address, customer id, gender, income group, education levels, etc.
Fact table contains numeric values that are known as measurements. A Fact table has two types of columns − facts and foreign key to dimension tables.
Measures in Fact table are of three types −
Additive − Measures that can be added across any dimension.
Additive − Measures that can be added across any dimension.
Non-Additive − Measures that cannot be added across any dimension.
Non-Additive − Measures that cannot be added across any dimension.
Semi-Additive − Measures that can be added across some dimensions.
Semi-Additive − Measures that can be added across some dimensions.
This fact tables contains foreign keys for time dimension, product dimension, customer dimension and measurement value unit sold.
Suppose a company sells products to customers. Every sale is a fact that happens within the company, and the fact table is used to record these facts.
Common facts are − number of unit sold, margin, sales revenue, etc. The dimension table list factors like customer, time, product, etc. by which we want to analyze the data.
Now if we consider the above Fact table and Customer dimension then there will also be a Product and time dimension. Given this fact table and these three dimension tables, we can ask questions like: How many watches were sold to male customers in 2010?
The functional difference between dimension tables and fact tables is that fact tables hold the data we want to analyze and dimension tables hold the information required to allow us to query it.
Aggregate table contains aggregated data which can be calculated by using different aggregate functions.
An aggregate function is a function where the values of multiple rows are grouped together as input on certain criteria to form a single value of more significant meaning or measurement.
Common aggregate functions include −
Average()
Count()
Maximum()
Median()
Minimum()
Mode()
Sum()
These aggregate tables are used for performance optimization to run complex queries in a data warehouse.
You save tables with aggregated data like yearly (1 row), quarterly (4 rows), monthly (12 rows) and now you have to do comparison of data, like Yearly only 1 row will be processed. However in an un-aggregated table, all the rows will be processed.
Select Avg (salary) from employee where title = ‘developer’. This statement will return the average salary for all employees whose title is equal to 'Developer'.
Aggregations can be applied at database level. You can create aggregates and save them in aggregate tables in the database or you can apply aggregate on the fly at the report level.
Note − If you save aggregates at the database level it saves time and provides performance optimization.
Schema is a logical description of the entire database. It includes the name and description of records of all types including all associated data-items and aggregates. Much like a database, DW also requires to maintain a schema. Database uses relational model, while DW uses Star, Snowflake, and Fact Constellation schema (Galaxy schema).
In a Star Schema, there are multiple dimension tables in de-normalized form that are joined to only one fact table. These tables are joined in a logical manner to meet some business requirement for analysis purpose. These schemas are multidimensional structures which are used to create reports using BI reporting tools.
Dimensions in Star schemas contain a set of attributes and Fact tables contain foreign keys for all dimensions and measurement values.
In the above Star Schema, there is a fact table “Sales Fact” at the center and is joined to 4 dimension tables using primary keys. Dimension tables are not further normalized and this joining of tables is known as Star Schema in DW.
Fact table also contains measure values − dollar_sold and units_sold.
In a Snowflakes Schema, there are multiple dimension tables in normalized form that are joined to only one fact table. These tables are joined in a logical manner to meet some business requirement for analysis purpose.
Only difference between a Star and Snowflakes schema is that dimension tables are further normalized. The normalization splits up the data into additional tables. Due to normalization in the Snowflake schema, the data redundancy is reduced without losing any information and therefore it becomes easy to maintain and saves storage space.
In above Snowflakes Schema example, Product and Customer table are further normalized to save storage space. Sometimes, it also provides performance optimization when you execute a query that requires processing of rows directly in normalized table so it doesn’t process rows in primary Dimension table and comes directly to Normalized table in Schema.
Granularity in a table represents the level of information stored in the table. High granularity of data means that data is at or near the transaction level, which has more detail. Low granularity means that data has low level of information.
A fact table is usually designed at a low level of granularity. This means that we need to find the lowest level of information that can be stored in a fact table. In date dimension, the granularity level could be year, month, quarter, period, week, and day.
The process of defining granularity consists of two steps −
Determining the dimensions that are to be included.
Determining the location to place the hierarchy of each dimension of information.
Slowly changing dimensions refer to changing value of an attribute over time. It is one of the common concepts in DW.
Andy is an employee of XYZ Inc. He was first located in New York City in July 2015. Original entry in the employee lookup table has the following record −
At a later date, he has relocated to LA, California. How should XYZ Inc. now modify its employee table to reflect this change?
This is known as "Slowly Changing Dimension" concept.
There are three ways to solve this type of problem −
The new record replaces the original record. No trace of the old record exists.
Slowly Changing Dimension, the new information simply overwrites the original information. In other words, no history is kept.
Benefit − This is the easiest way to handle the Slowly Changing Dimension problem as there is no need to keep track of the old information.
Benefit − This is the easiest way to handle the Slowly Changing Dimension problem as there is no need to keep track of the old information.
Disadvantage − All historical information is lost.
Disadvantage − All historical information is lost.
Use − Solution 1 should be used when it is not required for DW to keep track of historical information.
Use − Solution 1 should be used when it is not required for DW to keep track of historical information.
A new record is entered into the Employee dimension table. So the employee, Andy, is treated as two people.
A new record is added to the table to represent the new information and both the original and new record will be present. The new record gets its own primary key as follows −
Benefit − This method allows us to store all the historical information.
Benefit − This method allows us to store all the historical information.
Disadvantage − Size of the table grows faster. When the number of rows for the table is very high, space and performance of table can be a concern.
Disadvantage − Size of the table grows faster. When the number of rows for the table is very high, space and performance of table can be a concern.
Use − Solution 2 should be used when it is necessary for DW to keep historical data.
Use − Solution 2 should be used when it is necessary for DW to keep historical data.
The original record in Employee dimension is modified to reflect the change.
There will be two columns to indicate the particular attribute, one indicates original value and other indicates the new value. There will also be a column that indicates when the current value becomes active.
Benefits − This does not increase the size of the table, since new information is updated. This allows us to keep historical information.
Benefits − This does not increase the size of the table, since new information is updated. This allows us to keep historical information.
Disadvantage − This method doesn’t keep all history when an attribute value is changed more than once.
Disadvantage − This method doesn’t keep all history when an attribute value is changed more than once.
Use − Solution 3 should only be used when it is required for DW to keep information of historical changes.
Use − Solution 3 should only be used when it is required for DW to keep information of historical changes.
Normalization is the process of decomposing a table into less redundant smaller tables without losing any information. So Database normalization is the process of organizing the attributes and tables of a database to minimize data redundancy (duplicate data).
It is used to eliminate certain types of data (redundancy/ replication) to improve consistency.
It is used to eliminate certain types of data (redundancy/ replication) to improve consistency.
It provides maximum flexibility to meet future information needs by keeping tables corresponding to object types in their simplified forms.
It provides maximum flexibility to meet future information needs by keeping tables corresponding to object types in their simplified forms.
It produces a clearer and readable data model.
It produces a clearer and readable data model.
Data integrity.
Enhances data consistency.
Reduces data redundancy and space required.
Reduces update cost.
Maximum flexibility in responding to ad-hoc queries.
Reduces the total number of rows per block.
Slow performance of queries in database because joins have to be performed to retrieve relevant data from several normalized tables.
You have to understand the data model in order to perform proper joins among several tables.
In the above example, the table inside the green block represents a normalized table of the one inside the red block. The table in green block is less redundant and also with less number of rows without losing any information.
OBIEE stands for Oracle Business Intelligence Enterprise Edition, a set of Business Intelligence tools and is provided by Oracle Corporation. It enables the user to deliver robust set of reporting, ad-hoc query and analysis, OLAP, dashboard, and scorecard functionality with a rich end-user experience that includes visualization, collaboration, alerts and many more options.
OBIEE provides robust reporting which makes data easier for business users to access.
OBIEE provides robust reporting which makes data easier for business users to access.
OBIEE provides a common infrastructure for producing and delivering enterprise reports, scorecards, dashboards, ad-hoc analysis, and OLAP analysis.
OBIEE provides a common infrastructure for producing and delivering enterprise reports, scorecards, dashboards, ad-hoc analysis, and OLAP analysis.
OBIEE reduces cost with a proven web-based service-oriented architecture that integrates with existing IT infrastructure.
OBIEE reduces cost with a proven web-based service-oriented architecture that integrates with existing IT infrastructure.
OBIEE enables the user to include rich visualization, interactive dashboards, a vast range of animated charting options, OLAP-style interactions, innovative search, and actionable collaboration capabilities to increase the user adoption. These capabilities enable your organization to make better decisions, take informed actions, and implement more-efficient business processes.
OBIEE enables the user to include rich visualization, interactive dashboards, a vast range of animated charting options, OLAP-style interactions, innovative search, and actionable collaboration capabilities to increase the user adoption. These capabilities enable your organization to make better decisions, take informed actions, and implement more-efficient business processes.
The main competitors of OBIEE are Microsoft BI tools, SAP AG Business Objects, IBM Cognos and SAS Institute Inc.
As OBIEE enables the user to create interactive dashboards, robust reports, animated charts and also because of its cost-effectiveness, it is widely used by many companies as one of main tool for Business Intelligence solution.
OBIEE provides various types of visualizations to insert in dashboards to make it more interactive. It allows you to create flash reports, report templates, and ad-hoc reporting for end users. It provides close integration with major data sources and can also be integrated with third party vendors like Microsoft to embed data in PowerPoint presentations and word documents.
Following are the key features and benefits of OBIEE tool −
To sign into OBIEE, you can use web URL, user name and password.
To sign into Oracle BI Enterprise Edition −
Step 1 − In the Web browser address bar, enter URL to access OBIEE.
The "Sign In page" is displayed.
Step 2 − Enter your user name and password → Select the language (You can change the language by selecting another language in the User Interface Language field in the My Account dialog Preferences tab") → Click on Sign In tab.
It will take you to the next page as per configuration: OBIEE homepage as shown in the following image or to My Dashboard page/Personal Dashboard or a Dashboard specific to your job role.
OBIEE components are mainly divided into two types of components −
Server Components
Client Components
Server components are responsible to run OBIEE system and client components interact with user to create reports and dashboards.
Following are the server components −
Oracle BI (OBIEE) Server
Oracle Presentation Server
Application Server
Scheduler
Cluster Controller
This component is the heart of OBIEE system and is responsible to communicate with other components. It generates queries for report request and they are sent to database for execution.
It is also responsible for managing repository components which are presented to the user for report generation, handles security mechanism, multi user environment, etc.
It takes the request from users via browser and passes all requests to OBIEE server.
OBIEE Application Server helps to work on client components and Oracle provides Oracle10g Application server with OBIEE suite.
It is responsible to schedule jobs in OBIEE repository. When you create a repository, OBIEE also create a table inside the repository which saves all schedule-related information. This component is also mandatory to run agents in 11g.
All jobs which are scheduled by the Scheduler can be monitored by the job manager.
Following are some client components −
Following tools are provided in OBIEE web-based client −
Interactive Dashboards
Oracle Delivers
BI Publisher
BI Presentation Service Administrator
Answers
Disconnected Analytics
MS Office Plugin
In Non-Web based client, following are the key components −
OBIEE Administration − It is used to build repositories and has three layers − Physical, Business, and Presentation.
OBIEE Administration − It is used to build repositories and has three layers − Physical, Business, and Presentation.
ODBC Client − It is used to connect to database and execute SQL commands.
ODBC Client − It is used to connect to database and execute SQL commands.
OBIEE Architecture involves various BI system components which are required to process the end user’s request.
The initial request from the end user is sent to the Presentation server. The Presentation server converts this request in logical SQL and forwards it to BI server component. BI server converts this into physical SQL and sends it to database to get the required result. This result is presented to the end user through the same way.
The following diagram shows detailed OBIEE Architecture −
OBIEE Architecture contains Java and non-Java components. Java components are Web Logic Server components and non-Java components are called Oracle BI system component.
This part of OBIEE system contains Admin Server and Managed Server. Admin server is responsible for managing the start and stop processes for Managed server. Managed Server comprises of BI Plugin, Security, Publisher, SOA, BI Office, etc.
Node Manager triggers the auto start, stop, restart activities and provides process management activities for Admin and Managed server.
OPMN is used to start and stop all components of BI system. It is managed and controlled by Fusion Middleware Controller.
These are non-Java components in an OBIEE system.
This is the heart of Oracle BI system and is responsible for providing data and query access capabilities.
It is responsible to present data from BI server to web clients which is requested by the end users.
This component provides scheduling capability in BI system and it has its own scheduler to schedule jobs in OBIEE system.
This is responsible for enabling BI Presentation server to support various Java tasks for BI Scheduler, Publisher and graphs.
This is used for load balancing purposes to ensure that the load is evenly assigned to all BI server processes.
OBIEE repository contains all metadata of the BI Server and is managed through the administration tool. It is used to store information about the application environment such as −
Data Modeling
Aggregate Navigation
Caching
Security
Connectivity Information
SQL Information
The BI Server can access multiple repositories. OBIEE Repository can be accessed using the following path −
BI_ORACLE_HOME/server/Repository -> Oracle 10g
ORACLE_INSTANCE/bifoundation/OracleBIServerComponent/coreapplication_obisn/-> Oracle 11g
OBIEE repository database is also known as a RPD because of its file extension. The RPD file is password protected and you can only open or create RPD files using Oracle BI Administration tool. To deploy an OBIEE application, the RPD file must be uploaded to Oracle Enterprise Manager. After uploading the RPD, the RPD password then must be entered into Enterprise Manager.
It is a three layer process − starting from Physical Layer (Schema Design), Business Model Layer, Presentation Layer.
Following are the common steps involved in creating the Physical Layer −
Create physical joins between the Dimension and Fact tables.
Change the names in the physical layer if required.
The physical layer of repository contains information about the data sources. To create the schema in the physical layer you need to import metadata from databases and other data sources.
Note − Physical layer in OBIEE supports multiple data sources in a single repository - i.e. data sets from 2 different data sources can be performed in OBIEE.
Go to Start → Programs → Oracle Business Intelligence → BI Administration → Administration Tool → File → New Repository.
A new window will open → Enter the name of Repository → Location (It tells the default location of Repository directory) → to import metadata select radio button → Enter Password → Click Next.
Select the connection type → Enter Data Source name and User name and password to connect to data source → Click Next.
Accept the meta types you want to import → You can select Tables, Keys, Foreign Keys, System tables, Synonyms, Alias, Views, etc. → Click Next.
Once you click Next, you will see Data Source view and Repository view. Expand the Schema name and select tables you want to add to Repository using Import Selected button → Click Next.
Connection Pool window opens up → Click OK → Importing window → Finish to open the repository as shown in the following image.
Expand the Data Source → Schema name to see the list of tables Imported in Physical Layer in the new Repository.
Go to tools → Update all rows counts → Once it is completed you can move the cursor on the table and also for individual columns. To see Data of a table, right-click on Table name → View Data.
It is advisable that you use table aliases frequently in the Physical layer to eliminate extra joins. Right-click on table name and select New Object → Alias.
Once you create an Alias of a table it shows up under the same Physical Layer in the Repository.
When you create a repository in OBIEE system, physical join is commonly used in the Physical layer. Physical joins help to understand how two tables should be joined to each other. Physical joins are normally expressed with the use of Equal operator.
You can also use a physical join in BMM layer, however, it is very rarely seen. The purpose of using a physical join in BMM layer is to override the physical join in the physical layer. It allows users to define more complex joining logic as compared to physical join in the physical layer so it works similar to complex join in the physical layer. Therefore, if we are using a complex join in the physical layer for applying more join conditions, there is no need to use a physical join in BMM layer again.
In the above snapshot, you can see a physical join between two table names − Products and Sales. Physical Join expression tells how the tables should be joined with each other as shown in the snapshot.
It is always recommended to use a physical join in the physical layer and complex join in BMM layer as much as possible to keep Repository design simple. Only when there is an actual need for a different join, then use a physical join in BMM layer.
Now to join tables while designing Repository, select all the tables in the Physical layer → Right-click → Physical diagram → Selected objects only option or you can also use Physical Diagram button at the top.
Physical Diagram box as shown in the following image appears with all the table names added. Select the new foreign key at the top and select Dim and Fact table to join.
A Foreign key in the physical layer is used to define Primary key-Foreign key relation between two tables. When you create it in the physical diagram, you have to point first the dimension and then the fact table.
Note − When you import tables from schema into RPD Physical Layer, you can also select KEY and FOREIGN KEY along with the table data, then the primary key-foreign key joins are automatically defined, however it is not recommended from performance point of view.
The table you click first, it creates one-to-one or one-to-many relationship that joins column in first table with foreign key column in the second table → Click Ok. The join will be visible in Physical Diagram box between two tables. Once tables are joined, close the Physical diagram box using ‘X’ option.
To save the new Repository go to File → Save or click the save button at the top.
It defines the business or logical model of objects and their mapping between business model and Schema in the physical layer. It simplifies the Physical Schema and maps the user business requirement to physical tables.
The Business Model and Mapping layer of OBIEE system administration tool can contain one or more business model objects. A business model object defines the business model definitions and the mappings from logical to physical tables for the business model.
Following are the steps to build the Business Model and Mapping layer of a repository −
Create a business model
Examine logical joins
Examine logical columns
Examine logical table sources
Rename logical table objects manually
Rename logical table objects using the rename wizard and deleting unnecessary logical objects
Creating measures (Aggregations)
Right-click on Business Model and Mapping Space → New Business Model.
Enter the name of Business Model → click OK.
In the physical layer, select all the tables/alias tables to be added to Business Model and drag to Business Model. You can also add tables one by one. If you drag all the tables simultaneously, it will keep keys and joins between them.
Also note the difference in icon of Dimension and Fact tables. Last table is Fact table and top 3 are dimension tables.
Now right-click on Business model → select Business Model diagram → Whole diagram → All tables are dragged simultaneously so it will keep all joins and keys. Now double click on any join to open the logical join box.
Joins in this layer are logical joins. It doesn’t show expressions and tells the type of join between tables. It helps Oracle BI server to understand the relationships between the various pieces of the business model. When you send a query to Oracle BI server, the server determines how to construct physical queries by examining how the logical model is structured.
Click Ok → Click ‘X’ to close the Business model diagram.
To examine logical columns and logical table sources, first expand the columns under tables in BMM. Logical columns were created for each table when you dragged all tables from the physical layer. To check logical table sources → Expand the source folder under each table and it points to the table in the physical layer.
Double-click the logical table source (not the logical table) to open the logical table source dialog box → General tab → rename the logical table source. Logical table to physical table mapping is defined under "Map to these tables" option.
Next, Column mapping tab defines the logical column to physical column mappings. If mappings are not shown, check the option → Show mapped columns.
There is no specific explicit complex join like in OBIEE 11g. It only exists in Oracle 10g.
Go to Manage → Joins → Actions → New → Complex Join.
When complex joins are used in the BMM layer, they act as placeholders. They allow the OBI Server to decide on which are the best joins between fact and dimension logical table source to satisfy the request.
To rename logical table objects manually, click the column name under the Logical table in BMM. You can also right-click on column name and select option rename, to rename the object.
This is known as manual method to rename objects.
Go to Tools → Utilities → Rename Wizard → Execute to open the rename wizard.
In the Select Objects screen, click Business Model and Mapping. It will show Business Model name → Expand Business Model name → Expand logical tables.
Select all the columns under the logical table to rename using the Shift key → Click Add. Similarly, add columns from all other logical Dim and Fact tables → click Next.
It shows all logical columns/tables added to wizard → Click Next to open Rules screen → Add rules from the list to rename like : A;; text lower case and change each occurrence of ‘_’ to space as shown in the following snapshot.
Click Next → finish. Now, if you expand Object names under logical tables in Business model and Objects in the physical layer, objects under BMM are renamed as required.
In the BMM layer, expand Logical tables → select objects to be deleted → right-click → Delete → Yes.
Double-click on the column name in the logical Fact table → Go to Aggregation tab and select the Aggregate function from the dropdown list → Click OK.
Measures represent data that is additive, such as total revenue or total quantity. Click on save option at top to save the repository.
Right-click on Presentation area → New Subject Area → In the General tab enter the name of subject area (Recommended similar to Business Model) → Click OK.
Once subject area is created, right click on subject area → New presentation table → Enter the name of the presentation table → Click OK (Add number of presentation tables equal to number of parameters required in the report).
Now, to create columns under Presentation tables → Select the objects under logical tables in BMM and drag them to Presentation tables under subject area (Use Ctrl key to select multiple objects for dragging). Repeat the process and add the logical columns to the remaining presentation tables.
You can rename the objects in Presentation tables by a double-click on logical objects under subject area.
In General tab → Deselect the check box Use Logical column name → Edit the name field → Click OK.
Similarly, you can rename all the objects in the Presentation layer without changing their name in BMM layer.
To order the columns in a table, double-click on the table name under Presentation → Columns → Use up and down arrows to change the order → Click OK.
Similarly, you can change objects order in all presentation tables under Presentation area. Go to File → Click Save to save the Repository.
Go to File → Check Global Consistency → You will receive the following message → Click Yes.
Once you click OK → Business model under BMM will change to Green → Click save the repository without checking global consistency again.
To improve query performance, it is advised to disable BI server cache option.
Open a browser and enter the following URL to open Fusion Middleware Control Enterprise Manager: http://<machine name>:7001/em
Enter the user name and password and click Login.
On the left side, expand Business Intelligence → coreapplication → Capacity Management tab → Performance.
Enable BI Server Cache section is by default checked → Click Lock and Edit Configuration → Click Close.
Now deselect cache enabled option → It is used to improve query performance → Apply → Activate Changes → Completed Successfully.
Go to Deployment tab → Repository → Lock and Edit Configuration → Completed Successfully.
Click Upload BI Server Repository section → Browse to open the Choose file dialog box → Select the Repository .rpd file and click on Open → Enter Repository password → Apply → Activate Changes.
Activate Changes → Completed Successfully → Click Restart to apply recent changes option on top of the screen → Click Yes.
Repository is successfully created and loaded for query Analysis.
Business Layer defines the business or logical model of objects and their mapping between business model and Schema in the physical layer. It simplifies the Physical Schema and maps the user business requirement to physical tables.
The business model and mapping layer of OBIEE system administration tool can contain one or more business model objects. A business model object defines the business model definitions and the mappings from logical to physical tables for the business model.
The business model is used to simplify the schema structure and maps the users’ business requirement to physical data source. It involves creation of logical tables and columns in the business model. Each logical table can have one or more physical objects as sources.
There are two categories of logical tables − fact and dimension. Logical fact tables contain the measures on which analysis is done and Logical dimension tables contain the information about measures and objects in Schema.
While creating a new repository using OBIEE administration tool, once you define the physical layer, create joins and identify foreign keys. The next step is to create a business model and mapping BMM layer of the repository.
Steps involved in defining Business Layer −
Create a business model
Examine logical joins
Examine logical columns
Examine logical table sources
Rename logical table objects manually
Rename logical table objects using the rename wizard and delete unnecessary logical object
Creating measures (Aggregations)
To create a business layer in the repository, right-click → New Business Model → Enter the name of Business Model and click OK. You can also add description of this Business Model if you want.
Logical tables in OBIEE repository exist in the Business Model and Mapping BMM layer. The business model diagram should contain at least two logical tables and you need to define relationships between them.
Each logical table should have one or more logical columns and one or more logical table sources associated with it. You can also change the logical table name, reorder the objects in logical table and define logical joins using primary and foreign keys.
There are two ways of creating logical tables/objects in BMM layer −
First method is dragging physical tables to Business Model which is the fastest way of defining logical tables. When you drag the tables from the physical layer to BMM layer, it also preserves the joins and keys automatically. If you want you can change the joins and keys in logical tables, it doesn’t affect objects in the physical layer.
Select physical tables/alias tables under the physical layer that you want to add to Business Model Layer and drag those table under BMM layer.
These tables are known as logical tables and columns are called Logical objects in Business Model and Mapping Layer.
Second method is to create a logical table manually. In the Business Model and Mapping layer, right-click the business model → Select New Object → Logical Table → Logical Table dialog box appears.
Go to General tab → Enter name for the logical table → Type a description of the table → Click OK.
Logical columns in BMM layer are automatically created when you drag tables from the physical layer to the business model layer.
If the logical column is a primary key, this column is displayed with the key icon. If the column has an aggregation function, it is displayed with a sigma icon. You can also reorder logical columns in the Business Model and Mapping layer.
In BMM layer, right-click on logical table → select New Object → Logical Column → Logical Column dialog box will appear, click General tab.
Type a name for the logical column. The name of the business model and the logical table appear in the “Belongs to Table” field just below column name → click OK.
You can also apply Aggregations on the logical columns. Click Aggregation tab → Select Aggregation rule from the dropdown list → Click OK.
Once you apply Aggregate function on a column, logical column icon is changed to show Aggregation rule is applied.
You can also move or copy logical column in tables −
In the BMM layer, you can select multiple columns to move. In the Sources for moved columns dialog box, in the Action area, select an action. If you select Ignore, no logical source will be added in the Sources folder of the table.
If you click on Create new, a copy of the logical source with the logical column will be created in the Sources folder. If you select Use existing option, from the drop-down list, you must select a logical source from the Sources folder of the table.
Logical tables in BMM layer are joined to each other using logical joins. Cardinality is one of the key defining parameter in logical joins. Cardinality relation one-to-many means that each row in first logical dimension table there are 0, 1, many rows in second logical table.
When you drag all the tables of the physical layer to business model layer, logical joins are automatically created in Repository. This condition rarely happens only in case of simple business models.
When logical joins are same as physical joins, they are automatically created. Logical joins in BMM layer are created in two ways −
Business Model Diagram (already covered while designing repository)
Joins Manager
Logical joins in BMM layer cannot be specified using expressions or columns on which to create the join like in the physical layer where expressions and column names are shown on which physical joins are defined.
First let us see how to create logical foreign keys using Join Manager.
In the Administration Tool toolbar, go to Manage → Joins. The Joins Manager dialog box appears → Go to Action tab → New → Logical Foreign Key.
Now in the Browse dialog box, double-click a table → The Logical Foreign Key dialog box appears → Enter the name for the foreign key → From Table drop-down list of the dialog box, select the table that the foreign key references → Select the columns in the left table that the foreign key references → Select the columns in the right table that make up the foreign key columns → Select the join type from the Type drop-down list. To open the Expression Builder, click the button to the right of the Expression pane → The expression displays in the Expression pane → click OK to save the work.
Logical complex joins are recommended in Business Model and mapping layer as compared to the use of logical foreign keys.
In the Administration Tool toolbar, go to Manage → Join → Joins Manager dialog box appears → Go to Action → Click New → Logical Complex Join.
It will open a logical Join dialog box → Type a name for the complex join → In the table drop-down lists on the left and right side of the dialog box, select the tables that the complex join references → Select the join type from the Type drop-down list → Click OK.
Note − You can also define a table as driving table from the drop-down list. This is used for performance optimization when the table size is too large. If the table size is small, less than 1000 rows, it shouldn’t be defined as driving table as it can result in performance degradation.
Logical dimensions exist in BMM and Presentation layer of OBIEE repository. Creating logical dimensions with hierarchies allows you to define aggregation rules that vary with dimensions. It also provides a drill-down option on the charts and tables in analyses and dashboards, and define the content of aggregate sources.
Open the Repository in Offline mode → Go to File → Open → Offline → Select Repository .rpd file and click on open → Enter Repository password → click OK.
Next step is to create logical dimension and logical levels.
Right click on Business model name in BMM layer → New Object → Logical Dimension → Dimension with level-based hierarchy. It will open the dialogue box → Enter the name → click OK.
To create a logical level, right-click on logical dimension → New Object → Logical Level.
Enter the name of logical level example: Product_Name
If this level is Grand total level, select the checkbox and the system will set number of element at this level to 1 by default → Click OK.
If you want the logical level to roll up to its parent, select the Supports rollup to parent elements checkbox → click OK.
If the logical level is not the grand total level and does not roll up, do not select any of the checkbox → Click OK.
You can also add parent-child hierarchies in logical level by following these steps −
To define child logical levels, click Add in the Browse dialog box, select the child logical levels and click OK.
You can also right-click on logical level → New Object → Child level.
Enter the name of child level → Ok. You can repeat this to add multiple child levels for all logical columns as per requirement. You can also add Time and Region hierarchies in a similar way.
Now to add logical columns of a table to logical level → select logical column in BMM layer and drag it to logical level child name to which you want to map. Similarly you can drag all the columns of logical table to create parent-child hierarchies.
When you create a child level, it can be checked by a double-click on the logical level and it is displayed under child levels list of that level. You can add or delete child levels by using ‘+’ or ‘X’ option on top of this box.
Double-click on the column name in logical Fact table → Go to Aggregation tab and select the Aggregate function from the drop-down list → Click OK.
Measures represents data that is additive, such as total revenue or total quantity. Click on save option at the top to save the repository.
There are various Aggregate functions that can be used like Sum, Average, Count, Max, Min, etc.
Presentation layer is used to provide customized views of Business model in BMM layer to users. Subject areas are used in Presentation layer provided by Oracle BI Presentation Services.
There are various ways you can create subject areas in Presentation layer. Most common and simple method is by dragging Business Model in BMM layer to Presentation Layer and then making changes to it as per requirement.
You can move columns, remove or add columns in presentation layer so it allows you to make changes in a way that the user shouldn’t see columns that has no meaning for them.
Create Subject Areas/Presentation Catalogues and Presentation Tables in Presentation Layer
Right-click on Presentation area → New Subject Area → In General tab enter the name of subject area (Recommended similar to Business Model) → Click OK.
Once Subject area is created, right click on subject area → New Presentation table → in General tab, Enter name of presentation table → OK (Add number of presentation tables equal to number of parameters required in the report).
Click the Permissions tab → Permissions dialog box, where you can assign user or group permissions to the table.
In the Presentation layer, right-click on subject Area → Presentation Catalog dialog box, click the Presentation Tables tab → Go to Presentation Tables tab, select a table and click Remove.
A confirmation message appears → Click Yes to remove the table or No to leave the table in the catalog → Click OK.
Go to Presentation Tables tab by a right-click on Subject Area → In the Name list, select the table you want to reorder → Use drag-and-drop to reposition the table or you can also use the Up and Down buttons to reorder the tables.
The name of presentation columns are normally same to the logical column names in the Business Model and Mapping layer. However, you can also enter a different name by unchecking Use Logical Column Name and the Display Custom Name in the Presentation Column dialog box.
The most simple way to create columns under Presentation tables is by dragging the columns from logical tables in BMM layer.
Select the objects under logical tables in BMM and drag them to Presentation tables under subject area (Use Ctrl key to select multiple objects for dragging). Repeat the process and add the logical columns to the remaining presentation tables.
Create a New Presentation Column −
Right-click on Presentation table in the Presentation layer → New Presentation Column.
Presentation Column dialog box appears. To use the name of the logical column, select the Use Logical Column checkbox.
To specify a name that is different name, uncheck the Use Logical Column check box, and then type a name for the column.
To assign user or group permissions to the column, click Permissions → In the Permissions dialog box, assign permissions → click OK.
Right-click on presentation table in the Presentation layer → Click on Properties → Click on the Columns tab → Select the column you want to delete → Click Remove or press the Delete key →Click Yes.
Right-click on presentation table in the Presentation layer → Go to Properties → Click the Columns tab → Select the column you want to reorder → Use drag-and-drop or you can also click Up and Down button → Click OK.
You can check the repository for errors by using the consistency checking option. Once it is done, next step is to load the repository into Oracle BI Server. Then test the repository by running an Oracle BI analysis and verifying the results.
Go to File → click on Check Global Consistency → You will receive the following message → Click Yes.
Once you click OK → Business model under BMM will change to Green → Click on save the repository without checking global consistency again.
To improve query performance, it is advised to disable BI server cache option.
Open a browser and enter the following URL to open Fusion Middleware Control Enterprise Manager: http://<machine name>:7001/em
Enter the user name and password. Click Login.
On the left side, expand Business Intelligence → coreapplication → Capacity Management tab → Performance.
Enable BI Server Cache section is by default checked → Click on Lock and Edit Configuration → Close.
Now deselect cache enabled option. It is used to improve query performance. Go to Apply → Activate Changes → Completed Successfully.
Go to Deployment tab → Repository → Lock and Edit Configuration → Completed Successfully.
Click on Upload BI Server Repository section → Browse to open the Choose file dialog box → select the Repository .rpd file and click Open → Enter Repository password → Apply → Activate Changes.
Activate Changes → Completed Successfully → Click on Restart to apply recent changes option at the top → Click Yes.
Repository is successfully created and loaded for query analysis.
You can set up query logging level for individual users in OBIEE. Logging level controls the information that you will retrieve in log file.
Open the Administration tool → Go to File → Open → Online.
Online mode is used to edit the repository in Oracle BI server. To open a repository in online mode, your Oracle BI server should be running.
Enter the Repository password and user name password to login and click Open to open the repository.
Go to Manage → Identity → Security Manager Window will open. Click BI Repository on the left side and double-click on Administrative user → User dialogue box will open.
Click User tab in user dialogue box, you can set logging levels here.
In normal scenario − The user has a logging level set to 0 and the administrator has a logging level set to 2. Logging level can have values starting from Level 0 to level 5. Level 0 means no logging and Level 5 means maximum logging level information.
Logs the SQL statement issued from the client application
Logs elapsed times for query compilation, query execution, query cache processing, and back-end database processing
Logs the query status (success, failure, termination, or timeout). Logs the users ID, session ID, and request ID for each query
Logs everything logged in Level 1
Additionally, for each query, logs the repository name, business model name, presentation catalog (called Subject Area in Answer) name, SQL for the queries issued against physical databases, queries issued against the cache, number of rows returned from each query against a physical database and from queries issued against the cache, and the number of rows returned to the client application
Logs everything logged in Level 2
Additionally, adds a log entry for the logical query plan, when a query that was supposed to seed the cache was not inserted into the cache, when existing cache entries are purged to make room for the current query, and when the attempt to udate the exact match hit detector fails
Logs everything logged in Level 3
Additionally, logs the query execution plan.
Logs everything logged in Level 4
Additionally, logs intermediate row counts at various points in the execution plan.
In user dialogue box, enter value for logging level.
Once you click OK, it will open the checkout dialogue box. Click Checkout. Close the Security Manager.
Go to file → Click on check-in changes → Save the repository using the Save option at the top → To take changes in effect → Click OK.
You can check query logs once query logging level is set by going to Oracle Enterprise Manager and this helps to verify queries.
To check the query logs to verify queries, go to Oracle Enterprise Manager OEM.
Go to diagnostic tab → click Log messages.
Scroll down to bottom in log messages to see Server, Scheduler, Action Services and other log details. Click on Server log to open log messages box.
You can select various filters − Date Range, Message types and message contains/not contains fields, etc. as shown in the following snapshot −
Once you click on search, it will show log messages as per filters.
Clicking on collapse button allows you to check details of all log messages for queries.
When you drag and drop a column from a physical table that is not currently being used in your logical table in BMM layer, the physical table containing such column gets added as a new Logical Table Source (LTS).
When in BMM layer, you use more than one table as source table, it is called multiple logical table sources. You can have a Fact table as multiple logical table sources when it uses different physical tables as source.
Example
Multiple LTS are used to convert Snowflakes schema to Star schemas in BMM layer.
Let us say you have two dimensions − Dim_Emp and Dim_Dept and one fact table FCT_Attendance in the Physical layer.
Here your Dim_Emp is normalized to Dim_Dept to implement Snowflakes schema. So in your Physical diagram, it would be like this −
Dim_Dept<------Dim_Emp <-------FCT_Attendance
When we move these table to the BMM layer, we will create a single dimension table Dim_Employee with 2 logical sources corresponding to Dim_Emp and Dim_Dept. In your BMM diagram −
Dim_Employee <-----------FCT_Attendance
This is one approach where you can use concept of multiple LTS in BMM layer.
When you use multiple physical tables as sources, you expand table sources in BMM diagram. It shows all multiple LTS from where it is picking up the data in BMM layer.
To see table mapping in BMM layer, expand the sources under logical table in BMM layer. It will open Logical table source mapping dialogue box. You can check all tables which are mapped to provide data in logical table.
Calculated measures is used to perform calculation of facts in logical tables. It defines Aggregation functions in Aggregation tab of logical column in the repository.
Measures are defined in logical fact tables in repository. Any column with an aggregation function applied on it is called a measure.
Common measure examples are − Unit Price, quantity sold, etc.
Following are the guidelines to create measures in OBIEE −
All aggregation should be performed from a fact logical table and not from a dimension logical table.
All aggregation should be performed from a fact logical table and not from a dimension logical table.
All columns that cannot be aggregated should be expressed in a dimension logical table and not in a fact logical table.
All columns that cannot be aggregated should be expressed in a dimension logical table and not in a fact logical table.
Calculated measures can be defined in two ways in logical tables at BMM layer in Administration tool −
Aggregations in logical tables.
Aggregations in logical table source.
Double-click on the column name in the logical Fact table, you will see the following dialog box.
Go to Aggregation tab and select the Aggregate function from the drop-down list → Click OK.
You can add new measures using functions in Expression builder wizard in Column source. Measures represent data that is additive, such as total revenue or total quantity. Click on the save option at the top to save the repository. This is also called creating measures at logical level.
You can define Aggregations by a double-click on Logical table source to open logical table dialogue box.
Click on Expression builder wizard to define expression.
In Expression builder, you can choose multiple options like - Category, functions, and mathematical functions.
Once you select the category, it will show the subcategories inside it. Select the subcategory and mathematical function, and click on the arrow mark to insert it.
Now to edit the value to create measures, click on source number, enter the calculated value like multiple and divide → Go to Category and select logical table → Select column to apply this multiple/division to an existing column value.
Click OK to close the Expression builder. Again click OK to close the dialog box.
Hierarchies is a series of many-to-one relationships and can be of different levels. A Region hierarchy consists of: Region → Country → State → City → Street. Hierarchies follow top-down or bottom-up approach.
Logical dimensions or dimension hierarchies are created in BMM layer. There are two types of dimensional hierarchies that are possible −
Dimensions with level-based hierarchies.
Dimension with Parent-Child hierarchies.
In level-based hierarchies, members can be of different types and members of the same type come only at single level.
In Parent-Child hierarchies, all members are of the same type.
Level-based dimension hierarchies can also contain parent-child relationships. The common sequence to create level-based hierarchies is to start with grand total level and then working down to lower levels.
Level-based hierarchies allows you to perform −
Level-based calculated measures.
Aggregate navigation.
Drill down to child level in dashboards.
Each dimension can only have one grand total level and it doesn’t have a level key or dimension attributes. You can associate measures with grand total level and default aggregation for these measures are grand total always.
All lower levels should have at least one column and each dimension contains one or more hierarchies. Each lower level also contains a level key which defines unique value at that level.
Unbalanced hierarchies are those where all the lower levels don’t have the same depth.
Example − For one product, for one month you can have data for weeks and for other month you can have data available for day level.
In skip-level hierarchies, few members don’t have values at higher level.
Example − For one city, you have state → country → Region. However for other city, you have only state and it doesn’t fall under any country or region.
In parent-child hierarchy, all the members are of the same type. The most common example of parent-child hierarchy is the reporting structure in an organization. Parent-child hierarchy is based on a single logical table. Each row contains two keys – one for the member and another for the parent of the member.
Level-based measures are created to perform calculation at a specific level of aggregation. They allow to return data at multiple levels of aggregation with one single query. It also allows to create share measures.
Example
Let us say there is a company XYZ Electronics which sells its products in many regions, countries and cities. Now the company President wants to see the total revenue at country level - one level below region and one level above cities. So total revenue measure should be summed up to the country level.
These type of measures are called level-based measures. Similarly, you can apply level-based measures on the time hierarchies.
Once the dimension hierarchies are created, level-based measures can be created by double clicking on the total revenue column in the logical table and setting the level in the levels tab.
Open the repository in offline mode. Go to File → Open → Offline.
Select .rpd file and click open → Enter repository password and click Ok.
In BMM layer, right-click on Total Revenue column → New Object → Logical column.
It will open the logical column dialog box. Enter the name of logical column total revenue. Go to column source tab → Check derived from existing columns using an expression.
Once you select this option, expression edit wizard will be highlighted. In expression builder wizard, select the logical table → Column name → Total revenue from the left side menu → Click OK.
Now go to level tab in logical column dialog box → Click on logical dimension to select it as grand total under logical level. This specifies that the measure should be calculated at grand total level in the dimension hierarchy.
Once you click OK → Total Revenue logical table will appear under the logical dimension and Fact tables.
This column can be dragged to presentation layer in the subject area to be used by end users to generate reports. You can drag this column from fact tables or from logical dimension.
Aggregations are used to implement query performance optimization while running the reports. This eliminates the time taken by query to run the calculations and delivers the results at fast speed. Aggregate tables has less number of rows as compared to a normal table.
When you execute a query in OBIEE, BI server looks for the resources which has information to answer the query. Out of all available sources, the server selects the most aggregated source to answer that query.
Open the Repository in an offline mode in the Administrator tool. Go to File → Open → Offline.
Import the metadata and create logical table source in BMM layer. Expand the table name and click on source table name to open logical table source dialog box.
Go to column mapping tab to see map columns in Physical table. Go to content tab → Aggregate content group by selecting the logical level.
You can select different logical levels as per the columns in fact tables like Product Total, Total Revenue, and Quarter/Year for Time as per dimension hierarchies.
Click OK to close dialog box → save the repository.
When you define Aggregate in logical fact tables they are defined as per dimension hierarchies.
In OBIEE, there are two types of variables that are commonly used −
Repository variables
Session variables
Apart from this you can also define Presentation and Request variables.
A Repository variable has a single value at any point of time. Repository variables are defined using Oracle BI Administration tool. Repository variables can be used in place of constants in Expression Builder Wizard.
There are two types of Repository variables −
Static repository variables
Dynamic repository variables
Static repository variables are defined in variable dialog box and their value exists until they are changed by the administrator.
Static repository variables contain default initializers that are numeric or character values. In addition, you can use Expression Builder to insert a constant as the default initializer, such as date, time, etc. You cannot use any other value or expression as the default initializer for a static repository variable.
In older BI versions, the Administrator tool did not limit value of static repository variables. You may get warning in consistency check if your repository has been upgraded from older versions. In such case, update the static repository variables so that default initializers have a constant value.
Dynamic repository variables are same as static variables but the values are refreshed by data returned from queries. When defining a dynamic repository variable, you create an initialization block or use a preexisting one that contains a SQL query. You can also set up a schedule that the Oracle BI Server will follow to execute the query and refresh the value of the variable periodically.
When the value of a dynamic repository variable changes, all cache entries associated with a business model are deleted automatically.
Each query can refresh several variables: one variable for each column in the query. You schedule these queries to be executed by the Oracle BI server.
Dynamic repository variables are useful for defining the content of logical table sources. For example, suppose you have two sources for information about orders. One source contains current orders and the other contains historical data.
In the Administration Tool → Go to Manage → Select Variables → Variable Manager → Go to Action → New → Repository > Variable.
In the Variable dialog, type a name for the variable (Names for all variables should be unique) → Select the type of variable - Static or Dynamic.
If you select dynamic variable, use the initialization block list to select an existing initialization block that will be used to refresh the value on a continuing basis.
To create a new initialization block → Click New. To add a default initializer value, type the value in the default initializer box, or click the Expression Builder button to use Expression Builder.
For static repository variables, the value you specify in the default initializer window persists. It will not change unless you change it. If you initialize a variable using a character string, enclose the string in single quotes. Static repository variables must have default initializers that are constant values → Click OK to close the dialog box.
Session variables are similar to dynamic repository variables and they obtain their values from initialization blocks. When a user begins a session, the Oracle BI server creates new instances of session variables and initializes them.
There are as many instances of a session variable as there are active sessions on the Oracle BI server. Each instance of a session variable could be initialized to a different value.
There are two types of Session variables −
System session variables
Non-system session variables
System session variables are used by Oracle BI and Presentation server for specific purposes. They have predefined reserved names which can’t be used by other variables.
USER
USERGUID
GROUP
ROLES
ROLEGUIDS
PERMISSIONS
Non-system session variables are used for setting the user filters. Example, you could define a non-system variable called Sale_Region that would be initialized to the name of the sale_region of the user.
In the Administration Tool → Go to Manage → Select Variables.
In the Variable Manager dialog, click Action → New → Session → Variable.
In the Session Variable dialog, enter variable name (Names for all variables should be unique and names of system session variables are reserved and cannot be used for other types of variables).
For session variables, you can select the following options −
Enable any user to set the value − This option is used to set session variables after the initialization block has populated the value. Example - this option lets non-administrators set this variable for sampling.
Enable any user to set the value − This option is used to set session variables after the initialization block has populated the value. Example - this option lets non-administrators set this variable for sampling.
Security sensitive − This is used to identify the variable as sensitive to security when using a row-level database security strategy, such as a Virtual Private Database (VPD).
Security sensitive − This is used to identify the variable as sensitive to security when using a row-level database security strategy, such as a Virtual Private Database (VPD).
You can use the initialization block list option to choose an initialization block that will be used to refresh the value regularly. You can also create a new initialization block.
To add a default initializer value, enter the value in the default initializer box or click the Expression Builder button to use Expression Builder. Click OK to close the dialog box.
The administrator can create non-system session variables using Oracle BI Administration tool.
Presentation variables are created with creation of Dashboard prompts. There are two types of dashboard prompts that can be used −
Presentation variable created with column prompt is associated with a column, and the values that it can take comes from the column values.
To create a presentation variable go to New Prompt dialog or Edit Prompt dialog → Select Presentation Variable in the Set of a variable field → Enter the name for the variable.
Presentation variable created as variable prompt is not associated with any column and you need to define its values.
To create a presentation variable as part of a variable prompt, in the New Prompt dialog or Edit Prompt dialog → Select Presentation Variable in the Prompt for field → Enter the name for the variable.
The value of a presentation variable is populated by the column or variable prompt with which it is created. Each time a user selects a value in the column or variable prompt, the value of the presentation variable is set to the value that the user selects.
Initialization blocks are used to initialize OBIEE variables: Dynamic Repository variables, system session variables and non-system session variables.
It contains SQL statement that are executed to initialize or refresh the variables associated with that block. The SQL statement that are executed points to physical tables that can be accessed using the connection pool. Connection pool is defined in the initialization block dialog.
If you want the query for an initialization block to have database-specific SQL, you can select a database type for that query.
Default initiation string field of initialization block is used to set value of dynamic repository variables. You also define a schedule which is followed by Oracle BI server to execute the query and refresh the value of variable. If you set the logging level to 2 or higher, log information for all SQL queries executed to retrieve the value of variable is saved in nqquery.log file.
Location of this file on BI Server −
ORACLE_INSTANCE\diagnostics\logs\OracleBIServerComponent\coreapplication_obisn
Session variables also take their values from initialization block but their value never changes with time intervals. When a user begins a new session, Oracle BI server creates a new instance of session variables.
All SQL queries executed to retrieve session variable information by BI server if the logging level is set to 2 or higher in the Identity Manager User object or the LOGLEVEL system session variable is set to 2 or higher in the Variable Manager is saved in nqquery.log file.
Location of this file on BI Server −
ORACLE_INSTANCE\diagnostics\logs\OracleBIServerComponent\coreapplication_obisn
Go to Manager → Variables → Variable Manager Dialog box appears. Go to Action menu → Click New → Repository → Initialization Block → Enter the name of initialization block.
Go to Schedule tab → Select start date and time and refresh interval.
You can choose the following options for Initialization Blocks −
Disable − If you select this option, initialization block is disabled. To enable an initialization block, right-click an existing initialization block in the Variable Manager and choose Enable. This option enables you to change this property without opening the initialization block dialog.
Disable − If you select this option, initialization block is disabled. To enable an initialization block, right-click an existing initialization block in the Variable Manager and choose Enable. This option enables you to change this property without opening the initialization block dialog.
Allow deferred execution − This allows you to defer the execution of the initialization block until an associated session variable is accessed for the first time during the session.
Allow deferred execution − This allows you to defer the execution of the initialization block until an associated session variable is accessed for the first time during the session.
Required for authentication − If you select this, initialization block must execute for users to log in. Users are denied access to Oracle BI if the initialization block doesn’t execute.
Required for authentication − If you select this, initialization block must execute for users to log in. Users are denied access to Oracle BI if the initialization block doesn’t execute.
OBIEE dashboard is a tool that enables end users to run ad-hoc reports and analysis as per business requirement model. Interactive dashboards are pixel perfect reports which can be directly viewed or printed by end users.
OBIEE dashboard is part of Oracle BI Presentation layer services. If your end user is not interested in seeing all the data in the dashboard, it allows you to add prompts to the dashboard that allows the end user to enter what he wants to see. Dashboards also allow end users to select from drop-down lists, multi-select boxes and selection of columns to display in the reports.
Oracle BI dashboard allows you to set up alerts for sales executives that comes up on the interactive dashboard whenever the company’s projected sales is going to be below forecast.
To create a new Dashboard, go to New → Dashboard or you can also click on Dashboard option under create on the left side.
Once you click on Dashboard, new dashboard dialog box opens up. Enter the name of Dashboard and description and select the location where you want Dashboard to save → click OK.
If you save the dashboard in the Dashboards subfolder directly under the /Shared Folders/first level subfolder → dashboard will be listed in the Dashboard menu on the global header.
If you save it in a Dashboards subfolder at any other level (such as /Shared Folders/Sales/Eastern), it will not be listed.
If you choose a folder in the Dashboards subfolder directly under the /Shared Folders/first level subfolder in which no dashboards have been saved, a new Dashboards folder is automatically created for you.
Once you enter the above fields, Dashboard builder will open up as shown in the following snapshot −
Expand the catalog tab, select analysis to add to Dashboard and drag to page layout pane. Save and run the dashboard.
Go to Dashboard → My Dashboard → Edit Dashboard.
To edit Dashboard. Click on below icon → Dashboard properties.
A new dialog box will appear as shown in the following snapshot. You can perform the following tasks −
Change the styles (Styles control how dashboards and results are formatted for display, such as the color of text and links, the font and size of text, the borders in tables, the colors and attributes of graphs, and so on). You can add a description.
You can add hidden prompts, filters, and variables. Specify the links that will display with analyses on a dashboard page. You can rename, hide, reorder, set permissions for, and delete dashboard pages.
You can also edit Dashboard page properties by selecting page in the dialog box. You can make the following changes −
You can change the name of your dashboard page.
You can change the name of your dashboard page.
You can add a hidden prompt. Hidden prompts are used to set default values for all corresponding prompts on a dashboard page.
You can add a hidden prompt. Hidden prompts are used to set default values for all corresponding prompts on a dashboard page.
You can add permissions for the dashboard and can also delete the selected page. Dashboard pages are permanently deleted.
You can add permissions for the dashboard and can also delete the selected page. Dashboard pages are permanently deleted.
If more than one dashboard page is in this dashboard, the arrange order icons are enabled using up and down arrows.
If more than one dashboard page is in this dashboard, the arrange order icons are enabled using up and down arrows.
To set the report links at the dashboard level, dashboard page, or analysis level click the edit option of Dashboard reporting links.
To add a dashboard page, click on new Dashboard page icon → Enter the name of dashboard page and click OK.
In Catalog tab, you can add the new another analysis and drag it to page layout area of new dashboard page.
To edit the properties of dashboard like cell width, border, and height, click on column properties. You can set background color, wrap text and additional formatting options.
You can also add a condition on dashboard data display by clicking on condition option in column properties −
To add a condition, click on + sign in condition dialog box. You can add a condition based on analysis.
Select the condition data and enter the condition parameter.
You can also test, edit or remove the condition by clicking on ‘more’ sign next to + button.
You can save your customized dashboard by going to page options → Save current customizations → Enter the name of customization → Click OK.
To apply customization to a dashboard page, go to page option → Apply saved customization → Select name → Click OK.
It allows you to save and view dashboard pages in their current state such as filters, prompts, column sorts, drills in analyses, and section expansion and collapse. By saving customizations, you do not need to make these choices manually each time you access the dashboard page.
Filters are used to limit the results that are displayed when an analysis is run, so that the results answer a particular question. Based on the filters, only those results are shown that matches the criteria passed in the filter condition.
Filters are applied directly to attribute and measure columns. Filters are applied before the query is aggregated and affect the query and thus the resulting values for measures.
For example, you have a list of members in which the aggregate sums to 100. Over time, more members meet the set filter criteria, which increases the aggregate sum to 200.
Following are the ways to create filters −
Go to Oracle Business Intelligence homepage → New menu → Select filter. The Select Subject Area dialog is displayed.
From the Select Subject Area dialog, choose the subject area for which you want to create a filter. The "Filter editor" is displayed from the "Subject Areas pane". Double-click the column for which you want to create the filter. New Filter dialog is displayed.
Either create an analysis or access an existing analysis for which you want to create a filter.
Click the Criteria tab → Locate the "Filters pane" → Click create a filter for the current subject area button. The analysis selected columns are displayed in the cascading menu.
Select a column name from the menu or select the More Columns option to access the “Select Column dialog" from which you can select any column from the subject area.
Once you select a column, the "New Filter dialog" is displayed.
Oracle BI Enterprise Edition enables you to look at results of analyses in a meaningful way using its presentation capabilities. Different types of views can be added, such as graphs and pivot tables that allow drilling down to more detailed information and many more options like using filters, etc.
The results of the analysis is displayed using a table/Pivot table view and depends on the type of columns that the analysis contains −
Table view is used if the analysis contains only attribute columns/only measure columns or a combination of both.
Table view is used if the analysis contains only attribute columns/only measure columns or a combination of both.
Pivot table is the default view if the analysis contains at least one hierarchical column.
Pivot table is the default view if the analysis contains at least one hierarchical column.
A title view displays the name of the saved analysis.
A title view displays the name of the saved analysis.
You can edit or delete an existing view, add another view to an analysis and can also combine views.
You can edit or delete an existing view, add another view to an analysis and can also combine views.
Title
Title view displays a title, a subtitle, a logo, a link to a custom online help page and timestamps to the results.
Table
Table view is used to display results in a visual representation of data organized by rows and columns. It provides a summary view of data and enables users to see different views of data by dragging and dropping rows and columns.
Pivot Table
It displays results in a pivot table, which provides a summary view of data in cross-tab format and enables users to see different views of data by dragging and dropping rows and columns.
Pivot tables and standard tables are similar in structure but Pivot table can contain column groups and can also display multiple levels of both row and column headings.
Pivot table cell contains a unique value. Pivot table is more efficient than a row-based table. It is best suited for displaying a large quantity of data, for browsing data hierarchically, and for trend analysis.
Performance Tile
Performance tiles are used to display a single aggregate measure value in a manner that is visually simple but provides a summary metrics to the user that will likely be presented in more detail within a dashboard view.
Performance tiles are used to focus the user's attention on simple, need-to-know facts directly and prominently on the tile.
Communicate status through simple formatting by using color, labels, and limited styles, or through conditional formatting of the background color or measure value to make the tile visually prominent. For example, if revenue is not tracking to target, the revenue value may appear in red.
Respond to prompts, filters, and user roles and permissions by making them relevant to the user and their context.
Support a single, aggregate or calculated value.
Treemap
Tree map are used to display a space-constrained, 2-d visualization for hierarchical structures with multiple levels.
Treemaps are limited by a predefined area and display two levels of data.
Contain rectangular tiles. The size of the tile is based on a measure, and the color of the tile is based on a second measure.
Treemap are similar to a scatter plot graphs in that the map area is constrained, and the graph allows you to visualize large quantities of data and quickly identify trends and anomalies within that data.
Trellis
Trellis displays multi-dimensional data shown as a set of cells in a grid form and where each cell represents a subset of data using a particular graph type.
The trellis view has two subtypes − Simple Trellis and Advanced Trellis.
Simple trellis views are ideal for displaying multiple graphs that enable comparison of like to like. Advanced trellis views are ideal for displaying spark graphs that show a trend.
A simple trellis displays a single inner graph type, Example − a grid of multiple Bar graphs.
An advanced trellis displays a different inner graph type for each measure. Example: A mixture of Spark Line graphs and Spark Bar graphs, alongside numbers.
Graph
Graph displays numeric information visually which makes it easier to understand large quantities of data. Graphs often reveal patterns and trends that text-based displays cannot.
A graph is displayed on a background, called the graph canvas.
Gauge
Gauge are used to show a single data value. Cos of its compact size, a gauge is often more effective than a graph for displaying a single data value
Gauges identify problems in data. A gauge usually plots one data point with an indication of whether that point falls in an acceptable or unacceptable range. Thus, gauges are useful for showing performance against goals.
A gauge or gauge set is displayed on a background, called the gauge canvas.
Funnel
Funnel displays results in 3D graph that represents target and actual values using volume, level, and color. Funnel graphs are used to graphically represent data that changes over different periods or stages. Example: Funnel graphs are often used to represent the volume of sales over a quarter.
Funnel graphs are well suited for showing actual compared to targets for data where the target is known to decrease (or increase) significantly per stage, such as a sales pipeline.
Map view
Map view is used to display results overlain on a map. Depending on the data, the results can be overlain on top of a map as formats such as images, color fill areas, bar and pie graphs, and variably sized markers.
Filters
Filter are used to displays the filters in effect for an analysis. Filters allows you to add condition to an analysis to obtain results that answer a particular question. Filters are applied before the query is aggregated.
Selection Steps
Selection steps are used to displays the selection steps in effect for an analysis. Selection steps, like filters, allow you to obtain results that answer particular questions. Selection steps are applied after the query is aggregated.
Column Selector
Column selector is a set of drop-down lists that contain pre-selected columns. Users can dynamically select columns and change the data that is displayed in the views of the analysis.
View Selector
A view selector is a drop-down list from which users can select a specific view of the results from among the saved views.
Legend
It enables you to document the meaning of special formatting used in results-meaning of custom colors applied to gauges.
Narrative
It displays the results as one or more paragraphs of text.
Ticker
It displays the results as a ticker or marquee, similar in style to the stock tickers that run across many financial and news sites on the Internet. You can also control what information is presented and how it scrolls across the page.
Static Text
You can use HTML to add banners, tickers, ActiveX objects, Java applets, links, instructions, descriptions, graphics, etc. in the results.
Logical SQL
It displays the SQL statement that is generated for an analysis. This view is useful for trainers and administrators, and is usually not included in results for typical users.
You cannot modify this view, except to format its container or to delete it.
Create Segment
It is used to display a Create Segment link in the results.
Create Target List
It is used to display a create target list link in the results. Users can click this link to create a target list, based on the results data, in their Oracle's Siebel operational application.
This view is for users of Oracle's Siebel Life Sciences operational application integrated with Oracle's Siebel Life Sciences Analytics applications.
All view types except logical SQL view can be edited. Each view has its own editor in which you can perform edit task.
Each view editor contains a unique functionality for that view type but might also contain functionality that is the same across view types.
Open the analysis that contains the view to edit. Click the "Analysis editor: Results tab."
Click the Edit View button for the view. View editors is displayed. Now, using the editor for the view, make the required edits. Click done and then save the view.
You can delete a view from −
A compound layout − If you remove a view from a compound layout, it is only removed from the compound layout and not from the analysis.
A compound layout − If you remove a view from a compound layout, it is only removed from the compound layout and not from the analysis.
An analysis − If you remove a view from an analysis, it removes the view from the analysis and also from any compound layout to which it had been added.
An analysis − If you remove a view from an analysis, it removes the view from the analysis and also from any compound layout to which it had been added.
If you want to remove a view from −
A compound layout − In the view in the Compound Layout → click the Remove View from Compound Layout button.
A compound layout − In the view in the Compound Layout → click the Remove View from Compound Layout button.
An analysis − In the Views pane → select the view and then click the Remove View from Analysis toolbar button.
An analysis − In the Views pane → select the view and then click the Remove View from Analysis toolbar button.
A Prompt is a special type of filter that is used to filter analyses embedded in a dashboard. The main reason to use a dashboard prompt is that it allows the user to customize analysis output and also allows flexibility to change parameters of a report. There are three types of prompts that can be used −
The prompt created at the dashboard level is called a Named prompt. This Prompt is created outside of a specific dashboard and stored in the catalog as a prompt. You can apply a named prompt to any dashboard or dashboard page that contains the columns, mentioned in the prompt. It can filter one or any number of analyses embedded on the same dashboard page. You can create and save these named prompts to a private folder or a shared folder.
A named prompt always appears on the dashboard page and the user can prompt for different values without having to rerun the dashboard. A named prompt can also interact with selection steps. You can specify a dashboard prompt to override a specific selection step.
The step will be processed against the dashboard column with the user-specified data values collected by the dashboard column prompt, whereas all other steps will be processed as originally specified.
Inline prompts are embedded in an analysis and are not stored in the catalog for reuse. Inline prompt provides general filtering of a column within the analysis, depending on how it is configured.
Inline prompt works independently from a dashboard filter, which determines values for all matching columns on the dashboard. An inline prompt is an initial prompt. When the user selects the prompt value, the prompt field disappears from the analysis.
To select different prompt values, you need to rerun the analysis. Your input determines the content of the analyses embedded in the dashboard.
Named Prompt can be applied to any dashboard or dashboard page which contains the column specified in the Prompt.
A column prompt is the most common and flexible prompt type. A column prompt enables you to build very specific value prompts to either stand alone on the dashboard or analysis or to expand or refine existing dashboard and analysis filters. Column prompts can be created for hierarchical, measure, or attribute columns at the analysis or dashboard level.
Go to New → Dashboard Prompt → Select subject area.
Dashboard prompt dialog box appears. Go to ‘+’ sign, select the prompt type. Click on the column prompt → Select column → Click OK.
New Prompt dialog box appears (this appears only for column prompts). Enter the label name that will appear on dashboard next to Prompt → Select the Operator → User Input.
The User Input field's drop-down list appears for column and variable prompts, and provides you with the option to determine the User Input method for the user interface. You can select any of the following − checkboxes, radio buttons, a choice list, or a list box.
Example − If you select the User Input method of Choice List and Choice List Values item of all Column Values, the user will select the prompt's data value from a list that contains all of the data values contained in the data source.
You can also further make a selection by expanding the Options tab.
These series of checkboxes allow you to restrict the amount of data returned in output. Once selection is made, click OK.
The Prompt is added to Definition → Save the prompt using the save option at the top right corner → Enter the name → Click OK.
To test the Prompt, go to My Dashboard → Catalog and drag the prompt to column 1. This prompt can be applied to full dashboard or on a single page by clicking on Properties → Scope.
Save and run the Dashboard, select the value for a Prompt. Apply and Output value will change as per prompt value.
A currency prompt enables the user to change the currency type that is displayed in the currency columns on an analysis or dashboard.
Example − Suppose that an analysis contains the sales totals for a certain region of US in US dollars. However, because the users viewing the analysis reside in Canada, they can use the currency prompt to change the sales totals from USD to Canada dollars.
The prompt's currency selection list is populated with the currency preferences from the user’s → My Account dialog → Preferences tab. Currency prompt option is available only if the administrator has configured the userpref_currencies.xml file.
An image prompt provides an image that users click to select values for an analysis or dashboard.
Example − In a sales organization, users can click their territories from an image of a map to see sales information, or click a product image to see sales information about that product. If you know how to use the HTML <map> tag, then you can create an image map definition.
A variable prompt enables the user to select a value that is specified in the variable prompt to display on dashboard. A variable prompt is not dependent upon a column, but can still use a column.
You can add one or more existing reports to a dashboard page. The advantage is that you can share reports with other users and schedule the dashboard pages using agents. An agent sends the entire dashboard to the user, including all data pages that the report references.
When configuring an agent for a dashboard page that contains a BI Publisher report, ensure that the following criteria are met −
The output format of the BI Publisher report must be PDF.
The agent must be set to deliver PDF.
You can add reports to a dashboard page as embedded content and as a link. Embedded means that the report is displayed directly on the dashboard page. The link opens the report in BI Publisher within Oracle BIEE.
If you modify the report in BI Publisher and save your changes, then refresh the dashboard page to see the modifications. Navigate to the page to which you want to add a report.
Select a report in one of the following ways −
Select the report from the Catalog pane and drag and drop it into a section on the dashboard page.
Select the report from the Catalog pane and drag and drop it into a section on the dashboard page.
To add a report from a dashboard page, select the report from the folder that contains its dashboard in the Catalog pane.
To add a report from a dashboard page, select the report from the folder that contains its dashboard in the Catalog pane.
Set the properties of the object. To do so, hover the mouse pointer over the object in the page layout area to display the object's toolbar, and click the Properties button.
The "BI Publisher Report Properties dialog" is displayed. Complete the fields in the properties dialog as appropriate. Click OK and then click Save.
If required, add a prompt to the dashboard page to filter the results of an embedded parameterized report.
OBIEE security is defined by the use of a role-based access control model. It is defined in terms of roles that are aligned to different directory server groups and users. In this chapter, we will be discussing the components defined to compose a security policy.
One can define a Security structure with the following components
The directory Server User and Group managed by the Authentication provider.
The directory Server User and Group managed by the Authentication provider.
The application roles managed by the Policy store provide Security policy with the following components: Presentation catalog, repository, policy store.
The application roles managed by the Policy store provide Security policy with the following components: Presentation catalog, repository, policy store.
Security provider is called in order to get the security information. Following types of security providers are used by OBIEE −
Authentication provider to authenticate users.
Authentication provider to authenticate users.
Policy store provider is used to give privileges on all applications except for BI Presentation Services.
Policy store provider is used to give privileges on all applications except for BI Presentation Services.
Credential store provider is used to store credentials used internally by the BI application.
Credential store provider is used to store credentials used internally by the BI application.
Security policy in OBIEE is divided into the following components −
Presentation Catalog
Repository
Policy Store
It defines the catalog objects and Oracle BI Presentation Services functionality.
It enables you to set privileges for users to access features and functions such as editing views and creating agents and prompts.
Presentation Catalog privileges access to presentation catalog objects defined in the Permission dialog.
Presentation Services administration does not have its own authentication system and it relies on the authentication system that it inherits from the Oracle BI Server. All users who sign in to Presentation Services are granted the Authenticated User role and any other roles that they were assigned in Fusion Middleware Control.
You can assign permissions in one of the following ways −
To application roles − Most recommended way of assigning permissions and privileges.
To application roles − Most recommended way of assigning permissions and privileges.
To individual users − This is difficult to manage where you can assign permissions and privileges to specific users.
To individual users − This is difficult to manage where you can assign permissions and privileges to specific users.
To Catalog groups − It was used in previous releases for backward compatibility maintenance.
To Catalog groups − It was used in previous releases for backward compatibility maintenance.
This defines which application roles and users have access to which items of metadata within the repository. The Oracle BI Administration Tool through the security manager is used and enables you to perform the following tasks −
Set permissions for business models, tables, columns, and subject areas.
Specify database access for each user.
Specify filters to limit the data accessible by users.
Set authentication options.
It defines BI Server, BI Publisher, and Real Time Decisions functionality that can be accessed by given users or users with given Application Roles.
Authenticator Provider in Oracle WebLogic Server domain is used for user authentication. This authentication provider accesses users and group information stored in the LDAP server in the Oracle Business Intelligence's Oracle WebLogic Server domain.
To create and manage users and groups in an LDAP server, Oracle WebLogic Server Administration Console is used. You can also choose to configure an authentication provider for an alternative directory. In this case, Oracle WebLogic Server Administration Console enables you to view the users and groups in your directory; however, you need to continue to use the appropriate tools to make any modifications to the directory.
Example − If you reconfigure Oracle Business Intelligence to use OID, you can view users and groups in Oracle WebLogic Server Administration Console but you must manage them in OID Console.
Once authentication is done, the next step in security is to ensure that the user can do and see what they are authorized to do. Authorization for Oracle Business Intelligence 11g is managed by a security policy in terms of Applications Roles.
Security is normally defined in terms of Application roles that are assigned to directory server users and groups. Example: the default Application roles are BIAdministrator, BIConsumer, and BIAuthor.
Application roles are defined as functional role assigned to a user, which gives that user the privileges required to perform that role. Example: Marketing Analyst Application role might grant a user access to view, edit and create reports on a company's marketing pipeline.
This communication between Application roles and directory server users and groups allows the administrator to define the Application roles and policies without creating additional users or groups in LDAP server. Application roles allows business intelligence system to be easily moved between development, test and production environments.
This doesn’t require any change in security policy and all that is required is to assign the Application roles to the users and groups available in the target environment.
The group named 'BIConsumers' contains user1, user2, and user3. Users in the group 'BIConsumers' are assigned the Application role 'BIConsumer', which enables the users to view reports.
The group named 'BIAuthors' contains user4 and user5. Users in the group 'BIAuthors' are assigned the Application role 'BIAuthor', which enables the users to create reports.
The group named 'BIAdministrators' contains user6 and user7, user 8. Users in the group 'BIAdministrators' are assigned the Application role 'BIAdministrator', which enables the users to manage repositories.
In OBIEE 10g, most of OBIEE administration tasks were mostly performed either through the Administration tool, the web-based Presentation Server administration screen, or through editing files in the filesystem. There were around 700 or so configuration options spread over multiple tools and configuration files, with some options like users and groups were embedded in unrelated repositories (the RPD).
In OBIEE 11g, all administration and configuration tasks are moved into Fusion Middleware Control also called as Enterprise Manager.
Administration tool that was present in OBIEE 10g is also present in 11g and is used to maintain the semantic model used by the BI Server. It has few enhancements in terms of dimension handling and new data sources. A major change is around security - when you open the Security Manager dialog −
Go to Manage → Identity → Security Manager Dialog box appears.
Users and Application Roles are now defined in the WebLogic Server admin console. You use the Security Manager to define additional links through to other LDAP servers, register custom authenticators and set up filters, etc. In the above screenshot, the users shown in the users list are those that are held in WebLogic Server’s JPS (Java Platform Security) service, and there are no longer any users and groups in the RPD itself.
There is no administrator user in above snapshot. It has standard administrator user that you set up as the WebLogic Server administrator when you install OBIEE, which typically has the username weblogic.
There are also two additional default users: OracleSystemUser - this user is used by the various OBIEE web services to communicate with the BI Server and BISystemUser is used by BI Publisher to connect to the BI Server as a data source.
In Application Roles tab, you can see a list default application roles - BISystem, BIAdministrator, BIAuthor and BIConsumer - which are used to grant access to Presentation Server functionality.
To create a new user, log on to the WebLogic Server admin console → Go to Security Realms from the Fusion Middleware Control menu → Select myrealm → Select Users and Groups. Click on Users tab, it will show you a list of existing users.
Click the New. → New user dialog box opens up → enter the user’s details. You can also use the Groups tab to define a group for the user, or assign the user to an existing group.
Following are the key file locations In OBIEE 11g −
C:\Middleware\instances\instance1\bifoundation\OracleBIServerComponent\
coreapplication_obis1\repository
C:\Middleware\instances\instance1\config\OracleBIServerComponent\coreapplication_obis1\
nqsconfig.INI
C:\Middleware\instances\instance1\config\OracleBIApplication\coreapplication\
NQClusterConfig.INI
C:\Middleware\instances\instance1\diagnostics\logs\OracleBIServerComponent\
coreapplication_obis1\nqquery.log
C:\Middleware\instances\instance1\diagnostics\logs\OracleBIServerComponent\
coreapplication_obis1\nqserver.log
C:\Middleware\Oracle_BI1\bifoundation\server\bin\nqsserver.exe
C:\Middleware\instances\instance1\bifoundation\OracleBIPresentationServicesComponent\
coreapplication_obips1\catalog\
C:\Middleware\instances\instance1\config\OracleBIPresentationServicesComponent\
coreapplication_obips1\instanceconfig.xml
C:\Middleware\instances\instance1\config\OracleBIPresentationServicesComponent\
coreapplication_obips1\xdo.cfg
C:\Middleware\instances\instance1\diagnostics\logs\OracleBIPresentationServicesComponent\
coreapplication_obips1\sawlog0.log
C:\Middleware\Oracle_BI1\bifoundation\web\bin\sawserver.exe
Go to Overview. You can also stop, start and restart all of the system components like BI Server, Presentation Server etc. via OPMN.
You can click the Capacity Management, Diagnostics, Security or Deployment tabs to perform further maintenance.
We have the following four options available for capacity management −
Metrics gathered via DMS.
Metrics gathered via DMS.
Availability of all the individual system components (allowing you to stop, start and restart them individually).
Availability of all the individual system components (allowing you to stop, start and restart them individually).
Scalability is used to increase the number of BI Servers, Presentation Servers, Cluster Controllers and Schedulers in the cluster in conjunction with the “scale out” install option.
Scalability is used to increase the number of BI Servers, Presentation Servers, Cluster Controllers and Schedulers in the cluster in conjunction with the “scale out” install option.
Performance option allows you to turn caching on or off and modify other parameters associated with response time.
Performance option allows you to turn caching on or off and modify other parameters associated with response time.
Diagnostics − Log Messages show you view of all server errors and warnings. Log Configuration allows you to limit the size of logs and information gets included in them.
Security − It is used for enabling SSO and selecting the SSO provider.
Deployment − Presentation allows you to set dashboard defaults, section headings, etc. Scheduler is used to set the connection details for the scheduler schema. Marketing is for configuring the Siebel Marketing Content Server connection. Mail option is used for setting up the mail server to deliver for email alerts. Repository is used to upload new RPDs for use by the BI Server.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2480,
"s": 2076,
"text": "In today’s competitive market, most successful companies respond quickly to market changes and opportunities. The requirement to respond quickly is by effective and efficient use of data and information. “Data Warehouse” is a central repository of data that is organized by category to support the organization’s decision makers. Once data is stored in a data warehouse, it can be accessed for analysis."
},
{
"code": null,
"e": 2719,
"s": 2480,
"text": "The term \"Data Warehouse\" was first invented by Bill Inmon in 1990. According to him, “Data warehouse is a subject-oriented, integrated, time-variant and non-volatile collection of data in support of management's decision making process.”"
},
{
"code": null,
"e": 2905,
"s": 2719,
"text": "Ralph Kimball provided a definition of data warehouse based on its functionality. He said, “Data warehouse is a copy of transaction data specifically structured for query and analysis.”"
},
{
"code": null,
"e": 3242,
"s": 2905,
"text": "Data Warehouse (DW or DWH) is a system used for analysis of data and reporting purposes. They are repositories that saves data from one or more heterogeneous data sources. They store both current and historical data and are used for creating analytical reports. DW can be used to create interactive dashboards for the senior management."
},
{
"code": null,
"e": 3371,
"s": 3242,
"text": "For example, analytic reports can contain data for quarterly comparisons or for annual comparison of sales report for a company."
},
{
"code": null,
"e": 3750,
"s": 3371,
"text": "Data in DW comes from multiple operational systems like sales, human resource, marketing, warehouse management, etc. It contains historical data from different transaction systems but it can also include data from other sources. DW is used to separate data processing and analysis workload from transaction workload and enables to consolidate the data from several data sources."
},
{
"code": null,
"e": 4137,
"s": 3750,
"text": "For example − You have a home loan agency, where data comes from multiple SAP/non-SAP applications such as marketing, sales, ERP, HRM, etc. This data is extracted, transformed and loaded into DW. If you have to do quarterly/annual sales comparison of a product, you cannot use an operational database as this will hang the transaction system. This is where the need for using DW arises."
},
{
"code": null,
"e": 4181,
"s": 4137,
"text": "Some of the key characteristics of DW are −"
},
{
"code": null,
"e": 4225,
"s": 4181,
"text": "It is used for reporting and data analysis."
},
{
"code": null,
"e": 4305,
"s": 4225,
"text": "It provides a central repository with data integrated from one or more sources."
},
{
"code": null,
"e": 4344,
"s": 4305,
"text": "It stores current and historical data."
},
{
"code": null,
"e": 4445,
"s": 4344,
"text": "Following are few differences between Data Warehouse and Operational Database (Transaction System) −"
},
{
"code": null,
"e": 4647,
"s": 4445,
"text": "Transactional system is designed for known workloads and transactions like updating a user record, searching a record, etc. However, DW transactions are more complex and present a general form of data."
},
{
"code": null,
"e": 4849,
"s": 4647,
"text": "Transactional system is designed for known workloads and transactions like updating a user record, searching a record, etc. However, DW transactions are more complex and present a general form of data."
},
{
"code": null,
"e": 4961,
"s": 4849,
"text": "Transactional system contains the current data of an organization whereas DW normally contains historical data."
},
{
"code": null,
"e": 5073,
"s": 4961,
"text": "Transactional system contains the current data of an organization whereas DW normally contains historical data."
},
{
"code": null,
"e": 5247,
"s": 5073,
"text": "Transactional system supports parallel processing of multiple transactions. Concurrency control and recovery mechanisms are required to maintain consistency of the database."
},
{
"code": null,
"e": 5421,
"s": 5247,
"text": "Transactional system supports parallel processing of multiple transactions. Concurrency control and recovery mechanisms are required to maintain consistency of the database."
},
{
"code": null,
"e": 5589,
"s": 5421,
"text": "Operational database query allows to read and modify operations (delete and update), while an OLAP query needs only read-only access of stored data (select statement)."
},
{
"code": null,
"e": 5757,
"s": 5589,
"text": "Operational database query allows to read and modify operations (delete and update), while an OLAP query needs only read-only access of stored data (select statement)."
},
{
"code": null,
"e": 5827,
"s": 5757,
"text": "DW involves data cleaning, data integration, and data consolidations."
},
{
"code": null,
"e": 5897,
"s": 5827,
"text": "DW involves data cleaning, data integration, and data consolidations."
},
{
"code": null,
"e": 6075,
"s": 5897,
"text": "DW has a three-layer architecture − Data Source Layer, Integration Layer, and Presentation Layer. The following diagram shows the common architecture of a Data Warehouse system."
},
{
"code": null,
"e": 6114,
"s": 6075,
"text": "Following are the types of DW system −"
},
{
"code": null,
"e": 6124,
"s": 6114,
"text": "Data Mart"
},
{
"code": null,
"e": 6160,
"s": 6124,
"text": "Online Analytical Processing (OLAP)"
},
{
"code": null,
"e": 6197,
"s": 6160,
"text": "Online Transaction Processing (OLTP)"
},
{
"code": null,
"e": 6217,
"s": 6197,
"text": "Predictive Analysis"
},
{
"code": null,
"e": 6407,
"s": 6217,
"text": "Data Mart is the simplest form of DW and it normally focuses on a single functional area, such as sales, finance or marketing. Hence, data mart usually gets data only from few data sources."
},
{
"code": null,
"e": 6596,
"s": 6407,
"text": "Sources could be an internal transaction system, a central data warehouse, or an external data source application. De-normalization is the norm for data modeling techniques in this system."
},
{
"code": null,
"e": 6735,
"s": 6596,
"text": "An OLAP system contains less number of transactions but involves complex calculations like use of Aggregations − Sum, Count, Average, etc."
},
{
"code": null,
"e": 6972,
"s": 6735,
"text": "We save tables with aggregated data like yearly (1 row), quarterly (4 rows), monthly (12 rows) and now we want to compare data, like Yearly only 1 row will be processed. However, in an un-aggregated data, all the rows will be processed."
},
{
"code": null,
"e": 7131,
"s": 6972,
"text": "OLAP system normally stores data in multidimensional schemas like Star Schema, Galaxy schemas (with Fact and Dimensional tables are joined in logical manner)."
},
{
"code": null,
"e": 7499,
"s": 7131,
"text": "In an OLAP system, response time to execute a query is an effectiveness measure. OLAP applications are widely used by Data Mining techniques to get data from OLAP systems. OLAP databases store aggregated historical data in multi-dimensional schemas. OLAP systems have data latency of a few hours as compared to Data Marts where latency is normally closer to few days."
},
{
"code": null,
"e": 7722,
"s": 7499,
"text": "An OLTP system is known for large number of short online transactions like insert, update, delete, etc. OLTP systems provide fast query processing and also responsible to provide data integrity in multi-access environment."
},
{
"code": null,
"e": 8007,
"s": 7722,
"text": "For an OLTP systems, effectiveness is measured by the number of transactions processed per second. OLTP systems normally contain only current data. The schema used to store transactional databases is the entity model. Normalization is used for data modeling techniques in OLTP system."
},
{
"code": null,
"e": 8093,
"s": 8007,
"text": "The following illustration shows the key differences between an OLTP and OLAP system."
},
{
"code": null,
"e": 8226,
"s": 8093,
"text": "Indexes − In an OLTP system, there are only few indexes while in an OLAP system there are many indexes for performance optimization."
},
{
"code": null,
"e": 8366,
"s": 8226,
"text": "Joins − In an OLTP system, large number of joins and data is normalized; however, in an OLAP system there are less joins and de-normalized."
},
{
"code": null,
"e": 8476,
"s": 8366,
"text": "Aggregation − In an OLTP system, data is not aggregated while in an OLAP database more aggregations are used."
},
{
"code": null,
"e": 8916,
"s": 8476,
"text": "Dimensional modeling provides set of methods and concepts that are used in DW design. According to DW consultant, Ralph Kimball, dimensional modeling is a design technique for databases intended to support end-user queries in a data warehouse. It is oriented around understandability and performance. According to him, although transaction-oriented ER is very useful for the transaction capture, it should be avoided for end-user delivery."
},
{
"code": null,
"e": 9123,
"s": 8916,
"text": "Dimensional modeling always uses facts and dimension tables. Facts are numerical values which can be aggregated and analyzed on the fact values. Dimensions define hierarchies and description on fact values."
},
{
"code": null,
"e": 9348,
"s": 9123,
"text": "Dimension table stores the attributes that describe objects in a Fact table. A Dimension table has a primary key that uniquely identifies each dimension row. This key is used to associate the Dimension table to a Fact table."
},
{
"code": null,
"e": 9481,
"s": 9348,
"text": "Dimension tables are normally de-normalized as they are not created to execute transactions and only used to analyze data in detail."
},
{
"code": null,
"e": 9646,
"s": 9481,
"text": "In the following dimension table, the customer dimension normally includes the name of customers, address, customer id, gender, income group, education levels, etc."
},
{
"code": null,
"e": 9796,
"s": 9646,
"text": "Fact table contains numeric values that are known as measurements. A Fact table has two types of columns − facts and foreign key to dimension tables."
},
{
"code": null,
"e": 9840,
"s": 9796,
"text": "Measures in Fact table are of three types −"
},
{
"code": null,
"e": 9900,
"s": 9840,
"text": "Additive − Measures that can be added across any dimension."
},
{
"code": null,
"e": 9960,
"s": 9900,
"text": "Additive − Measures that can be added across any dimension."
},
{
"code": null,
"e": 10027,
"s": 9960,
"text": "Non-Additive − Measures that cannot be added across any dimension."
},
{
"code": null,
"e": 10094,
"s": 10027,
"text": "Non-Additive − Measures that cannot be added across any dimension."
},
{
"code": null,
"e": 10161,
"s": 10094,
"text": "Semi-Additive − Measures that can be added across some dimensions."
},
{
"code": null,
"e": 10228,
"s": 10161,
"text": "Semi-Additive − Measures that can be added across some dimensions."
},
{
"code": null,
"e": 10358,
"s": 10228,
"text": "This fact tables contains foreign keys for time dimension, product dimension, customer dimension and measurement value unit sold."
},
{
"code": null,
"e": 10509,
"s": 10358,
"text": "Suppose a company sells products to customers. Every sale is a fact that happens within the company, and the fact table is used to record these facts."
},
{
"code": null,
"e": 10683,
"s": 10509,
"text": "Common facts are − number of unit sold, margin, sales revenue, etc. The dimension table list factors like customer, time, product, etc. by which we want to analyze the data."
},
{
"code": null,
"e": 10937,
"s": 10683,
"text": "Now if we consider the above Fact table and Customer dimension then there will also be a Product and time dimension. Given this fact table and these three dimension tables, we can ask questions like: How many watches were sold to male customers in 2010?"
},
{
"code": null,
"e": 11133,
"s": 10937,
"text": "The functional difference between dimension tables and fact tables is that fact tables hold the data we want to analyze and dimension tables hold the information required to allow us to query it."
},
{
"code": null,
"e": 11238,
"s": 11133,
"text": "Aggregate table contains aggregated data which can be calculated by using different aggregate functions."
},
{
"code": null,
"e": 11425,
"s": 11238,
"text": "An aggregate function is a function where the values of multiple rows are grouped together as input on certain criteria to form a single value of more significant meaning or measurement."
},
{
"code": null,
"e": 11462,
"s": 11425,
"text": "Common aggregate functions include −"
},
{
"code": null,
"e": 11472,
"s": 11462,
"text": "Average()"
},
{
"code": null,
"e": 11480,
"s": 11472,
"text": "Count()"
},
{
"code": null,
"e": 11490,
"s": 11480,
"text": "Maximum()"
},
{
"code": null,
"e": 11499,
"s": 11490,
"text": "Median()"
},
{
"code": null,
"e": 11509,
"s": 11499,
"text": "Minimum()"
},
{
"code": null,
"e": 11516,
"s": 11509,
"text": "Mode()"
},
{
"code": null,
"e": 11522,
"s": 11516,
"text": "Sum()"
},
{
"code": null,
"e": 11627,
"s": 11522,
"text": "These aggregate tables are used for performance optimization to run complex queries in a data warehouse."
},
{
"code": null,
"e": 11875,
"s": 11627,
"text": "You save tables with aggregated data like yearly (1 row), quarterly (4 rows), monthly (12 rows) and now you have to do comparison of data, like Yearly only 1 row will be processed. However in an un-aggregated table, all the rows will be processed."
},
{
"code": null,
"e": 12037,
"s": 11875,
"text": "Select Avg (salary) from employee where title = ‘developer’. This statement will return the average salary for all employees whose title is equal to 'Developer'."
},
{
"code": null,
"e": 12219,
"s": 12037,
"text": "Aggregations can be applied at database level. You can create aggregates and save them in aggregate tables in the database or you can apply aggregate on the fly at the report level."
},
{
"code": null,
"e": 12324,
"s": 12219,
"text": "Note − If you save aggregates at the database level it saves time and provides performance optimization."
},
{
"code": null,
"e": 12664,
"s": 12324,
"text": "Schema is a logical description of the entire database. It includes the name and description of records of all types including all associated data-items and aggregates. Much like a database, DW also requires to maintain a schema. Database uses relational model, while DW uses Star, Snowflake, and Fact Constellation schema (Galaxy schema)."
},
{
"code": null,
"e": 12985,
"s": 12664,
"text": "In a Star Schema, there are multiple dimension tables in de-normalized form that are joined to only one fact table. These tables are joined in a logical manner to meet some business requirement for analysis purpose. These schemas are multidimensional structures which are used to create reports using BI reporting tools."
},
{
"code": null,
"e": 13120,
"s": 12985,
"text": "Dimensions in Star schemas contain a set of attributes and Fact tables contain foreign keys for all dimensions and measurement values."
},
{
"code": null,
"e": 13353,
"s": 13120,
"text": "In the above Star Schema, there is a fact table “Sales Fact” at the center and is joined to 4 dimension tables using primary keys. Dimension tables are not further normalized and this joining of tables is known as Star Schema in DW."
},
{
"code": null,
"e": 13423,
"s": 13353,
"text": "Fact table also contains measure values − dollar_sold and units_sold."
},
{
"code": null,
"e": 13642,
"s": 13423,
"text": "In a Snowflakes Schema, there are multiple dimension tables in normalized form that are joined to only one fact table. These tables are joined in a logical manner to meet some business requirement for analysis purpose."
},
{
"code": null,
"e": 13980,
"s": 13642,
"text": "Only difference between a Star and Snowflakes schema is that dimension tables are further normalized. The normalization splits up the data into additional tables. Due to normalization in the Snowflake schema, the data redundancy is reduced without losing any information and therefore it becomes easy to maintain and saves storage space."
},
{
"code": null,
"e": 14333,
"s": 13980,
"text": "In above Snowflakes Schema example, Product and Customer table are further normalized to save storage space. Sometimes, it also provides performance optimization when you execute a query that requires processing of rows directly in normalized table so it doesn’t process rows in primary Dimension table and comes directly to Normalized table in Schema."
},
{
"code": null,
"e": 14576,
"s": 14333,
"text": "Granularity in a table represents the level of information stored in the table. High granularity of data means that data is at or near the transaction level, which has more detail. Low granularity means that data has low level of information."
},
{
"code": null,
"e": 14835,
"s": 14576,
"text": "A fact table is usually designed at a low level of granularity. This means that we need to find the lowest level of information that can be stored in a fact table. In date dimension, the granularity level could be year, month, quarter, period, week, and day."
},
{
"code": null,
"e": 14895,
"s": 14835,
"text": "The process of defining granularity consists of two steps −"
},
{
"code": null,
"e": 14947,
"s": 14895,
"text": "Determining the dimensions that are to be included."
},
{
"code": null,
"e": 15029,
"s": 14947,
"text": "Determining the location to place the hierarchy of each dimension of information."
},
{
"code": null,
"e": 15147,
"s": 15029,
"text": "Slowly changing dimensions refer to changing value of an attribute over time. It is one of the common concepts in DW."
},
{
"code": null,
"e": 15302,
"s": 15147,
"text": "Andy is an employee of XYZ Inc. He was first located in New York City in July 2015. Original entry in the employee lookup table has the following record −"
},
{
"code": null,
"e": 15429,
"s": 15302,
"text": "At a later date, he has relocated to LA, California. How should XYZ Inc. now modify its employee table to reflect this change?"
},
{
"code": null,
"e": 15483,
"s": 15429,
"text": "This is known as \"Slowly Changing Dimension\" concept."
},
{
"code": null,
"e": 15536,
"s": 15483,
"text": "There are three ways to solve this type of problem −"
},
{
"code": null,
"e": 15616,
"s": 15536,
"text": "The new record replaces the original record. No trace of the old record exists."
},
{
"code": null,
"e": 15743,
"s": 15616,
"text": "Slowly Changing Dimension, the new information simply overwrites the original information. In other words, no history is kept."
},
{
"code": null,
"e": 15883,
"s": 15743,
"text": "Benefit − This is the easiest way to handle the Slowly Changing Dimension problem as there is no need to keep track of the old information."
},
{
"code": null,
"e": 16023,
"s": 15883,
"text": "Benefit − This is the easiest way to handle the Slowly Changing Dimension problem as there is no need to keep track of the old information."
},
{
"code": null,
"e": 16074,
"s": 16023,
"text": "Disadvantage − All historical information is lost."
},
{
"code": null,
"e": 16125,
"s": 16074,
"text": "Disadvantage − All historical information is lost."
},
{
"code": null,
"e": 16229,
"s": 16125,
"text": "Use − Solution 1 should be used when it is not required for DW to keep track of historical information."
},
{
"code": null,
"e": 16333,
"s": 16229,
"text": "Use − Solution 1 should be used when it is not required for DW to keep track of historical information."
},
{
"code": null,
"e": 16441,
"s": 16333,
"text": "A new record is entered into the Employee dimension table. So the employee, Andy, is treated as two people."
},
{
"code": null,
"e": 16616,
"s": 16441,
"text": "A new record is added to the table to represent the new information and both the original and new record will be present. The new record gets its own primary key as follows −"
},
{
"code": null,
"e": 16689,
"s": 16616,
"text": "Benefit − This method allows us to store all the historical information."
},
{
"code": null,
"e": 16762,
"s": 16689,
"text": "Benefit − This method allows us to store all the historical information."
},
{
"code": null,
"e": 16910,
"s": 16762,
"text": "Disadvantage − Size of the table grows faster. When the number of rows for the table is very high, space and performance of table can be a concern."
},
{
"code": null,
"e": 17058,
"s": 16910,
"text": "Disadvantage − Size of the table grows faster. When the number of rows for the table is very high, space and performance of table can be a concern."
},
{
"code": null,
"e": 17143,
"s": 17058,
"text": "Use − Solution 2 should be used when it is necessary for DW to keep historical data."
},
{
"code": null,
"e": 17228,
"s": 17143,
"text": "Use − Solution 2 should be used when it is necessary for DW to keep historical data."
},
{
"code": null,
"e": 17305,
"s": 17228,
"text": "The original record in Employee dimension is modified to reflect the change."
},
{
"code": null,
"e": 17515,
"s": 17305,
"text": "There will be two columns to indicate the particular attribute, one indicates original value and other indicates the new value. There will also be a column that indicates when the current value becomes active."
},
{
"code": null,
"e": 17653,
"s": 17515,
"text": "Benefits − This does not increase the size of the table, since new information is updated. This allows us to keep historical information."
},
{
"code": null,
"e": 17791,
"s": 17653,
"text": "Benefits − This does not increase the size of the table, since new information is updated. This allows us to keep historical information."
},
{
"code": null,
"e": 17894,
"s": 17791,
"text": "Disadvantage − This method doesn’t keep all history when an attribute value is changed more than once."
},
{
"code": null,
"e": 17997,
"s": 17894,
"text": "Disadvantage − This method doesn’t keep all history when an attribute value is changed more than once."
},
{
"code": null,
"e": 18104,
"s": 17997,
"text": "Use − Solution 3 should only be used when it is required for DW to keep information of historical changes."
},
{
"code": null,
"e": 18211,
"s": 18104,
"text": "Use − Solution 3 should only be used when it is required for DW to keep information of historical changes."
},
{
"code": null,
"e": 18471,
"s": 18211,
"text": "Normalization is the process of decomposing a table into less redundant smaller tables without losing any information. So Database normalization is the process of organizing the attributes and tables of a database to minimize data redundancy (duplicate data)."
},
{
"code": null,
"e": 18567,
"s": 18471,
"text": "It is used to eliminate certain types of data (redundancy/ replication) to improve consistency."
},
{
"code": null,
"e": 18663,
"s": 18567,
"text": "It is used to eliminate certain types of data (redundancy/ replication) to improve consistency."
},
{
"code": null,
"e": 18803,
"s": 18663,
"text": "It provides maximum flexibility to meet future information needs by keeping tables corresponding to object types in their simplified forms."
},
{
"code": null,
"e": 18943,
"s": 18803,
"text": "It provides maximum flexibility to meet future information needs by keeping tables corresponding to object types in their simplified forms."
},
{
"code": null,
"e": 18990,
"s": 18943,
"text": "It produces a clearer and readable data model."
},
{
"code": null,
"e": 19037,
"s": 18990,
"text": "It produces a clearer and readable data model."
},
{
"code": null,
"e": 19053,
"s": 19037,
"text": "Data integrity."
},
{
"code": null,
"e": 19080,
"s": 19053,
"text": "Enhances data consistency."
},
{
"code": null,
"e": 19124,
"s": 19080,
"text": "Reduces data redundancy and space required."
},
{
"code": null,
"e": 19145,
"s": 19124,
"text": "Reduces update cost."
},
{
"code": null,
"e": 19198,
"s": 19145,
"text": "Maximum flexibility in responding to ad-hoc queries."
},
{
"code": null,
"e": 19242,
"s": 19198,
"text": "Reduces the total number of rows per block."
},
{
"code": null,
"e": 19375,
"s": 19242,
"text": "Slow performance of queries in database because joins have to be performed to retrieve relevant data from several normalized tables."
},
{
"code": null,
"e": 19468,
"s": 19375,
"text": "You have to understand the data model in order to perform proper joins among several tables."
},
{
"code": null,
"e": 19695,
"s": 19468,
"text": "In the above example, the table inside the green block represents a normalized table of the one inside the red block. The table in green block is less redundant and also with less number of rows without losing any information."
},
{
"code": null,
"e": 20071,
"s": 19695,
"text": "OBIEE stands for Oracle Business Intelligence Enterprise Edition, a set of Business Intelligence tools and is provided by Oracle Corporation. It enables the user to deliver robust set of reporting, ad-hoc query and analysis, OLAP, dashboard, and scorecard functionality with a rich end-user experience that includes visualization, collaboration, alerts and many more options."
},
{
"code": null,
"e": 20157,
"s": 20071,
"text": "OBIEE provides robust reporting which makes data easier for business users to access."
},
{
"code": null,
"e": 20243,
"s": 20157,
"text": "OBIEE provides robust reporting which makes data easier for business users to access."
},
{
"code": null,
"e": 20391,
"s": 20243,
"text": "OBIEE provides a common infrastructure for producing and delivering enterprise reports, scorecards, dashboards, ad-hoc analysis, and OLAP analysis."
},
{
"code": null,
"e": 20539,
"s": 20391,
"text": "OBIEE provides a common infrastructure for producing and delivering enterprise reports, scorecards, dashboards, ad-hoc analysis, and OLAP analysis."
},
{
"code": null,
"e": 20661,
"s": 20539,
"text": "OBIEE reduces cost with a proven web-based service-oriented architecture that integrates with existing IT infrastructure."
},
{
"code": null,
"e": 20783,
"s": 20661,
"text": "OBIEE reduces cost with a proven web-based service-oriented architecture that integrates with existing IT infrastructure."
},
{
"code": null,
"e": 21163,
"s": 20783,
"text": "OBIEE enables the user to include rich visualization, interactive dashboards, a vast range of animated charting options, OLAP-style interactions, innovative search, and actionable collaboration capabilities to increase the user adoption. These capabilities enable your organization to make better decisions, take informed actions, and implement more-efficient business processes."
},
{
"code": null,
"e": 21543,
"s": 21163,
"text": "OBIEE enables the user to include rich visualization, interactive dashboards, a vast range of animated charting options, OLAP-style interactions, innovative search, and actionable collaboration capabilities to increase the user adoption. These capabilities enable your organization to make better decisions, take informed actions, and implement more-efficient business processes."
},
{
"code": null,
"e": 21656,
"s": 21543,
"text": "The main competitors of OBIEE are Microsoft BI tools, SAP AG Business Objects, IBM Cognos and SAS Institute Inc."
},
{
"code": null,
"e": 21884,
"s": 21656,
"text": "As OBIEE enables the user to create interactive dashboards, robust reports, animated charts and also because of its cost-effectiveness, it is widely used by many companies as one of main tool for Business Intelligence solution."
},
{
"code": null,
"e": 22260,
"s": 21884,
"text": "OBIEE provides various types of visualizations to insert in dashboards to make it more interactive. It allows you to create flash reports, report templates, and ad-hoc reporting for end users. It provides close integration with major data sources and can also be integrated with third party vendors like Microsoft to embed data in PowerPoint presentations and word documents."
},
{
"code": null,
"e": 22320,
"s": 22260,
"text": "Following are the key features and benefits of OBIEE tool −"
},
{
"code": null,
"e": 22385,
"s": 22320,
"text": "To sign into OBIEE, you can use web URL, user name and password."
},
{
"code": null,
"e": 22429,
"s": 22385,
"text": "To sign into Oracle BI Enterprise Edition −"
},
{
"code": null,
"e": 22497,
"s": 22429,
"text": "Step 1 − In the Web browser address bar, enter URL to access OBIEE."
},
{
"code": null,
"e": 22530,
"s": 22497,
"text": "The \"Sign In page\" is displayed."
},
{
"code": null,
"e": 22758,
"s": 22530,
"text": "Step 2 − Enter your user name and password → Select the language (You can change the language by selecting another language in the User Interface Language field in the My Account dialog Preferences tab\") → Click on Sign In tab."
},
{
"code": null,
"e": 22946,
"s": 22758,
"text": "It will take you to the next page as per configuration: OBIEE homepage as shown in the following image or to My Dashboard page/Personal Dashboard or a Dashboard specific to your job role."
},
{
"code": null,
"e": 23013,
"s": 22946,
"text": "OBIEE components are mainly divided into two types of components −"
},
{
"code": null,
"e": 23031,
"s": 23013,
"text": "Server Components"
},
{
"code": null,
"e": 23049,
"s": 23031,
"text": "Client Components"
},
{
"code": null,
"e": 23178,
"s": 23049,
"text": "Server components are responsible to run OBIEE system and client components interact with user to create reports and dashboards."
},
{
"code": null,
"e": 23216,
"s": 23178,
"text": "Following are the server components −"
},
{
"code": null,
"e": 23241,
"s": 23216,
"text": "Oracle BI (OBIEE) Server"
},
{
"code": null,
"e": 23268,
"s": 23241,
"text": "Oracle Presentation Server"
},
{
"code": null,
"e": 23287,
"s": 23268,
"text": "Application Server"
},
{
"code": null,
"e": 23297,
"s": 23287,
"text": "Scheduler"
},
{
"code": null,
"e": 23316,
"s": 23297,
"text": "Cluster Controller"
},
{
"code": null,
"e": 23502,
"s": 23316,
"text": "This component is the heart of OBIEE system and is responsible to communicate with other components. It generates queries for report request and they are sent to database for execution."
},
{
"code": null,
"e": 23672,
"s": 23502,
"text": "It is also responsible for managing repository components which are presented to the user for report generation, handles security mechanism, multi user environment, etc."
},
{
"code": null,
"e": 23757,
"s": 23672,
"text": "It takes the request from users via browser and passes all requests to OBIEE server."
},
{
"code": null,
"e": 23884,
"s": 23757,
"text": "OBIEE Application Server helps to work on client components and Oracle provides Oracle10g Application server with OBIEE suite."
},
{
"code": null,
"e": 24119,
"s": 23884,
"text": "It is responsible to schedule jobs in OBIEE repository. When you create a repository, OBIEE also create a table inside the repository which saves all schedule-related information. This component is also mandatory to run agents in 11g."
},
{
"code": null,
"e": 24202,
"s": 24119,
"text": "All jobs which are scheduled by the Scheduler can be monitored by the job manager."
},
{
"code": null,
"e": 24241,
"s": 24202,
"text": "Following are some client components −"
},
{
"code": null,
"e": 24298,
"s": 24241,
"text": "Following tools are provided in OBIEE web-based client −"
},
{
"code": null,
"e": 24321,
"s": 24298,
"text": "Interactive Dashboards"
},
{
"code": null,
"e": 24337,
"s": 24321,
"text": "Oracle Delivers"
},
{
"code": null,
"e": 24350,
"s": 24337,
"text": "BI Publisher"
},
{
"code": null,
"e": 24388,
"s": 24350,
"text": "BI Presentation Service Administrator"
},
{
"code": null,
"e": 24396,
"s": 24388,
"text": "Answers"
},
{
"code": null,
"e": 24419,
"s": 24396,
"text": "Disconnected Analytics"
},
{
"code": null,
"e": 24436,
"s": 24419,
"text": "MS Office Plugin"
},
{
"code": null,
"e": 24496,
"s": 24436,
"text": "In Non-Web based client, following are the key components −"
},
{
"code": null,
"e": 24613,
"s": 24496,
"text": "OBIEE Administration − It is used to build repositories and has three layers − Physical, Business, and Presentation."
},
{
"code": null,
"e": 24730,
"s": 24613,
"text": "OBIEE Administration − It is used to build repositories and has three layers − Physical, Business, and Presentation."
},
{
"code": null,
"e": 24804,
"s": 24730,
"text": "ODBC Client − It is used to connect to database and execute SQL commands."
},
{
"code": null,
"e": 24878,
"s": 24804,
"text": "ODBC Client − It is used to connect to database and execute SQL commands."
},
{
"code": null,
"e": 24989,
"s": 24878,
"text": "OBIEE Architecture involves various BI system components which are required to process the end user’s request."
},
{
"code": null,
"e": 25322,
"s": 24989,
"text": "The initial request from the end user is sent to the Presentation server. The Presentation server converts this request in logical SQL and forwards it to BI server component. BI server converts this into physical SQL and sends it to database to get the required result. This result is presented to the end user through the same way."
},
{
"code": null,
"e": 25380,
"s": 25322,
"text": "The following diagram shows detailed OBIEE Architecture −"
},
{
"code": null,
"e": 25549,
"s": 25380,
"text": "OBIEE Architecture contains Java and non-Java components. Java components are Web Logic Server components and non-Java components are called Oracle BI system component."
},
{
"code": null,
"e": 25788,
"s": 25549,
"text": "This part of OBIEE system contains Admin Server and Managed Server. Admin server is responsible for managing the start and stop processes for Managed server. Managed Server comprises of BI Plugin, Security, Publisher, SOA, BI Office, etc."
},
{
"code": null,
"e": 25924,
"s": 25788,
"text": "Node Manager triggers the auto start, stop, restart activities and provides process management activities for Admin and Managed server."
},
{
"code": null,
"e": 26046,
"s": 25924,
"text": "OPMN is used to start and stop all components of BI system. It is managed and controlled by Fusion Middleware Controller."
},
{
"code": null,
"e": 26096,
"s": 26046,
"text": "These are non-Java components in an OBIEE system."
},
{
"code": null,
"e": 26203,
"s": 26096,
"text": "This is the heart of Oracle BI system and is responsible for providing data and query access capabilities."
},
{
"code": null,
"e": 26304,
"s": 26203,
"text": "It is responsible to present data from BI server to web clients which is requested by the end users."
},
{
"code": null,
"e": 26426,
"s": 26304,
"text": "This component provides scheduling capability in BI system and it has its own scheduler to schedule jobs in OBIEE system."
},
{
"code": null,
"e": 26552,
"s": 26426,
"text": "This is responsible for enabling BI Presentation server to support various Java tasks for BI Scheduler, Publisher and graphs."
},
{
"code": null,
"e": 26664,
"s": 26552,
"text": "This is used for load balancing purposes to ensure that the load is evenly assigned to all BI server processes."
},
{
"code": null,
"e": 26844,
"s": 26664,
"text": "OBIEE repository contains all metadata of the BI Server and is managed through the administration tool. It is used to store information about the application environment such as −"
},
{
"code": null,
"e": 26858,
"s": 26844,
"text": "Data Modeling"
},
{
"code": null,
"e": 26879,
"s": 26858,
"text": "Aggregate Navigation"
},
{
"code": null,
"e": 26887,
"s": 26879,
"text": "Caching"
},
{
"code": null,
"e": 26896,
"s": 26887,
"text": "Security"
},
{
"code": null,
"e": 26921,
"s": 26896,
"text": "Connectivity Information"
},
{
"code": null,
"e": 26937,
"s": 26921,
"text": "SQL Information"
},
{
"code": null,
"e": 27045,
"s": 26937,
"text": "The BI Server can access multiple repositories. OBIEE Repository can be accessed using the following path −"
},
{
"code": null,
"e": 27182,
"s": 27045,
"text": "BI_ORACLE_HOME/server/Repository -> Oracle 10g\nORACLE_INSTANCE/bifoundation/OracleBIServerComponent/coreapplication_obisn/-> Oracle 11g\n"
},
{
"code": null,
"e": 27556,
"s": 27182,
"text": "OBIEE repository database is also known as a RPD because of its file extension. The RPD file is password protected and you can only open or create RPD files using Oracle BI Administration tool. To deploy an OBIEE application, the RPD file must be uploaded to Oracle Enterprise Manager. After uploading the RPD, the RPD password then must be entered into Enterprise Manager."
},
{
"code": null,
"e": 27674,
"s": 27556,
"text": "It is a three layer process − starting from Physical Layer (Schema Design), Business Model Layer, Presentation Layer."
},
{
"code": null,
"e": 27747,
"s": 27674,
"text": "Following are the common steps involved in creating the Physical Layer −"
},
{
"code": null,
"e": 27808,
"s": 27747,
"text": "Create physical joins between the Dimension and Fact tables."
},
{
"code": null,
"e": 27860,
"s": 27808,
"text": "Change the names in the physical layer if required."
},
{
"code": null,
"e": 28048,
"s": 27860,
"text": "The physical layer of repository contains information about the data sources. To create the schema in the physical layer you need to import metadata from databases and other data sources."
},
{
"code": null,
"e": 28207,
"s": 28048,
"text": "Note − Physical layer in OBIEE supports multiple data sources in a single repository - i.e. data sets from 2 different data sources can be performed in OBIEE."
},
{
"code": null,
"e": 28328,
"s": 28207,
"text": "Go to Start → Programs → Oracle Business Intelligence → BI Administration → Administration Tool → File → New Repository."
},
{
"code": null,
"e": 28521,
"s": 28328,
"text": "A new window will open → Enter the name of Repository → Location (It tells the default location of Repository directory) → to import metadata select radio button → Enter Password → Click Next."
},
{
"code": null,
"e": 28640,
"s": 28521,
"text": "Select the connection type → Enter Data Source name and User name and password to connect to data source → Click Next."
},
{
"code": null,
"e": 28784,
"s": 28640,
"text": "Accept the meta types you want to import → You can select Tables, Keys, Foreign Keys, System tables, Synonyms, Alias, Views, etc. → Click Next."
},
{
"code": null,
"e": 28970,
"s": 28784,
"text": "Once you click Next, you will see Data Source view and Repository view. Expand the Schema name and select tables you want to add to Repository using Import Selected button → Click Next."
},
{
"code": null,
"e": 29097,
"s": 28970,
"text": "Connection Pool window opens up → Click OK → Importing window → Finish to open the repository as shown in the following image."
},
{
"code": null,
"e": 29210,
"s": 29097,
"text": "Expand the Data Source → Schema name to see the list of tables Imported in Physical Layer in the new Repository."
},
{
"code": null,
"e": 29403,
"s": 29210,
"text": "Go to tools → Update all rows counts → Once it is completed you can move the cursor on the table and also for individual columns. To see Data of a table, right-click on Table name → View Data."
},
{
"code": null,
"e": 29562,
"s": 29403,
"text": "It is advisable that you use table aliases frequently in the Physical layer to eliminate extra joins. Right-click on table name and select New Object → Alias."
},
{
"code": null,
"e": 29659,
"s": 29562,
"text": "Once you create an Alias of a table it shows up under the same Physical Layer in the Repository."
},
{
"code": null,
"e": 29910,
"s": 29659,
"text": "When you create a repository in OBIEE system, physical join is commonly used in the Physical layer. Physical joins help to understand how two tables should be joined to each other. Physical joins are normally expressed with the use of Equal operator."
},
{
"code": null,
"e": 30418,
"s": 29910,
"text": "You can also use a physical join in BMM layer, however, it is very rarely seen. The purpose of using a physical join in BMM layer is to override the physical join in the physical layer. It allows users to define more complex joining logic as compared to physical join in the physical layer so it works similar to complex join in the physical layer. Therefore, if we are using a complex join in the physical layer for applying more join conditions, there is no need to use a physical join in BMM layer again."
},
{
"code": null,
"e": 30620,
"s": 30418,
"text": "In the above snapshot, you can see a physical join between two table names − Products and Sales. Physical Join expression tells how the tables should be joined with each other as shown in the snapshot."
},
{
"code": null,
"e": 30869,
"s": 30620,
"text": "It is always recommended to use a physical join in the physical layer and complex join in BMM layer as much as possible to keep Repository design simple. Only when there is an actual need for a different join, then use a physical join in BMM layer."
},
{
"code": null,
"e": 31080,
"s": 30869,
"text": "Now to join tables while designing Repository, select all the tables in the Physical layer → Right-click → Physical diagram → Selected objects only option or you can also use Physical Diagram button at the top."
},
{
"code": null,
"e": 31250,
"s": 31080,
"text": "Physical Diagram box as shown in the following image appears with all the table names added. Select the new foreign key at the top and select Dim and Fact table to join."
},
{
"code": null,
"e": 31464,
"s": 31250,
"text": "A Foreign key in the physical layer is used to define Primary key-Foreign key relation between two tables. When you create it in the physical diagram, you have to point first the dimension and then the fact table."
},
{
"code": null,
"e": 31726,
"s": 31464,
"text": "Note − When you import tables from schema into RPD Physical Layer, you can also select KEY and FOREIGN KEY along with the table data, then the primary key-foreign key joins are automatically defined, however it is not recommended from performance point of view."
},
{
"code": null,
"e": 32034,
"s": 31726,
"text": "The table you click first, it creates one-to-one or one-to-many relationship that joins column in first table with foreign key column in the second table → Click Ok. The join will be visible in Physical Diagram box between two tables. Once tables are joined, close the Physical diagram box using ‘X’ option."
},
{
"code": null,
"e": 32116,
"s": 32034,
"text": "To save the new Repository go to File → Save or click the save button at the top."
},
{
"code": null,
"e": 32336,
"s": 32116,
"text": "It defines the business or logical model of objects and their mapping between business model and Schema in the physical layer. It simplifies the Physical Schema and maps the user business requirement to physical tables."
},
{
"code": null,
"e": 32593,
"s": 32336,
"text": "The Business Model and Mapping layer of OBIEE system administration tool can contain one or more business model objects. A business model object defines the business model definitions and the mappings from logical to physical tables for the business model."
},
{
"code": null,
"e": 32681,
"s": 32593,
"text": "Following are the steps to build the Business Model and Mapping layer of a repository −"
},
{
"code": null,
"e": 32705,
"s": 32681,
"text": "Create a business model"
},
{
"code": null,
"e": 32727,
"s": 32705,
"text": "Examine logical joins"
},
{
"code": null,
"e": 32751,
"s": 32727,
"text": "Examine logical columns"
},
{
"code": null,
"e": 32781,
"s": 32751,
"text": "Examine logical table sources"
},
{
"code": null,
"e": 32819,
"s": 32781,
"text": "Rename logical table objects manually"
},
{
"code": null,
"e": 32913,
"s": 32819,
"text": "Rename logical table objects using the rename wizard and deleting unnecessary logical objects"
},
{
"code": null,
"e": 32946,
"s": 32913,
"text": "Creating measures (Aggregations)"
},
{
"code": null,
"e": 33016,
"s": 32946,
"text": "Right-click on Business Model and Mapping Space → New Business Model."
},
{
"code": null,
"e": 33061,
"s": 33016,
"text": "Enter the name of Business Model → click OK."
},
{
"code": null,
"e": 33298,
"s": 33061,
"text": "In the physical layer, select all the tables/alias tables to be added to Business Model and drag to Business Model. You can also add tables one by one. If you drag all the tables simultaneously, it will keep keys and joins between them."
},
{
"code": null,
"e": 33418,
"s": 33298,
"text": "Also note the difference in icon of Dimension and Fact tables. Last table is Fact table and top 3 are dimension tables."
},
{
"code": null,
"e": 33635,
"s": 33418,
"text": "Now right-click on Business model → select Business Model diagram → Whole diagram → All tables are dragged simultaneously so it will keep all joins and keys. Now double click on any join to open the logical join box."
},
{
"code": null,
"e": 34002,
"s": 33635,
"text": "Joins in this layer are logical joins. It doesn’t show expressions and tells the type of join between tables. It helps Oracle BI server to understand the relationships between the various pieces of the business model. When you send a query to Oracle BI server, the server determines how to construct physical queries by examining how the logical model is structured."
},
{
"code": null,
"e": 34060,
"s": 34002,
"text": "Click Ok → Click ‘X’ to close the Business model diagram."
},
{
"code": null,
"e": 34382,
"s": 34060,
"text": "To examine logical columns and logical table sources, first expand the columns under tables in BMM. Logical columns were created for each table when you dragged all tables from the physical layer. To check logical table sources → Expand the source folder under each table and it points to the table in the physical layer."
},
{
"code": null,
"e": 34624,
"s": 34382,
"text": "Double-click the logical table source (not the logical table) to open the logical table source dialog box → General tab → rename the logical table source. Logical table to physical table mapping is defined under \"Map to these tables\" option."
},
{
"code": null,
"e": 34772,
"s": 34624,
"text": "Next, Column mapping tab defines the logical column to physical column mappings. If mappings are not shown, check the option → Show mapped columns."
},
{
"code": null,
"e": 34864,
"s": 34772,
"text": "There is no specific explicit complex join like in OBIEE 11g. It only exists in Oracle 10g."
},
{
"code": null,
"e": 34917,
"s": 34864,
"text": "Go to Manage → Joins → Actions → New → Complex Join."
},
{
"code": null,
"e": 35125,
"s": 34917,
"text": "When complex joins are used in the BMM layer, they act as placeholders. They allow the OBI Server to decide on which are the best joins between fact and dimension logical table source to satisfy the request."
},
{
"code": null,
"e": 35309,
"s": 35125,
"text": "To rename logical table objects manually, click the column name under the Logical table in BMM. You can also right-click on column name and select option rename, to rename the object."
},
{
"code": null,
"e": 35359,
"s": 35309,
"text": "This is known as manual method to rename objects."
},
{
"code": null,
"e": 35436,
"s": 35359,
"text": "Go to Tools → Utilities → Rename Wizard → Execute to open the rename wizard."
},
{
"code": null,
"e": 35587,
"s": 35436,
"text": "In the Select Objects screen, click Business Model and Mapping. It will show Business Model name → Expand Business Model name → Expand logical tables."
},
{
"code": null,
"e": 35757,
"s": 35587,
"text": "Select all the columns under the logical table to rename using the Shift key → Click Add. Similarly, add columns from all other logical Dim and Fact tables → click Next."
},
{
"code": null,
"e": 35985,
"s": 35757,
"text": "It shows all logical columns/tables added to wizard → Click Next to open Rules screen → Add rules from the list to rename like : A;; text lower case and change each occurrence of ‘_’ to space as shown in the following snapshot."
},
{
"code": null,
"e": 36155,
"s": 35985,
"text": "Click Next → finish. Now, if you expand Object names under logical tables in Business model and Objects in the physical layer, objects under BMM are renamed as required."
},
{
"code": null,
"e": 36256,
"s": 36155,
"text": "In the BMM layer, expand Logical tables → select objects to be deleted → right-click → Delete → Yes."
},
{
"code": null,
"e": 36407,
"s": 36256,
"text": "Double-click on the column name in the logical Fact table → Go to Aggregation tab and select the Aggregate function from the dropdown list → Click OK."
},
{
"code": null,
"e": 36542,
"s": 36407,
"text": "Measures represent data that is additive, such as total revenue or total quantity. Click on save option at top to save the repository."
},
{
"code": null,
"e": 36698,
"s": 36542,
"text": "Right-click on Presentation area → New Subject Area → In the General tab enter the name of subject area (Recommended similar to Business Model) → Click OK."
},
{
"code": null,
"e": 36925,
"s": 36698,
"text": "Once subject area is created, right click on subject area → New presentation table → Enter the name of the presentation table → Click OK (Add number of presentation tables equal to number of parameters required in the report)."
},
{
"code": null,
"e": 37220,
"s": 36925,
"text": "Now, to create columns under Presentation tables → Select the objects under logical tables in BMM and drag them to Presentation tables under subject area (Use Ctrl key to select multiple objects for dragging). Repeat the process and add the logical columns to the remaining presentation tables."
},
{
"code": null,
"e": 37327,
"s": 37220,
"text": "You can rename the objects in Presentation tables by a double-click on logical objects under subject area."
},
{
"code": null,
"e": 37425,
"s": 37327,
"text": "In General tab → Deselect the check box Use Logical column name → Edit the name field → Click OK."
},
{
"code": null,
"e": 37535,
"s": 37425,
"text": "Similarly, you can rename all the objects in the Presentation layer without changing their name in BMM layer."
},
{
"code": null,
"e": 37685,
"s": 37535,
"text": "To order the columns in a table, double-click on the table name under Presentation → Columns → Use up and down arrows to change the order → Click OK."
},
{
"code": null,
"e": 37825,
"s": 37685,
"text": "Similarly, you can change objects order in all presentation tables under Presentation area. Go to File → Click Save to save the Repository."
},
{
"code": null,
"e": 37917,
"s": 37825,
"text": "Go to File → Check Global Consistency → You will receive the following message → Click Yes."
},
{
"code": null,
"e": 38054,
"s": 37917,
"text": "Once you click OK → Business model under BMM will change to Green → Click save the repository without checking global consistency again."
},
{
"code": null,
"e": 38133,
"s": 38054,
"text": "To improve query performance, it is advised to disable BI server cache option."
},
{
"code": null,
"e": 38260,
"s": 38133,
"text": "Open a browser and enter the following URL to open Fusion Middleware Control Enterprise Manager: http://<machine name>:7001/em"
},
{
"code": null,
"e": 38310,
"s": 38260,
"text": "Enter the user name and password and click Login."
},
{
"code": null,
"e": 38416,
"s": 38310,
"text": "On the left side, expand Business Intelligence → coreapplication → Capacity Management tab → Performance."
},
{
"code": null,
"e": 38520,
"s": 38416,
"text": "Enable BI Server Cache section is by default checked → Click Lock and Edit Configuration → Click Close."
},
{
"code": null,
"e": 38649,
"s": 38520,
"text": "Now deselect cache enabled option → It is used to improve query performance → Apply → Activate Changes → Completed Successfully."
},
{
"code": null,
"e": 38739,
"s": 38649,
"text": "Go to Deployment tab → Repository → Lock and Edit Configuration → Completed Successfully."
},
{
"code": null,
"e": 38933,
"s": 38739,
"text": "Click Upload BI Server Repository section → Browse to open the Choose file dialog box → Select the Repository .rpd file and click on Open → Enter Repository password → Apply → Activate Changes."
},
{
"code": null,
"e": 39056,
"s": 38933,
"text": "Activate Changes → Completed Successfully → Click Restart to apply recent changes option on top of the screen → Click Yes."
},
{
"code": null,
"e": 39122,
"s": 39056,
"text": "Repository is successfully created and loaded for query Analysis."
},
{
"code": null,
"e": 39354,
"s": 39122,
"text": "Business Layer defines the business or logical model of objects and their mapping between business model and Schema in the physical layer. It simplifies the Physical Schema and maps the user business requirement to physical tables."
},
{
"code": null,
"e": 39611,
"s": 39354,
"text": "The business model and mapping layer of OBIEE system administration tool can contain one or more business model objects. A business model object defines the business model definitions and the mappings from logical to physical tables for the business model."
},
{
"code": null,
"e": 39880,
"s": 39611,
"text": "The business model is used to simplify the schema structure and maps the users’ business requirement to physical data source. It involves creation of logical tables and columns in the business model. Each logical table can have one or more physical objects as sources."
},
{
"code": null,
"e": 40103,
"s": 39880,
"text": "There are two categories of logical tables − fact and dimension. Logical fact tables contain the measures on which analysis is done and Logical dimension tables contain the information about measures and objects in Schema."
},
{
"code": null,
"e": 40329,
"s": 40103,
"text": "While creating a new repository using OBIEE administration tool, once you define the physical layer, create joins and identify foreign keys. The next step is to create a business model and mapping BMM layer of the repository."
},
{
"code": null,
"e": 40373,
"s": 40329,
"text": "Steps involved in defining Business Layer −"
},
{
"code": null,
"e": 40397,
"s": 40373,
"text": "Create a business model"
},
{
"code": null,
"e": 40419,
"s": 40397,
"text": "Examine logical joins"
},
{
"code": null,
"e": 40443,
"s": 40419,
"text": "Examine logical columns"
},
{
"code": null,
"e": 40473,
"s": 40443,
"text": "Examine logical table sources"
},
{
"code": null,
"e": 40511,
"s": 40473,
"text": "Rename logical table objects manually"
},
{
"code": null,
"e": 40602,
"s": 40511,
"text": "Rename logical table objects using the rename wizard and delete unnecessary logical object"
},
{
"code": null,
"e": 40635,
"s": 40602,
"text": "Creating measures (Aggregations)"
},
{
"code": null,
"e": 40828,
"s": 40635,
"text": "To create a business layer in the repository, right-click → New Business Model → Enter the name of Business Model and click OK. You can also add description of this Business Model if you want."
},
{
"code": null,
"e": 41035,
"s": 40828,
"text": "Logical tables in OBIEE repository exist in the Business Model and Mapping BMM layer. The business model diagram should contain at least two logical tables and you need to define relationships between them."
},
{
"code": null,
"e": 41290,
"s": 41035,
"text": "Each logical table should have one or more logical columns and one or more logical table sources associated with it. You can also change the logical table name, reorder the objects in logical table and define logical joins using primary and foreign keys."
},
{
"code": null,
"e": 41359,
"s": 41290,
"text": "There are two ways of creating logical tables/objects in BMM layer −"
},
{
"code": null,
"e": 41700,
"s": 41359,
"text": "First method is dragging physical tables to Business Model which is the fastest way of defining logical tables. When you drag the tables from the physical layer to BMM layer, it also preserves the joins and keys automatically. If you want you can change the joins and keys in logical tables, it doesn’t affect objects in the physical layer."
},
{
"code": null,
"e": 41844,
"s": 41700,
"text": "Select physical tables/alias tables under the physical layer that you want to add to Business Model Layer and drag those table under BMM layer."
},
{
"code": null,
"e": 41961,
"s": 41844,
"text": "These tables are known as logical tables and columns are called Logical objects in Business Model and Mapping Layer."
},
{
"code": null,
"e": 42158,
"s": 41961,
"text": "Second method is to create a logical table manually. In the Business Model and Mapping layer, right-click the business model → Select New Object → Logical Table → Logical Table dialog box appears."
},
{
"code": null,
"e": 42257,
"s": 42158,
"text": "Go to General tab → Enter name for the logical table → Type a description of the table → Click OK."
},
{
"code": null,
"e": 42386,
"s": 42257,
"text": "Logical columns in BMM layer are automatically created when you drag tables from the physical layer to the business model layer."
},
{
"code": null,
"e": 42626,
"s": 42386,
"text": "If the logical column is a primary key, this column is displayed with the key icon. If the column has an aggregation function, it is displayed with a sigma icon. You can also reorder logical columns in the Business Model and Mapping layer."
},
{
"code": null,
"e": 42766,
"s": 42626,
"text": "In BMM layer, right-click on logical table → select New Object → Logical Column → Logical Column dialog box will appear, click General tab."
},
{
"code": null,
"e": 42929,
"s": 42766,
"text": "Type a name for the logical column. The name of the business model and the logical table appear in the “Belongs to Table” field just below column name → click OK."
},
{
"code": null,
"e": 43068,
"s": 42929,
"text": "You can also apply Aggregations on the logical columns. Click Aggregation tab → Select Aggregation rule from the dropdown list → Click OK."
},
{
"code": null,
"e": 43183,
"s": 43068,
"text": "Once you apply Aggregate function on a column, logical column icon is changed to show Aggregation rule is applied."
},
{
"code": null,
"e": 43236,
"s": 43183,
"text": "You can also move or copy logical column in tables −"
},
{
"code": null,
"e": 43468,
"s": 43236,
"text": "In the BMM layer, you can select multiple columns to move. In the Sources for moved columns dialog box, in the Action area, select an action. If you select Ignore, no logical source will be added in the Sources folder of the table."
},
{
"code": null,
"e": 43719,
"s": 43468,
"text": "If you click on Create new, a copy of the logical source with the logical column will be created in the Sources folder. If you select Use existing option, from the drop-down list, you must select a logical source from the Sources folder of the table."
},
{
"code": null,
"e": 43997,
"s": 43719,
"text": "Logical tables in BMM layer are joined to each other using logical joins. Cardinality is one of the key defining parameter in logical joins. Cardinality relation one-to-many means that each row in first logical dimension table there are 0, 1, many rows in second logical table."
},
{
"code": null,
"e": 44198,
"s": 43997,
"text": "When you drag all the tables of the physical layer to business model layer, logical joins are automatically created in Repository. This condition rarely happens only in case of simple business models."
},
{
"code": null,
"e": 44330,
"s": 44198,
"text": "When logical joins are same as physical joins, they are automatically created. Logical joins in BMM layer are created in two ways −"
},
{
"code": null,
"e": 44398,
"s": 44330,
"text": "Business Model Diagram (already covered while designing repository)"
},
{
"code": null,
"e": 44412,
"s": 44398,
"text": "Joins Manager"
},
{
"code": null,
"e": 44625,
"s": 44412,
"text": "Logical joins in BMM layer cannot be specified using expressions or columns on which to create the join like in the physical layer where expressions and column names are shown on which physical joins are defined."
},
{
"code": null,
"e": 44697,
"s": 44625,
"text": "First let us see how to create logical foreign keys using Join Manager."
},
{
"code": null,
"e": 44840,
"s": 44697,
"text": "In the Administration Tool toolbar, go to Manage → Joins. The Joins Manager dialog box appears → Go to Action tab → New → Logical Foreign Key."
},
{
"code": null,
"e": 45433,
"s": 44840,
"text": "Now in the Browse dialog box, double-click a table → The Logical Foreign Key dialog box appears → Enter the name for the foreign key → From Table drop-down list of the dialog box, select the table that the foreign key references → Select the columns in the left table that the foreign key references → Select the columns in the right table that make up the foreign key columns → Select the join type from the Type drop-down list. To open the Expression Builder, click the button to the right of the Expression pane → The expression displays in the Expression pane → click OK to save the work."
},
{
"code": null,
"e": 45555,
"s": 45433,
"text": "Logical complex joins are recommended in Business Model and mapping layer as compared to the use of logical foreign keys."
},
{
"code": null,
"e": 45697,
"s": 45555,
"text": "In the Administration Tool toolbar, go to Manage → Join → Joins Manager dialog box appears → Go to Action → Click New → Logical Complex Join."
},
{
"code": null,
"e": 45963,
"s": 45697,
"text": "It will open a logical Join dialog box → Type a name for the complex join → In the table drop-down lists on the left and right side of the dialog box, select the tables that the complex join references → Select the join type from the Type drop-down list → Click OK."
},
{
"code": null,
"e": 46251,
"s": 45963,
"text": "Note − You can also define a table as driving table from the drop-down list. This is used for performance optimization when the table size is too large. If the table size is small, less than 1000 rows, it shouldn’t be defined as driving table as it can result in performance degradation."
},
{
"code": null,
"e": 46573,
"s": 46251,
"text": "Logical dimensions exist in BMM and Presentation layer of OBIEE repository. Creating logical dimensions with hierarchies allows you to define aggregation rules that vary with dimensions. It also provides a drill-down option on the charts and tables in analyses and dashboards, and define the content of aggregate sources."
},
{
"code": null,
"e": 46727,
"s": 46573,
"text": "Open the Repository in Offline mode → Go to File → Open → Offline → Select Repository .rpd file and click on open → Enter Repository password → click OK."
},
{
"code": null,
"e": 46788,
"s": 46727,
"text": "Next step is to create logical dimension and logical levels."
},
{
"code": null,
"e": 46968,
"s": 46788,
"text": "Right click on Business model name in BMM layer → New Object → Logical Dimension → Dimension with level-based hierarchy. It will open the dialogue box → Enter the name → click OK."
},
{
"code": null,
"e": 47058,
"s": 46968,
"text": "To create a logical level, right-click on logical dimension → New Object → Logical Level."
},
{
"code": null,
"e": 47112,
"s": 47058,
"text": "Enter the name of logical level example: Product_Name"
},
{
"code": null,
"e": 47252,
"s": 47112,
"text": "If this level is Grand total level, select the checkbox and the system will set number of element at this level to 1 by default → Click OK."
},
{
"code": null,
"e": 47375,
"s": 47252,
"text": "If you want the logical level to roll up to its parent, select the Supports rollup to parent elements checkbox → click OK."
},
{
"code": null,
"e": 47493,
"s": 47375,
"text": "If the logical level is not the grand total level and does not roll up, do not select any of the checkbox → Click OK."
},
{
"code": null,
"e": 47579,
"s": 47493,
"text": "You can also add parent-child hierarchies in logical level by following these steps −"
},
{
"code": null,
"e": 47693,
"s": 47579,
"text": "To define child logical levels, click Add in the Browse dialog box, select the child logical levels and click OK."
},
{
"code": null,
"e": 47763,
"s": 47693,
"text": "You can also right-click on logical level → New Object → Child level."
},
{
"code": null,
"e": 47955,
"s": 47763,
"text": "Enter the name of child level → Ok. You can repeat this to add multiple child levels for all logical columns as per requirement. You can also add Time and Region hierarchies in a similar way."
},
{
"code": null,
"e": 48205,
"s": 47955,
"text": "Now to add logical columns of a table to logical level → select logical column in BMM layer and drag it to logical level child name to which you want to map. Similarly you can drag all the columns of logical table to create parent-child hierarchies."
},
{
"code": null,
"e": 48434,
"s": 48205,
"text": "When you create a child level, it can be checked by a double-click on the logical level and it is displayed under child levels list of that level. You can add or delete child levels by using ‘+’ or ‘X’ option on top of this box."
},
{
"code": null,
"e": 48582,
"s": 48434,
"text": "Double-click on the column name in logical Fact table → Go to Aggregation tab and select the Aggregate function from the drop-down list → Click OK."
},
{
"code": null,
"e": 48722,
"s": 48582,
"text": "Measures represents data that is additive, such as total revenue or total quantity. Click on save option at the top to save the repository."
},
{
"code": null,
"e": 48818,
"s": 48722,
"text": "There are various Aggregate functions that can be used like Sum, Average, Count, Max, Min, etc."
},
{
"code": null,
"e": 49004,
"s": 48818,
"text": "Presentation layer is used to provide customized views of Business model in BMM layer to users. Subject areas are used in Presentation layer provided by Oracle BI Presentation Services."
},
{
"code": null,
"e": 49224,
"s": 49004,
"text": "There are various ways you can create subject areas in Presentation layer. Most common and simple method is by dragging Business Model in BMM layer to Presentation Layer and then making changes to it as per requirement."
},
{
"code": null,
"e": 49398,
"s": 49224,
"text": "You can move columns, remove or add columns in presentation layer so it allows you to make changes in a way that the user shouldn’t see columns that has no meaning for them."
},
{
"code": null,
"e": 49489,
"s": 49398,
"text": "Create Subject Areas/Presentation Catalogues and Presentation Tables in Presentation Layer"
},
{
"code": null,
"e": 49641,
"s": 49489,
"text": "Right-click on Presentation area → New Subject Area → In General tab enter the name of subject area (Recommended similar to Business Model) → Click OK."
},
{
"code": null,
"e": 49870,
"s": 49641,
"text": "Once Subject area is created, right click on subject area → New Presentation table → in General tab, Enter name of presentation table → OK (Add number of presentation tables equal to number of parameters required in the report)."
},
{
"code": null,
"e": 49983,
"s": 49870,
"text": "Click the Permissions tab → Permissions dialog box, where you can assign user or group permissions to the table."
},
{
"code": null,
"e": 50173,
"s": 49983,
"text": "In the Presentation layer, right-click on subject Area → Presentation Catalog dialog box, click the Presentation Tables tab → Go to Presentation Tables tab, select a table and click Remove."
},
{
"code": null,
"e": 50288,
"s": 50173,
"text": "A confirmation message appears → Click Yes to remove the table or No to leave the table in the catalog → Click OK."
},
{
"code": null,
"e": 50519,
"s": 50288,
"text": "Go to Presentation Tables tab by a right-click on Subject Area → In the Name list, select the table you want to reorder → Use drag-and-drop to reposition the table or you can also use the Up and Down buttons to reorder the tables."
},
{
"code": null,
"e": 50789,
"s": 50519,
"text": "The name of presentation columns are normally same to the logical column names in the Business Model and Mapping layer. However, you can also enter a different name by unchecking Use Logical Column Name and the Display Custom Name in the Presentation Column dialog box."
},
{
"code": null,
"e": 50914,
"s": 50789,
"text": "The most simple way to create columns under Presentation tables is by dragging the columns from logical tables in BMM layer."
},
{
"code": null,
"e": 51158,
"s": 50914,
"text": "Select the objects under logical tables in BMM and drag them to Presentation tables under subject area (Use Ctrl key to select multiple objects for dragging). Repeat the process and add the logical columns to the remaining presentation tables."
},
{
"code": null,
"e": 51193,
"s": 51158,
"text": "Create a New Presentation Column −"
},
{
"code": null,
"e": 51280,
"s": 51193,
"text": "Right-click on Presentation table in the Presentation layer → New Presentation Column."
},
{
"code": null,
"e": 51399,
"s": 51280,
"text": "Presentation Column dialog box appears. To use the name of the logical column, select the Use Logical Column checkbox."
},
{
"code": null,
"e": 51520,
"s": 51399,
"text": "To specify a name that is different name, uncheck the Use Logical Column check box, and then type a name for the column."
},
{
"code": null,
"e": 51653,
"s": 51520,
"text": "To assign user or group permissions to the column, click Permissions → In the Permissions dialog box, assign permissions → click OK."
},
{
"code": null,
"e": 51852,
"s": 51653,
"text": "Right-click on presentation table in the Presentation layer → Click on Properties → Click on the Columns tab → Select the column you want to delete → Click Remove or press the Delete key →Click Yes."
},
{
"code": null,
"e": 52068,
"s": 51852,
"text": "Right-click on presentation table in the Presentation layer → Go to Properties → Click the Columns tab → Select the column you want to reorder → Use drag-and-drop or you can also click Up and Down button → Click OK."
},
{
"code": null,
"e": 52311,
"s": 52068,
"text": "You can check the repository for errors by using the consistency checking option. Once it is done, next step is to load the repository into Oracle BI Server. Then test the repository by running an Oracle BI analysis and verifying the results."
},
{
"code": null,
"e": 52412,
"s": 52311,
"text": "Go to File → click on Check Global Consistency → You will receive the following message → Click Yes."
},
{
"code": null,
"e": 52552,
"s": 52412,
"text": "Once you click OK → Business model under BMM will change to Green → Click on save the repository without checking global consistency again."
},
{
"code": null,
"e": 52631,
"s": 52552,
"text": "To improve query performance, it is advised to disable BI server cache option."
},
{
"code": null,
"e": 52758,
"s": 52631,
"text": "Open a browser and enter the following URL to open Fusion Middleware Control Enterprise Manager: http://<machine name>:7001/em"
},
{
"code": null,
"e": 52805,
"s": 52758,
"text": "Enter the user name and password. Click Login."
},
{
"code": null,
"e": 52911,
"s": 52805,
"text": "On the left side, expand Business Intelligence → coreapplication → Capacity Management tab → Performance."
},
{
"code": null,
"e": 53012,
"s": 52911,
"text": "Enable BI Server Cache section is by default checked → Click on Lock and Edit Configuration → Close."
},
{
"code": null,
"e": 53145,
"s": 53012,
"text": "Now deselect cache enabled option. It is used to improve query performance. Go to Apply → Activate Changes → Completed Successfully."
},
{
"code": null,
"e": 53235,
"s": 53145,
"text": "Go to Deployment tab → Repository → Lock and Edit Configuration → Completed Successfully."
},
{
"code": null,
"e": 53429,
"s": 53235,
"text": "Click on Upload BI Server Repository section → Browse to open the Choose file dialog box → select the Repository .rpd file and click Open → Enter Repository password → Apply → Activate Changes."
},
{
"code": null,
"e": 53545,
"s": 53429,
"text": "Activate Changes → Completed Successfully → Click on Restart to apply recent changes option at the top → Click Yes."
},
{
"code": null,
"e": 53611,
"s": 53545,
"text": "Repository is successfully created and loaded for query analysis."
},
{
"code": null,
"e": 53752,
"s": 53611,
"text": "You can set up query logging level for individual users in OBIEE. Logging level controls the information that you will retrieve in log file."
},
{
"code": null,
"e": 53811,
"s": 53752,
"text": "Open the Administration tool → Go to File → Open → Online."
},
{
"code": null,
"e": 53953,
"s": 53811,
"text": "Online mode is used to edit the repository in Oracle BI server. To open a repository in online mode, your Oracle BI server should be running."
},
{
"code": null,
"e": 54054,
"s": 53953,
"text": "Enter the Repository password and user name password to login and click Open to open the repository."
},
{
"code": null,
"e": 54223,
"s": 54054,
"text": "Go to Manage → Identity → Security Manager Window will open. Click BI Repository on the left side and double-click on Administrative user → User dialogue box will open."
},
{
"code": null,
"e": 54293,
"s": 54223,
"text": "Click User tab in user dialogue box, you can set logging levels here."
},
{
"code": null,
"e": 54546,
"s": 54293,
"text": "In normal scenario − The user has a logging level set to 0 and the administrator has a logging level set to 2. Logging level can have values starting from Level 0 to level 5. Level 0 means no logging and Level 5 means maximum logging level information."
},
{
"code": null,
"e": 54604,
"s": 54546,
"text": "Logs the SQL statement issued from the client application"
},
{
"code": null,
"e": 54720,
"s": 54604,
"text": "Logs elapsed times for query compilation, query execution, query cache processing, and back-end database processing"
},
{
"code": null,
"e": 54848,
"s": 54720,
"text": "Logs the query status (success, failure, termination, or timeout). Logs the users ID, session ID, and request ID for each query"
},
{
"code": null,
"e": 54882,
"s": 54848,
"text": "Logs everything logged in Level 1"
},
{
"code": null,
"e": 55276,
"s": 54882,
"text": "Additionally, for each query, logs the repository name, business model name, presentation catalog (called Subject Area in Answer) name, SQL for the queries issued against physical databases, queries issued against the cache, number of rows returned from each query against a physical database and from queries issued against the cache, and the number of rows returned to the client application"
},
{
"code": null,
"e": 55310,
"s": 55276,
"text": "Logs everything logged in Level 2"
},
{
"code": null,
"e": 55593,
"s": 55312,
"text": "Additionally, adds a log entry for the logical query plan, when a query that was supposed to seed the cache was not inserted into the cache, when existing cache entries are purged to make room for the current query, and when the attempt to udate the exact match hit detector fails"
},
{
"code": null,
"e": 55627,
"s": 55593,
"text": "Logs everything logged in Level 3"
},
{
"code": null,
"e": 55672,
"s": 55627,
"text": "Additionally, logs the query execution plan."
},
{
"code": null,
"e": 55706,
"s": 55672,
"text": "Logs everything logged in Level 4"
},
{
"code": null,
"e": 55790,
"s": 55706,
"text": "Additionally, logs intermediate row counts at various points in the execution plan."
},
{
"code": null,
"e": 55843,
"s": 55790,
"text": "In user dialogue box, enter value for logging level."
},
{
"code": null,
"e": 55946,
"s": 55843,
"text": "Once you click OK, it will open the checkout dialogue box. Click Checkout. Close the Security Manager."
},
{
"code": null,
"e": 56080,
"s": 55946,
"text": "Go to file → Click on check-in changes → Save the repository using the Save option at the top → To take changes in effect → Click OK."
},
{
"code": null,
"e": 56209,
"s": 56080,
"text": "You can check query logs once query logging level is set by going to Oracle Enterprise Manager and this helps to verify queries."
},
{
"code": null,
"e": 56289,
"s": 56209,
"text": "To check the query logs to verify queries, go to Oracle Enterprise Manager OEM."
},
{
"code": null,
"e": 56332,
"s": 56289,
"text": "Go to diagnostic tab → click Log messages."
},
{
"code": null,
"e": 56481,
"s": 56332,
"text": "Scroll down to bottom in log messages to see Server, Scheduler, Action Services and other log details. Click on Server log to open log messages box."
},
{
"code": null,
"e": 56624,
"s": 56481,
"text": "You can select various filters − Date Range, Message types and message contains/not contains fields, etc. as shown in the following snapshot −"
},
{
"code": null,
"e": 56692,
"s": 56624,
"text": "Once you click on search, it will show log messages as per filters."
},
{
"code": null,
"e": 56781,
"s": 56692,
"text": "Clicking on collapse button allows you to check details of all log messages for queries."
},
{
"code": null,
"e": 56994,
"s": 56781,
"text": "When you drag and drop a column from a physical table that is not currently being used in your logical table in BMM layer, the physical table containing such column gets added as a new Logical Table Source (LTS)."
},
{
"code": null,
"e": 57213,
"s": 56994,
"text": "When in BMM layer, you use more than one table as source table, it is called multiple logical table sources. You can have a Fact table as multiple logical table sources when it uses different physical tables as source."
},
{
"code": null,
"e": 57221,
"s": 57213,
"text": "Example"
},
{
"code": null,
"e": 57302,
"s": 57221,
"text": "Multiple LTS are used to convert Snowflakes schema to Star schemas in BMM layer."
},
{
"code": null,
"e": 57417,
"s": 57302,
"text": "Let us say you have two dimensions − Dim_Emp and Dim_Dept and one fact table FCT_Attendance in the Physical layer."
},
{
"code": null,
"e": 57546,
"s": 57417,
"text": "Here your Dim_Emp is normalized to Dim_Dept to implement Snowflakes schema. So in your Physical diagram, it would be like this −"
},
{
"code": null,
"e": 57593,
"s": 57546,
"text": "Dim_Dept<------Dim_Emp <-------FCT_Attendance\n"
},
{
"code": null,
"e": 57773,
"s": 57593,
"text": "When we move these table to the BMM layer, we will create a single dimension table Dim_Employee with 2 logical sources corresponding to Dim_Emp and Dim_Dept. In your BMM diagram −"
},
{
"code": null,
"e": 57814,
"s": 57773,
"text": "Dim_Employee <-----------FCT_Attendance\n"
},
{
"code": null,
"e": 57891,
"s": 57814,
"text": "This is one approach where you can use concept of multiple LTS in BMM layer."
},
{
"code": null,
"e": 58059,
"s": 57891,
"text": "When you use multiple physical tables as sources, you expand table sources in BMM diagram. It shows all multiple LTS from where it is picking up the data in BMM layer."
},
{
"code": null,
"e": 58279,
"s": 58059,
"text": "To see table mapping in BMM layer, expand the sources under logical table in BMM layer. It will open Logical table source mapping dialogue box. You can check all tables which are mapped to provide data in logical table."
},
{
"code": null,
"e": 58447,
"s": 58279,
"text": "Calculated measures is used to perform calculation of facts in logical tables. It defines Aggregation functions in Aggregation tab of logical column in the repository."
},
{
"code": null,
"e": 58581,
"s": 58447,
"text": "Measures are defined in logical fact tables in repository. Any column with an aggregation function applied on it is called a measure."
},
{
"code": null,
"e": 58643,
"s": 58581,
"text": "Common measure examples are − Unit Price, quantity sold, etc."
},
{
"code": null,
"e": 58702,
"s": 58643,
"text": "Following are the guidelines to create measures in OBIEE −"
},
{
"code": null,
"e": 58804,
"s": 58702,
"text": "All aggregation should be performed from a fact logical table and not from a dimension logical table."
},
{
"code": null,
"e": 58906,
"s": 58804,
"text": "All aggregation should be performed from a fact logical table and not from a dimension logical table."
},
{
"code": null,
"e": 59026,
"s": 58906,
"text": "All columns that cannot be aggregated should be expressed in a dimension logical table and not in a fact logical table."
},
{
"code": null,
"e": 59146,
"s": 59026,
"text": "All columns that cannot be aggregated should be expressed in a dimension logical table and not in a fact logical table."
},
{
"code": null,
"e": 59249,
"s": 59146,
"text": "Calculated measures can be defined in two ways in logical tables at BMM layer in Administration tool −"
},
{
"code": null,
"e": 59281,
"s": 59249,
"text": "Aggregations in logical tables."
},
{
"code": null,
"e": 59319,
"s": 59281,
"text": "Aggregations in logical table source."
},
{
"code": null,
"e": 59417,
"s": 59319,
"text": "Double-click on the column name in the logical Fact table, you will see the following dialog box."
},
{
"code": null,
"e": 59509,
"s": 59417,
"text": "Go to Aggregation tab and select the Aggregate function from the drop-down list → Click OK."
},
{
"code": null,
"e": 59796,
"s": 59509,
"text": "You can add new measures using functions in Expression builder wizard in Column source. Measures represent data that is additive, such as total revenue or total quantity. Click on the save option at the top to save the repository. This is also called creating measures at logical level."
},
{
"code": null,
"e": 59902,
"s": 59796,
"text": "You can define Aggregations by a double-click on Logical table source to open logical table dialogue box."
},
{
"code": null,
"e": 59959,
"s": 59902,
"text": "Click on Expression builder wizard to define expression."
},
{
"code": null,
"e": 60070,
"s": 59959,
"text": "In Expression builder, you can choose multiple options like - Category, functions, and mathematical functions."
},
{
"code": null,
"e": 60234,
"s": 60070,
"text": "Once you select the category, it will show the subcategories inside it. Select the subcategory and mathematical function, and click on the arrow mark to insert it."
},
{
"code": null,
"e": 60471,
"s": 60234,
"text": "Now to edit the value to create measures, click on source number, enter the calculated value like multiple and divide → Go to Category and select logical table → Select column to apply this multiple/division to an existing column value."
},
{
"code": null,
"e": 60553,
"s": 60471,
"text": "Click OK to close the Expression builder. Again click OK to close the dialog box."
},
{
"code": null,
"e": 60763,
"s": 60553,
"text": "Hierarchies is a series of many-to-one relationships and can be of different levels. A Region hierarchy consists of: Region → Country → State → City → Street. Hierarchies follow top-down or bottom-up approach."
},
{
"code": null,
"e": 60900,
"s": 60763,
"text": "Logical dimensions or dimension hierarchies are created in BMM layer. There are two types of dimensional hierarchies that are possible −"
},
{
"code": null,
"e": 60941,
"s": 60900,
"text": "Dimensions with level-based hierarchies."
},
{
"code": null,
"e": 60982,
"s": 60941,
"text": "Dimension with Parent-Child hierarchies."
},
{
"code": null,
"e": 61100,
"s": 60982,
"text": "In level-based hierarchies, members can be of different types and members of the same type come only at single level."
},
{
"code": null,
"e": 61163,
"s": 61100,
"text": "In Parent-Child hierarchies, all members are of the same type."
},
{
"code": null,
"e": 61370,
"s": 61163,
"text": "Level-based dimension hierarchies can also contain parent-child relationships. The common sequence to create level-based hierarchies is to start with grand total level and then working down to lower levels."
},
{
"code": null,
"e": 61418,
"s": 61370,
"text": "Level-based hierarchies allows you to perform −"
},
{
"code": null,
"e": 61451,
"s": 61418,
"text": "Level-based calculated measures."
},
{
"code": null,
"e": 61473,
"s": 61451,
"text": "Aggregate navigation."
},
{
"code": null,
"e": 61514,
"s": 61473,
"text": "Drill down to child level in dashboards."
},
{
"code": null,
"e": 61739,
"s": 61514,
"text": "Each dimension can only have one grand total level and it doesn’t have a level key or dimension attributes. You can associate measures with grand total level and default aggregation for these measures are grand total always."
},
{
"code": null,
"e": 61926,
"s": 61739,
"text": "All lower levels should have at least one column and each dimension contains one or more hierarchies. Each lower level also contains a level key which defines unique value at that level."
},
{
"code": null,
"e": 62013,
"s": 61926,
"text": "Unbalanced hierarchies are those where all the lower levels don’t have the same depth."
},
{
"code": null,
"e": 62145,
"s": 62013,
"text": "Example − For one product, for one month you can have data for weeks and for other month you can have data available for day level."
},
{
"code": null,
"e": 62219,
"s": 62145,
"text": "In skip-level hierarchies, few members don’t have values at higher level."
},
{
"code": null,
"e": 62371,
"s": 62219,
"text": "Example − For one city, you have state → country → Region. However for other city, you have only state and it doesn’t fall under any country or region."
},
{
"code": null,
"e": 62682,
"s": 62371,
"text": "In parent-child hierarchy, all the members are of the same type. The most common example of parent-child hierarchy is the reporting structure in an organization. Parent-child hierarchy is based on a single logical table. Each row contains two keys – one for the member and another for the parent of the member."
},
{
"code": null,
"e": 62898,
"s": 62682,
"text": "Level-based measures are created to perform calculation at a specific level of aggregation. They allow to return data at multiple levels of aggregation with one single query. It also allows to create share measures."
},
{
"code": null,
"e": 62906,
"s": 62898,
"text": "Example"
},
{
"code": null,
"e": 63210,
"s": 62906,
"text": "Let us say there is a company XYZ Electronics which sells its products in many regions, countries and cities. Now the company President wants to see the total revenue at country level - one level below region and one level above cities. So total revenue measure should be summed up to the country level."
},
{
"code": null,
"e": 63337,
"s": 63210,
"text": "These type of measures are called level-based measures. Similarly, you can apply level-based measures on the time hierarchies."
},
{
"code": null,
"e": 63526,
"s": 63337,
"text": "Once the dimension hierarchies are created, level-based measures can be created by double clicking on the total revenue column in the logical table and setting the level in the levels tab."
},
{
"code": null,
"e": 63592,
"s": 63526,
"text": "Open the repository in offline mode. Go to File → Open → Offline."
},
{
"code": null,
"e": 63666,
"s": 63592,
"text": "Select .rpd file and click open → Enter repository password and click Ok."
},
{
"code": null,
"e": 63747,
"s": 63666,
"text": "In BMM layer, right-click on Total Revenue column → New Object → Logical column."
},
{
"code": null,
"e": 63922,
"s": 63747,
"text": "It will open the logical column dialog box. Enter the name of logical column total revenue. Go to column source tab → Check derived from existing columns using an expression."
},
{
"code": null,
"e": 64116,
"s": 63922,
"text": "Once you select this option, expression edit wizard will be highlighted. In expression builder wizard, select the logical table → Column name → Total revenue from the left side menu → Click OK."
},
{
"code": null,
"e": 64345,
"s": 64116,
"text": "Now go to level tab in logical column dialog box → Click on logical dimension to select it as grand total under logical level. This specifies that the measure should be calculated at grand total level in the dimension hierarchy."
},
{
"code": null,
"e": 64450,
"s": 64345,
"text": "Once you click OK → Total Revenue logical table will appear under the logical dimension and Fact tables."
},
{
"code": null,
"e": 64633,
"s": 64450,
"text": "This column can be dragged to presentation layer in the subject area to be used by end users to generate reports. You can drag this column from fact tables or from logical dimension."
},
{
"code": null,
"e": 64902,
"s": 64633,
"text": "Aggregations are used to implement query performance optimization while running the reports. This eliminates the time taken by query to run the calculations and delivers the results at fast speed. Aggregate tables has less number of rows as compared to a normal table."
},
{
"code": null,
"e": 65112,
"s": 64902,
"text": "When you execute a query in OBIEE, BI server looks for the resources which has information to answer the query. Out of all available sources, the server selects the most aggregated source to answer that query."
},
{
"code": null,
"e": 65207,
"s": 65112,
"text": "Open the Repository in an offline mode in the Administrator tool. Go to File → Open → Offline."
},
{
"code": null,
"e": 65367,
"s": 65207,
"text": "Import the metadata and create logical table source in BMM layer. Expand the table name and click on source table name to open logical table source dialog box."
},
{
"code": null,
"e": 65506,
"s": 65367,
"text": "Go to column mapping tab to see map columns in Physical table. Go to content tab → Aggregate content group by selecting the logical level."
},
{
"code": null,
"e": 65671,
"s": 65506,
"text": "You can select different logical levels as per the columns in fact tables like Product Total, Total Revenue, and Quarter/Year for Time as per dimension hierarchies."
},
{
"code": null,
"e": 65723,
"s": 65671,
"text": "Click OK to close dialog box → save the repository."
},
{
"code": null,
"e": 65819,
"s": 65723,
"text": "When you define Aggregate in logical fact tables they are defined as per dimension hierarchies."
},
{
"code": null,
"e": 65887,
"s": 65819,
"text": "In OBIEE, there are two types of variables that are commonly used −"
},
{
"code": null,
"e": 65908,
"s": 65887,
"text": "Repository variables"
},
{
"code": null,
"e": 65926,
"s": 65908,
"text": "Session variables"
},
{
"code": null,
"e": 65998,
"s": 65926,
"text": "Apart from this you can also define Presentation and Request variables."
},
{
"code": null,
"e": 66216,
"s": 65998,
"text": "A Repository variable has a single value at any point of time. Repository variables are defined using Oracle BI Administration tool. Repository variables can be used in place of constants in Expression Builder Wizard."
},
{
"code": null,
"e": 66262,
"s": 66216,
"text": "There are two types of Repository variables −"
},
{
"code": null,
"e": 66290,
"s": 66262,
"text": "Static repository variables"
},
{
"code": null,
"e": 66319,
"s": 66290,
"text": "Dynamic repository variables"
},
{
"code": null,
"e": 66450,
"s": 66319,
"text": "Static repository variables are defined in variable dialog box and their value exists until they are changed by the administrator."
},
{
"code": null,
"e": 66769,
"s": 66450,
"text": "Static repository variables contain default initializers that are numeric or character values. In addition, you can use Expression Builder to insert a constant as the default initializer, such as date, time, etc. You cannot use any other value or expression as the default initializer for a static repository variable."
},
{
"code": null,
"e": 67070,
"s": 66769,
"text": "In older BI versions, the Administrator tool did not limit value of static repository variables. You may get warning in consistency check if your repository has been upgraded from older versions. In such case, update the static repository variables so that default initializers have a constant value."
},
{
"code": null,
"e": 67462,
"s": 67070,
"text": "Dynamic repository variables are same as static variables but the values are refreshed by data returned from queries. When defining a dynamic repository variable, you create an initialization block or use a preexisting one that contains a SQL query. You can also set up a schedule that the Oracle BI Server will follow to execute the query and refresh the value of the variable periodically."
},
{
"code": null,
"e": 67597,
"s": 67462,
"text": "When the value of a dynamic repository variable changes, all cache entries associated with a business model are deleted automatically."
},
{
"code": null,
"e": 67749,
"s": 67597,
"text": "Each query can refresh several variables: one variable for each column in the query. You schedule these queries to be executed by the Oracle BI server."
},
{
"code": null,
"e": 67987,
"s": 67749,
"text": "Dynamic repository variables are useful for defining the content of logical table sources. For example, suppose you have two sources for information about orders. One source contains current orders and the other contains historical data."
},
{
"code": null,
"e": 68113,
"s": 67987,
"text": "In the Administration Tool → Go to Manage → Select Variables → Variable Manager → Go to Action → New → Repository > Variable."
},
{
"code": null,
"e": 68260,
"s": 68113,
"text": "In the Variable dialog, type a name for the variable (Names for all variables should be unique) → Select the type of variable - Static or Dynamic."
},
{
"code": null,
"e": 68431,
"s": 68260,
"text": "If you select dynamic variable, use the initialization block list to select an existing initialization block that will be used to refresh the value on a continuing basis."
},
{
"code": null,
"e": 68630,
"s": 68431,
"text": "To create a new initialization block → Click New. To add a default initializer value, type the value in the default initializer box, or click the Expression Builder button to use Expression Builder."
},
{
"code": null,
"e": 68982,
"s": 68630,
"text": "For static repository variables, the value you specify in the default initializer window persists. It will not change unless you change it. If you initialize a variable using a character string, enclose the string in single quotes. Static repository variables must have default initializers that are constant values → Click OK to close the dialog box."
},
{
"code": null,
"e": 69217,
"s": 68982,
"text": "Session variables are similar to dynamic repository variables and they obtain their values from initialization blocks. When a user begins a session, the Oracle BI server creates new instances of session variables and initializes them."
},
{
"code": null,
"e": 69400,
"s": 69217,
"text": "There are as many instances of a session variable as there are active sessions on the Oracle BI server. Each instance of a session variable could be initialized to a different value."
},
{
"code": null,
"e": 69443,
"s": 69400,
"text": "There are two types of Session variables −"
},
{
"code": null,
"e": 69468,
"s": 69443,
"text": "System session variables"
},
{
"code": null,
"e": 69497,
"s": 69468,
"text": "Non-system session variables"
},
{
"code": null,
"e": 69667,
"s": 69497,
"text": "System session variables are used by Oracle BI and Presentation server for specific purposes. They have predefined reserved names which can’t be used by other variables."
},
{
"code": null,
"e": 69672,
"s": 69667,
"text": "USER"
},
{
"code": null,
"e": 69681,
"s": 69672,
"text": "USERGUID"
},
{
"code": null,
"e": 69687,
"s": 69681,
"text": "GROUP"
},
{
"code": null,
"e": 69693,
"s": 69687,
"text": "ROLES"
},
{
"code": null,
"e": 69703,
"s": 69693,
"text": "ROLEGUIDS"
},
{
"code": null,
"e": 69715,
"s": 69703,
"text": "PERMISSIONS"
},
{
"code": null,
"e": 69920,
"s": 69715,
"text": "Non-system session variables are used for setting the user filters. Example, you could define a non-system variable called Sale_Region that would be initialized to the name of the sale_region of the user."
},
{
"code": null,
"e": 69982,
"s": 69920,
"text": "In the Administration Tool → Go to Manage → Select Variables."
},
{
"code": null,
"e": 70055,
"s": 69982,
"text": "In the Variable Manager dialog, click Action → New → Session → Variable."
},
{
"code": null,
"e": 70250,
"s": 70055,
"text": "In the Session Variable dialog, enter variable name (Names for all variables should be unique and names of system session variables are reserved and cannot be used for other types of variables)."
},
{
"code": null,
"e": 70312,
"s": 70250,
"text": "For session variables, you can select the following options −"
},
{
"code": null,
"e": 70526,
"s": 70312,
"text": "Enable any user to set the value − This option is used to set session variables after the initialization block has populated the value. Example - this option lets non-administrators set this variable for sampling."
},
{
"code": null,
"e": 70740,
"s": 70526,
"text": "Enable any user to set the value − This option is used to set session variables after the initialization block has populated the value. Example - this option lets non-administrators set this variable for sampling."
},
{
"code": null,
"e": 70917,
"s": 70740,
"text": "Security sensitive − This is used to identify the variable as sensitive to security when using a row-level database security strategy, such as a Virtual Private Database (VPD)."
},
{
"code": null,
"e": 71094,
"s": 70917,
"text": "Security sensitive − This is used to identify the variable as sensitive to security when using a row-level database security strategy, such as a Virtual Private Database (VPD)."
},
{
"code": null,
"e": 71275,
"s": 71094,
"text": "You can use the initialization block list option to choose an initialization block that will be used to refresh the value regularly. You can also create a new initialization block."
},
{
"code": null,
"e": 71458,
"s": 71275,
"text": "To add a default initializer value, enter the value in the default initializer box or click the Expression Builder button to use Expression Builder. Click OK to close the dialog box."
},
{
"code": null,
"e": 71553,
"s": 71458,
"text": "The administrator can create non-system session variables using Oracle BI Administration tool."
},
{
"code": null,
"e": 71684,
"s": 71553,
"text": "Presentation variables are created with creation of Dashboard prompts. There are two types of dashboard prompts that can be used −"
},
{
"code": null,
"e": 71824,
"s": 71684,
"text": "Presentation variable created with column prompt is associated with a column, and the values that it can take comes from the column values."
},
{
"code": null,
"e": 72001,
"s": 71824,
"text": "To create a presentation variable go to New Prompt dialog or Edit Prompt dialog → Select Presentation Variable in the Set of a variable field → Enter the name for the variable."
},
{
"code": null,
"e": 72119,
"s": 72001,
"text": "Presentation variable created as variable prompt is not associated with any column and you need to define its values."
},
{
"code": null,
"e": 72320,
"s": 72119,
"text": "To create a presentation variable as part of a variable prompt, in the New Prompt dialog or Edit Prompt dialog → Select Presentation Variable in the Prompt for field → Enter the name for the variable."
},
{
"code": null,
"e": 72578,
"s": 72320,
"text": "The value of a presentation variable is populated by the column or variable prompt with which it is created. Each time a user selects a value in the column or variable prompt, the value of the presentation variable is set to the value that the user selects."
},
{
"code": null,
"e": 72729,
"s": 72578,
"text": "Initialization blocks are used to initialize OBIEE variables: Dynamic Repository variables, system session variables and non-system session variables."
},
{
"code": null,
"e": 73013,
"s": 72729,
"text": "It contains SQL statement that are executed to initialize or refresh the variables associated with that block. The SQL statement that are executed points to physical tables that can be accessed using the connection pool. Connection pool is defined in the initialization block dialog."
},
{
"code": null,
"e": 73141,
"s": 73013,
"text": "If you want the query for an initialization block to have database-specific SQL, you can select a database type for that query."
},
{
"code": null,
"e": 73526,
"s": 73141,
"text": "Default initiation string field of initialization block is used to set value of dynamic repository variables. You also define a schedule which is followed by Oracle BI server to execute the query and refresh the value of variable. If you set the logging level to 2 or higher, log information for all SQL queries executed to retrieve the value of variable is saved in nqquery.log file."
},
{
"code": null,
"e": 73563,
"s": 73526,
"text": "Location of this file on BI Server −"
},
{
"code": null,
"e": 73642,
"s": 73563,
"text": "ORACLE_INSTANCE\\diagnostics\\logs\\OracleBIServerComponent\\coreapplication_obisn"
},
{
"code": null,
"e": 73856,
"s": 73642,
"text": "Session variables also take their values from initialization block but their value never changes with time intervals. When a user begins a new session, Oracle BI server creates a new instance of session variables."
},
{
"code": null,
"e": 74130,
"s": 73856,
"text": "All SQL queries executed to retrieve session variable information by BI server if the logging level is set to 2 or higher in the Identity Manager User object or the LOGLEVEL system session variable is set to 2 or higher in the Variable Manager is saved in nqquery.log file."
},
{
"code": null,
"e": 74167,
"s": 74130,
"text": "Location of this file on BI Server −"
},
{
"code": null,
"e": 74246,
"s": 74167,
"text": "ORACLE_INSTANCE\\diagnostics\\logs\\OracleBIServerComponent\\coreapplication_obisn"
},
{
"code": null,
"e": 74419,
"s": 74246,
"text": "Go to Manager → Variables → Variable Manager Dialog box appears. Go to Action menu → Click New → Repository → Initialization Block → Enter the name of initialization block."
},
{
"code": null,
"e": 74489,
"s": 74419,
"text": "Go to Schedule tab → Select start date and time and refresh interval."
},
{
"code": null,
"e": 74554,
"s": 74489,
"text": "You can choose the following options for Initialization Blocks −"
},
{
"code": null,
"e": 74845,
"s": 74554,
"text": "Disable − If you select this option, initialization block is disabled. To enable an initialization block, right-click an existing initialization block in the Variable Manager and choose Enable. This option enables you to change this property without opening the initialization block dialog."
},
{
"code": null,
"e": 75136,
"s": 74845,
"text": "Disable − If you select this option, initialization block is disabled. To enable an initialization block, right-click an existing initialization block in the Variable Manager and choose Enable. This option enables you to change this property without opening the initialization block dialog."
},
{
"code": null,
"e": 75318,
"s": 75136,
"text": "Allow deferred execution − This allows you to defer the execution of the initialization block until an associated session variable is accessed for the first time during the session."
},
{
"code": null,
"e": 75500,
"s": 75318,
"text": "Allow deferred execution − This allows you to defer the execution of the initialization block until an associated session variable is accessed for the first time during the session."
},
{
"code": null,
"e": 75687,
"s": 75500,
"text": "Required for authentication − If you select this, initialization block must execute for users to log in. Users are denied access to Oracle BI if the initialization block doesn’t execute."
},
{
"code": null,
"e": 75874,
"s": 75687,
"text": "Required for authentication − If you select this, initialization block must execute for users to log in. Users are denied access to Oracle BI if the initialization block doesn’t execute."
},
{
"code": null,
"e": 76096,
"s": 75874,
"text": "OBIEE dashboard is a tool that enables end users to run ad-hoc reports and analysis as per business requirement model. Interactive dashboards are pixel perfect reports which can be directly viewed or printed by end users."
},
{
"code": null,
"e": 76475,
"s": 76096,
"text": "OBIEE dashboard is part of Oracle BI Presentation layer services. If your end user is not interested in seeing all the data in the dashboard, it allows you to add prompts to the dashboard that allows the end user to enter what he wants to see. Dashboards also allow end users to select from drop-down lists, multi-select boxes and selection of columns to display in the reports."
},
{
"code": null,
"e": 76657,
"s": 76475,
"text": "Oracle BI dashboard allows you to set up alerts for sales executives that comes up on the interactive dashboard whenever the company’s projected sales is going to be below forecast."
},
{
"code": null,
"e": 76779,
"s": 76657,
"text": "To create a new Dashboard, go to New → Dashboard or you can also click on Dashboard option under create on the left side."
},
{
"code": null,
"e": 76956,
"s": 76779,
"text": "Once you click on Dashboard, new dashboard dialog box opens up. Enter the name of Dashboard and description and select the location where you want Dashboard to save → click OK."
},
{
"code": null,
"e": 77138,
"s": 76956,
"text": "If you save the dashboard in the Dashboards subfolder directly under the /Shared Folders/first level subfolder → dashboard will be listed in the Dashboard menu on the global header."
},
{
"code": null,
"e": 77262,
"s": 77138,
"text": "If you save it in a Dashboards subfolder at any other level (such as /Shared Folders/Sales/Eastern), it will not be listed."
},
{
"code": null,
"e": 77468,
"s": 77262,
"text": "If you choose a folder in the Dashboards subfolder directly under the /Shared Folders/first level subfolder in which no dashboards have been saved, a new Dashboards folder is automatically created for you."
},
{
"code": null,
"e": 77569,
"s": 77468,
"text": "Once you enter the above fields, Dashboard builder will open up as shown in the following snapshot −"
},
{
"code": null,
"e": 77687,
"s": 77569,
"text": "Expand the catalog tab, select analysis to add to Dashboard and drag to page layout pane. Save and run the dashboard."
},
{
"code": null,
"e": 77736,
"s": 77687,
"text": "Go to Dashboard → My Dashboard → Edit Dashboard."
},
{
"code": null,
"e": 77799,
"s": 77736,
"text": "To edit Dashboard. Click on below icon → Dashboard properties."
},
{
"code": null,
"e": 77902,
"s": 77799,
"text": "A new dialog box will appear as shown in the following snapshot. You can perform the following tasks −"
},
{
"code": null,
"e": 78153,
"s": 77902,
"text": "Change the styles (Styles control how dashboards and results are formatted for display, such as the color of text and links, the font and size of text, the borders in tables, the colors and attributes of graphs, and so on). You can add a description."
},
{
"code": null,
"e": 78356,
"s": 78153,
"text": "You can add hidden prompts, filters, and variables. Specify the links that will display with analyses on a dashboard page. You can rename, hide, reorder, set permissions for, and delete dashboard pages."
},
{
"code": null,
"e": 78474,
"s": 78356,
"text": "You can also edit Dashboard page properties by selecting page in the dialog box. You can make the following changes −"
},
{
"code": null,
"e": 78522,
"s": 78474,
"text": "You can change the name of your dashboard page."
},
{
"code": null,
"e": 78570,
"s": 78522,
"text": "You can change the name of your dashboard page."
},
{
"code": null,
"e": 78696,
"s": 78570,
"text": "You can add a hidden prompt. Hidden prompts are used to set default values for all corresponding prompts on a dashboard page."
},
{
"code": null,
"e": 78822,
"s": 78696,
"text": "You can add a hidden prompt. Hidden prompts are used to set default values for all corresponding prompts on a dashboard page."
},
{
"code": null,
"e": 78944,
"s": 78822,
"text": "You can add permissions for the dashboard and can also delete the selected page. Dashboard pages are permanently deleted."
},
{
"code": null,
"e": 79066,
"s": 78944,
"text": "You can add permissions for the dashboard and can also delete the selected page. Dashboard pages are permanently deleted."
},
{
"code": null,
"e": 79182,
"s": 79066,
"text": "If more than one dashboard page is in this dashboard, the arrange order icons are enabled using up and down arrows."
},
{
"code": null,
"e": 79298,
"s": 79182,
"text": "If more than one dashboard page is in this dashboard, the arrange order icons are enabled using up and down arrows."
},
{
"code": null,
"e": 79432,
"s": 79298,
"text": "To set the report links at the dashboard level, dashboard page, or analysis level click the edit option of Dashboard reporting links."
},
{
"code": null,
"e": 79539,
"s": 79432,
"text": "To add a dashboard page, click on new Dashboard page icon → Enter the name of dashboard page and click OK."
},
{
"code": null,
"e": 79647,
"s": 79539,
"text": "In Catalog tab, you can add the new another analysis and drag it to page layout area of new dashboard page."
},
{
"code": null,
"e": 79823,
"s": 79647,
"text": "To edit the properties of dashboard like cell width, border, and height, click on column properties. You can set background color, wrap text and additional formatting options."
},
{
"code": null,
"e": 79933,
"s": 79823,
"text": "You can also add a condition on dashboard data display by clicking on condition option in column properties −"
},
{
"code": null,
"e": 80037,
"s": 79933,
"text": "To add a condition, click on + sign in condition dialog box. You can add a condition based on analysis."
},
{
"code": null,
"e": 80098,
"s": 80037,
"text": "Select the condition data and enter the condition parameter."
},
{
"code": null,
"e": 80191,
"s": 80098,
"text": "You can also test, edit or remove the condition by clicking on ‘more’ sign next to + button."
},
{
"code": null,
"e": 80331,
"s": 80191,
"text": "You can save your customized dashboard by going to page options → Save current customizations → Enter the name of customization → Click OK."
},
{
"code": null,
"e": 80447,
"s": 80331,
"text": "To apply customization to a dashboard page, go to page option → Apply saved customization → Select name → Click OK."
},
{
"code": null,
"e": 80727,
"s": 80447,
"text": "It allows you to save and view dashboard pages in their current state such as filters, prompts, column sorts, drills in analyses, and section expansion and collapse. By saving customizations, you do not need to make these choices manually each time you access the dashboard page."
},
{
"code": null,
"e": 80968,
"s": 80727,
"text": "Filters are used to limit the results that are displayed when an analysis is run, so that the results answer a particular question. Based on the filters, only those results are shown that matches the criteria passed in the filter condition."
},
{
"code": null,
"e": 81147,
"s": 80968,
"text": "Filters are applied directly to attribute and measure columns. Filters are applied before the query is aggregated and affect the query and thus the resulting values for measures."
},
{
"code": null,
"e": 81319,
"s": 81147,
"text": "For example, you have a list of members in which the aggregate sums to 100. Over time, more members meet the set filter criteria, which increases the aggregate sum to 200."
},
{
"code": null,
"e": 81362,
"s": 81319,
"text": "Following are the ways to create filters −"
},
{
"code": null,
"e": 81479,
"s": 81362,
"text": "Go to Oracle Business Intelligence homepage → New menu → Select filter. The Select Subject Area dialog is displayed."
},
{
"code": null,
"e": 81740,
"s": 81479,
"text": "From the Select Subject Area dialog, choose the subject area for which you want to create a filter. The \"Filter editor\" is displayed from the \"Subject Areas pane\". Double-click the column for which you want to create the filter. New Filter dialog is displayed."
},
{
"code": null,
"e": 81836,
"s": 81740,
"text": "Either create an analysis or access an existing analysis for which you want to create a filter."
},
{
"code": null,
"e": 82015,
"s": 81836,
"text": "Click the Criteria tab → Locate the \"Filters pane\" → Click create a filter for the current subject area button. The analysis selected columns are displayed in the cascading menu."
},
{
"code": null,
"e": 82181,
"s": 82015,
"text": "Select a column name from the menu or select the More Columns option to access the “Select Column dialog\" from which you can select any column from the subject area."
},
{
"code": null,
"e": 82245,
"s": 82181,
"text": "Once you select a column, the \"New Filter dialog\" is displayed."
},
{
"code": null,
"e": 82546,
"s": 82245,
"text": "Oracle BI Enterprise Edition enables you to look at results of analyses in a meaningful way using its presentation capabilities. Different types of views can be added, such as graphs and pivot tables that allow drilling down to more detailed information and many more options like using filters, etc."
},
{
"code": null,
"e": 82682,
"s": 82546,
"text": "The results of the analysis is displayed using a table/Pivot table view and depends on the type of columns that the analysis contains −"
},
{
"code": null,
"e": 82796,
"s": 82682,
"text": "Table view is used if the analysis contains only attribute columns/only measure columns or a combination of both."
},
{
"code": null,
"e": 82910,
"s": 82796,
"text": "Table view is used if the analysis contains only attribute columns/only measure columns or a combination of both."
},
{
"code": null,
"e": 83001,
"s": 82910,
"text": "Pivot table is the default view if the analysis contains at least one hierarchical column."
},
{
"code": null,
"e": 83092,
"s": 83001,
"text": "Pivot table is the default view if the analysis contains at least one hierarchical column."
},
{
"code": null,
"e": 83146,
"s": 83092,
"text": "A title view displays the name of the saved analysis."
},
{
"code": null,
"e": 83200,
"s": 83146,
"text": "A title view displays the name of the saved analysis."
},
{
"code": null,
"e": 83301,
"s": 83200,
"text": "You can edit or delete an existing view, add another view to an analysis and can also combine views."
},
{
"code": null,
"e": 83402,
"s": 83301,
"text": "You can edit or delete an existing view, add another view to an analysis and can also combine views."
},
{
"code": null,
"e": 83408,
"s": 83402,
"text": "Title"
},
{
"code": null,
"e": 83524,
"s": 83408,
"text": "Title view displays a title, a subtitle, a logo, a link to a custom online help page and timestamps to the results."
},
{
"code": null,
"e": 83530,
"s": 83524,
"text": "Table"
},
{
"code": null,
"e": 83761,
"s": 83530,
"text": "Table view is used to display results in a visual representation of data organized by rows and columns. It provides a summary view of data and enables users to see different views of data by dragging and dropping rows and columns."
},
{
"code": null,
"e": 83773,
"s": 83761,
"text": "Pivot Table"
},
{
"code": null,
"e": 83961,
"s": 83773,
"text": "It displays results in a pivot table, which provides a summary view of data in cross-tab format and enables users to see different views of data by dragging and dropping rows and columns."
},
{
"code": null,
"e": 84131,
"s": 83961,
"text": "Pivot tables and standard tables are similar in structure but Pivot table can contain column groups and can also display multiple levels of both row and column headings."
},
{
"code": null,
"e": 84344,
"s": 84131,
"text": "Pivot table cell contains a unique value. Pivot table is more efficient than a row-based table. It is best suited for displaying a large quantity of data, for browsing data hierarchically, and for trend analysis."
},
{
"code": null,
"e": 84361,
"s": 84344,
"text": "Performance Tile"
},
{
"code": null,
"e": 84581,
"s": 84361,
"text": "Performance tiles are used to display a single aggregate measure value in a manner that is visually simple but provides a summary metrics to the user that will likely be presented in more detail within a dashboard view."
},
{
"code": null,
"e": 84706,
"s": 84581,
"text": "Performance tiles are used to focus the user's attention on simple, need-to-know facts directly and prominently on the tile."
},
{
"code": null,
"e": 84995,
"s": 84706,
"text": "Communicate status through simple formatting by using color, labels, and limited styles, or through conditional formatting of the background color or measure value to make the tile visually prominent. For example, if revenue is not tracking to target, the revenue value may appear in red."
},
{
"code": null,
"e": 85110,
"s": 84995,
"text": "Respond to prompts, filters, and user roles and permissions by making them relevant to the user and their context."
},
{
"code": null,
"e": 85159,
"s": 85110,
"text": "Support a single, aggregate or calculated value."
},
{
"code": null,
"e": 85167,
"s": 85159,
"text": "Treemap"
},
{
"code": null,
"e": 85285,
"s": 85167,
"text": "Tree map are used to display a space-constrained, 2-d visualization for hierarchical structures with multiple levels."
},
{
"code": null,
"e": 85359,
"s": 85285,
"text": "Treemaps are limited by a predefined area and display two levels of data."
},
{
"code": null,
"e": 85486,
"s": 85359,
"text": "Contain rectangular tiles. The size of the tile is based on a measure, and the color of the tile is based on a second measure."
},
{
"code": null,
"e": 85691,
"s": 85486,
"text": "Treemap are similar to a scatter plot graphs in that the map area is constrained, and the graph allows you to visualize large quantities of data and quickly identify trends and anomalies within that data."
},
{
"code": null,
"e": 85699,
"s": 85691,
"text": "Trellis"
},
{
"code": null,
"e": 85857,
"s": 85699,
"text": "Trellis displays multi-dimensional data shown as a set of cells in a grid form and where each cell represents a subset of data using a particular graph type."
},
{
"code": null,
"e": 85930,
"s": 85857,
"text": "The trellis view has two subtypes − Simple Trellis and Advanced Trellis."
},
{
"code": null,
"e": 86112,
"s": 85930,
"text": "Simple trellis views are ideal for displaying multiple graphs that enable comparison of like to like. Advanced trellis views are ideal for displaying spark graphs that show a trend."
},
{
"code": null,
"e": 86206,
"s": 86112,
"text": "A simple trellis displays a single inner graph type, Example − a grid of multiple Bar graphs."
},
{
"code": null,
"e": 86363,
"s": 86206,
"text": "An advanced trellis displays a different inner graph type for each measure. Example: A mixture of Spark Line graphs and Spark Bar graphs, alongside numbers."
},
{
"code": null,
"e": 86369,
"s": 86363,
"text": "Graph"
},
{
"code": null,
"e": 86548,
"s": 86369,
"text": "Graph displays numeric information visually which makes it easier to understand large quantities of data. Graphs often reveal patterns and trends that text-based displays cannot."
},
{
"code": null,
"e": 86611,
"s": 86548,
"text": "A graph is displayed on a background, called the graph canvas."
},
{
"code": null,
"e": 86617,
"s": 86611,
"text": "Gauge"
},
{
"code": null,
"e": 86766,
"s": 86617,
"text": "Gauge are used to show a single data value. Cos of its compact size, a gauge is often more effective than a graph for displaying a single data value"
},
{
"code": null,
"e": 86987,
"s": 86766,
"text": "Gauges identify problems in data. A gauge usually plots one data point with an indication of whether that point falls in an acceptable or unacceptable range. Thus, gauges are useful for showing performance against goals."
},
{
"code": null,
"e": 87063,
"s": 86987,
"text": "A gauge or gauge set is displayed on a background, called the gauge canvas."
},
{
"code": null,
"e": 87070,
"s": 87063,
"text": "Funnel"
},
{
"code": null,
"e": 87366,
"s": 87070,
"text": "Funnel displays results in 3D graph that represents target and actual values using volume, level, and color. Funnel graphs are used to graphically represent data that changes over different periods or stages. Example: Funnel graphs are often used to represent the volume of sales over a quarter."
},
{
"code": null,
"e": 87547,
"s": 87366,
"text": "Funnel graphs are well suited for showing actual compared to targets for data where the target is known to decrease (or increase) significantly per stage, such as a sales pipeline."
},
{
"code": null,
"e": 87556,
"s": 87547,
"text": "Map view"
},
{
"code": null,
"e": 87771,
"s": 87556,
"text": "Map view is used to display results overlain on a map. Depending on the data, the results can be overlain on top of a map as formats such as images, color fill areas, bar and pie graphs, and variably sized markers."
},
{
"code": null,
"e": 87779,
"s": 87771,
"text": "Filters"
},
{
"code": null,
"e": 88002,
"s": 87779,
"text": "Filter are used to displays the filters in effect for an analysis. Filters allows you to add condition to an analysis to obtain results that answer a particular question. Filters are applied before the query is aggregated."
},
{
"code": null,
"e": 88018,
"s": 88002,
"text": "Selection Steps"
},
{
"code": null,
"e": 88254,
"s": 88018,
"text": "Selection steps are used to displays the selection steps in effect for an analysis. Selection steps, like filters, allow you to obtain results that answer particular questions. Selection steps are applied after the query is aggregated."
},
{
"code": null,
"e": 88270,
"s": 88254,
"text": "Column Selector"
},
{
"code": null,
"e": 88454,
"s": 88270,
"text": "Column selector is a set of drop-down lists that contain pre-selected columns. Users can dynamically select columns and change the data that is displayed in the views of the analysis."
},
{
"code": null,
"e": 88468,
"s": 88454,
"text": "View Selector"
},
{
"code": null,
"e": 88591,
"s": 88468,
"text": "A view selector is a drop-down list from which users can select a specific view of the results from among the saved views."
},
{
"code": null,
"e": 88598,
"s": 88591,
"text": "Legend"
},
{
"code": null,
"e": 88719,
"s": 88598,
"text": "It enables you to document the meaning of special formatting used in results-meaning of custom colors applied to gauges."
},
{
"code": null,
"e": 88729,
"s": 88719,
"text": "Narrative"
},
{
"code": null,
"e": 88788,
"s": 88729,
"text": "It displays the results as one or more paragraphs of text."
},
{
"code": null,
"e": 88795,
"s": 88788,
"text": "Ticker"
},
{
"code": null,
"e": 89031,
"s": 88795,
"text": "It displays the results as a ticker or marquee, similar in style to the stock tickers that run across many financial and news sites on the Internet. You can also control what information is presented and how it scrolls across the page."
},
{
"code": null,
"e": 89043,
"s": 89031,
"text": "Static Text"
},
{
"code": null,
"e": 89182,
"s": 89043,
"text": "You can use HTML to add banners, tickers, ActiveX objects, Java applets, links, instructions, descriptions, graphics, etc. in the results."
},
{
"code": null,
"e": 89194,
"s": 89182,
"text": "Logical SQL"
},
{
"code": null,
"e": 89370,
"s": 89194,
"text": "It displays the SQL statement that is generated for an analysis. This view is useful for trainers and administrators, and is usually not included in results for typical users."
},
{
"code": null,
"e": 89447,
"s": 89370,
"text": "You cannot modify this view, except to format its container or to delete it."
},
{
"code": null,
"e": 89462,
"s": 89447,
"text": "Create Segment"
},
{
"code": null,
"e": 89522,
"s": 89462,
"text": "It is used to display a Create Segment link in the results."
},
{
"code": null,
"e": 89541,
"s": 89522,
"text": "Create Target List"
},
{
"code": null,
"e": 89733,
"s": 89541,
"text": "It is used to display a create target list link in the results. Users can click this link to create a target list, based on the results data, in their Oracle's Siebel operational application."
},
{
"code": null,
"e": 89883,
"s": 89733,
"text": "This view is for users of Oracle's Siebel Life Sciences operational application integrated with Oracle's Siebel Life Sciences Analytics applications."
},
{
"code": null,
"e": 90002,
"s": 89883,
"text": "All view types except logical SQL view can be edited. Each view has its own editor in which you can perform edit task."
},
{
"code": null,
"e": 90143,
"s": 90002,
"text": "Each view editor contains a unique functionality for that view type but might also contain functionality that is the same across view types."
},
{
"code": null,
"e": 90235,
"s": 90143,
"text": "Open the analysis that contains the view to edit. Click the \"Analysis editor: Results tab.\""
},
{
"code": null,
"e": 90399,
"s": 90235,
"text": "Click the Edit View button for the view. View editors is displayed. Now, using the editor for the view, make the required edits. Click done and then save the view."
},
{
"code": null,
"e": 90428,
"s": 90399,
"text": "You can delete a view from −"
},
{
"code": null,
"e": 90564,
"s": 90428,
"text": "A compound layout − If you remove a view from a compound layout, it is only removed from the compound layout and not from the analysis."
},
{
"code": null,
"e": 90700,
"s": 90564,
"text": "A compound layout − If you remove a view from a compound layout, it is only removed from the compound layout and not from the analysis."
},
{
"code": null,
"e": 90853,
"s": 90700,
"text": "An analysis − If you remove a view from an analysis, it removes the view from the analysis and also from any compound layout to which it had been added."
},
{
"code": null,
"e": 91006,
"s": 90853,
"text": "An analysis − If you remove a view from an analysis, it removes the view from the analysis and also from any compound layout to which it had been added."
},
{
"code": null,
"e": 91042,
"s": 91006,
"text": "If you want to remove a view from −"
},
{
"code": null,
"e": 91150,
"s": 91042,
"text": "A compound layout − In the view in the Compound Layout → click the Remove View from Compound Layout button."
},
{
"code": null,
"e": 91258,
"s": 91150,
"text": "A compound layout − In the view in the Compound Layout → click the Remove View from Compound Layout button."
},
{
"code": null,
"e": 91369,
"s": 91258,
"text": "An analysis − In the Views pane → select the view and then click the Remove View from Analysis toolbar button."
},
{
"code": null,
"e": 91480,
"s": 91369,
"text": "An analysis − In the Views pane → select the view and then click the Remove View from Analysis toolbar button."
},
{
"code": null,
"e": 91786,
"s": 91480,
"text": "A Prompt is a special type of filter that is used to filter analyses embedded in a dashboard. The main reason to use a dashboard prompt is that it allows the user to customize analysis output and also allows flexibility to change parameters of a report. There are three types of prompts that can be used −"
},
{
"code": null,
"e": 92229,
"s": 91786,
"text": "The prompt created at the dashboard level is called a Named prompt. This Prompt is created outside of a specific dashboard and stored in the catalog as a prompt. You can apply a named prompt to any dashboard or dashboard page that contains the columns, mentioned in the prompt. It can filter one or any number of analyses embedded on the same dashboard page. You can create and save these named prompts to a private folder or a shared folder."
},
{
"code": null,
"e": 92494,
"s": 92229,
"text": "A named prompt always appears on the dashboard page and the user can prompt for different values without having to rerun the dashboard. A named prompt can also interact with selection steps. You can specify a dashboard prompt to override a specific selection step."
},
{
"code": null,
"e": 92695,
"s": 92494,
"text": "The step will be processed against the dashboard column with the user-specified data values collected by the dashboard column prompt, whereas all other steps will be processed as originally specified."
},
{
"code": null,
"e": 92892,
"s": 92695,
"text": "Inline prompts are embedded in an analysis and are not stored in the catalog for reuse. Inline prompt provides general filtering of a column within the analysis, depending on how it is configured."
},
{
"code": null,
"e": 93144,
"s": 92892,
"text": "Inline prompt works independently from a dashboard filter, which determines values for all matching columns on the dashboard. An inline prompt is an initial prompt. When the user selects the prompt value, the prompt field disappears from the analysis."
},
{
"code": null,
"e": 93288,
"s": 93144,
"text": "To select different prompt values, you need to rerun the analysis. Your input determines the content of the analyses embedded in the dashboard."
},
{
"code": null,
"e": 93402,
"s": 93288,
"text": "Named Prompt can be applied to any dashboard or dashboard page which contains the column specified in the Prompt."
},
{
"code": null,
"e": 93757,
"s": 93402,
"text": "A column prompt is the most common and flexible prompt type. A column prompt enables you to build very specific value prompts to either stand alone on the dashboard or analysis or to expand or refine existing dashboard and analysis filters. Column prompts can be created for hierarchical, measure, or attribute columns at the analysis or dashboard level."
},
{
"code": null,
"e": 93809,
"s": 93757,
"text": "Go to New → Dashboard Prompt → Select subject area."
},
{
"code": null,
"e": 93941,
"s": 93809,
"text": "Dashboard prompt dialog box appears. Go to ‘+’ sign, select the prompt type. Click on the column prompt → Select column → Click OK."
},
{
"code": null,
"e": 94113,
"s": 93941,
"text": "New Prompt dialog box appears (this appears only for column prompts). Enter the label name that will appear on dashboard next to Prompt → Select the Operator → User Input."
},
{
"code": null,
"e": 94379,
"s": 94113,
"text": "The User Input field's drop-down list appears for column and variable prompts, and provides you with the option to determine the User Input method for the user interface. You can select any of the following − checkboxes, radio buttons, a choice list, or a list box."
},
{
"code": null,
"e": 94614,
"s": 94379,
"text": "Example − If you select the User Input method of Choice List and Choice List Values item of all Column Values, the user will select the prompt's data value from a list that contains all of the data values contained in the data source."
},
{
"code": null,
"e": 94682,
"s": 94614,
"text": "You can also further make a selection by expanding the Options tab."
},
{
"code": null,
"e": 94804,
"s": 94682,
"text": "These series of checkboxes allow you to restrict the amount of data returned in output. Once selection is made, click OK."
},
{
"code": null,
"e": 94931,
"s": 94804,
"text": "The Prompt is added to Definition → Save the prompt using the save option at the top right corner → Enter the name → Click OK."
},
{
"code": null,
"e": 95113,
"s": 94931,
"text": "To test the Prompt, go to My Dashboard → Catalog and drag the prompt to column 1. This prompt can be applied to full dashboard or on a single page by clicking on Properties → Scope."
},
{
"code": null,
"e": 95228,
"s": 95113,
"text": "Save and run the Dashboard, select the value for a Prompt. Apply and Output value will change as per prompt value."
},
{
"code": null,
"e": 95362,
"s": 95228,
"text": "A currency prompt enables the user to change the currency type that is displayed in the currency columns on an analysis or dashboard."
},
{
"code": null,
"e": 95619,
"s": 95362,
"text": "Example − Suppose that an analysis contains the sales totals for a certain region of US in US dollars. However, because the users viewing the analysis reside in Canada, they can use the currency prompt to change the sales totals from USD to Canada dollars."
},
{
"code": null,
"e": 95865,
"s": 95619,
"text": "The prompt's currency selection list is populated with the currency preferences from the user’s → My Account dialog → Preferences tab. Currency prompt option is available only if the administrator has configured the userpref_currencies.xml file."
},
{
"code": null,
"e": 95963,
"s": 95865,
"text": "An image prompt provides an image that users click to select values for an analysis or dashboard."
},
{
"code": null,
"e": 96239,
"s": 95963,
"text": "Example − In a sales organization, users can click their territories from an image of a map to see sales information, or click a product image to see sales information about that product. If you know how to use the HTML <map> tag, then you can create an image map definition."
},
{
"code": null,
"e": 96436,
"s": 96239,
"text": "A variable prompt enables the user to select a value that is specified in the variable prompt to display on dashboard. A variable prompt is not dependent upon a column, but can still use a column."
},
{
"code": null,
"e": 96708,
"s": 96436,
"text": "You can add one or more existing reports to a dashboard page. The advantage is that you can share reports with other users and schedule the dashboard pages using agents. An agent sends the entire dashboard to the user, including all data pages that the report references."
},
{
"code": null,
"e": 96837,
"s": 96708,
"text": "When configuring an agent for a dashboard page that contains a BI Publisher report, ensure that the following criteria are met −"
},
{
"code": null,
"e": 96895,
"s": 96837,
"text": "The output format of the BI Publisher report must be PDF."
},
{
"code": null,
"e": 96933,
"s": 96895,
"text": "The agent must be set to deliver PDF."
},
{
"code": null,
"e": 97146,
"s": 96933,
"text": "You can add reports to a dashboard page as embedded content and as a link. Embedded means that the report is displayed directly on the dashboard page. The link opens the report in BI Publisher within Oracle BIEE."
},
{
"code": null,
"e": 97324,
"s": 97146,
"text": "If you modify the report in BI Publisher and save your changes, then refresh the dashboard page to see the modifications. Navigate to the page to which you want to add a report."
},
{
"code": null,
"e": 97371,
"s": 97324,
"text": "Select a report in one of the following ways −"
},
{
"code": null,
"e": 97470,
"s": 97371,
"text": "Select the report from the Catalog pane and drag and drop it into a section on the dashboard page."
},
{
"code": null,
"e": 97569,
"s": 97470,
"text": "Select the report from the Catalog pane and drag and drop it into a section on the dashboard page."
},
{
"code": null,
"e": 97691,
"s": 97569,
"text": "To add a report from a dashboard page, select the report from the folder that contains its dashboard in the Catalog pane."
},
{
"code": null,
"e": 97813,
"s": 97691,
"text": "To add a report from a dashboard page, select the report from the folder that contains its dashboard in the Catalog pane."
},
{
"code": null,
"e": 97987,
"s": 97813,
"text": "Set the properties of the object. To do so, hover the mouse pointer over the object in the page layout area to display the object's toolbar, and click the Properties button."
},
{
"code": null,
"e": 98136,
"s": 97987,
"text": "The \"BI Publisher Report Properties dialog\" is displayed. Complete the fields in the properties dialog as appropriate. Click OK and then click Save."
},
{
"code": null,
"e": 98243,
"s": 98136,
"text": "If required, add a prompt to the dashboard page to filter the results of an embedded parameterized report."
},
{
"code": null,
"e": 98507,
"s": 98243,
"text": "OBIEE security is defined by the use of a role-based access control model. It is defined in terms of roles that are aligned to different directory server groups and users. In this chapter, we will be discussing the components defined to compose a security policy."
},
{
"code": null,
"e": 98573,
"s": 98507,
"text": "One can define a Security structure with the following components"
},
{
"code": null,
"e": 98649,
"s": 98573,
"text": "The directory Server User and Group managed by the Authentication provider."
},
{
"code": null,
"e": 98725,
"s": 98649,
"text": "The directory Server User and Group managed by the Authentication provider."
},
{
"code": null,
"e": 98878,
"s": 98725,
"text": "The application roles managed by the Policy store provide Security policy with the following components: Presentation catalog, repository, policy store."
},
{
"code": null,
"e": 99031,
"s": 98878,
"text": "The application roles managed by the Policy store provide Security policy with the following components: Presentation catalog, repository, policy store."
},
{
"code": null,
"e": 99159,
"s": 99031,
"text": "Security provider is called in order to get the security information. Following types of security providers are used by OBIEE −"
},
{
"code": null,
"e": 99206,
"s": 99159,
"text": "Authentication provider to authenticate users."
},
{
"code": null,
"e": 99253,
"s": 99206,
"text": "Authentication provider to authenticate users."
},
{
"code": null,
"e": 99359,
"s": 99253,
"text": "Policy store provider is used to give privileges on all applications except for BI Presentation Services."
},
{
"code": null,
"e": 99465,
"s": 99359,
"text": "Policy store provider is used to give privileges on all applications except for BI Presentation Services."
},
{
"code": null,
"e": 99559,
"s": 99465,
"text": "Credential store provider is used to store credentials used internally by the BI application."
},
{
"code": null,
"e": 99653,
"s": 99559,
"text": "Credential store provider is used to store credentials used internally by the BI application."
},
{
"code": null,
"e": 99721,
"s": 99653,
"text": "Security policy in OBIEE is divided into the following components −"
},
{
"code": null,
"e": 99742,
"s": 99721,
"text": "Presentation Catalog"
},
{
"code": null,
"e": 99753,
"s": 99742,
"text": "Repository"
},
{
"code": null,
"e": 99766,
"s": 99753,
"text": "Policy Store"
},
{
"code": null,
"e": 99848,
"s": 99766,
"text": "It defines the catalog objects and Oracle BI Presentation Services functionality."
},
{
"code": null,
"e": 99979,
"s": 99848,
"text": "It enables you to set privileges for users to access features and functions such as editing views and creating agents and prompts."
},
{
"code": null,
"e": 100084,
"s": 99979,
"text": "Presentation Catalog privileges access to presentation catalog objects defined in the Permission dialog."
},
{
"code": null,
"e": 100413,
"s": 100084,
"text": "Presentation Services administration does not have its own authentication system and it relies on the authentication system that it inherits from the Oracle BI Server. All users who sign in to Presentation Services are granted the Authenticated User role and any other roles that they were assigned in Fusion Middleware Control."
},
{
"code": null,
"e": 100471,
"s": 100413,
"text": "You can assign permissions in one of the following ways −"
},
{
"code": null,
"e": 100556,
"s": 100471,
"text": "To application roles − Most recommended way of assigning permissions and privileges."
},
{
"code": null,
"e": 100641,
"s": 100556,
"text": "To application roles − Most recommended way of assigning permissions and privileges."
},
{
"code": null,
"e": 100758,
"s": 100641,
"text": "To individual users − This is difficult to manage where you can assign permissions and privileges to specific users."
},
{
"code": null,
"e": 100875,
"s": 100758,
"text": "To individual users − This is difficult to manage where you can assign permissions and privileges to specific users."
},
{
"code": null,
"e": 100968,
"s": 100875,
"text": "To Catalog groups − It was used in previous releases for backward compatibility maintenance."
},
{
"code": null,
"e": 101061,
"s": 100968,
"text": "To Catalog groups − It was used in previous releases for backward compatibility maintenance."
},
{
"code": null,
"e": 101290,
"s": 101061,
"text": "This defines which application roles and users have access to which items of metadata within the repository. The Oracle BI Administration Tool through the security manager is used and enables you to perform the following tasks −"
},
{
"code": null,
"e": 101363,
"s": 101290,
"text": "Set permissions for business models, tables, columns, and subject areas."
},
{
"code": null,
"e": 101402,
"s": 101363,
"text": "Specify database access for each user."
},
{
"code": null,
"e": 101457,
"s": 101402,
"text": "Specify filters to limit the data accessible by users."
},
{
"code": null,
"e": 101485,
"s": 101457,
"text": "Set authentication options."
},
{
"code": null,
"e": 101634,
"s": 101485,
"text": "It defines BI Server, BI Publisher, and Real Time Decisions functionality that can be accessed by given users or users with given Application Roles."
},
{
"code": null,
"e": 101884,
"s": 101634,
"text": "Authenticator Provider in Oracle WebLogic Server domain is used for user authentication. This authentication provider accesses users and group information stored in the LDAP server in the Oracle Business Intelligence's Oracle WebLogic Server domain."
},
{
"code": null,
"e": 102309,
"s": 101884,
"text": "To create and manage users and groups in an LDAP server, Oracle WebLogic Server Administration Console is used. You can also choose to configure an authentication provider for an alternative directory. In this case, Oracle WebLogic Server Administration Console enables you to view the users and groups in your directory; however, you need to continue to use the appropriate tools to make any modifications to the directory."
},
{
"code": null,
"e": 102499,
"s": 102309,
"text": "Example − If you reconfigure Oracle Business Intelligence to use OID, you can view users and groups in Oracle WebLogic Server Administration Console but you must manage them in OID Console."
},
{
"code": null,
"e": 102743,
"s": 102499,
"text": "Once authentication is done, the next step in security is to ensure that the user can do and see what they are authorized to do. Authorization for Oracle Business Intelligence 11g is managed by a security policy in terms of Applications Roles."
},
{
"code": null,
"e": 102944,
"s": 102743,
"text": "Security is normally defined in terms of Application roles that are assigned to directory server users and groups. Example: the default Application roles are BIAdministrator, BIConsumer, and BIAuthor."
},
{
"code": null,
"e": 103219,
"s": 102944,
"text": "Application roles are defined as functional role assigned to a user, which gives that user the privileges required to perform that role. Example: Marketing Analyst Application role might grant a user access to view, edit and create reports on a company's marketing pipeline."
},
{
"code": null,
"e": 103560,
"s": 103219,
"text": "This communication between Application roles and directory server users and groups allows the administrator to define the Application roles and policies without creating additional users or groups in LDAP server. Application roles allows business intelligence system to be easily moved between development, test and production environments."
},
{
"code": null,
"e": 103732,
"s": 103560,
"text": "This doesn’t require any change in security policy and all that is required is to assign the Application roles to the users and groups available in the target environment."
},
{
"code": null,
"e": 103918,
"s": 103732,
"text": "The group named 'BIConsumers' contains user1, user2, and user3. Users in the group 'BIConsumers' are assigned the Application role 'BIConsumer', which enables the users to view reports."
},
{
"code": null,
"e": 104092,
"s": 103918,
"text": "The group named 'BIAuthors' contains user4 and user5. Users in the group 'BIAuthors' are assigned the Application role 'BIAuthor', which enables the users to create reports."
},
{
"code": null,
"e": 104300,
"s": 104092,
"text": "The group named 'BIAdministrators' contains user6 and user7, user 8. Users in the group 'BIAdministrators' are assigned the Application role 'BIAdministrator', which enables the users to manage repositories."
},
{
"code": null,
"e": 104705,
"s": 104300,
"text": "In OBIEE 10g, most of OBIEE administration tasks were mostly performed either through the Administration tool, the web-based Presentation Server administration screen, or through editing files in the filesystem. There were around 700 or so configuration options spread over multiple tools and configuration files, with some options like users and groups were embedded in unrelated repositories (the RPD)."
},
{
"code": null,
"e": 104838,
"s": 104705,
"text": "In OBIEE 11g, all administration and configuration tasks are moved into Fusion Middleware Control also called as Enterprise Manager."
},
{
"code": null,
"e": 105134,
"s": 104838,
"text": "Administration tool that was present in OBIEE 10g is also present in 11g and is used to maintain the semantic model used by the BI Server. It has few enhancements in terms of dimension handling and new data sources. A major change is around security - when you open the Security Manager dialog −"
},
{
"code": null,
"e": 105197,
"s": 105134,
"text": "Go to Manage → Identity → Security Manager Dialog box appears."
},
{
"code": null,
"e": 105628,
"s": 105197,
"text": "Users and Application Roles are now defined in the WebLogic Server admin console. You use the Security Manager to define additional links through to other LDAP servers, register custom authenticators and set up filters, etc. In the above screenshot, the users shown in the users list are those that are held in WebLogic Server’s JPS (Java Platform Security) service, and there are no longer any users and groups in the RPD itself."
},
{
"code": null,
"e": 105833,
"s": 105628,
"text": "There is no administrator user in above snapshot. It has standard administrator user that you set up as the WebLogic Server administrator when you install OBIEE, which typically has the username weblogic."
},
{
"code": null,
"e": 106070,
"s": 105833,
"text": "There are also two additional default users: OracleSystemUser - this user is used by the various OBIEE web services to communicate with the BI Server and BISystemUser is used by BI Publisher to connect to the BI Server as a data source."
},
{
"code": null,
"e": 106265,
"s": 106070,
"text": "In Application Roles tab, you can see a list default application roles - BISystem, BIAdministrator, BIAuthor and BIConsumer - which are used to grant access to Presentation Server functionality."
},
{
"code": null,
"e": 106502,
"s": 106265,
"text": "To create a new user, log on to the WebLogic Server admin console → Go to Security Realms from the Fusion Middleware Control menu → Select myrealm → Select Users and Groups. Click on Users tab, it will show you a list of existing users."
},
{
"code": null,
"e": 106681,
"s": 106502,
"text": "Click the New. → New user dialog box opens up → enter the user’s details. You can also use the Groups tab to define a group for the user, or assign the user to an existing group."
},
{
"code": null,
"e": 106733,
"s": 106681,
"text": "Following are the key file locations In OBIEE 11g −"
},
{
"code": null,
"e": 106839,
"s": 106733,
"text": "C:\\Middleware\\instances\\instance1\\bifoundation\\OracleBIServerComponent\\\ncoreapplication_obis1\\repository\n"
},
{
"code": null,
"e": 106942,
"s": 106839,
"text": "C:\\Middleware\\instances\\instance1\\config\\OracleBIServerComponent\\coreapplication_obis1\\\nnqsconfig.INI\n"
},
{
"code": null,
"e": 107041,
"s": 106942,
"text": "C:\\Middleware\\instances\\instance1\\config\\OracleBIApplication\\coreapplication\\\nNQClusterConfig.INI\n"
},
{
"code": null,
"e": 107152,
"s": 107041,
"text": "C:\\Middleware\\instances\\instance1\\diagnostics\\logs\\OracleBIServerComponent\\\ncoreapplication_obis1\\nqquery.log\n"
},
{
"code": null,
"e": 107264,
"s": 107152,
"text": "C:\\Middleware\\instances\\instance1\\diagnostics\\logs\\OracleBIServerComponent\\\ncoreapplication_obis1\\nqserver.log\n"
},
{
"code": null,
"e": 107328,
"s": 107264,
"text": "C:\\Middleware\\Oracle_BI1\\bifoundation\\server\\bin\\nqsserver.exe\n"
},
{
"code": null,
"e": 107447,
"s": 107328,
"text": "C:\\Middleware\\instances\\instance1\\bifoundation\\OracleBIPresentationServicesComponent\\\ncoreapplication_obips1\\catalog\\\n"
},
{
"code": null,
"e": 107570,
"s": 107447,
"text": "C:\\Middleware\\instances\\instance1\\config\\OracleBIPresentationServicesComponent\\\ncoreapplication_obips1\\instanceconfig.xml\n"
},
{
"code": null,
"e": 107682,
"s": 107570,
"text": "C:\\Middleware\\instances\\instance1\\config\\OracleBIPresentationServicesComponent\\\ncoreapplication_obips1\\xdo.cfg\n"
},
{
"code": null,
"e": 107808,
"s": 107682,
"text": "C:\\Middleware\\instances\\instance1\\diagnostics\\logs\\OracleBIPresentationServicesComponent\\\ncoreapplication_obips1\\sawlog0.log\n"
},
{
"code": null,
"e": 107869,
"s": 107808,
"text": "C:\\Middleware\\Oracle_BI1\\bifoundation\\web\\bin\\sawserver.exe\n"
},
{
"code": null,
"e": 108002,
"s": 107869,
"text": "Go to Overview. You can also stop, start and restart all of the system components like BI Server, Presentation Server etc. via OPMN."
},
{
"code": null,
"e": 108114,
"s": 108002,
"text": "You can click the Capacity Management, Diagnostics, Security or Deployment tabs to perform further maintenance."
},
{
"code": null,
"e": 108185,
"s": 108114,
"text": "We have the following four options available for capacity management −"
},
{
"code": null,
"e": 108211,
"s": 108185,
"text": "Metrics gathered via DMS."
},
{
"code": null,
"e": 108237,
"s": 108211,
"text": "Metrics gathered via DMS."
},
{
"code": null,
"e": 108351,
"s": 108237,
"text": "Availability of all the individual system components (allowing you to stop, start and restart them individually)."
},
{
"code": null,
"e": 108465,
"s": 108351,
"text": "Availability of all the individual system components (allowing you to stop, start and restart them individually)."
},
{
"code": null,
"e": 108647,
"s": 108465,
"text": "Scalability is used to increase the number of BI Servers, Presentation Servers, Cluster Controllers and Schedulers in the cluster in conjunction with the “scale out” install option."
},
{
"code": null,
"e": 108829,
"s": 108647,
"text": "Scalability is used to increase the number of BI Servers, Presentation Servers, Cluster Controllers and Schedulers in the cluster in conjunction with the “scale out” install option."
},
{
"code": null,
"e": 108944,
"s": 108829,
"text": "Performance option allows you to turn caching on or off and modify other parameters associated with response time."
},
{
"code": null,
"e": 109059,
"s": 108944,
"text": "Performance option allows you to turn caching on or off and modify other parameters associated with response time."
},
{
"code": null,
"e": 109229,
"s": 109059,
"text": "Diagnostics − Log Messages show you view of all server errors and warnings. Log Configuration allows you to limit the size of logs and information gets included in them."
},
{
"code": null,
"e": 109300,
"s": 109229,
"text": "Security − It is used for enabling SSO and selecting the SSO provider."
},
{
"code": null,
"e": 109682,
"s": 109300,
"text": "Deployment − Presentation allows you to set dashboard defaults, section headings, etc. Scheduler is used to set the connection details for the scheduler schema. Marketing is for configuring the Siebel Marketing Content Server connection. Mail option is used for setting up the mail server to deliver for email alerts. Repository is used to upload new RPDs for use by the BI Server."
},
{
"code": null,
"e": 109689,
"s": 109682,
"text": " Print"
},
{
"code": null,
"e": 109700,
"s": 109689,
"text": " Add Notes"
}
]
|
C++ Program to Check Whether a Given Tree is Binary Search Tree | Binary Search Tree is a binary tree data structure in which we have 3 properties
The left subtree of a binary search tree of a node contains only nodes with keys lesser than the node’s key.
The left subtree of a binary search tree of a node contains only nodes with keys lesser than the node’s key.
The right subtree of a binary search tree node contains only nodes with keys greater than the node’s key.
The right subtree of a binary search tree node contains only nodes with keys greater than the node’s key.
The left and right trees of a subtree each must also be a binary search tree.
The left and right trees of a subtree each must also be a binary search tree.
Begin
function BSTUtill()
If node is equals to NULL then
Returns 1.
If data of node is less than minimum or greater than
maximum data then
Return 0.
Traverse left and right sub-trees recursively.
End.
Live Demo
#include <iostream>
#include <cstdlib>
#include <climits>
using namespace std;
struct n {
int d;
n* l;
n* r;
};
int BSTUtil(n* node, int min, int max);
int isBST(n* node) {
return(BSTUtil(node, INT_MIN, INT_MAX));
}
int BSTUtil(struct n* node, int min, int max) {
if (node==NULL)
return 1;
if (node->d < min || node->d > max)
return 0;
return BSTUtil(node->l, min, node->d - 1) && BSTUtil(node->r, node->d + 1, max);
}
n* newN(int d) {
n* nod = new n;
nod->d = d;
nod->l = NULL;
nod->r = NULL;
return nod;
}
int main() {
n *root = newN(7);
root->l = newN(6);
root->r = newN(10);
root->l->l = newN(2);
root->l->r = newN(4);
if (isBST(root))
cout<<"The Given Tree is a BST"<<endl;
else
cout<<"The Given Tree is not a BST"<<endl;
n *root1 = newN(10);
root1->l = newN(6);
root1->r = newN(11);
root1->l->l = newN(2);
root1->l->r = newN(7);
if (isBST(root1))
cout<<"The Given Tree is a BST"<<endl;
else
cout<<"The Given Tree is not a BST"<<endl;
return 0;
}
The Given Tree is not a BST
The Given Tree is a BST | [
{
"code": null,
"e": 1143,
"s": 1062,
"text": "Binary Search Tree is a binary tree data structure in which we have 3 properties"
},
{
"code": null,
"e": 1252,
"s": 1143,
"text": "The left subtree of a binary search tree of a node contains only nodes with keys lesser than the node’s key."
},
{
"code": null,
"e": 1361,
"s": 1252,
"text": "The left subtree of a binary search tree of a node contains only nodes with keys lesser than the node’s key."
},
{
"code": null,
"e": 1467,
"s": 1361,
"text": "The right subtree of a binary search tree node contains only nodes with keys greater than the node’s key."
},
{
"code": null,
"e": 1573,
"s": 1467,
"text": "The right subtree of a binary search tree node contains only nodes with keys greater than the node’s key."
},
{
"code": null,
"e": 1651,
"s": 1573,
"text": "The left and right trees of a subtree each must also be a binary search tree."
},
{
"code": null,
"e": 1729,
"s": 1651,
"text": "The left and right trees of a subtree each must also be a binary search tree."
},
{
"code": null,
"e": 1976,
"s": 1729,
"text": "Begin\n function BSTUtill()\n If node is equals to NULL then\n Returns 1.\n If data of node is less than minimum or greater than\n maximum data then\n Return 0.\n Traverse left and right sub-trees recursively. \nEnd."
},
{
"code": null,
"e": 1987,
"s": 1976,
"text": " Live Demo"
},
{
"code": null,
"e": 3077,
"s": 1987,
"text": "#include <iostream>\n#include <cstdlib>\n#include <climits>\nusing namespace std;\nstruct n {\n int d;\n n* l;\n n* r;\n};\nint BSTUtil(n* node, int min, int max);\nint isBST(n* node) {\n return(BSTUtil(node, INT_MIN, INT_MAX));\n}\nint BSTUtil(struct n* node, int min, int max) {\n if (node==NULL)\n return 1;\n if (node->d < min || node->d > max)\n return 0;\n return BSTUtil(node->l, min, node->d - 1) && BSTUtil(node->r, node->d + 1, max);\n}\nn* newN(int d) {\n n* nod = new n;\n nod->d = d;\n nod->l = NULL;\n nod->r = NULL;\n return nod;\n}\nint main() {\n n *root = newN(7);\n root->l = newN(6);\n root->r = newN(10);\n root->l->l = newN(2);\n root->l->r = newN(4);\n if (isBST(root))\n cout<<\"The Given Tree is a BST\"<<endl;\n else\n cout<<\"The Given Tree is not a BST\"<<endl;\n n *root1 = newN(10);\n root1->l = newN(6);\n root1->r = newN(11);\n root1->l->l = newN(2);\n root1->l->r = newN(7);\n if (isBST(root1))\n cout<<\"The Given Tree is a BST\"<<endl;\n else\n cout<<\"The Given Tree is not a BST\"<<endl;\n return 0;\n}"
},
{
"code": null,
"e": 3129,
"s": 3077,
"text": "The Given Tree is not a BST\nThe Given Tree is a BST"
}
]
|
jQuery - ajaxError( callback ) Method | The ajaxError( callback ) method attaches a function to be executed whenever an AJAX request fails. This is an Ajax Event.
Here is the simple syntax to use this method −
$(document).ajaxError( callback )
Here is the description of all the parameters used by this method −
callback − The function to execute. The XMLHttpRequest and settings used for that request are passed as arguments to this function. A third argument, an exception object, is passed if an exception occured while processing the request.
callback − The function to execute. The XMLHttpRequest and settings used for that request are passed as arguments to this function. A third argument, an exception object, is passed if an exception occured while processing the request.
Following is a simple example a simple showing the usage of this method.
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("#driver").click(function(event){
/* Assume result.text does not exist. */
$('#stage1').load('/jquery/result.text');
});
$(document).ajaxError(function(event, request, settings ){
$("#stage2").html("<h1>Error in loading page.</h1>");
});
});
</script>
</head>
<body>
<p>Click on the button to load result.text file:</p>
<div id = "stage1" style = "background-color:blue;">
STAGE - 1
</div>
<div id = "stage2" style = "background-color:blue;">
STAGE - 2
</div>
<input type = "button" id = "driver" value = "Load Data" />
</body>
</html>
This will produce following result −
Click on the button to load result.text file −
27 Lectures
1 hours
Mahesh Kumar
27 Lectures
1.5 hours
Pratik Singh
72 Lectures
4.5 hours
Frahaan Hussain
60 Lectures
9 hours
Eduonix Learning Solutions
17 Lectures
2 hours
Sandip Bhattacharya
12 Lectures
53 mins
Laurence Svekis
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2445,
"s": 2322,
"text": "The ajaxError( callback ) method attaches a function to be executed whenever an AJAX request fails. This is an Ajax Event."
},
{
"code": null,
"e": 2492,
"s": 2445,
"text": "Here is the simple syntax to use this method −"
},
{
"code": null,
"e": 2527,
"s": 2492,
"text": "$(document).ajaxError( callback )\n"
},
{
"code": null,
"e": 2595,
"s": 2527,
"text": "Here is the description of all the parameters used by this method −"
},
{
"code": null,
"e": 2830,
"s": 2595,
"text": "callback − The function to execute. The XMLHttpRequest and settings used for that request are passed as arguments to this function. A third argument, an exception object, is passed if an exception occured while processing the request."
},
{
"code": null,
"e": 3065,
"s": 2830,
"text": "callback − The function to execute. The XMLHttpRequest and settings used for that request are passed as arguments to this function. A third argument, an exception object, is passed if an exception occured while processing the request."
},
{
"code": null,
"e": 3138,
"s": 3065,
"text": "Following is a simple example a simple showing the usage of this method."
},
{
"code": null,
"e": 4170,
"s": 3138,
"text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\" language = \"javascript\">\n $(document).ready(function() {\n\t\t\t\n $(\"#driver\").click(function(event){\n /* Assume result.text does not exist. */\n $('#stage1').load('/jquery/result.text');\n });\n\n $(document).ajaxError(function(event, request, settings ){\n $(\"#stage2\").html(\"<h1>Error in loading page.</h1>\");\n });\n\t\t\t\t\n });\n </script>\n </head>\n\n <body>\n <p>Click on the button to load result.text file:</p>\n\t\t\n <div id = \"stage1\" style = \"background-color:blue;\">\n STAGE - 1\n </div>\n\t\t\n <div id = \"stage2\" style = \"background-color:blue;\">\n STAGE - 2\n </div>\n\t\t\n <input type = \"button\" id = \"driver\" value = \"Load Data\" />\n </body>\n</html>"
},
{
"code": null,
"e": 4207,
"s": 4170,
"text": "This will produce following result −"
},
{
"code": null,
"e": 4254,
"s": 4207,
"text": "Click on the button to load result.text file −"
},
{
"code": null,
"e": 4287,
"s": 4254,
"text": "\n 27 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4301,
"s": 4287,
"text": " Mahesh Kumar"
},
{
"code": null,
"e": 4336,
"s": 4301,
"text": "\n 27 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4350,
"s": 4336,
"text": " Pratik Singh"
},
{
"code": null,
"e": 4385,
"s": 4350,
"text": "\n 72 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 4402,
"s": 4385,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4435,
"s": 4402,
"text": "\n 60 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 4463,
"s": 4435,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4496,
"s": 4463,
"text": "\n 17 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4517,
"s": 4496,
"text": " Sandip Bhattacharya"
},
{
"code": null,
"e": 4549,
"s": 4517,
"text": "\n 12 Lectures \n 53 mins\n"
},
{
"code": null,
"e": 4566,
"s": 4549,
"text": " Laurence Svekis"
},
{
"code": null,
"e": 4573,
"s": 4566,
"text": " Print"
},
{
"code": null,
"e": 4584,
"s": 4573,
"text": " Add Notes"
}
]
|
Character streams in Java | Character Streams − These handle data in 16 bit Unicode. Using these you can read and write text data only.
The Reader and Writer classes (abstract) are the super classes of all the character stream classes: classes that are used to read/write character streams. Following are the character array stream classes provided by Java −
The following Java program reads data from a particular file using FileReader and writes it to another, using FileWriter.
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class IOStreamsExample {
public static void main(String args[]) throws IOException {
//Creating FileReader object
File file = new File("D:/myFile.txt");
FileReader reader = new FileReader(file);
char chars[] = new char[(int) file.length()];
//Reading data from the file
reader.read(chars);
//Writing data to another file
File out = new File("D:/CopyOfmyFile.txt");
FileWriter writer = new FileWriter(out);
//Writing data to the file
writer.write(chars);
writer.flush();
System.out.println("Data successfully written in the specified file");
}
}
Data successfully written in the specified file | [
{
"code": null,
"e": 1170,
"s": 1062,
"text": "Character Streams − These handle data in 16 bit Unicode. Using these you can read and write text data only."
},
{
"code": null,
"e": 1393,
"s": 1170,
"text": "The Reader and Writer classes (abstract) are the super classes of all the character stream classes: classes that are used to read/write character streams. Following are the character array stream classes provided by Java −"
},
{
"code": null,
"e": 1515,
"s": 1393,
"text": "The following Java program reads data from a particular file using FileReader and writes it to another, using FileWriter."
},
{
"code": null,
"e": 2254,
"s": 1515,
"text": "import java.io.File;\nimport java.io.FileReader;\nimport java.io.FileWriter;\nimport java.io.IOException;\npublic class IOStreamsExample {\n public static void main(String args[]) throws IOException {\n //Creating FileReader object\n File file = new File(\"D:/myFile.txt\");\n FileReader reader = new FileReader(file);\n char chars[] = new char[(int) file.length()];\n //Reading data from the file\n reader.read(chars);\n //Writing data to another file\n File out = new File(\"D:/CopyOfmyFile.txt\");\n FileWriter writer = new FileWriter(out);\n //Writing data to the file\n writer.write(chars);\n writer.flush();\n System.out.println(\"Data successfully written in the specified file\");\n }\n}"
},
{
"code": null,
"e": 2302,
"s": 2254,
"text": "Data successfully written in the specified file"
}
]
|
How to get the next auto-increment id in MySQL? | MySQL has the AUTO_INCREMENT keyword to perform auto-increment. The starting value for AUTO_INCREMENT is 1, which is the default. It will get increment by 1 for each new record.
To get the next auto increment id in MySQL, we can use the function last_insert_id() from MySQL or auto_increment with SELECT.
Creating a table, with “id” as auto-increment.
mysql> create table NextIdDemo
-> (
-> id int auto_increment,
-> primary key(id)
-> );
Query OK, 0 rows affected (1.31 sec)
Inserting records into the table.
mysql> insert into NextIdDemo values(1);
Query OK, 1 row affected (0.22 sec)
mysql> insert into NextIdDemo values(2);
Query OK, 1 row affected (0.20 sec)
mysql> insert into NextIdDemo values(3);
Query OK, 1 row affected (0.14 sec)
To display all the records.
mysql> select *from NextIdDemo;
The following is the output.
+----+
| id |
+----+
| 1 |
| 2 |
| 3 |
+----+
3 rows in set (0.04 sec)
We have inserted 3 records above. Therefore, the next id must be 4.
The following is the syntax to know the next id.
SELECT AUTO_INCREMENT
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = "yourDatabaseName"
AND TABLE_NAME = "yourTableName"
The following is the query.
mysql> SELECT AUTO_INCREMENT
-> FROM information_schema.TABLES
-> WHERE TABLE_SCHEMA = "business"
-> AND TABLE_NAME = "NextIdDemo";
Here is the output that displays the next auto-increment.
+----------------+
| AUTO_INCREMENT |
+----------------+
| 4 |
+----------------+
1 row in set (0.25 sec) | [
{
"code": null,
"e": 1240,
"s": 1062,
"text": "MySQL has the AUTO_INCREMENT keyword to perform auto-increment. The starting value for AUTO_INCREMENT is 1, which is the default. It will get increment by 1 for each new record."
},
{
"code": null,
"e": 1367,
"s": 1240,
"text": "To get the next auto increment id in MySQL, we can use the function last_insert_id() from MySQL or auto_increment with SELECT."
},
{
"code": null,
"e": 1414,
"s": 1367,
"text": "Creating a table, with “id” as auto-increment."
},
{
"code": null,
"e": 1550,
"s": 1414,
"text": "mysql> create table NextIdDemo\n -> (\n -> id int auto_increment,\n -> primary key(id)\n -> );\nQuery OK, 0 rows affected (1.31 sec)"
},
{
"code": null,
"e": 1584,
"s": 1550,
"text": "Inserting records into the table."
},
{
"code": null,
"e": 1819,
"s": 1584,
"text": "mysql> insert into NextIdDemo values(1);\nQuery OK, 1 row affected (0.22 sec)\n\nmysql> insert into NextIdDemo values(2);\nQuery OK, 1 row affected (0.20 sec)\n\nmysql> insert into NextIdDemo values(3);\nQuery OK, 1 row affected (0.14 sec)"
},
{
"code": null,
"e": 1847,
"s": 1819,
"text": "To display all the records."
},
{
"code": null,
"e": 1879,
"s": 1847,
"text": "mysql> select *from NextIdDemo;"
},
{
"code": null,
"e": 1908,
"s": 1879,
"text": "The following is the output."
},
{
"code": null,
"e": 1983,
"s": 1908,
"text": "+----+\n| id |\n+----+\n| 1 |\n| 2 |\n| 3 |\n+----+\n3 rows in set (0.04 sec)\n"
},
{
"code": null,
"e": 2051,
"s": 1983,
"text": "We have inserted 3 records above. Therefore, the next id must be 4."
},
{
"code": null,
"e": 2100,
"s": 2051,
"text": "The following is the syntax to know the next id."
},
{
"code": null,
"e": 2226,
"s": 2100,
"text": "SELECT AUTO_INCREMENT\nFROM information_schema.TABLES\nWHERE TABLE_SCHEMA = \"yourDatabaseName\"\nAND TABLE_NAME = \"yourTableName\""
},
{
"code": null,
"e": 2254,
"s": 2226,
"text": "The following is the query."
},
{
"code": null,
"e": 2398,
"s": 2254,
"text": "mysql> SELECT AUTO_INCREMENT\n -> FROM information_schema.TABLES\n -> WHERE TABLE_SCHEMA = \"business\"\n -> AND TABLE_NAME = \"NextIdDemo\";"
},
{
"code": null,
"e": 2456,
"s": 2398,
"text": "Here is the output that displays the next auto-increment."
},
{
"code": null,
"e": 2576,
"s": 2456,
"text": "+----------------+\n| AUTO_INCREMENT |\n+----------------+\n| 4 |\n+----------------+\n1 row in set (0.25 sec)\n"
}
]
|
Create Matrix from Vectors in R - GeeksforGeeks | 22 Apr, 2020
In R programming language, vector is a basic object which consists of homogeneous elements. The data type of vector can be integer, double, character, logical, complex or raw. A vector can be created by using c() function.Syntax:
x <- c(val1, val2, .....)
Vectors in R are the same as the arrays in C language which are used to hold multiple data values of the same type. Vectors can also be used to create matrices.
Matrices can be created with the help of Vectors by using pre-defined functions in R Programming Language. These functions take vectors as arguments along with several other arguments for matrix dimensions, etc.
Functions used for Matrix creation:
matrix() function
cbind() function
rbind() function
The available data is present in a single/multiple vector, then matrix() function can be used to create the matrix by passing the following arguments in the function.
Syntax:
matrix(data, nrow, ncol, byrow, dimnames)
where,
data is the input vector which represents the elements in the matrixnrow specifies the number of rows to be createdncol specifies the number of columns to be createdbyrow specifies logical value. If TRUE, matrix will be filled by row. Default value is FALSE.dimnames specifies the names of rows and columns
Example 1:
# defining data in the vectorx <- c(5:16) # defining row names and column namesrown <- c("row_1", "row_2", "row_3")coln <- c("col_1", "col_2", "col_3", "col_4") # creating matrixm <- matrix(x, nrow = 3, byrow = TRUE, dimnames = list(rown, coln)) # print matrixprint(m) # print class of mclass(m)
Output:
col_1 col_2 col_3 col_4
row_1 5 6 7 8
row_2 9 10 11 12
row_3 13 14 15 16
[1] "matrix"
If matrix to be created using data present in multiple vectors, then vector of multiple vectors is created and passed to matrix() function as an argument.
Example 2:
# defining multiple vectorsx <- c(1:5)y <- c(11:15)z <- c(21:25) # creating matrixm <- matrix(c(x, y, z), ncol = 3) # print matrixprint(m) # print class of mclass(m)
Output:
[, 1] [, 2] [, 3]
[1, ] 1 11 21
[2, ] 2 12 22
[3, ] 3 13 23
[4, ] 4 14 24
[5, ] 5 15 25
[1] "matrix"
cbind() function in R programming is used to combine vectors, data frames or matrices by columns and number of rows of data sets should be equal otherwise, output will be incomprehensible.Syntax:
cbind(v1, v2, v3, ....., deparse.level)
where,
v1, v2, v3, .... represent vectors, matrices or data framesdeparse.level used for constructing labels for non-matrix like arguments. 0 for no labels. Default value is 1 or 2 for labelling from the arguments names.
Example:
# defining multiple vectorsx <- c(1:5)y <- c(11:15)z <- c(21:25) # creating matrixm <- cbind(x, y, z) # print matrixprint(m) # print class of mclass(m)
Output:
x y z
[1, ] 1 11 21
[2, ] 2 12 22
[3, ] 3 13 23
[4, ] 4 14 24
[5, ] 5 15 25
[1] "matrix"
rbind() function in R programming is used to combine vectors, data frames or matrices by rows and number of columns of data sets should be equal otherwise, output will be insignificant.Syntax:
rbind(v1, v2, v3, ....., deparse.level)
where,
v1, v2, v3, .... represent vectors, matrices or data framesdeparse.level used for constructing labels for non-matrix like arguments. 0 for no labels. Default value is 1 or 2 for labelling from the arguments names.
Example:
# defining multiple vectorsx <- c(1:5)y <- c(11:15)z <- c(21:25) # creating matrixn <- rbind(x, y, z) # print matrixprint(n) # print class of mclass(n)
Output:
[, 1] [, 2] [, 3] [, 4] [, 5]
x 1 2 3 4 5
y 11 12 13 14 15
z 21 22 23 24 25
[1] "matrix"
Picked
R-Matrix
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Replace specific values in column in R DataFrame ?
How to change Row Names of DataFrame in R ?
Filter data by multiple conditions in R using Dplyr
Change Color of Bars in Barchart using ggplot2 in R
Loops in R (for, while, repeat)
Printing Output of an R Program
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
K-Means Clustering in R Programming | [
{
"code": null,
"e": 24305,
"s": 24277,
"text": "\n22 Apr, 2020"
},
{
"code": null,
"e": 24535,
"s": 24305,
"text": "In R programming language, vector is a basic object which consists of homogeneous elements. The data type of vector can be integer, double, character, logical, complex or raw. A vector can be created by using c() function.Syntax:"
},
{
"code": null,
"e": 24562,
"s": 24535,
"text": "x <- c(val1, val2, .....)\n"
},
{
"code": null,
"e": 24723,
"s": 24562,
"text": "Vectors in R are the same as the arrays in C language which are used to hold multiple data values of the same type. Vectors can also be used to create matrices."
},
{
"code": null,
"e": 24935,
"s": 24723,
"text": "Matrices can be created with the help of Vectors by using pre-defined functions in R Programming Language. These functions take vectors as arguments along with several other arguments for matrix dimensions, etc."
},
{
"code": null,
"e": 24971,
"s": 24935,
"text": "Functions used for Matrix creation:"
},
{
"code": null,
"e": 24989,
"s": 24971,
"text": "matrix() function"
},
{
"code": null,
"e": 25006,
"s": 24989,
"text": "cbind() function"
},
{
"code": null,
"e": 25023,
"s": 25006,
"text": "rbind() function"
},
{
"code": null,
"e": 25190,
"s": 25023,
"text": "The available data is present in a single/multiple vector, then matrix() function can be used to create the matrix by passing the following arguments in the function."
},
{
"code": null,
"e": 25198,
"s": 25190,
"text": "Syntax:"
},
{
"code": null,
"e": 25241,
"s": 25198,
"text": "matrix(data, nrow, ncol, byrow, dimnames)\n"
},
{
"code": null,
"e": 25248,
"s": 25241,
"text": "where,"
},
{
"code": null,
"e": 25555,
"s": 25248,
"text": "data is the input vector which represents the elements in the matrixnrow specifies the number of rows to be createdncol specifies the number of columns to be createdbyrow specifies logical value. If TRUE, matrix will be filled by row. Default value is FALSE.dimnames specifies the names of rows and columns"
},
{
"code": null,
"e": 25566,
"s": 25555,
"text": "Example 1:"
},
{
"code": "# defining data in the vectorx <- c(5:16) # defining row names and column namesrown <- c(\"row_1\", \"row_2\", \"row_3\")coln <- c(\"col_1\", \"col_2\", \"col_3\", \"col_4\") # creating matrixm <- matrix(x, nrow = 3, byrow = TRUE, dimnames = list(rown, coln)) # print matrixprint(m) # print class of mclass(m)",
"e": 25878,
"s": 25566,
"text": null
},
{
"code": null,
"e": 25886,
"s": 25878,
"text": "Output:"
},
{
"code": null,
"e": 26020,
"s": 25886,
"text": " col_1 col_2 col_3 col_4\nrow_1 5 6 7 8\nrow_2 9 10 11 12\nrow_3 13 14 15 16\n[1] \"matrix\"\n"
},
{
"code": null,
"e": 26175,
"s": 26020,
"text": "If matrix to be created using data present in multiple vectors, then vector of multiple vectors is created and passed to matrix() function as an argument."
},
{
"code": null,
"e": 26186,
"s": 26175,
"text": "Example 2:"
},
{
"code": "# defining multiple vectorsx <- c(1:5)y <- c(11:15)z <- c(21:25) # creating matrixm <- matrix(c(x, y, z), ncol = 3) # print matrixprint(m) # print class of mclass(m)",
"e": 26355,
"s": 26186,
"text": null
},
{
"code": null,
"e": 26363,
"s": 26355,
"text": "Output:"
},
{
"code": null,
"e": 26505,
"s": 26363,
"text": " [, 1] [, 2] [, 3]\n[1, ] 1 11 21\n[2, ] 2 12 22\n[3, ] 3 13 23\n[4, ] 4 14 24\n[5, ] 5 15 25\n[1] \"matrix\"\n"
},
{
"code": null,
"e": 26701,
"s": 26505,
"text": "cbind() function in R programming is used to combine vectors, data frames or matrices by columns and number of rows of data sets should be equal otherwise, output will be incomprehensible.Syntax:"
},
{
"code": null,
"e": 26742,
"s": 26701,
"text": "cbind(v1, v2, v3, ....., deparse.level)\n"
},
{
"code": null,
"e": 26749,
"s": 26742,
"text": "where,"
},
{
"code": null,
"e": 26963,
"s": 26749,
"text": "v1, v2, v3, .... represent vectors, matrices or data framesdeparse.level used for constructing labels for non-matrix like arguments. 0 for no labels. Default value is 1 or 2 for labelling from the arguments names."
},
{
"code": null,
"e": 26972,
"s": 26963,
"text": "Example:"
},
{
"code": "# defining multiple vectorsx <- c(1:5)y <- c(11:15)z <- c(21:25) # creating matrixm <- cbind(x, y, z) # print matrixprint(m) # print class of mclass(m)",
"e": 27127,
"s": 26972,
"text": null
},
{
"code": null,
"e": 27135,
"s": 27127,
"text": "Output:"
},
{
"code": null,
"e": 27232,
"s": 27135,
"text": " x y z\n[1, ] 1 11 21\n[2, ] 2 12 22\n[3, ] 3 13 23\n[4, ] 4 14 24\n[5, ] 5 15 25\n[1] \"matrix\"\n"
},
{
"code": null,
"e": 27425,
"s": 27232,
"text": "rbind() function in R programming is used to combine vectors, data frames or matrices by rows and number of columns of data sets should be equal otherwise, output will be insignificant.Syntax:"
},
{
"code": null,
"e": 27466,
"s": 27425,
"text": "rbind(v1, v2, v3, ....., deparse.level)\n"
},
{
"code": null,
"e": 27473,
"s": 27466,
"text": "where,"
},
{
"code": null,
"e": 27687,
"s": 27473,
"text": "v1, v2, v3, .... represent vectors, matrices or data framesdeparse.level used for constructing labels for non-matrix like arguments. 0 for no labels. Default value is 1 or 2 for labelling from the arguments names."
},
{
"code": null,
"e": 27696,
"s": 27687,
"text": "Example:"
},
{
"code": "# defining multiple vectorsx <- c(1:5)y <- c(11:15)z <- c(21:25) # creating matrixn <- rbind(x, y, z) # print matrixprint(n) # print class of mclass(n)",
"e": 27851,
"s": 27696,
"text": null
},
{
"code": null,
"e": 27859,
"s": 27851,
"text": "Output:"
},
{
"code": null,
"e": 27986,
"s": 27859,
"text": " [, 1] [, 2] [, 3] [, 4] [, 5]\nx 1 2 3 4 5\ny 11 12 13 14 15\nz 21 22 23 24 25\n[1] \"matrix\"\n"
},
{
"code": null,
"e": 27993,
"s": 27986,
"text": "Picked"
},
{
"code": null,
"e": 28002,
"s": 27993,
"text": "R-Matrix"
},
{
"code": null,
"e": 28013,
"s": 28002,
"text": "R Language"
},
{
"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": 28120,
"s": 28111,
"text": "Comments"
},
{
"code": null,
"e": 28133,
"s": 28120,
"text": "Old Comments"
},
{
"code": null,
"e": 28191,
"s": 28133,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 28235,
"s": 28191,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 28287,
"s": 28235,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 28339,
"s": 28287,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 28371,
"s": 28339,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 28403,
"s": 28371,
"text": "Printing Output of an R Program"
},
{
"code": null,
"e": 28441,
"s": 28403,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 28476,
"s": 28441,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 28534,
"s": 28476,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
}
]
|
Ruby - Exceptions | The execution and the exception always go together. If you are opening a file, which does not exist, then if you did not handle this situation properly, then your program is considered to be of bad quality.
The program stops if an exception occurs. So exceptions are used to handle various type of errors, which may occur during a program execution and take appropriate action instead of halting program completely.
Ruby provide a nice mechanism to handle exceptions. We enclose the code that could raise an exception in a begin/end block and use rescue clauses to tell Ruby the types of exceptions we want to handle.
begin
# -
rescue OneTypeOfException
# -
rescue AnotherTypeOfException
# -
else
# Other exceptions
ensure
# Always will be executed
end
Everything from begin to rescue is protected. If an exception occurs during the execution of this block of code, control is passed to the block between rescue and end.
For each rescue clause in the begin block, Ruby compares the raised Exception against each of the parameters in turn. The match will succeed if the exception named in the rescue clause is the same as the type of the currently thrown exception, or is a superclass of that exception.
In an event that an exception does not match any of the error types specified, we are allowed to use an else clause after all the rescue clauses.
#!/usr/bin/ruby
begin
file = open("/unexistant_file")
if file
puts "File opened successfully"
end
rescue
file = STDIN
end
print file, "==", STDIN, "\n"
This will produce the following result. You can see that STDIN is substituted to file because open failed.
#<IO:0xb7d16f84>==#<IO:0xb7d16f84>
You can capture an exception using rescue block and then use retry statement to execute begin block from the beginning.
begin
# Exceptions raised by this code will
# be caught by the following rescue clause
rescue
# This block will capture all types of exceptions
retry # This will move control to the beginning of begin
end
#!/usr/bin/ruby
begin
file = open("/unexistant_file")
if file
puts "File opened successfully"
end
rescue
fname = "existant_file"
retry
end
The following is the flow of the process −
An exception occurred at open.
Went to rescue. fname was re-assigned.
By retry went to the beginning of the begin.
This time file opens successfully.
Continued the essential process.
NOTE − Notice that if the file of re-substituted name does not exist this example code retries infinitely. Be careful if you use retry for an exception process.
You can use raise statement to raise an exception. The following method raises an exception whenever it's called. It's second message will be printed.
raise
OR
raise "Error Message"
OR
raise ExceptionType, "Error Message"
OR
raise ExceptionType, "Error Message" condition
The first form simply re-raises the current exception (or a RuntimeError if there is no current exception). This is used in exception handlers that need to intercept an exception before passing it on.
The second form creates a new RuntimeError exception, setting its message to the given string. This exception is then raised up the call stack.
The third form uses the first argument to create an exception and then sets the associated message to the second argument.
The fourth form is similar to the third form but you can add any conditional statement like unless to raise an exception.
#!/usr/bin/ruby
begin
puts 'I am before the raise.'
raise 'An error has occurred.'
puts 'I am after the raise.'
rescue
puts 'I am rescued.'
end
puts 'I am after the begin block.'
This will produce the following result −
I am before the raise.
I am rescued.
I am after the begin block.
One more example showing the usage of raise −
#!/usr/bin/ruby
begin
raise 'A test exception.'
rescue Exception => e
puts e.message
puts e.backtrace.inspect
end
This will produce the following result −
A test exception.
["main.rb:4"]
Sometimes, you need to guarantee that some processing is done at the end of a block of code, regardless of whether an exception was raised. For example, you may have a file open on entry to the block and you need to make sure it gets closed as the block exits.
The ensure clause does just this. ensure goes after the last rescue clause and contains a chunk of code that will always be executed as the block terminates. It doesn't matter if the block exits normally, if it raises and rescues an exception, or if it is terminated by an uncaught exception, the ensure block will get run.
begin
#.. process
#..raise exception
rescue
#.. handle error
ensure
#.. finally ensure execution
#.. This will always execute.
end
begin
raise 'A test exception.'
rescue Exception => e
puts e.message
puts e.backtrace.inspect
ensure
puts "Ensuring execution"
end
This will produce the following result −
A test exception.
["main.rb:4"]
Ensuring execution
If the else clause is present, it goes after the rescue clauses and before any ensure.
The body of an else clause is executed only if no exceptions are raised by the main body of code.
begin
#.. process
#..raise exception
rescue
# .. handle error
else
#.. executes if there is no exception
ensure
#.. finally ensure execution
#.. This will always execute.
end
begin
# raise 'A test exception.'
puts "I'm not raising exception"
rescue Exception => e
puts e.message
puts e.backtrace.inspect
else
puts "Congratulations-- no errors!"
ensure
puts "Ensuring execution"
end
This will produce the following result −
I'm not raising exception
Congratulations-- no errors!
Ensuring execution
Raised error message can be captured using $! variable.
While the exception mechanism of raise and rescue is great for abandoning the execution when things go wrong, it's sometimes nice to be able to jump out of some deeply nested construct during normal processing. This is where catch and throw come in handy.
The catch defines a block that is labeled with the given name (which may be a Symbol or a String). The block is executed normally until a throw is encountered.
throw :lablename
#.. this will not be executed
catch :lablename do
#.. matching catch will be executed after a throw is encountered.
end
OR
throw :lablename condition
#.. this will not be executed
catch :lablename do
#.. matching catch will be executed after a throw is encountered.
end
The following example uses a throw to terminate interaction with the user if '!' is typed in response to any prompt.
def promptAndGet(prompt)
print prompt
res = readline.chomp
throw :quitRequested if res == "!"
return res
end
catch :quitRequested do
name = promptAndGet("Name: ")
age = promptAndGet("Age: ")
sex = promptAndGet("Sex: ")
# ..
# process information
end
promptAndGet("Name:")
You should try the above program on your machine because it needs manual interaction. This will produce the following result −
Name: Ruby on Rails
Age: 3
Sex: !
Name:Just Ruby
Ruby's standard classes and modules raise exceptions. All the exception classes form a hierarchy, with the class Exception at the top. The next level contains seven different types −
Interrupt
NoMemoryError
SignalException
ScriptError
StandardError
SystemExit
There is one other exception at this level, Fatal, but the Ruby interpreter only uses this internally.
Both ScriptError and StandardError have a number of subclasses, but we do not need to go into the details here. The important thing is that if we create our own exception classes, they need to be subclasses of either class Exception or one of its descendants.
Let's look at an example −
class FileSaveError < StandardError
attr_reader :reason
def initialize(reason)
@reason = reason
end
end
Now, look at the following example, which will use this exception −
File.open(path, "w") do |file|
begin
# Write out the data ...
rescue
# Something went wrong!
raise FileSaveError.new($!)
end
end
The important line here is raise FileSaveError.new($!). We call raise to signal that an exception has occurred, passing it a new instance of FileSaveError, with the reason being that specific exception caused the writing of the data to fail.
46 Lectures
9.5 hours
Eduonix Learning Solutions
97 Lectures
7.5 hours
Skillbakerystudios
227 Lectures
40 hours
YouAccel
19 Lectures
10 hours
Programming Line
51 Lectures
5 hours
Stone River ELearning
39 Lectures
4.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2501,
"s": 2294,
"text": "The execution and the exception always go together. If you are opening a file, which does not exist, then if you did not handle this situation properly, then your program is considered to be of bad quality."
},
{
"code": null,
"e": 2710,
"s": 2501,
"text": "The program stops if an exception occurs. So exceptions are used to handle various type of errors, which may occur during a program execution and take appropriate action instead of halting program completely."
},
{
"code": null,
"e": 2912,
"s": 2710,
"text": "Ruby provide a nice mechanism to handle exceptions. We enclose the code that could raise an exception in a begin/end block and use rescue clauses to tell Ruby the types of exceptions we want to handle."
},
{
"code": null,
"e": 3062,
"s": 2912,
"text": "begin \n# - \nrescue OneTypeOfException \n# - \nrescue AnotherTypeOfException \n# - \nelse \n# Other exceptions\nensure\n# Always will be executed\nend\n"
},
{
"code": null,
"e": 3230,
"s": 3062,
"text": "Everything from begin to rescue is protected. If an exception occurs during the execution of this block of code, control is passed to the block between rescue and end."
},
{
"code": null,
"e": 3512,
"s": 3230,
"text": "For each rescue clause in the begin block, Ruby compares the raised Exception against each of the parameters in turn. The match will succeed if the exception named in the rescue clause is the same as the type of the currently thrown exception, or is a superclass of that exception."
},
{
"code": null,
"e": 3658,
"s": 3512,
"text": "In an event that an exception does not match any of the error types specified, we are allowed to use an else clause after all the rescue clauses."
},
{
"code": null,
"e": 3832,
"s": 3658,
"text": "#!/usr/bin/ruby\n\nbegin\n file = open(\"/unexistant_file\")\n if file\n puts \"File opened successfully\"\n end\nrescue\n file = STDIN\nend\nprint file, \"==\", STDIN, \"\\n\""
},
{
"code": null,
"e": 3939,
"s": 3832,
"text": "This will produce the following result. You can see that STDIN is substituted to file because open failed."
},
{
"code": null,
"e": 3975,
"s": 3939,
"text": "#<IO:0xb7d16f84>==#<IO:0xb7d16f84>\n"
},
{
"code": null,
"e": 4095,
"s": 3975,
"text": "You can capture an exception using rescue block and then use retry statement to execute begin block from the beginning."
},
{
"code": null,
"e": 4315,
"s": 4095,
"text": "begin\n # Exceptions raised by this code will \n # be caught by the following rescue clause\nrescue\n # This block will capture all types of exceptions\n retry # This will move control to the beginning of begin\nend\n"
},
{
"code": null,
"e": 4476,
"s": 4315,
"text": "#!/usr/bin/ruby\n\nbegin\n file = open(\"/unexistant_file\")\n if file\n puts \"File opened successfully\"\n end\nrescue\n fname = \"existant_file\"\n retry\nend"
},
{
"code": null,
"e": 4519,
"s": 4476,
"text": "The following is the flow of the process −"
},
{
"code": null,
"e": 4550,
"s": 4519,
"text": "An exception occurred at open."
},
{
"code": null,
"e": 4589,
"s": 4550,
"text": "Went to rescue. fname was re-assigned."
},
{
"code": null,
"e": 4634,
"s": 4589,
"text": "By retry went to the beginning of the begin."
},
{
"code": null,
"e": 4669,
"s": 4634,
"text": "This time file opens successfully."
},
{
"code": null,
"e": 4702,
"s": 4669,
"text": "Continued the essential process."
},
{
"code": null,
"e": 4863,
"s": 4702,
"text": "NOTE − Notice that if the file of re-substituted name does not exist this example code retries infinitely. Be careful if you use retry for an exception process."
},
{
"code": null,
"e": 5014,
"s": 4863,
"text": "You can use raise statement to raise an exception. The following method raises an exception whenever it's called. It's second message will be printed."
},
{
"code": null,
"e": 5144,
"s": 5014,
"text": "raise \n\nOR\n\nraise \"Error Message\" \n\nOR\n\nraise ExceptionType, \"Error Message\"\n\nOR\n\nraise ExceptionType, \"Error Message\" condition\n"
},
{
"code": null,
"e": 5345,
"s": 5144,
"text": "The first form simply re-raises the current exception (or a RuntimeError if there is no current exception). This is used in exception handlers that need to intercept an exception before passing it on."
},
{
"code": null,
"e": 5489,
"s": 5345,
"text": "The second form creates a new RuntimeError exception, setting its message to the given string. This exception is then raised up the call stack."
},
{
"code": null,
"e": 5612,
"s": 5489,
"text": "The third form uses the first argument to create an exception and then sets the associated message to the second argument."
},
{
"code": null,
"e": 5734,
"s": 5612,
"text": "The fourth form is similar to the third form but you can add any conditional statement like unless to raise an exception."
},
{
"code": null,
"e": 5942,
"s": 5734,
"text": "#!/usr/bin/ruby\n\nbegin \n puts 'I am before the raise.' \n raise 'An error has occurred.' \n puts 'I am after the raise.' \nrescue \n puts 'I am rescued.' \nend \nputs 'I am after the begin block.' "
},
{
"code": null,
"e": 5983,
"s": 5942,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 6055,
"s": 5983,
"text": "I am before the raise. \nI am rescued. \nI am after the begin block. \n"
},
{
"code": null,
"e": 6101,
"s": 6055,
"text": "One more example showing the usage of raise −"
},
{
"code": null,
"e": 6237,
"s": 6101,
"text": "#!/usr/bin/ruby\n\nbegin \n raise 'A test exception.' \nrescue Exception => e \n puts e.message \n puts e.backtrace.inspect \nend "
},
{
"code": null,
"e": 6278,
"s": 6237,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 6311,
"s": 6278,
"text": "A test exception.\n[\"main.rb:4\"]\n"
},
{
"code": null,
"e": 6572,
"s": 6311,
"text": "Sometimes, you need to guarantee that some processing is done at the end of a block of code, regardless of whether an exception was raised. For example, you may have a file open on entry to the block and you need to make sure it gets closed as the block exits."
},
{
"code": null,
"e": 6896,
"s": 6572,
"text": "The ensure clause does just this. ensure goes after the last rescue clause and contains a chunk of code that will always be executed as the block terminates. It doesn't matter if the block exits normally, if it raises and rescues an exception, or if it is terminated by an uncaught exception, the ensure block will get run."
},
{
"code": null,
"e": 7048,
"s": 6896,
"text": "begin \n #.. process \n #..raise exception\nrescue \n #.. handle error \nensure \n #.. finally ensure execution\n #.. This will always execute.\nend\n"
},
{
"code": null,
"e": 7191,
"s": 7048,
"text": "begin\n raise 'A test exception.'\nrescue Exception => e\n puts e.message\n puts e.backtrace.inspect\nensure\n puts \"Ensuring execution\"\nend"
},
{
"code": null,
"e": 7232,
"s": 7191,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 7284,
"s": 7232,
"text": "A test exception.\n[\"main.rb:4\"]\nEnsuring execution\n"
},
{
"code": null,
"e": 7371,
"s": 7284,
"text": "If the else clause is present, it goes after the rescue clauses and before any ensure."
},
{
"code": null,
"e": 7469,
"s": 7371,
"text": "The body of an else clause is executed only if no exceptions are raised by the main body of code."
},
{
"code": null,
"e": 7667,
"s": 7469,
"text": "begin \n #.. process \n #..raise exception\nrescue \n # .. handle error\nelse\n #.. executes if there is no exception\nensure \n #.. finally ensure execution\n #.. This will always execute.\nend\n"
},
{
"code": null,
"e": 7892,
"s": 7667,
"text": "begin\n # raise 'A test exception.'\n puts \"I'm not raising exception\"\nrescue Exception => e\n puts e.message\n puts e.backtrace.inspect\nelse\n puts \"Congratulations-- no errors!\"\nensure\n puts \"Ensuring execution\"\nend"
},
{
"code": null,
"e": 7933,
"s": 7892,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 8008,
"s": 7933,
"text": "I'm not raising exception\nCongratulations-- no errors!\nEnsuring execution\n"
},
{
"code": null,
"e": 8064,
"s": 8008,
"text": "Raised error message can be captured using $! variable."
},
{
"code": null,
"e": 8320,
"s": 8064,
"text": "While the exception mechanism of raise and rescue is great for abandoning the execution when things go wrong, it's sometimes nice to be able to jump out of some deeply nested construct during normal processing. This is where catch and throw come in handy."
},
{
"code": null,
"e": 8480,
"s": 8320,
"text": "The catch defines a block that is labeled with the given name (which may be a Symbol or a String). The block is executed normally until a throw is encountered."
},
{
"code": null,
"e": 8770,
"s": 8480,
"text": "throw :lablename\n#.. this will not be executed\ncatch :lablename do\n#.. matching catch will be executed after a throw is encountered.\nend\n\nOR\n\nthrow :lablename condition\n#.. this will not be executed\ncatch :lablename do\n#.. matching catch will be executed after a throw is encountered.\nend\n"
},
{
"code": null,
"e": 8887,
"s": 8770,
"text": "The following example uses a throw to terminate interaction with the user if '!' is typed in response to any prompt."
},
{
"code": null,
"e": 9187,
"s": 8887,
"text": "def promptAndGet(prompt)\n print prompt\n res = readline.chomp\n throw :quitRequested if res == \"!\"\n return res\nend\n\ncatch :quitRequested do\n name = promptAndGet(\"Name: \")\n age = promptAndGet(\"Age: \")\n sex = promptAndGet(\"Sex: \")\n # ..\n # process information\nend\npromptAndGet(\"Name:\")"
},
{
"code": null,
"e": 9314,
"s": 9187,
"text": "You should try the above program on your machine because it needs manual interaction. This will produce the following result −"
},
{
"code": null,
"e": 9364,
"s": 9314,
"text": "Name: Ruby on Rails\nAge: 3\nSex: !\nName:Just Ruby\n"
},
{
"code": null,
"e": 9547,
"s": 9364,
"text": "Ruby's standard classes and modules raise exceptions. All the exception classes form a hierarchy, with the class Exception at the top. The next level contains seven different types −"
},
{
"code": null,
"e": 9557,
"s": 9547,
"text": "Interrupt"
},
{
"code": null,
"e": 9571,
"s": 9557,
"text": "NoMemoryError"
},
{
"code": null,
"e": 9587,
"s": 9571,
"text": "SignalException"
},
{
"code": null,
"e": 9599,
"s": 9587,
"text": "ScriptError"
},
{
"code": null,
"e": 9613,
"s": 9599,
"text": "StandardError"
},
{
"code": null,
"e": 9624,
"s": 9613,
"text": "SystemExit"
},
{
"code": null,
"e": 9727,
"s": 9624,
"text": "There is one other exception at this level, Fatal, but the Ruby interpreter only uses this internally."
},
{
"code": null,
"e": 9987,
"s": 9727,
"text": "Both ScriptError and StandardError have a number of subclasses, but we do not need to go into the details here. The important thing is that if we create our own exception classes, they need to be subclasses of either class Exception or one of its descendants."
},
{
"code": null,
"e": 10014,
"s": 9987,
"text": "Let's look at an example −"
},
{
"code": null,
"e": 10133,
"s": 10014,
"text": "class FileSaveError < StandardError\n attr_reader :reason\n def initialize(reason)\n @reason = reason\n end\nend"
},
{
"code": null,
"e": 10201,
"s": 10133,
"text": "Now, look at the following example, which will use this exception −"
},
{
"code": null,
"e": 10339,
"s": 10201,
"text": "File.open(path, \"w\") do |file|\nbegin\n # Write out the data ...\nrescue\n # Something went wrong!\n raise FileSaveError.new($!)\nend\nend"
},
{
"code": null,
"e": 10581,
"s": 10339,
"text": "The important line here is raise FileSaveError.new($!). We call raise to signal that an exception has occurred, passing it a new instance of FileSaveError, with the reason being that specific exception caused the writing of the data to fail."
},
{
"code": null,
"e": 10616,
"s": 10581,
"text": "\n 46 Lectures \n 9.5 hours \n"
},
{
"code": null,
"e": 10644,
"s": 10616,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 10679,
"s": 10644,
"text": "\n 97 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 10699,
"s": 10679,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 10734,
"s": 10699,
"text": "\n 227 Lectures \n 40 hours \n"
},
{
"code": null,
"e": 10744,
"s": 10734,
"text": " YouAccel"
},
{
"code": null,
"e": 10778,
"s": 10744,
"text": "\n 19 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 10796,
"s": 10778,
"text": " Programming Line"
},
{
"code": null,
"e": 10829,
"s": 10796,
"text": "\n 51 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 10852,
"s": 10829,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 10887,
"s": 10852,
"text": "\n 39 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 10910,
"s": 10887,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 10917,
"s": 10910,
"text": " Print"
},
{
"code": null,
"e": 10928,
"s": 10917,
"text": " Add Notes"
}
]
|
C++ STL List | Practice | GeeksforGeeks | Implement different operation on List A i.e. adding an element in front and end, removing an element from the front and end, sorting elements, reversing the list and printing the list.
Input:
The first line of input contains an integer T denoting the no of test cases.For each test case, the first line of input contains an integer Q denoting the no of queries. Then in the next line are Q space separated queries.
A query can be of eight types
1 x (Adds an element x to the list A at the end and print list A)
2 (Sorts the list A in ascending order and print list A )
3 (Reverses the list A and print list A)
4 (Prints the size of the list A)
5 (Prints space-separated values of the list)
6 (Remove an element from the back of the list and print list A )
7(Remove an element from the front of the list and print list A)
8 x (Adds element x in front of the list and print list A)
Output:
The output for each test case will be according to the query that is performed and if the list is empty output is -1.
Constraints:
1<=T<=100
1<=Q<=100
Example:
Input:
1
8
1 5
8 1
3
4
5
6
1 6
7
Output:
5
1 5
5 1
2
5 1
5
5 6
6
0
sagargupta25265 months ago
Can i use cbegin
+1
Purushottam Bca8 months ago
Purushottam Bca
void print(list<int> &A){ if(A.empty()) cout<<"-1"; else { for(auto i=A.begin();i!=A.end();i++) cout<<*i<<" "; } cout<<"\n";}void remove_from_back(list<int> &A){if(A.empty()) cout<<"-1";else A.pop_back();}void remove_from_front(list<int> &A){if(A.empty()) cout<<"-1";else A.pop_front();}void add_to_list(list<int> &A,int x){ A.push_back(x);}void sort_list(list<int> &A){ if(A.empty()) cout<<"-1"; else A.sort();}void reverse_list(list<int> &A){if(A.empty()) cout<<"-1";else A.reverse();}int size_of_list(list<int> &A){ return A.size();}void add_from_front(list<int> &A,int x){ A.push_front(x);}
0
Purushottam Bca8 months ago
Purushottam Bca
NOTE -> READ OUTPUT FORMAT CAREFULLY
0
Sukesh Seth1 year ago
Sukesh Seth
/*User function Template for C++You are required to complete below methods*//*prints space separated elements of list A*/void print(list<int> &A){ if(A.empty()){ cout << -1 << "\n"; return; } for(auto x: A) cout << x << " "; cout << "\n";}/*remove element from back of list A*/void remove_from_back(list<int> &A){ A.pop_back(); return;}/*remove element from front of list A*/void remove_from_front(list<int> &A){ A.pop_front(); return;}/*inserts an element x at the back of the list A */void add_to_list(list<int> &A,int x){ A.emplace_back(x); return;}/*sort the list A in ascending order*/void sort_list(list<int> &A){ A.sort(); return;}/*reverses the list A*/void reverse_list(list<int> &A){ A.reverse(); return;}/*returns the size of the list A */int size_of_list(list<int> &A){ return A.size();}/*inserts an element x at the front of the list A*/void add_from_front(list<int> &A,int x){ A.emplace_front(x); return;}
0
GauriK1 year ago
GauriK
void print(list<int> &A)why we use &A???
0
Amar Prakash1 year ago
Amar Prakash
void print(list<int> &A){ if(A.empty()) { cout<<"-1"; } else { for(auto x: A) { cout<<x<<" ";="" }="" }="" cout<<endl;="" your="" code="" here="" }="" *remove="" element="" from="" back="" of="" list="" a*="" void="" remove_from_back(list<int=""> &A){ if(A.empty()) { cout<<"-1"; } else { A.pop_back();
}
//Your code here}/*remove element from front of list A*/void remove_from_front(list<int> &A){ if(A.empty()) { cout<<"-1"; } else { A.pop_front(); } //Your code here}
/*inserts an element x at the back of the list A */void add_to_list(list<int> &A,int x){ A.push_back(x);//Your code here}
/*sort the list A in ascending order*/void sort_list(list<int> &A){ if(A.empty()) { cout<<"-1"; } else { A.sort(); }//Your code here}
/*reverses the list A*/void reverse_list(list<int> &A){ if(A.empty()) { cout<<"-1"; } else { A.reverse(); }//Your code here}
/*returns the size of the list A */int size_of_list(list<int> &A){ return A.size(); cout<<endl; your="" code="" here="" }="" *inserts="" an="" element="" x="" at="" the="" front="" of="" the="" list="" a*="" void="" add_from_front(list<int=""> &A,int x){ A.push_front(x);//Your code here}
0
Yash Parmar2 years ago
Yash Parmar
void print(list<int> &A){list<int> :: iterator i;if(A.empty()) cout<<"-1";else {for(i=A.begin();i!=A.end();i++) cout<<*i<<" ";}cout<<"\n";}/*remove element from back of list A*/void remove_from_back(list<int> &A){ if(A.empty()) cout<<"-1"; else A.pop_back();}/*remove element from front of list A*/void remove_from_front(list<int> &A){ if(A.empty()) cout<<"-1"; else A.pop_front();}/*inserts an element x at the back of the list A */void add_to_list(list<int> &A,int x){A.push_back(x);}/*sort the list A in ascending order*/void sort_list(list<int> &A){if(A.empty()) cout<<"-1";else A.sort();}/*reverses the list A*/void reverse_list(list<int> &A){if(A.empty()) cout<<"-1";else A.reverse();}/*returns the size of the list A */int size_of_list(list<int> &A){ return A.size();
}/*inserts an element x at the front of the list A*/void add_from_front(list<int> &A,int x){A.push_front(x);}
0
Anurag Parothia2 years ago
Anurag Parothia
Someone please helpWrong Answer. !!!
Possibly your code doesn't work correctly for multiple test-cases (TCs).
The first test case where your code failed:
Input:208 568321 951732721 193
void print(list<int> &A){//Your code herefor (auto it = A.begin(); it != A.end(); ++it) { cout<<*it<<" ";}cout<<endl; }="" *remove="" element="" from="" back="" of="" list="" a*="" void="" remove_from_back(list<int=""> &A){ //Your code here A.pop_back();}/*remove element from front of list A*/void remove_from_front(list<int> &A){ //Your code here if(A.empty()) cout<<"-1"; A.pop_front();}/*inserts an element x at the back of the list A */void add_to_list(list<int> &A,int x){//Your code hereA.push_back(x);}/*sort the list A in ascending order*/void sort_list(list<int> &A){//Your code hereA.sort();}/*reverses the list A*/void reverse_list(list<int> &A){//Your code hereA.reverse();}/*returns the size of the list A */int size_of_list(list<int> &A){//Your code herereturn A.size();}/*inserts an element x at the front of the list A*/void add_from_front(list<int> &A,int x){//Your code hereA.push_front(x);}
0
Deepak Yadav4 years ago
Deepak Yadav
I case u stuck see this https://ide.geeksforgeeks.o...
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": 423,
"s": 238,
"text": "Implement different operation on List A i.e. adding an element in front and end, removing an element from the front and end, sorting elements, reversing the list and printing the list."
},
{
"code": null,
"e": 1119,
"s": 423,
"text": "Input:\nThe first line of input contains an integer T denoting the no of test cases.For each test case, the first line of input contains an integer Q denoting the no of queries. Then in the next line are Q space separated queries.\nA query can be of eight types \n1 x (Adds an element x to the list A at the end and print list A)\n2 (Sorts the list A in ascending order and print list A )\n3 (Reverses the list A and print list A)\n4 (Prints the size of the list A)\n5 (Prints space-separated values of the list)\n6 (Remove an element from the back of the list and print list A )\n7(Remove an element from the front of the list and print list A)\n8 x (Adds element x in front of the list and print list A)"
},
{
"code": null,
"e": 1246,
"s": 1119,
"text": "Output:\nThe output for each test case will be according to the query that is performed and if the list is empty output is -1. "
},
{
"code": null,
"e": 1279,
"s": 1246,
"text": "Constraints:\n1<=T<=100\n1<=Q<=100"
},
{
"code": null,
"e": 1354,
"s": 1279,
"text": "Example:\nInput:\n1\n8\n1 5\n8 1\n3\n4\n5\n6\n1 6\n7\nOutput:\n5\n1 5\n5 1 \n2\n5 1\n5\n5 6\n6"
},
{
"code": null,
"e": 1356,
"s": 1354,
"text": "0"
},
{
"code": null,
"e": 1383,
"s": 1356,
"text": "sagargupta25265 months ago"
},
{
"code": null,
"e": 1400,
"s": 1383,
"text": "Can i use cbegin"
},
{
"code": null,
"e": 1403,
"s": 1400,
"text": "+1"
},
{
"code": null,
"e": 1431,
"s": 1403,
"text": "Purushottam Bca8 months ago"
},
{
"code": null,
"e": 1447,
"s": 1431,
"text": "Purushottam Bca"
},
{
"code": null,
"e": 2132,
"s": 1447,
"text": "void print(list<int> &A){ if(A.empty()) cout<<\"-1\"; else { for(auto i=A.begin();i!=A.end();i++) cout<<*i<<\" \"; } cout<<\"\\n\";}void remove_from_back(list<int> &A){if(A.empty()) cout<<\"-1\";else A.pop_back();}void remove_from_front(list<int> &A){if(A.empty()) cout<<\"-1\";else A.pop_front();}void add_to_list(list<int> &A,int x){ A.push_back(x);}void sort_list(list<int> &A){ if(A.empty()) cout<<\"-1\"; else A.sort();}void reverse_list(list<int> &A){if(A.empty()) cout<<\"-1\";else A.reverse();}int size_of_list(list<int> &A){ return A.size();}void add_from_front(list<int> &A,int x){ A.push_front(x);}"
},
{
"code": null,
"e": 2134,
"s": 2132,
"text": "0"
},
{
"code": null,
"e": 2162,
"s": 2134,
"text": "Purushottam Bca8 months ago"
},
{
"code": null,
"e": 2178,
"s": 2162,
"text": "Purushottam Bca"
},
{
"code": null,
"e": 2215,
"s": 2178,
"text": "NOTE -> READ OUTPUT FORMAT CAREFULLY"
},
{
"code": null,
"e": 2217,
"s": 2215,
"text": "0"
},
{
"code": null,
"e": 2239,
"s": 2217,
"text": "Sukesh Seth1 year ago"
},
{
"code": null,
"e": 2251,
"s": 2239,
"text": "Sukesh Seth"
},
{
"code": null,
"e": 3240,
"s": 2251,
"text": "/*User function Template for C++You are required to complete below methods*//*prints space separated elements of list A*/void print(list<int> &A){ if(A.empty()){ cout << -1 << \"\\n\"; return; } for(auto x: A) cout << x << \" \"; cout << \"\\n\";}/*remove element from back of list A*/void remove_from_back(list<int> &A){ A.pop_back(); return;}/*remove element from front of list A*/void remove_from_front(list<int> &A){ A.pop_front(); return;}/*inserts an element x at the back of the list A */void add_to_list(list<int> &A,int x){ A.emplace_back(x); return;}/*sort the list A in ascending order*/void sort_list(list<int> &A){ A.sort(); return;}/*reverses the list A*/void reverse_list(list<int> &A){ A.reverse(); return;}/*returns the size of the list A */int size_of_list(list<int> &A){ return A.size();}/*inserts an element x at the front of the list A*/void add_from_front(list<int> &A,int x){ A.emplace_front(x); return;}"
},
{
"code": null,
"e": 3242,
"s": 3240,
"text": "0"
},
{
"code": null,
"e": 3259,
"s": 3242,
"text": "GauriK1 year ago"
},
{
"code": null,
"e": 3266,
"s": 3259,
"text": "GauriK"
},
{
"code": null,
"e": 3307,
"s": 3266,
"text": "void print(list<int> &A)why we use &A???"
},
{
"code": null,
"e": 3309,
"s": 3307,
"text": "0"
},
{
"code": null,
"e": 3332,
"s": 3309,
"text": "Amar Prakash1 year ago"
},
{
"code": null,
"e": 3345,
"s": 3332,
"text": "Amar Prakash"
},
{
"code": null,
"e": 3722,
"s": 3345,
"text": "void print(list<int> &A){ if(A.empty()) { cout<<\"-1\"; } else { for(auto x: A) { cout<<x<<\" \";=\"\" }=\"\" }=\"\" cout<<endl;=\"\" your=\"\" code=\"\" here=\"\" }=\"\" *remove=\"\" element=\"\" from=\"\" back=\"\" of=\"\" list=\"\" a*=\"\" void=\"\" remove_from_back(list<int=\"\"> &A){ if(A.empty()) { cout<<\"-1\"; } else { A.pop_back();"
},
{
"code": null,
"e": 3728,
"s": 3722,
"text": " }"
},
{
"code": null,
"e": 3930,
"s": 3728,
"text": " //Your code here}/*remove element from front of list A*/void remove_from_front(list<int> &A){ if(A.empty()) { cout<<\"-1\"; } else { A.pop_front(); } //Your code here}"
},
{
"code": null,
"e": 4055,
"s": 3930,
"text": "/*inserts an element x at the back of the list A */void add_to_list(list<int> &A,int x){ A.push_back(x);//Your code here}"
},
{
"code": null,
"e": 4221,
"s": 4055,
"text": "/*sort the list A in ascending order*/void sort_list(list<int> &A){ if(A.empty()) { cout<<\"-1\"; } else { A.sort(); }//Your code here}"
},
{
"code": null,
"e": 4376,
"s": 4221,
"text": "/*reverses the list A*/void reverse_list(list<int> &A){ if(A.empty()) { cout<<\"-1\"; } else { A.reverse(); }//Your code here}"
},
{
"code": null,
"e": 4676,
"s": 4376,
"text": "/*returns the size of the list A */int size_of_list(list<int> &A){ return A.size(); cout<<endl; your=\"\" code=\"\" here=\"\" }=\"\" *inserts=\"\" an=\"\" element=\"\" x=\"\" at=\"\" the=\"\" front=\"\" of=\"\" the=\"\" list=\"\" a*=\"\" void=\"\" add_from_front(list<int=\"\"> &A,int x){ A.push_front(x);//Your code here}"
},
{
"code": null,
"e": 4678,
"s": 4676,
"text": "0"
},
{
"code": null,
"e": 4701,
"s": 4678,
"text": "Yash Parmar2 years ago"
},
{
"code": null,
"e": 4713,
"s": 4701,
"text": "Yash Parmar"
},
{
"code": null,
"e": 5501,
"s": 4713,
"text": "void print(list<int> &A){list<int> :: iterator i;if(A.empty()) cout<<\"-1\";else {for(i=A.begin();i!=A.end();i++) cout<<*i<<\" \";}cout<<\"\\n\";}/*remove element from back of list A*/void remove_from_back(list<int> &A){ if(A.empty()) cout<<\"-1\"; else A.pop_back();}/*remove element from front of list A*/void remove_from_front(list<int> &A){ if(A.empty()) cout<<\"-1\"; else A.pop_front();}/*inserts an element x at the back of the list A */void add_to_list(list<int> &A,int x){A.push_back(x);}/*sort the list A in ascending order*/void sort_list(list<int> &A){if(A.empty()) cout<<\"-1\";else A.sort();}/*reverses the list A*/void reverse_list(list<int> &A){if(A.empty()) cout<<\"-1\";else A.reverse();}/*returns the size of the list A */int size_of_list(list<int> &A){ return A.size();"
},
{
"code": null,
"e": 5611,
"s": 5501,
"text": "}/*inserts an element x at the front of the list A*/void add_from_front(list<int> &A,int x){A.push_front(x);}"
},
{
"code": null,
"e": 5613,
"s": 5611,
"text": "0"
},
{
"code": null,
"e": 5640,
"s": 5613,
"text": "Anurag Parothia2 years ago"
},
{
"code": null,
"e": 5656,
"s": 5640,
"text": "Anurag Parothia"
},
{
"code": null,
"e": 5693,
"s": 5656,
"text": "Someone please helpWrong Answer. !!!"
},
{
"code": null,
"e": 5766,
"s": 5693,
"text": "Possibly your code doesn't work correctly for multiple test-cases (TCs)."
},
{
"code": null,
"e": 5810,
"s": 5766,
"text": "The first test case where your code failed:"
},
{
"code": null,
"e": 5841,
"s": 5810,
"text": "Input:208 568321 951732721 193"
},
{
"code": null,
"e": 6766,
"s": 5841,
"text": "void print(list<int> &A){//Your code herefor (auto it = A.begin(); it != A.end(); ++it) { cout<<*it<<\" \";}cout<<endl; }=\"\" *remove=\"\" element=\"\" from=\"\" back=\"\" of=\"\" list=\"\" a*=\"\" void=\"\" remove_from_back(list<int=\"\"> &A){ //Your code here A.pop_back();}/*remove element from front of list A*/void remove_from_front(list<int> &A){ //Your code here if(A.empty()) cout<<\"-1\"; A.pop_front();}/*inserts an element x at the back of the list A */void add_to_list(list<int> &A,int x){//Your code hereA.push_back(x);}/*sort the list A in ascending order*/void sort_list(list<int> &A){//Your code hereA.sort();}/*reverses the list A*/void reverse_list(list<int> &A){//Your code hereA.reverse();}/*returns the size of the list A */int size_of_list(list<int> &A){//Your code herereturn A.size();}/*inserts an element x at the front of the list A*/void add_from_front(list<int> &A,int x){//Your code hereA.push_front(x);}"
},
{
"code": null,
"e": 6768,
"s": 6766,
"text": "0"
},
{
"code": null,
"e": 6792,
"s": 6768,
"text": "Deepak Yadav4 years ago"
},
{
"code": null,
"e": 6805,
"s": 6792,
"text": "Deepak Yadav"
},
{
"code": null,
"e": 6861,
"s": 6805,
"text": "I case u stuck see this https://ide.geeksforgeeks.o..."
},
{
"code": null,
"e": 7007,
"s": 6861,
"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": 7043,
"s": 7007,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 7053,
"s": 7043,
"text": "\nProblem\n"
},
{
"code": null,
"e": 7063,
"s": 7053,
"text": "\nContest\n"
},
{
"code": null,
"e": 7126,
"s": 7063,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 7274,
"s": 7126,
"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": 7482,
"s": 7274,
"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": 7588,
"s": 7482,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
]
|
Spring Boot Actuator Example | Spring Boot 2.x Actuator OnlineTutorialsPoint | PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
In this tutorials, we are going to see what is Spring Boot Actuator and how it is useful to our production release applications.
Actuator is a sub-project of Spring Boot. It brings production-ready features of our application. It is mainly used to expose operational information about the running application such as :
The health of the application, metrics, loggings, dumps, env and etc. It typically uses HTTP endpoints to enable us to interact with it.
It allows us to monitor our application
To gather the application’s metrics
Understand the real traffic
We can get the production grade tools via the HTTP end pints, by making use of these we can get the above information and we are also free to configure and extend these features in many ways.
The simplest way to enable the actuator feature in our application is to add the spring-boot-starter-actuator ‘Starter’. This dependency provides all of the Spring Boot’s production-ready features.
To add the actuator to a Maven based project, add the following ‘Starter’ dependency:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
spring-boot-starter-parent-2.0.4 RELEASE
spring-boot-starter-actuator
Java8
IntelliJ IDEA
If you are familiar with actuator 1.x versions, most of the actuator endpoints were available.
Comming to the actuator 2.x versions, Actuator comes with most of the endpoints disabled.
Would we want to enable all of them at a time, we should set management.endpoints.web.exposure.include=* property in application.properties file.
You can find the further details about the 2.x version in the official document
@Bean
public SecurityWebFilterChain securityWebFilterChain(
ServerHttpSecurity http) {
return http.authorizeExchange()
.pathMatchers("/actuator/**").permitAll()
.anyExchange().authenticated()
.and().build();
}
/auditevents – Exposes audit events information for the current application.
/beans – returns all available beans in your application
/conditions – Shows the conditions that were evaluated on configuration and auto-configuration classes and the reasons why they did or did not match
/configprops – Displays a collated list of all @ConfigurationProperties beans.
/env – returns the current environment properties.Properties from Spring’s ConfigurableEnvironment.
/flyway – provides details about our Flyway database migrations
/health – shows the health status of our application
/heapdump – returns a GZip compressed hprof heap dump file of yor application.
/info – returns general information about the application. It might be custom data, build information or details about the latest commit
/liquibase – Shows any Liquibase database migrations that have been applied.
/logfile – Returns the contents of the logfile (if logging.file or logging.path properties have been set).
/loggers – enables us to query and modify the logging level of our application
/metrics – details metrics of our current application. This might include generic metrics as well as custom ones
/prometheus – exposes metrics in a format that can be scraped by a Prometheus server.
/scheduledtasks – provides details about every scheduled task within our application
/sessions – Allows retrieval and deletion of user sessions from a Spring Session-backed session store. It may not available when using Spring Session’s support for reactive web applications
/shutdown – performs a graceful shutdown of the application
/threaddump – dumps the thread information of the underlying JVM
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.onlinetutorialspoint</groupId>
<artifactId>SpringBoot-Actuator-Example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>SpringBoot-Actuator-Example</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
server.port: 9000
management.server.port: 9001
management.server.address: 127.0.0.1
management.endpoints.web.exposure.include=*
package com.onlinetutorialspoint;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class HelloController {
@GetMapping("hello")
@ResponseBody
public String hello(@RequestParam(name="name",required = false,defaultValue = "user") String name){
return "hello "+name+" :)";
}
}
package com.onlinetutorialspoint;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.PropertySource;
@SpringBootApplication
@PropertySource("classpath:application.properties")
public class SpringBootActuatorApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootActuatorApplication.class, args);
}
}
Run Application:
E:\work\SpringBoot-Actuator-Example>mvn spring-boot:run
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building SpringBoot-Actuator-Example 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] >>> spring-boot-maven-plugin:2.0.4.RELEASE:run (default-cli) > test-compile @ SpringBoot-Actuator-Example >>>
[INFO]
[INFO] --- maven-resources-plugin:3.0.2:resources (default-resources) @ SpringBoot-Actuator-Example ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 1 resource
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.7.0:compile (default-compile) @ SpringBoot-Actuator-Example ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 2 source files to E:\work\SpringBoot-Actuator-Example\target\classes
[INFO]
[INFO] --- maven-resources-plugin:3.0.2:testResources (default-testResources) @ SpringBoot-Actuator-Example ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory E:\work\SpringBoot-Actuator-Example\src\test\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.7.0:testCompile (default-testCompile) @ SpringBoot-Actuator-Example ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] <<< spring-boot-maven-plugin:2.0.4.RELEASE:run (default-cli) < test-compile @ SpringBoot-Actuator-Example <<<
[INFO]
[INFO]
[INFO] --- spring-boot-maven-plugin:2.0.4.RELEASE:run (default-cli) @ SpringBoot-Actuator-Example ---
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.0.4.RELEASE)
2018-08-12 08:42:59.223 INFO 6280 --- [ main] c.o.SpringBootActuatorApplication : Starting SpringBootActuatorApplication on DESKTOP-RN4SMHT with PID 6280 (E:\work\S
pringBoot-Actuator-Example\target\classes started by Lenovo in E:\work\SpringBoot-Actuator-Example)
2018-08-12 08:42:59.239 INFO 6280 --- [ main] c.o.SpringBootActuatorApplication : No active profile set, falling back to default profiles: default
2018-08-12 08:42:59.444 INFO 6280 --- [ main] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWeb
ServerApplicationContext@4f1d523f: startup date [Sun Aug 12 08:42:59 IST 2018]; root of context hierarchy
2018-08-12 08:43:04.229 INFO 6280 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 9000 (http)
2018-08-12 08:43:04.338 INFO 6280 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2018-08-12 08:43:04.338 INFO 6280 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.32
2018-08-12 08:43:04.354 INFO 6280 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener : The APR based Apache Tomcat Native library which allows optimal performance in pro
duction environments was not found on the java.library.path: [C:\Program Files\Java\jdk1.8.0_161\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\ProgramData\Oracle\Java
\javapath;C:\oraclexe\app\oracle\product.2.0\server\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\
MySQL\MySQL Server 5.5\bin;C:\php;C:\Apache24;C:\Apache24\bin;C:\Program Files\Java\jdk1.8.0_161\bin;D:\Softwares\apache-maven-3.5.2\bin;C:\Program Files\Git\cmd;C:\Program Files\Git
\mingw64\bin;C:\Program Files\Git\usr\bin;D:\Softwares\apache-ant-1.10.2\bin;C:\ProgramData\chocolatey\bin;;C:\WINDOWS\System32\OpenSSH\;C:\Users\Lenovo\AppData\Local\Programs\Python
\Python36\Scripts\;C:\Users\Lenovo\AppData\Local\Programs\Python\Python36\;C:\Users\Lenovo\AppData\Local\Microsoft\WindowsApps;C:\Users\Lenovo\AppData\Local\atom\bin;C:\Users\Lenovo\
AppData\Local\Microsoft\WindowsApps;;C:\Program Files\Microsoft VS Code\bin;C:\Program Files\Docker Toolbox;.]
2018-08-12 08:43:04.620 INFO 6280 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2018-08-12 08:43:04.635 INFO 6280 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 5222 ms
.........
.........
Output:
Accessing Spring Boot Actuator endpoints:
http://localhost:9001/actuator/metrics
http://localhost:9001/actuator/health
http://localhost:9001/actuator/heapdump
Happy Learning 🙂
SpringBoot-Actuator-Example
File size: 79 KB
Downloads: 647
How to set Spring Boot SetTimeZone
Spring Boot Environment Properties reading based on activeprofile
Spring Boot Apache ActiveMq In Memory Example
Spring Boot How to change the Tomcat to Jetty Server
Spring Boot In Memory Basic Authentication Security
SSL Spring Boot HTTPs Enabling Example
MicroServices Spring Boot Eureka Server Example
Simple Spring Boot Example
How to use Spring Boot Random Port
Spring Boot EhCache Example
Spring Boot Basic Authentication Example
External Apache ActiveMQ Spring Boot Example
Spring Boot JdbcTemplate CRUD Operations Mysql
Spring Boot JNDI Configuration – External Tomcat
Spring Boot Actuator Database Health Check
How to set Spring Boot SetTimeZone
Spring Boot Environment Properties reading based on activeprofile
Spring Boot Apache ActiveMq In Memory Example
Spring Boot How to change the Tomcat to Jetty Server
Spring Boot In Memory Basic Authentication Security
SSL Spring Boot HTTPs Enabling Example
MicroServices Spring Boot Eureka Server Example
Simple Spring Boot Example
How to use Spring Boot Random Port
Spring Boot EhCache Example
Spring Boot Basic Authentication Example
External Apache ActiveMQ Spring Boot Example
Spring Boot JdbcTemplate CRUD Operations Mysql
Spring Boot JNDI Configuration – External Tomcat
Spring Boot Actuator Database Health Check
Δ
Spring Boot – Hello World
Spring Boot – MVC Example
Spring Boot- Change Context Path
Spring Boot – Change Tomcat Port Number
Spring Boot – Change Tomcat to Jetty Server
Spring Boot – Tomcat session timeout
Spring Boot – Enable Random Port
Spring Boot – Properties File
Spring Boot – Beans Lazy Loading
Spring Boot – Set Favicon image
Spring Boot – Set Custom Banner
Spring Boot – Set Application TimeZone
Spring Boot – Send Mail
Spring Boot – FileUpload Ajax
Spring Boot – Actuator
Spring Boot – Actuator Database Health Check
Spring Boot – Swagger
Spring Boot – Enable CORS
Spring Boot – External Apache ActiveMQ Setup
Spring Boot – Inmemory Apache ActiveMq
Spring Boot – Scheduler Job
Spring Boot – Exception Handling
Spring Boot – Hibernate CRUD
Spring Boot – JPA Integration CRUD
Spring Boot – JPA DataRest CRUD
Spring Boot – JdbcTemplate CRUD
Spring Boot – Multiple Data Sources Config
Spring Boot – JNDI Configuration
Spring Boot – H2 Database CRUD
Spring Boot – MongoDB CRUD
Spring Boot – Redis Data CRUD
Spring Boot – MVC Login Form Validation
Spring Boot – Custom Error Pages
Spring Boot – iText PDF
Spring Boot – Enable SSL (HTTPs)
Spring Boot – Basic Authentication
Spring Boot – In Memory Basic Authentication
Spring Boot – Security MySQL Database Integration
Spring Boot – Redis Cache – Redis Server
Spring Boot – Hazelcast Cache
Spring Boot – EhCache
Spring Boot – Kafka Producer
Spring Boot – Kafka Consumer
Spring Boot – Kafka JSON Message to Kafka Topic
Spring Boot – RabbitMQ Publisher
Spring Boot – RabbitMQ Consumer
Spring Boot – SOAP Consumer
Spring Boot – Soap WebServices
Spring Boot – Batch Csv to Database
Spring Boot – Eureka Server
Spring Boot – MockMvc JUnit
Spring Boot – Docker Deployment | [
{
"code": null,
"e": 158,
"s": 123,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 172,
"s": 158,
"text": "Java Examples"
},
{
"code": null,
"e": 183,
"s": 172,
"text": "C Examples"
},
{
"code": null,
"e": 195,
"s": 183,
"text": "C Tutorials"
},
{
"code": null,
"e": 199,
"s": 195,
"text": "aws"
},
{
"code": null,
"e": 234,
"s": 199,
"text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC"
},
{
"code": null,
"e": 245,
"s": 234,
"text": "EXCEPTIONS"
},
{
"code": null,
"e": 257,
"s": 245,
"text": "COLLECTIONS"
},
{
"code": null,
"e": 263,
"s": 257,
"text": "SWING"
},
{
"code": null,
"e": 268,
"s": 263,
"text": "JDBC"
},
{
"code": null,
"e": 275,
"s": 268,
"text": "JAVA 8"
},
{
"code": null,
"e": 282,
"s": 275,
"text": "SPRING"
},
{
"code": null,
"e": 294,
"s": 282,
"text": "SPRING BOOT"
},
{
"code": null,
"e": 304,
"s": 294,
"text": "HIBERNATE"
},
{
"code": null,
"e": 311,
"s": 304,
"text": "PYTHON"
},
{
"code": null,
"e": 315,
"s": 311,
"text": "PHP"
},
{
"code": null,
"e": 322,
"s": 315,
"text": "JQUERY"
},
{
"code": null,
"e": 357,
"s": 322,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 371,
"s": 357,
"text": "Java Examples"
},
{
"code": null,
"e": 382,
"s": 371,
"text": "C Examples"
},
{
"code": null,
"e": 394,
"s": 382,
"text": "C Tutorials"
},
{
"code": null,
"e": 398,
"s": 394,
"text": "aws"
},
{
"code": null,
"e": 527,
"s": 398,
"text": "In this tutorials, we are going to see what is Spring Boot Actuator and how it is useful to our production release applications."
},
{
"code": null,
"e": 717,
"s": 527,
"text": "Actuator is a sub-project of Spring Boot. It brings production-ready features of our application. It is mainly used to expose operational information about the running application such as :"
},
{
"code": null,
"e": 854,
"s": 717,
"text": "The health of the application, metrics, loggings, dumps, env and etc. It typically uses HTTP endpoints to enable us to interact with it."
},
{
"code": null,
"e": 894,
"s": 854,
"text": "It allows us to monitor our application"
},
{
"code": null,
"e": 930,
"s": 894,
"text": "To gather the application’s metrics"
},
{
"code": null,
"e": 958,
"s": 930,
"text": "Understand the real traffic"
},
{
"code": null,
"e": 1150,
"s": 958,
"text": "We can get the production grade tools via the HTTP end pints, by making use of these we can get the above information and we are also free to configure and extend these features in many ways."
},
{
"code": null,
"e": 1348,
"s": 1150,
"text": "The simplest way to enable the actuator feature in our application is to add the spring-boot-starter-actuator ‘Starter’. This dependency provides all of the Spring Boot’s production-ready features."
},
{
"code": null,
"e": 1434,
"s": 1348,
"text": "To add the actuator to a Maven based project, add the following ‘Starter’ dependency:"
},
{
"code": null,
"e": 1602,
"s": 1434,
"text": "<dependencies>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-actuator</artifactId>\n </dependency>\n</dependencies>"
},
{
"code": null,
"e": 1643,
"s": 1602,
"text": "spring-boot-starter-parent-2.0.4 RELEASE"
},
{
"code": null,
"e": 1672,
"s": 1643,
"text": "spring-boot-starter-actuator"
},
{
"code": null,
"e": 1678,
"s": 1672,
"text": "Java8"
},
{
"code": null,
"e": 1692,
"s": 1678,
"text": "IntelliJ IDEA"
},
{
"code": null,
"e": 1787,
"s": 1692,
"text": "If you are familiar with actuator 1.x versions, most of the actuator endpoints were available."
},
{
"code": null,
"e": 1877,
"s": 1787,
"text": "Comming to the actuator 2.x versions, Actuator comes with most of the endpoints disabled."
},
{
"code": null,
"e": 2023,
"s": 1877,
"text": "Would we want to enable all of them at a time, we should set management.endpoints.web.exposure.include=* property in application.properties file."
},
{
"code": null,
"e": 2103,
"s": 2023,
"text": "You can find the further details about the 2.x version in the official document"
},
{
"code": null,
"e": 2337,
"s": 2103,
"text": "@Bean\npublic SecurityWebFilterChain securityWebFilterChain(\n ServerHttpSecurity http) {\n return http.authorizeExchange()\n .pathMatchers(\"/actuator/**\").permitAll()\n .anyExchange().authenticated()\n .and().build();\n}"
},
{
"code": null,
"e": 3995,
"s": 2337,
"text": "/auditevents – Exposes audit events information for the current application.\n/beans – returns all available beans in your application\n/conditions – Shows the conditions that were evaluated on configuration and auto-configuration classes and the reasons why they did or did not match\n/configprops – Displays a collated list of all @ConfigurationProperties beans.\n/env – returns the current environment properties.Properties from Spring’s ConfigurableEnvironment.\n/flyway – provides details about our Flyway database migrations\n/health – shows the health status of our application\n/heapdump – returns a GZip compressed hprof heap dump file of yor application.\n/info – returns general information about the application. It might be custom data, build information or details about the latest commit\n/liquibase – Shows any Liquibase database migrations that have been applied.\n/logfile – Returns the contents of the logfile (if logging.file or logging.path properties have been set).\n/loggers – enables us to query and modify the logging level of our application\n/metrics – details metrics of our current application. This might include generic metrics as well as custom ones\n/prometheus – exposes metrics in a format that can be scraped by a Prometheus server.\n/scheduledtasks – provides details about every scheduled task within our application\n/sessions – Allows retrieval and deletion of user sessions from a Spring Session-backed session store. It may not available when using Spring Session’s support for reactive web applications\n/shutdown – performs a graceful shutdown of the application\n/threaddump – dumps the thread information of the underlying JVM\n"
},
{
"code": null,
"e": 5514,
"s": 3995,
"text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n\n <groupId>com.onlinetutorialspoint</groupId>\n <artifactId>SpringBoot-Actuator-Example</artifactId>\n <version>0.0.1-SNAPSHOT</version>\n <packaging>jar</packaging>\n\n <name>SpringBoot-Actuator-Example</name>\n <description>Demo project for Spring Boot</description>\n\n <parent>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-parent</artifactId>\n <version>2.0.4.RELEASE</version>\n <relativePath/> <!-- lookup parent from repository -->\n </parent>\n\n <properties>\n <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>\n <java.version>1.8</java.version>\n </properties>\n\n <dependencies>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-web</artifactId>\n </dependency>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-actuator</artifactId>\n </dependency>\n </dependencies>\n <build>\n <plugins>\n <plugin>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-maven-plugin</artifactId>\n </plugin>\n </plugins>\n </build>\n</project>\n"
},
{
"code": null,
"e": 5645,
"s": 5514,
"text": "server.port: 9000 \nmanagement.server.port: 9001 \nmanagement.server.address: 127.0.0.1 \nmanagement.endpoints.web.exposure.include=*"
},
{
"code": null,
"e": 6148,
"s": 5645,
"text": "package com.onlinetutorialspoint;\n\nimport org.springframework.stereotype.Controller;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.RequestParam;\nimport org.springframework.web.bind.annotation.ResponseBody;\n\n@Controller\npublic class HelloController {\n\n @GetMapping(\"hello\")\n @ResponseBody\n public String hello(@RequestParam(name=\"name\",required = false,defaultValue = \"user\") String name){\n return \"hello \"+name+\" :)\";\n }\n}\n"
},
{
"code": null,
"e": 6610,
"s": 6148,
"text": "package com.onlinetutorialspoint;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.context.annotation.PropertySource;\n\n@SpringBootApplication\n@PropertySource(\"classpath:application.properties\")\npublic class SpringBootActuatorApplication {\n\n public static void main(String[] args) {\n SpringApplication.run(SpringBootActuatorApplication.class, args);\n }\n}\n\n"
},
{
"code": null,
"e": 6627,
"s": 6610,
"text": "Run Application:"
},
{
"code": null,
"e": 11202,
"s": 6627,
"text": "E:\\work\\SpringBoot-Actuator-Example>mvn spring-boot:run\n[INFO] Scanning for projects...\n[INFO]\n[INFO] ------------------------------------------------------------------------\n[INFO] Building SpringBoot-Actuator-Example 0.0.1-SNAPSHOT\n[INFO] ------------------------------------------------------------------------\n[INFO]\n[INFO] >>> spring-boot-maven-plugin:2.0.4.RELEASE:run (default-cli) > test-compile @ SpringBoot-Actuator-Example >>>\n[INFO]\n[INFO] --- maven-resources-plugin:3.0.2:resources (default-resources) @ SpringBoot-Actuator-Example ---\n[INFO] Using 'UTF-8' encoding to copy filtered resources.\n[INFO] Copying 1 resource\n[INFO] Copying 0 resource\n[INFO]\n[INFO] --- maven-compiler-plugin:3.7.0:compile (default-compile) @ SpringBoot-Actuator-Example ---\n[INFO] Changes detected - recompiling the module!\n[INFO] Compiling 2 source files to E:\\work\\SpringBoot-Actuator-Example\\target\\classes\n[INFO]\n[INFO] --- maven-resources-plugin:3.0.2:testResources (default-testResources) @ SpringBoot-Actuator-Example ---\n[INFO] Using 'UTF-8' encoding to copy filtered resources.\n[INFO] skip non existing resourceDirectory E:\\work\\SpringBoot-Actuator-Example\\src\\test\\resources\n[INFO]\n[INFO] --- maven-compiler-plugin:3.7.0:testCompile (default-testCompile) @ SpringBoot-Actuator-Example ---\n[INFO] Nothing to compile - all classes are up to date\n[INFO]\n[INFO] <<< spring-boot-maven-plugin:2.0.4.RELEASE:run (default-cli) < test-compile @ SpringBoot-Actuator-Example <<<\n[INFO]\n[INFO]\n[INFO] --- spring-boot-maven-plugin:2.0.4.RELEASE:run (default-cli) @ SpringBoot-Actuator-Example ---\n\n . ____ _ __ _ _\n /\\\\ / ___'_ __ _ _(_)_ __ __ _ \\ \\ \\ \\\n( ( )\\___ | '_ | '_| | '_ \\/ _` | \\ \\ \\ \\\n \\\\/ ___)| |_)| | | | | || (_| | ) ) ) )\n ' |____| .__|_| |_|_| |_\\__, | / / / /\n =========|_|==============|___/=/_/_/_/\n :: Spring Boot :: (v2.0.4.RELEASE)\n\n2018-08-12 08:42:59.223 INFO 6280 --- [ main] c.o.SpringBootActuatorApplication : Starting SpringBootActuatorApplication on DESKTOP-RN4SMHT with PID 6280 (E:\\work\\S\npringBoot-Actuator-Example\\target\\classes started by Lenovo in E:\\work\\SpringBoot-Actuator-Example)\n2018-08-12 08:42:59.239 INFO 6280 --- [ main] c.o.SpringBootActuatorApplication : No active profile set, falling back to default profiles: default\n2018-08-12 08:42:59.444 INFO 6280 --- [ main] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWeb\nServerApplicationContext@4f1d523f: startup date [Sun Aug 12 08:42:59 IST 2018]; root of context hierarchy\n2018-08-12 08:43:04.229 INFO 6280 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 9000 (http)\n2018-08-12 08:43:04.338 INFO 6280 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]\n2018-08-12 08:43:04.338 INFO 6280 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.32\n2018-08-12 08:43:04.354 INFO 6280 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener : The APR based Apache Tomcat Native library which allows optimal performance in pro\nduction environments was not found on the java.library.path: [C:\\Program Files\\Java\\jdk1.8.0_161\\bin;C:\\WINDOWS\\Sun\\Java\\bin;C:\\WINDOWS\\system32;C:\\WINDOWS;C:\\ProgramData\\Oracle\\Java\n\\javapath;C:\\oraclexe\\app\\oracle\\product.2.0\\server\\bin;C:\\WINDOWS\\system32;C:\\WINDOWS;C:\\WINDOWS\\System32\\Wbem;C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\;C:\\Program Files (x86)\\\nMySQL\\MySQL Server 5.5\\bin;C:\\php;C:\\Apache24;C:\\Apache24\\bin;C:\\Program Files\\Java\\jdk1.8.0_161\\bin;D:\\Softwares\\apache-maven-3.5.2\\bin;C:\\Program Files\\Git\\cmd;C:\\Program Files\\Git\n\\mingw64\\bin;C:\\Program Files\\Git\\usr\\bin;D:\\Softwares\\apache-ant-1.10.2\\bin;C:\\ProgramData\\chocolatey\\bin;;C:\\WINDOWS\\System32\\OpenSSH\\;C:\\Users\\Lenovo\\AppData\\Local\\Programs\\Python\n\\Python36\\Scripts\\;C:\\Users\\Lenovo\\AppData\\Local\\Programs\\Python\\Python36\\;C:\\Users\\Lenovo\\AppData\\Local\\Microsoft\\WindowsApps;C:\\Users\\Lenovo\\AppData\\Local\\atom\\bin;C:\\Users\\Lenovo\\\nAppData\\Local\\Microsoft\\WindowsApps;;C:\\Program Files\\Microsoft VS Code\\bin;C:\\Program Files\\Docker Toolbox;.]\n2018-08-12 08:43:04.620 INFO 6280 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext\n2018-08-12 08:43:04.635 INFO 6280 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 5222 ms\n.........\n.........\n"
},
{
"code": null,
"e": 11210,
"s": 11202,
"text": "Output:"
},
{
"code": null,
"e": 11252,
"s": 11210,
"text": "Accessing Spring Boot Actuator endpoints:"
},
{
"code": null,
"e": 11291,
"s": 11252,
"text": "http://localhost:9001/actuator/metrics"
},
{
"code": null,
"e": 11329,
"s": 11291,
"text": "http://localhost:9001/actuator/health"
},
{
"code": null,
"e": 11369,
"s": 11329,
"text": "http://localhost:9001/actuator/heapdump"
},
{
"code": null,
"e": 11386,
"s": 11369,
"text": "Happy Learning 🙂"
},
{
"code": null,
"e": 11450,
"s": 11386,
"text": "\n\nSpringBoot-Actuator-Example\n\nFile size: 79 KB\nDownloads: 647\n"
},
{
"code": null,
"e": 12106,
"s": 11450,
"text": "\nHow to set Spring Boot SetTimeZone\nSpring Boot Environment Properties reading based on activeprofile\nSpring Boot Apache ActiveMq In Memory Example\nSpring Boot How to change the Tomcat to Jetty Server\nSpring Boot In Memory Basic Authentication Security\nSSL Spring Boot HTTPs Enabling Example\nMicroServices Spring Boot Eureka Server Example\nSimple Spring Boot Example\nHow to use Spring Boot Random Port\nSpring Boot EhCache Example\nSpring Boot Basic Authentication Example\nExternal Apache ActiveMQ Spring Boot Example\nSpring Boot JdbcTemplate CRUD Operations Mysql\nSpring Boot JNDI Configuration – External Tomcat\nSpring Boot Actuator Database Health Check\n"
},
{
"code": null,
"e": 12141,
"s": 12106,
"text": "How to set Spring Boot SetTimeZone"
},
{
"code": null,
"e": 12207,
"s": 12141,
"text": "Spring Boot Environment Properties reading based on activeprofile"
},
{
"code": null,
"e": 12253,
"s": 12207,
"text": "Spring Boot Apache ActiveMq In Memory Example"
},
{
"code": null,
"e": 12306,
"s": 12253,
"text": "Spring Boot How to change the Tomcat to Jetty Server"
},
{
"code": null,
"e": 12358,
"s": 12306,
"text": "Spring Boot In Memory Basic Authentication Security"
},
{
"code": null,
"e": 12397,
"s": 12358,
"text": "SSL Spring Boot HTTPs Enabling Example"
},
{
"code": null,
"e": 12445,
"s": 12397,
"text": "MicroServices Spring Boot Eureka Server Example"
},
{
"code": null,
"e": 12472,
"s": 12445,
"text": "Simple Spring Boot Example"
},
{
"code": null,
"e": 12507,
"s": 12472,
"text": "How to use Spring Boot Random Port"
},
{
"code": null,
"e": 12535,
"s": 12507,
"text": "Spring Boot EhCache Example"
},
{
"code": null,
"e": 12576,
"s": 12535,
"text": "Spring Boot Basic Authentication Example"
},
{
"code": null,
"e": 12621,
"s": 12576,
"text": "External Apache ActiveMQ Spring Boot Example"
},
{
"code": null,
"e": 12668,
"s": 12621,
"text": "Spring Boot JdbcTemplate CRUD Operations Mysql"
},
{
"code": null,
"e": 12717,
"s": 12668,
"text": "Spring Boot JNDI Configuration – External Tomcat"
},
{
"code": null,
"e": 12760,
"s": 12717,
"text": "Spring Boot Actuator Database Health Check"
},
{
"code": null,
"e": 12766,
"s": 12764,
"text": "Δ"
},
{
"code": null,
"e": 12793,
"s": 12766,
"text": " Spring Boot – Hello World"
},
{
"code": null,
"e": 12820,
"s": 12793,
"text": " Spring Boot – MVC Example"
},
{
"code": null,
"e": 12854,
"s": 12820,
"text": " Spring Boot- Change Context Path"
},
{
"code": null,
"e": 12895,
"s": 12854,
"text": " Spring Boot – Change Tomcat Port Number"
},
{
"code": null,
"e": 12940,
"s": 12895,
"text": " Spring Boot – Change Tomcat to Jetty Server"
},
{
"code": null,
"e": 12978,
"s": 12940,
"text": " Spring Boot – Tomcat session timeout"
},
{
"code": null,
"e": 13012,
"s": 12978,
"text": " Spring Boot – Enable Random Port"
},
{
"code": null,
"e": 13043,
"s": 13012,
"text": " Spring Boot – Properties File"
},
{
"code": null,
"e": 13077,
"s": 13043,
"text": " Spring Boot – Beans Lazy Loading"
},
{
"code": null,
"e": 13110,
"s": 13077,
"text": " Spring Boot – Set Favicon image"
},
{
"code": null,
"e": 13143,
"s": 13110,
"text": " Spring Boot – Set Custom Banner"
},
{
"code": null,
"e": 13183,
"s": 13143,
"text": " Spring Boot – Set Application TimeZone"
},
{
"code": null,
"e": 13208,
"s": 13183,
"text": " Spring Boot – Send Mail"
},
{
"code": null,
"e": 13239,
"s": 13208,
"text": " Spring Boot – FileUpload Ajax"
},
{
"code": null,
"e": 13263,
"s": 13239,
"text": " Spring Boot – Actuator"
},
{
"code": null,
"e": 13309,
"s": 13263,
"text": " Spring Boot – Actuator Database Health Check"
},
{
"code": null,
"e": 13332,
"s": 13309,
"text": " Spring Boot – Swagger"
},
{
"code": null,
"e": 13359,
"s": 13332,
"text": " Spring Boot – Enable CORS"
},
{
"code": null,
"e": 13405,
"s": 13359,
"text": " Spring Boot – External Apache ActiveMQ Setup"
},
{
"code": null,
"e": 13445,
"s": 13405,
"text": " Spring Boot – Inmemory Apache ActiveMq"
},
{
"code": null,
"e": 13474,
"s": 13445,
"text": " Spring Boot – Scheduler Job"
},
{
"code": null,
"e": 13508,
"s": 13474,
"text": " Spring Boot – Exception Handling"
},
{
"code": null,
"e": 13538,
"s": 13508,
"text": " Spring Boot – Hibernate CRUD"
},
{
"code": null,
"e": 13574,
"s": 13538,
"text": " Spring Boot – JPA Integration CRUD"
},
{
"code": null,
"e": 13607,
"s": 13574,
"text": " Spring Boot – JPA DataRest CRUD"
},
{
"code": null,
"e": 13640,
"s": 13607,
"text": " Spring Boot – JdbcTemplate CRUD"
},
{
"code": null,
"e": 13684,
"s": 13640,
"text": " Spring Boot – Multiple Data Sources Config"
},
{
"code": null,
"e": 13718,
"s": 13684,
"text": " Spring Boot – JNDI Configuration"
},
{
"code": null,
"e": 13750,
"s": 13718,
"text": " Spring Boot – H2 Database CRUD"
},
{
"code": null,
"e": 13778,
"s": 13750,
"text": " Spring Boot – MongoDB CRUD"
},
{
"code": null,
"e": 13809,
"s": 13778,
"text": " Spring Boot – Redis Data CRUD"
},
{
"code": null,
"e": 13850,
"s": 13809,
"text": " Spring Boot – MVC Login Form Validation"
},
{
"code": null,
"e": 13884,
"s": 13850,
"text": " Spring Boot – Custom Error Pages"
},
{
"code": null,
"e": 13909,
"s": 13884,
"text": " Spring Boot – iText PDF"
},
{
"code": null,
"e": 13943,
"s": 13909,
"text": " Spring Boot – Enable SSL (HTTPs)"
},
{
"code": null,
"e": 13979,
"s": 13943,
"text": " Spring Boot – Basic Authentication"
},
{
"code": null,
"e": 14025,
"s": 13979,
"text": " Spring Boot – In Memory Basic Authentication"
},
{
"code": null,
"e": 14076,
"s": 14025,
"text": " Spring Boot – Security MySQL Database Integration"
},
{
"code": null,
"e": 14118,
"s": 14076,
"text": " Spring Boot – Redis Cache – Redis Server"
},
{
"code": null,
"e": 14149,
"s": 14118,
"text": " Spring Boot – Hazelcast Cache"
},
{
"code": null,
"e": 14172,
"s": 14149,
"text": " Spring Boot – EhCache"
},
{
"code": null,
"e": 14202,
"s": 14172,
"text": " Spring Boot – Kafka Producer"
},
{
"code": null,
"e": 14232,
"s": 14202,
"text": " Spring Boot – Kafka Consumer"
},
{
"code": null,
"e": 14281,
"s": 14232,
"text": " Spring Boot – Kafka JSON Message to Kafka Topic"
},
{
"code": null,
"e": 14315,
"s": 14281,
"text": " Spring Boot – RabbitMQ Publisher"
},
{
"code": null,
"e": 14348,
"s": 14315,
"text": " Spring Boot – RabbitMQ Consumer"
},
{
"code": null,
"e": 14377,
"s": 14348,
"text": " Spring Boot – SOAP Consumer"
},
{
"code": null,
"e": 14409,
"s": 14377,
"text": " Spring Boot – Soap WebServices"
},
{
"code": null,
"e": 14446,
"s": 14409,
"text": " Spring Boot – Batch Csv to Database"
},
{
"code": null,
"e": 14475,
"s": 14446,
"text": " Spring Boot – Eureka Server"
},
{
"code": null,
"e": 14504,
"s": 14475,
"text": " Spring Boot – MockMvc JUnit"
}
]
|
Change data type of given numpy array in Python | We have a method called astype(data_type) to change the data type of a numpy array. If we have a numpy array of type float64, then we can change it to int32 by giving the data type to the astype() method of numpy array.
We can check the type of numpy array using the dtype class. Let's check the data type of sample numpy array.
# importing numpy library
import numpy as np
# creating numpy array
array = np.array([1, 2, 3, 4, 5])
# printing the data type of the numpy array
print(array.dtype)
If you run the above code, you will get the following results.
int32
Let's see how to change the data type of a numpy array from float64 to &int32.
# importing numpy library
import numpy as np
# creating numpy array of type float64
array = np.array([1.5, 2.6, 3.7, 4.8, 5.9])
# type of array before changing
print(f'Before changing {array.dtype}')
# changing the data type of numpy array using astype() method
array = array.astype(np.int32)
# type of array after changing
print(f'\nAfter changing {array.dtype}')
If you run the above program, you will get the following results.
Before changing float64
After changing int32
We can use any data type present in the numpy module or general data types of Python. You can find the list of data types present in numpy here.
I hope you have learned the conversion of data types for numpy array. If you are facing any problems related to the tutorial, mention them in the comment section. | [
{
"code": null,
"e": 1282,
"s": 1062,
"text": "We have a method called astype(data_type) to change the data type of a numpy array. If we have a numpy array of type float64, then we can change it to int32 by giving the data type to the astype() method of numpy array."
},
{
"code": null,
"e": 1391,
"s": 1282,
"text": "We can check the type of numpy array using the dtype class. Let's check the data type of sample numpy array."
},
{
"code": null,
"e": 1556,
"s": 1391,
"text": "# importing numpy library\nimport numpy as np\n# creating numpy array\narray = np.array([1, 2, 3, 4, 5])\n# printing the data type of the numpy array\nprint(array.dtype)"
},
{
"code": null,
"e": 1619,
"s": 1556,
"text": "If you run the above code, you will get the following results."
},
{
"code": null,
"e": 1625,
"s": 1619,
"text": "int32"
},
{
"code": null,
"e": 1704,
"s": 1625,
"text": "Let's see how to change the data type of a numpy array from float64 to &int32."
},
{
"code": null,
"e": 2069,
"s": 1704,
"text": "# importing numpy library\nimport numpy as np\n# creating numpy array of type float64\narray = np.array([1.5, 2.6, 3.7, 4.8, 5.9])\n# type of array before changing\nprint(f'Before changing {array.dtype}')\n# changing the data type of numpy array using astype() method\narray = array.astype(np.int32)\n# type of array after changing\nprint(f'\\nAfter changing {array.dtype}')"
},
{
"code": null,
"e": 2135,
"s": 2069,
"text": "If you run the above program, you will get the following results."
},
{
"code": null,
"e": 2180,
"s": 2135,
"text": "Before changing float64\nAfter changing int32"
},
{
"code": null,
"e": 2325,
"s": 2180,
"text": "We can use any data type present in the numpy module or general data types of Python. You can find the list of data types present in numpy here."
},
{
"code": null,
"e": 2488,
"s": 2325,
"text": "I hope you have learned the conversion of data types for numpy array. If you are facing any problems related to the tutorial, mention them in the comment section."
}
]
|
Sliding Puzzle in C++ | Suppose we have one 2x3 board, there are 5 tiles those are represented by the numbers 1 through 5, and one empty square is there, that is represented by 0.
Here a move means 0 and one adjacent number (top, bottom, left or right) and swapping it. This will be solved when the elements are arranged in this manner: [[1,2,3],[4,5,0]].
We have the puzzle board; we have to find the least number of moves required so that the state of the board is solved. If this is not possible to solve, then return -1.
So, if the input is like [[1,2,3],[0,4,5]], then the output will be 2, as we have to swap [0,4], then [0,5].
To solve this, we will follow these steps −
Define one function slidingPuzzle(), this will take board as input
Define one function slidingPuzzle(), this will take board as input
if board is perfectly arranged then −return 0
if board is perfectly arranged then −
return 0
return 0
Define one queue q of 2d matrices
Define one queue q of 2d matrices
insert board into q
insert board into q
Define one set visited for 2d matrices
Define one set visited for 2d matrices
insert board into visited
insert board into visited
for initialize lvl := 1, when not q is empty, update (increase lvl by 1), do −sz := size of qwhile sz is non-zero, decrease sz after each iteration, do −Define one 2D array node = front element of qdelete element from qdx := -1, y := -1for initialize i := 0, when i < size of board, update (increase i by 1), do −for initialize j := 0, when j < size of board[0], update (increase j by 1), do −if node[i, j] is same as 0, then −x := iy := jCome out from the loopfor initialize k := 0, when k < 4, update (increase k by 1), do −if nx < 0 or ny < 0 or nx >= row count of board or ny >= column count of board, then −Ignore following part, skip to the next iterationexchange node[x, y] and node[nx, ny]if node is in visited, then −exchange node[x, y] and node[nx, ny]Ignore following part, skip to the next iterationinsert node into visitedif node is perfect arrangemen of boards, then −return lvlinsert node into qexchange node[x, y] and node[nx, ny]
for initialize lvl := 1, when not q is empty, update (increase lvl by 1), do −
sz := size of q
sz := size of q
while sz is non-zero, decrease sz after each iteration, do −Define one 2D array node = front element of qdelete element from qdx := -1, y := -1for initialize i := 0, when i < size of board, update (increase i by 1), do −for initialize j := 0, when j < size of board[0], update (increase j by 1), do −if node[i, j] is same as 0, then −x := iy := jCome out from the loopfor initialize k := 0, when k < 4, update (increase k by 1), do −if nx < 0 or ny < 0 or nx >= row count of board or ny >= column count of board, then −Ignore following part, skip to the next iterationexchange node[x, y] and node[nx, ny]if node is in visited, then −exchange node[x, y] and node[nx, ny]Ignore following part, skip to the next iterationinsert node into visitedif node is perfect arrangemen of boards, then −return lvlinsert node into qexchange node[x, y] and node[nx, ny]
while sz is non-zero, decrease sz after each iteration, do −
Define one 2D array node = front element of q
Define one 2D array node = front element of q
delete element from q
delete element from q
dx := -1, y := -1
dx := -1, y := -1
for initialize i := 0, when i < size of board, update (increase i by 1), do −for initialize j := 0, when j < size of board[0], update (increase j by 1), do −if node[i, j] is same as 0, then −x := iy := jCome out from the loop
for initialize i := 0, when i < size of board, update (increase i by 1), do −
for initialize j := 0, when j < size of board[0], update (increase j by 1), do −if node[i, j] is same as 0, then −x := iy := jCome out from the loop
for initialize j := 0, when j < size of board[0], update (increase j by 1), do −
if node[i, j] is same as 0, then −x := iy := jCome out from the loop
if node[i, j] is same as 0, then −
x := i
x := i
y := j
y := j
Come out from the loop
Come out from the loop
for initialize k := 0, when k < 4, update (increase k by 1), do −
for initialize k := 0, when k < 4, update (increase k by 1), do −
if nx < 0 or ny < 0 or nx >= row count of board or ny >= column count of board, then −Ignore following part, skip to the next iteration
if nx < 0 or ny < 0 or nx >= row count of board or ny >= column count of board, then −
Ignore following part, skip to the next iteration
Ignore following part, skip to the next iteration
exchange node[x, y] and node[nx, ny]
exchange node[x, y] and node[nx, ny]
if node is in visited, then −exchange node[x, y] and node[nx, ny]Ignore following part, skip to the next iteration
if node is in visited, then −
exchange node[x, y] and node[nx, ny]
exchange node[x, y] and node[nx, ny]
Ignore following part, skip to the next iteration
Ignore following part, skip to the next iteration
insert node into visited
insert node into visited
if node is perfect arrangemen of boards, then −return lvl
if node is perfect arrangemen of boards, then −
return lvl
return lvl
insert node into q
insert node into q
exchange node[x, y] and node[nx, ny]
exchange node[x, y] and node[nx, ny]
return -1
return -1
Let us see the following implementation to get better understanding −
Live Demo
#include <bits/stdc++.h>
using namespace std;
int dir[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
class Solution {
public:
bool ok(vector < vector <int> >& b){
return b[0][0] == 1 && b[0][1] == 2 && b[0][2] == 3 && b[1]
[0] == 4 && b[1][1] == 5;
}
int slidingPuzzle(vector<vector<int>>& board) {
if (ok(board))
return 0;
queue<vector<vector<int> > > q;
q.push(board);
set<vector<vector<int> > > visited;
visited.insert(board);
for (int lvl = 1; !q.empty(); lvl++) {
int sz = q.size();
while (sz--) {
vector<vector<int> > node = q.front();
q.pop();
int x = -1;
int y = -1;
for (int i = 0; i < board.size(); i++) {
for (int j = 0; j < board[0].size(); j++) {
if (node[i][j] == 0) {
x = i;
y = j;
break;
}
}
}
for (int k = 0; k < 4; k++) {
int nx = x + dir[k][0];
int ny = y + dir[k][1];
if (nx < 0 || ny < 0 || nx >= board.size() || ny
>= board[0].size())
continue;
swap(node[x][y], node[nx][ny]);
if (visited.count(node)) {
swap(node[x][y], node[nx][ny]);
continue;
}
visited.insert(node);
if (ok(node))
return lvl;
q.push(node);
swap(node[x][y], node[nx][ny]);
}
}
}
return -1;
}
};
main(){
Solution ob;
vector<vector<int>> v = {{1,2,3},{0,4,5}};
cout << (ob.slidingPuzzle(v));
}
{{1,2,3},{0,4,5}}
2 | [
{
"code": null,
"e": 1218,
"s": 1062,
"text": "Suppose we have one 2x3 board, there are 5 tiles those are represented by the numbers 1 through 5, and one empty square is there, that is represented by 0."
},
{
"code": null,
"e": 1394,
"s": 1218,
"text": "Here a move means 0 and one adjacent number (top, bottom, left or right) and swapping it. This will be solved when the elements are arranged in this manner: [[1,2,3],[4,5,0]]."
},
{
"code": null,
"e": 1563,
"s": 1394,
"text": "We have the puzzle board; we have to find the least number of moves required so that the state of the board is solved. If this is not possible to solve, then return -1."
},
{
"code": null,
"e": 1672,
"s": 1563,
"text": "So, if the input is like [[1,2,3],[0,4,5]], then the output will be 2, as we have to swap [0,4], then [0,5]."
},
{
"code": null,
"e": 1716,
"s": 1672,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1783,
"s": 1716,
"text": "Define one function slidingPuzzle(), this will take board as input"
},
{
"code": null,
"e": 1850,
"s": 1783,
"text": "Define one function slidingPuzzle(), this will take board as input"
},
{
"code": null,
"e": 1896,
"s": 1850,
"text": "if board is perfectly arranged then −return 0"
},
{
"code": null,
"e": 1934,
"s": 1896,
"text": "if board is perfectly arranged then −"
},
{
"code": null,
"e": 1943,
"s": 1934,
"text": "return 0"
},
{
"code": null,
"e": 1952,
"s": 1943,
"text": "return 0"
},
{
"code": null,
"e": 1986,
"s": 1952,
"text": "Define one queue q of 2d matrices"
},
{
"code": null,
"e": 2020,
"s": 1986,
"text": "Define one queue q of 2d matrices"
},
{
"code": null,
"e": 2040,
"s": 2020,
"text": "insert board into q"
},
{
"code": null,
"e": 2060,
"s": 2040,
"text": "insert board into q"
},
{
"code": null,
"e": 2099,
"s": 2060,
"text": "Define one set visited for 2d matrices"
},
{
"code": null,
"e": 2138,
"s": 2099,
"text": "Define one set visited for 2d matrices"
},
{
"code": null,
"e": 2164,
"s": 2138,
"text": "insert board into visited"
},
{
"code": null,
"e": 2190,
"s": 2164,
"text": "insert board into visited"
},
{
"code": null,
"e": 3137,
"s": 2190,
"text": "for initialize lvl := 1, when not q is empty, update (increase lvl by 1), do −sz := size of qwhile sz is non-zero, decrease sz after each iteration, do −Define one 2D array node = front element of qdelete element from qdx := -1, y := -1for initialize i := 0, when i < size of board, update (increase i by 1), do −for initialize j := 0, when j < size of board[0], update (increase j by 1), do −if node[i, j] is same as 0, then −x := iy := jCome out from the loopfor initialize k := 0, when k < 4, update (increase k by 1), do −if nx < 0 or ny < 0 or nx >= row count of board or ny >= column count of board, then −Ignore following part, skip to the next iterationexchange node[x, y] and node[nx, ny]if node is in visited, then −exchange node[x, y] and node[nx, ny]Ignore following part, skip to the next iterationinsert node into visitedif node is perfect arrangemen of boards, then −return lvlinsert node into qexchange node[x, y] and node[nx, ny]"
},
{
"code": null,
"e": 3216,
"s": 3137,
"text": "for initialize lvl := 1, when not q is empty, update (increase lvl by 1), do −"
},
{
"code": null,
"e": 3232,
"s": 3216,
"text": "sz := size of q"
},
{
"code": null,
"e": 3248,
"s": 3232,
"text": "sz := size of q"
},
{
"code": null,
"e": 4102,
"s": 3248,
"text": "while sz is non-zero, decrease sz after each iteration, do −Define one 2D array node = front element of qdelete element from qdx := -1, y := -1for initialize i := 0, when i < size of board, update (increase i by 1), do −for initialize j := 0, when j < size of board[0], update (increase j by 1), do −if node[i, j] is same as 0, then −x := iy := jCome out from the loopfor initialize k := 0, when k < 4, update (increase k by 1), do −if nx < 0 or ny < 0 or nx >= row count of board or ny >= column count of board, then −Ignore following part, skip to the next iterationexchange node[x, y] and node[nx, ny]if node is in visited, then −exchange node[x, y] and node[nx, ny]Ignore following part, skip to the next iterationinsert node into visitedif node is perfect arrangemen of boards, then −return lvlinsert node into qexchange node[x, y] and node[nx, ny]"
},
{
"code": null,
"e": 4163,
"s": 4102,
"text": "while sz is non-zero, decrease sz after each iteration, do −"
},
{
"code": null,
"e": 4209,
"s": 4163,
"text": "Define one 2D array node = front element of q"
},
{
"code": null,
"e": 4255,
"s": 4209,
"text": "Define one 2D array node = front element of q"
},
{
"code": null,
"e": 4277,
"s": 4255,
"text": "delete element from q"
},
{
"code": null,
"e": 4299,
"s": 4277,
"text": "delete element from q"
},
{
"code": null,
"e": 4317,
"s": 4299,
"text": "dx := -1, y := -1"
},
{
"code": null,
"e": 4335,
"s": 4317,
"text": "dx := -1, y := -1"
},
{
"code": null,
"e": 4561,
"s": 4335,
"text": "for initialize i := 0, when i < size of board, update (increase i by 1), do −for initialize j := 0, when j < size of board[0], update (increase j by 1), do −if node[i, j] is same as 0, then −x := iy := jCome out from the loop"
},
{
"code": null,
"e": 4639,
"s": 4561,
"text": "for initialize i := 0, when i < size of board, update (increase i by 1), do −"
},
{
"code": null,
"e": 4788,
"s": 4639,
"text": "for initialize j := 0, when j < size of board[0], update (increase j by 1), do −if node[i, j] is same as 0, then −x := iy := jCome out from the loop"
},
{
"code": null,
"e": 4869,
"s": 4788,
"text": "for initialize j := 0, when j < size of board[0], update (increase j by 1), do −"
},
{
"code": null,
"e": 4938,
"s": 4869,
"text": "if node[i, j] is same as 0, then −x := iy := jCome out from the loop"
},
{
"code": null,
"e": 4973,
"s": 4938,
"text": "if node[i, j] is same as 0, then −"
},
{
"code": null,
"e": 4980,
"s": 4973,
"text": "x := i"
},
{
"code": null,
"e": 4987,
"s": 4980,
"text": "x := i"
},
{
"code": null,
"e": 4994,
"s": 4987,
"text": "y := j"
},
{
"code": null,
"e": 5001,
"s": 4994,
"text": "y := j"
},
{
"code": null,
"e": 5024,
"s": 5001,
"text": "Come out from the loop"
},
{
"code": null,
"e": 5047,
"s": 5024,
"text": "Come out from the loop"
},
{
"code": null,
"e": 5113,
"s": 5047,
"text": "for initialize k := 0, when k < 4, update (increase k by 1), do −"
},
{
"code": null,
"e": 5179,
"s": 5113,
"text": "for initialize k := 0, when k < 4, update (increase k by 1), do −"
},
{
"code": null,
"e": 5315,
"s": 5179,
"text": "if nx < 0 or ny < 0 or nx >= row count of board or ny >= column count of board, then −Ignore following part, skip to the next iteration"
},
{
"code": null,
"e": 5402,
"s": 5315,
"text": "if nx < 0 or ny < 0 or nx >= row count of board or ny >= column count of board, then −"
},
{
"code": null,
"e": 5452,
"s": 5402,
"text": "Ignore following part, skip to the next iteration"
},
{
"code": null,
"e": 5502,
"s": 5452,
"text": "Ignore following part, skip to the next iteration"
},
{
"code": null,
"e": 5539,
"s": 5502,
"text": "exchange node[x, y] and node[nx, ny]"
},
{
"code": null,
"e": 5576,
"s": 5539,
"text": "exchange node[x, y] and node[nx, ny]"
},
{
"code": null,
"e": 5691,
"s": 5576,
"text": "if node is in visited, then −exchange node[x, y] and node[nx, ny]Ignore following part, skip to the next iteration"
},
{
"code": null,
"e": 5721,
"s": 5691,
"text": "if node is in visited, then −"
},
{
"code": null,
"e": 5758,
"s": 5721,
"text": "exchange node[x, y] and node[nx, ny]"
},
{
"code": null,
"e": 5795,
"s": 5758,
"text": "exchange node[x, y] and node[nx, ny]"
},
{
"code": null,
"e": 5845,
"s": 5795,
"text": "Ignore following part, skip to the next iteration"
},
{
"code": null,
"e": 5895,
"s": 5845,
"text": "Ignore following part, skip to the next iteration"
},
{
"code": null,
"e": 5920,
"s": 5895,
"text": "insert node into visited"
},
{
"code": null,
"e": 5945,
"s": 5920,
"text": "insert node into visited"
},
{
"code": null,
"e": 6003,
"s": 5945,
"text": "if node is perfect arrangemen of boards, then −return lvl"
},
{
"code": null,
"e": 6051,
"s": 6003,
"text": "if node is perfect arrangemen of boards, then −"
},
{
"code": null,
"e": 6062,
"s": 6051,
"text": "return lvl"
},
{
"code": null,
"e": 6073,
"s": 6062,
"text": "return lvl"
},
{
"code": null,
"e": 6092,
"s": 6073,
"text": "insert node into q"
},
{
"code": null,
"e": 6111,
"s": 6092,
"text": "insert node into q"
},
{
"code": null,
"e": 6148,
"s": 6111,
"text": "exchange node[x, y] and node[nx, ny]"
},
{
"code": null,
"e": 6185,
"s": 6148,
"text": "exchange node[x, y] and node[nx, ny]"
},
{
"code": null,
"e": 6195,
"s": 6185,
"text": "return -1"
},
{
"code": null,
"e": 6205,
"s": 6195,
"text": "return -1"
},
{
"code": null,
"e": 6275,
"s": 6205,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 6286,
"s": 6275,
"text": " Live Demo"
},
{
"code": null,
"e": 8039,
"s": 6286,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nint dir[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};\nclass Solution {\n public:\n bool ok(vector < vector <int> >& b){\n return b[0][0] == 1 && b[0][1] == 2 && b[0][2] == 3 && b[1]\n [0] == 4 && b[1][1] == 5;\n }\n int slidingPuzzle(vector<vector<int>>& board) {\n if (ok(board))\n return 0;\n queue<vector<vector<int> > > q;\n q.push(board);\n set<vector<vector<int> > > visited;\n visited.insert(board);\n for (int lvl = 1; !q.empty(); lvl++) {\n int sz = q.size();\n while (sz--) {\n vector<vector<int> > node = q.front();\n q.pop();\n int x = -1;\n int y = -1;\n for (int i = 0; i < board.size(); i++) {\n for (int j = 0; j < board[0].size(); j++) {\n if (node[i][j] == 0) {\n x = i;\n y = j;\n break;\n }\n }\n }\n for (int k = 0; k < 4; k++) {\n int nx = x + dir[k][0];\n int ny = y + dir[k][1];\n if (nx < 0 || ny < 0 || nx >= board.size() || ny\n >= board[0].size())\n continue;\n swap(node[x][y], node[nx][ny]);\n if (visited.count(node)) {\n swap(node[x][y], node[nx][ny]);\n continue;\n }\n visited.insert(node);\n if (ok(node))\n return lvl;\n q.push(node);\n swap(node[x][y], node[nx][ny]);\n }\n }\n }\n return -1;\n }\n};\nmain(){\n Solution ob;\n vector<vector<int>> v = {{1,2,3},{0,4,5}};\n cout << (ob.slidingPuzzle(v));\n}"
},
{
"code": null,
"e": 8057,
"s": 8039,
"text": "{{1,2,3},{0,4,5}}"
},
{
"code": null,
"e": 8059,
"s": 8057,
"text": "2"
}
]
|
Python Blockchain - Developing Client | A client is somebody who holds TPCoins and transacts those for goods/services from other vendors on the network including his own. We should define a Client class for this purpose. To create a globally unique identification for the client, we use PKI (Public Key Infrastructure). In this chapter, let us talk about this in detail.
The client should be able to send money from his wallet to another known person. Similarly, the client should be able to accept money from a third party. For spending money, the client would create a transaction specifying the sender’s name and the amount to be paid. For receiving money, the client will provide his identity to the third party − essentially a sender of the money. We do not store the balance amount of money the client holds in his wallet. During a transaction, we will compute the actual balance to ensure that the client has sufficient balance to make the payment.
To develop the Client class and for the rest of the code in the project, we will need to import many Python libraries. These are listed below −
# import libraries
import hashlib
import random
import string
import json
import binascii
import numpy as np
import pandas as pd
import pylab as pl
import logging
import datetime
import collections
In addition to the above standard libraries, we are going to sign our transactions, create hash of the objects, etc. For this, you will need to import the following libraries −
# following imports are required by PKI
import Crypto
import Crypto.Random
from Crypto.Hash import SHA
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
In the next chapter, let us talk about client class.
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2326,
"s": 1995,
"text": "A client is somebody who holds TPCoins and transacts those for goods/services from other vendors on the network including his own. We should define a Client class for this purpose. To create a globally unique identification for the client, we use PKI (Public Key Infrastructure). In this chapter, let us talk about this in detail."
},
{
"code": null,
"e": 2911,
"s": 2326,
"text": "The client should be able to send money from his wallet to another known person. Similarly, the client should be able to accept money from a third party. For spending money, the client would create a transaction specifying the sender’s name and the amount to be paid. For receiving money, the client will provide his identity to the third party − essentially a sender of the money. We do not store the balance amount of money the client holds in his wallet. During a transaction, we will compute the actual balance to ensure that the client has sufficient balance to make the payment."
},
{
"code": null,
"e": 3055,
"s": 2911,
"text": "To develop the Client class and for the rest of the code in the project, we will need to import many Python libraries. These are listed below −"
},
{
"code": null,
"e": 3254,
"s": 3055,
"text": "# import libraries\nimport hashlib\nimport random\nimport string\nimport json\nimport binascii\nimport numpy as np\nimport pandas as pd\nimport pylab as pl\nimport logging\nimport datetime\nimport collections\n"
},
{
"code": null,
"e": 3431,
"s": 3254,
"text": "In addition to the above standard libraries, we are going to sign our transactions, create hash of the objects, etc. For this, you will need to import the following libraries −"
},
{
"code": null,
"e": 3608,
"s": 3431,
"text": "# following imports are required by PKI\nimport Crypto\nimport Crypto.Random\nfrom Crypto.Hash import SHA\nfrom Crypto.PublicKey import RSA\nfrom Crypto.Signature import PKCS1_v1_5\n"
},
{
"code": null,
"e": 3661,
"s": 3608,
"text": "In the next chapter, let us talk about client class."
},
{
"code": null,
"e": 3698,
"s": 3661,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3714,
"s": 3698,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3747,
"s": 3714,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3766,
"s": 3747,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3801,
"s": 3766,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 3823,
"s": 3801,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 3857,
"s": 3823,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3885,
"s": 3857,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3920,
"s": 3885,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3934,
"s": 3920,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3967,
"s": 3934,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3984,
"s": 3967,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3991,
"s": 3984,
"text": " Print"
},
{
"code": null,
"e": 4002,
"s": 3991,
"text": " Add Notes"
}
]
|
iText - Overview | The Portable Document Format (PDF) is a file format that helps to present data in a manner that is independent of application software, hardware, and operating systems. Each PDF file holds description of a fixed-layout flat document, including text, fonts, graphics, and other information needed to display it.
There are several libraries available to create and manipulate PDF documents through programs, such as −
Adobe PDF Library − This library provides API in languages such as C++, .NET and Java. Using this, we can edit, view, print, and extract text from PDF documents.
Adobe PDF Library − This library provides API in languages such as C++, .NET and Java. Using this, we can edit, view, print, and extract text from PDF documents.
Formatting Objects Processor − Open-source print formatter driven by XSL Formatting Objects and an output independent formatter. The primary output target is PDF.
Formatting Objects Processor − Open-source print formatter driven by XSL Formatting Objects and an output independent formatter. The primary output target is PDF.
PDF Box − Apache PDFBox is an open-source Java library that supports the development and conversion of PDF documents. Using this library, you can develop Java programs that create, convert and manipulate PDF documents.
PDF Box − Apache PDFBox is an open-source Java library that supports the development and conversion of PDF documents. Using this library, you can develop Java programs that create, convert and manipulate PDF documents.
Jasper Reports − This is a Java reporting tool which generates reports in PDF document including Microsoft Excel, RTF, ODT, comma-separated values and XML files.
Jasper Reports − This is a Java reporting tool which generates reports in PDF document including Microsoft Excel, RTF, ODT, comma-separated values and XML files.
Similar to above listed software's iText is a Java PDF library using which, you can develop Java programs that create, convert, and manipulate PDF documents.
Following are the notable features of iText library −
Interactive − iText provides you classes (API's) to generate interactive PDF documents. Using these, you can create maps and books.
Interactive − iText provides you classes (API's) to generate interactive PDF documents. Using these, you can create maps and books.
Adding bookmarks, page numbers, etc − Using iText, you can add bookmarks, page numbers, and watermarks.
Adding bookmarks, page numbers, etc − Using iText, you can add bookmarks, page numbers, and watermarks.
Split & Merge − Using iText, you can split an existing PDF into multiple PDFs and also add/concatenate additional pages to it.
Split & Merge − Using iText, you can split an existing PDF into multiple PDFs and also add/concatenate additional pages to it.
Fill Forms − Using iText, you can fill interactive forms in a PDF document.
Fill Forms − Using iText, you can fill interactive forms in a PDF document.
Save as Image − Using iText, you can save PDFs as image files, such as PNG or JPEG.
Save as Image − Using iText, you can save PDFs as image files, such as PNG or JPEG.
Canvas − iText library provides you a Canvas class using which you can draw various geometrical shapes on a PDF document like circle, line, etc.
Canvas − iText library provides you a Canvas class using which you can draw various geometrical shapes on a PDF document like circle, line, etc.
Create PDFs − Using iText, you can create a new PDF file from your Java programs. You can include images and fonts too.
Create PDFs − Using iText, you can create a new PDF file from your Java programs. You can include images and fonts too.
Follow the steps given below to set the iText environment on Eclipse.
Step 1 − Install Eclipse and open a new project in it as shown below.
Step 2 − Create an iTextSample project as shown below.
Step 3 − Right-click on the project and convert it into a Maven project as shown below. Once you convert it into Maven project, it will give you a pom.xml where you need to mention the required dependencies. Thereafter, the jar files of those dependencies will be automatically downloaded into your project.
Step 4 − Now, in the pom.xml of the project, copy and paste the following content (dependencies for iText application) and refresh the project.
Using pom.xml
Convert the project into Maven project and add the following content to its pom.xml.
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>SanthoshExample</groupId>
<artifactId>SanthoshExample</artifactId>
<version>0.0.1-SNAPSHOT</version>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<!-- always needed -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>kernel</artifactId>
<version>7.0.2</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>io</artifactId>
<version>7.0.2</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>layout</artifactId>
<version>7.0.2</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>forms</artifactId>
<version>7.0.2</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>pdfa</artifactId>
<version>7.0.2</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>sign</artifactId>
<version>7.0.2</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>barcodes</artifactId>
<version>7.0.2</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>font-asian</artifactId>
<version>7.0.2</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>hyph</artifactId>
<version>7.0.2</version>
</dependency>
</dependencies>
</project>
Finally, if you observe the Maven dependencies, you can observe that all the required jar files were downloaded.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2679,
"s": 2368,
"text": "The Portable Document Format (PDF) is a file format that helps to present data in a manner that is independent of application software, hardware, and operating systems. Each PDF file holds description of a fixed-layout flat document, including text, fonts, graphics, and other information needed to display it."
},
{
"code": null,
"e": 2784,
"s": 2679,
"text": "There are several libraries available to create and manipulate PDF documents through programs, such as −"
},
{
"code": null,
"e": 2946,
"s": 2784,
"text": "Adobe PDF Library − This library provides API in languages such as C++, .NET and Java. Using this, we can edit, view, print, and extract text from PDF documents."
},
{
"code": null,
"e": 3108,
"s": 2946,
"text": "Adobe PDF Library − This library provides API in languages such as C++, .NET and Java. Using this, we can edit, view, print, and extract text from PDF documents."
},
{
"code": null,
"e": 3271,
"s": 3108,
"text": "Formatting Objects Processor − Open-source print formatter driven by XSL Formatting Objects and an output independent formatter. The primary output target is PDF."
},
{
"code": null,
"e": 3434,
"s": 3271,
"text": "Formatting Objects Processor − Open-source print formatter driven by XSL Formatting Objects and an output independent formatter. The primary output target is PDF."
},
{
"code": null,
"e": 3653,
"s": 3434,
"text": "PDF Box − Apache PDFBox is an open-source Java library that supports the development and conversion of PDF documents. Using this library, you can develop Java programs that create, convert and manipulate PDF documents."
},
{
"code": null,
"e": 3872,
"s": 3653,
"text": "PDF Box − Apache PDFBox is an open-source Java library that supports the development and conversion of PDF documents. Using this library, you can develop Java programs that create, convert and manipulate PDF documents."
},
{
"code": null,
"e": 4034,
"s": 3872,
"text": "Jasper Reports − This is a Java reporting tool which generates reports in PDF document including Microsoft Excel, RTF, ODT, comma-separated values and XML files."
},
{
"code": null,
"e": 4196,
"s": 4034,
"text": "Jasper Reports − This is a Java reporting tool which generates reports in PDF document including Microsoft Excel, RTF, ODT, comma-separated values and XML files."
},
{
"code": null,
"e": 4354,
"s": 4196,
"text": "Similar to above listed software's iText is a Java PDF library using which, you can develop Java programs that create, convert, and manipulate PDF documents."
},
{
"code": null,
"e": 4408,
"s": 4354,
"text": "Following are the notable features of iText library −"
},
{
"code": null,
"e": 4540,
"s": 4408,
"text": "Interactive − iText provides you classes (API's) to generate interactive PDF documents. Using these, you can create maps and books."
},
{
"code": null,
"e": 4672,
"s": 4540,
"text": "Interactive − iText provides you classes (API's) to generate interactive PDF documents. Using these, you can create maps and books."
},
{
"code": null,
"e": 4776,
"s": 4672,
"text": "Adding bookmarks, page numbers, etc − Using iText, you can add bookmarks, page numbers, and watermarks."
},
{
"code": null,
"e": 4880,
"s": 4776,
"text": "Adding bookmarks, page numbers, etc − Using iText, you can add bookmarks, page numbers, and watermarks."
},
{
"code": null,
"e": 5007,
"s": 4880,
"text": "Split & Merge − Using iText, you can split an existing PDF into multiple PDFs and also add/concatenate additional pages to it."
},
{
"code": null,
"e": 5134,
"s": 5007,
"text": "Split & Merge − Using iText, you can split an existing PDF into multiple PDFs and also add/concatenate additional pages to it."
},
{
"code": null,
"e": 5210,
"s": 5134,
"text": "Fill Forms − Using iText, you can fill interactive forms in a PDF document."
},
{
"code": null,
"e": 5286,
"s": 5210,
"text": "Fill Forms − Using iText, you can fill interactive forms in a PDF document."
},
{
"code": null,
"e": 5370,
"s": 5286,
"text": "Save as Image − Using iText, you can save PDFs as image files, such as PNG or JPEG."
},
{
"code": null,
"e": 5454,
"s": 5370,
"text": "Save as Image − Using iText, you can save PDFs as image files, such as PNG or JPEG."
},
{
"code": null,
"e": 5599,
"s": 5454,
"text": "Canvas − iText library provides you a Canvas class using which you can draw various geometrical shapes on a PDF document like circle, line, etc."
},
{
"code": null,
"e": 5744,
"s": 5599,
"text": "Canvas − iText library provides you a Canvas class using which you can draw various geometrical shapes on a PDF document like circle, line, etc."
},
{
"code": null,
"e": 5864,
"s": 5744,
"text": "Create PDFs − Using iText, you can create a new PDF file from your Java programs. You can include images and fonts too."
},
{
"code": null,
"e": 5984,
"s": 5864,
"text": "Create PDFs − Using iText, you can create a new PDF file from your Java programs. You can include images and fonts too."
},
{
"code": null,
"e": 6054,
"s": 5984,
"text": "Follow the steps given below to set the iText environment on Eclipse."
},
{
"code": null,
"e": 6124,
"s": 6054,
"text": "Step 1 − Install Eclipse and open a new project in it as shown below."
},
{
"code": null,
"e": 6179,
"s": 6124,
"text": "Step 2 − Create an iTextSample project as shown below."
},
{
"code": null,
"e": 6487,
"s": 6179,
"text": "Step 3 − Right-click on the project and convert it into a Maven project as shown below. Once you convert it into Maven project, it will give you a pom.xml where you need to mention the required dependencies. Thereafter, the jar files of those dependencies will be automatically downloaded into your project."
},
{
"code": null,
"e": 6631,
"s": 6487,
"text": "Step 4 − Now, in the pom.xml of the project, copy and paste the following content (dependencies for iText application) and refresh the project."
},
{
"code": null,
"e": 6645,
"s": 6631,
"text": "Using pom.xml"
},
{
"code": null,
"e": 6730,
"s": 6645,
"text": "Convert the project into Maven project and add the following content to its pom.xml."
},
{
"code": null,
"e": 9417,
"s": 6730,
"text": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" \n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \n xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 \n http://maven.apache.org/xsd/maven-4.0.0.xsd\"> \n \n <modelVersion>4.0.0</modelVersion> \n <groupId>SanthoshExample</groupId> \n <artifactId>SanthoshExample</artifactId> \n <version>0.0.1-SNAPSHOT</version> \n <build> \n <sourceDirectory>src</sourceDirectory> \n <plugins> \n <plugin> \n <artifactId>maven-compiler-plugin</artifactId> \n <version>3.5.1</version> \n <configuration> \n <source>1.8</source> \n <target>1.8</target> \n </configuration> \n </plugin> \n </plugins> \n </build> \n \n <dependencies> \n <!-- always needed --> \n <dependency> \n <groupId>com.itextpdf</groupId> \n <artifactId>kernel</artifactId> \n <version>7.0.2</version> \n </dependency> \n \n <dependency> \n <groupId>com.itextpdf</groupId> \n <artifactId>io</artifactId> \n <version>7.0.2</version> \n </dependency> \n \n <dependency> \n <groupId>com.itextpdf</groupId> \n <artifactId>layout</artifactId> \n <version>7.0.2</version>\n </dependency> \n \n <dependency> \n <groupId>com.itextpdf</groupId> \n <artifactId>forms</artifactId> \n <version>7.0.2</version> \n </dependency> \n \n <dependency> \n <groupId>com.itextpdf</groupId> \n <artifactId>pdfa</artifactId> \n <version>7.0.2</version> \n </dependency> \n \n <dependency> \n <groupId>com.itextpdf</groupId> \n <artifactId>sign</artifactId> \n <version>7.0.2</version> \n </dependency> \n \n <dependency> \n <groupId>com.itextpdf</groupId> \n <artifactId>barcodes</artifactId> \n <version>7.0.2</version> \n </dependency> \n \n <dependency> \n <groupId>com.itextpdf</groupId> \n <artifactId>font-asian</artifactId> \n <version>7.0.2</version> \n </dependency> \n \n <dependency> \n <groupId>com.itextpdf</groupId> \n <artifactId>hyph</artifactId> \n <version>7.0.2</version> \n </dependency> \n </dependencies>\n \n</project>"
},
{
"code": null,
"e": 9530,
"s": 9417,
"text": "Finally, if you observe the Maven dependencies, you can observe that all the required jar files were downloaded."
},
{
"code": null,
"e": 9537,
"s": 9530,
"text": " Print"
},
{
"code": null,
"e": 9548,
"s": 9537,
"text": " Add Notes"
}
]
|
C++ string class and its applications - GeeksforGeeks | 13 Sep, 2021
In C++ we can store string by one of the two ways –
C style stringsstring class (discussed in this post)
C style strings
string class (discussed in this post)
In this post, the second method is discussed. string class is part of C++ library that supports a lot much functionality over C style strings.C++ string class internally uses char array to store character but all memory management, allocation, and null termination is handled by string class itself that is why it is easy to use. The length of the C++ string can be changed at runtime because of dynamic allocation of memory similar to vectors. As string class is a container class, we can iterate over all its characters using an iterator similar to other containers like vector, set and maps, but generally, we use a simple for loop for iterating over the characters and index them using the [] operator.C++ string class has a lot of functions to handle string easily. Most useful of them are demonstrated in below code.
// C++ program to demonstrate various function string class#include <bits/stdc++.h>using namespace std; int main(){ // various constructor of string class // initialization by raw string string str1("first string"); // initialization by another string string str2(str1); // initialization by character with number of occurrence string str3(5, '#'); // initialization by part of another string string str4(str1, 6, 6); // from 6th index (second parameter) // 6 characters (third parameter) // initialization by part of another string : iterator version string str5(str2.begin(), str2.begin() + 5); cout << str1 << endl; cout << str2 << endl; cout << str3 << endl; cout << str4 << endl; cout << str5 << endl; // assignment operator string str6 = str4; // clear function deletes all character from string str4.clear(); // both size() and length() return length of string and // they work as synonyms int len = str6.length(); // Same as "len = str6.size();" cout << "Length of string is : " << len << endl; // a particular character can be accessed using at / // [] operator char ch = str6.at(2); // Same as "ch = str6[2];" cout << "third character of string is : " << ch << endl; // front return first character and back returns last character // of string char ch_f = str6.front(); // Same as "ch_f = str6[0];" char ch_b = str6.back(); // Same as below // "ch_b = str6[str6.length() - 1];" cout << "First char is : " << ch_f << ", Last char is : " << ch_b << endl; // c_str returns null terminated char array version of string const char* charstr = str6.c_str(); printf("%s\n", charstr); // append add the argument string at the end str6.append(" extension"); // same as str6 += " extension" // another version of append, which appends part of other // string str4.append(str6, 0, 6); // at 0th position 6 character cout << str6 << endl; cout << str4 << endl; // find returns index where pattern is found. // If pattern is not there it returns predefined // constant npos whose value is -1 if (str6.find(str4) != string::npos) cout << "str4 found in str6 at " << str6.find(str4) << " pos" << endl; else cout << "str4 not found in str6" << endl; // substr(a, b) function returns a substring of b length // starting from index a cout << str6.substr(7, 3) << endl; // if second argument is not passed, string till end is // taken as substring cout << str6.substr(7) << endl; // erase(a, b) deletes b characters at index a str6.erase(7, 4); cout << str6 << endl; // iterator version of erase str6.erase(str6.begin() + 5, str6.end() - 3); cout << str6 << endl; str6 = "This is a examples"; // replace(a, b, str) replaces b characters from a index by str str6.replace(2, 7, "ese are test"); cout << str6 << endl; return 0;}
Output :
first string
first string
#####
string
first
Length of string is : 6
third character of string is : r
First char is : s, Last char is : g
string
string extension
string
str4 found in str6 at 0 pos
ext
extension
string nsion
strinion
These are test examples
As seen in the above code, we can get the length of the string by size() as well as length() but length() is preferred for strings. We can concat a string to another string by += or by append(), but += is slightly slower than append() because each time + is called a new string (creation of new buffer) is made which is returned that is a bit overhead in case of many append operation.
Applications :On basis of above string function some application are written below :
// C++ program to demonstrate uses of some string function#include <bits/stdc++.h>using namespace std; // this function returns floating point part of a number-stringstring returnFloatingPart(string str){ int pos = str.find("."); if (pos == string::npos) return ""; else return str.substr(pos + 1);} // This function checks whether a string contains all digit or notbool containsOnlyDigit(string str){ int l = str.length(); for (int i = 0; i < l; i++) { if (str.at(i) < '0' || str.at(i) > '9') return false; } // if we reach here all character are digits return true;} // this function replaces all single space by %20// Used in URLSstring replaceBlankWith20(string str){ string replaceby = "%20"; int n = 0; // loop till all space are replaced while ((n = str.find(" ", n)) != string::npos ) { str.replace(n, 1, replaceby); n += replaceby.length(); } return str;} // driver function to check above methodsint main(){ string fnum = "23.342"; cout << "Floating part is : " << returnFloatingPart(fnum) << endl; string num = "3452"; if (containsOnlyDigit(num)) cout << "string contains only digit" << endl; string urlex = "google com in"; cout << replaceBlankWith20(urlex) << endl; return 0; }
Output :
Floating part is : 342
string contains only digit
google%20com%20in
Related Articles:
How to quickly reverse a string in C++?
C++ String Class and its Applications | Set 2
Array of Strings in C++
Converting string to number and vice-versa in C++
This article is contributed by Utkarsh Trivedi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
BabisSarantoglou
ManasChhabra2
nidhi_biet
sumitgumber28
CPP-Library
cpp-string
STL
C Language
C++
School Programming
Strings
Strings
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Multidimensional Arrays in C / C++
rand() and srand() in C/C++
Command line arguments in C/C++
Core Dump (Segmentation fault) in C/C++
Left Shift and Right Shift Operators in C/C++
Vector in C++ STL
Initialize a vector in C++ (6 different ways)
Map in C++ Standard Template Library (STL)
Socket Programming in C/C++
Multidimensional Arrays in C / C++ | [
{
"code": null,
"e": 24220,
"s": 24192,
"text": "\n13 Sep, 2021"
},
{
"code": null,
"e": 24272,
"s": 24220,
"text": "In C++ we can store string by one of the two ways –"
},
{
"code": null,
"e": 24325,
"s": 24272,
"text": "C style stringsstring class (discussed in this post)"
},
{
"code": null,
"e": 24341,
"s": 24325,
"text": "C style strings"
},
{
"code": null,
"e": 24379,
"s": 24341,
"text": "string class (discussed in this post)"
},
{
"code": null,
"e": 25202,
"s": 24379,
"text": "In this post, the second method is discussed. string class is part of C++ library that supports a lot much functionality over C style strings.C++ string class internally uses char array to store character but all memory management, allocation, and null termination is handled by string class itself that is why it is easy to use. The length of the C++ string can be changed at runtime because of dynamic allocation of memory similar to vectors. As string class is a container class, we can iterate over all its characters using an iterator similar to other containers like vector, set and maps, but generally, we use a simple for loop for iterating over the characters and index them using the [] operator.C++ string class has a lot of functions to handle string easily. Most useful of them are demonstrated in below code."
},
{
"code": "// C++ program to demonstrate various function string class#include <bits/stdc++.h>using namespace std; int main(){ // various constructor of string class // initialization by raw string string str1(\"first string\"); // initialization by another string string str2(str1); // initialization by character with number of occurrence string str3(5, '#'); // initialization by part of another string string str4(str1, 6, 6); // from 6th index (second parameter) // 6 characters (third parameter) // initialization by part of another string : iterator version string str5(str2.begin(), str2.begin() + 5); cout << str1 << endl; cout << str2 << endl; cout << str3 << endl; cout << str4 << endl; cout << str5 << endl; // assignment operator string str6 = str4; // clear function deletes all character from string str4.clear(); // both size() and length() return length of string and // they work as synonyms int len = str6.length(); // Same as \"len = str6.size();\" cout << \"Length of string is : \" << len << endl; // a particular character can be accessed using at / // [] operator char ch = str6.at(2); // Same as \"ch = str6[2];\" cout << \"third character of string is : \" << ch << endl; // front return first character and back returns last character // of string char ch_f = str6.front(); // Same as \"ch_f = str6[0];\" char ch_b = str6.back(); // Same as below // \"ch_b = str6[str6.length() - 1];\" cout << \"First char is : \" << ch_f << \", Last char is : \" << ch_b << endl; // c_str returns null terminated char array version of string const char* charstr = str6.c_str(); printf(\"%s\\n\", charstr); // append add the argument string at the end str6.append(\" extension\"); // same as str6 += \" extension\" // another version of append, which appends part of other // string str4.append(str6, 0, 6); // at 0th position 6 character cout << str6 << endl; cout << str4 << endl; // find returns index where pattern is found. // If pattern is not there it returns predefined // constant npos whose value is -1 if (str6.find(str4) != string::npos) cout << \"str4 found in str6 at \" << str6.find(str4) << \" pos\" << endl; else cout << \"str4 not found in str6\" << endl; // substr(a, b) function returns a substring of b length // starting from index a cout << str6.substr(7, 3) << endl; // if second argument is not passed, string till end is // taken as substring cout << str6.substr(7) << endl; // erase(a, b) deletes b characters at index a str6.erase(7, 4); cout << str6 << endl; // iterator version of erase str6.erase(str6.begin() + 5, str6.end() - 3); cout << str6 << endl; str6 = \"This is a examples\"; // replace(a, b, str) replaces b characters from a index by str str6.replace(2, 7, \"ese are test\"); cout << str6 << endl; return 0;}",
"e": 28293,
"s": 25202,
"text": null
},
{
"code": null,
"e": 28302,
"s": 28293,
"text": "Output :"
},
{
"code": null,
"e": 28559,
"s": 28302,
"text": "first string\nfirst string\n#####\nstring\nfirst\nLength of string is : 6\nthird character of string is : r\nFirst char is : s, Last char is : g\nstring\nstring extension\nstring\nstr4 found in str6 at 0 pos\next\nextension\nstring nsion\nstrinion\nThese are test examples"
},
{
"code": null,
"e": 28945,
"s": 28559,
"text": "As seen in the above code, we can get the length of the string by size() as well as length() but length() is preferred for strings. We can concat a string to another string by += or by append(), but += is slightly slower than append() because each time + is called a new string (creation of new buffer) is made which is returned that is a bit overhead in case of many append operation."
},
{
"code": null,
"e": 29030,
"s": 28945,
"text": "Applications :On basis of above string function some application are written below :"
},
{
"code": "// C++ program to demonstrate uses of some string function#include <bits/stdc++.h>using namespace std; // this function returns floating point part of a number-stringstring returnFloatingPart(string str){ int pos = str.find(\".\"); if (pos == string::npos) return \"\"; else return str.substr(pos + 1);} // This function checks whether a string contains all digit or notbool containsOnlyDigit(string str){ int l = str.length(); for (int i = 0; i < l; i++) { if (str.at(i) < '0' || str.at(i) > '9') return false; } // if we reach here all character are digits return true;} // this function replaces all single space by %20// Used in URLSstring replaceBlankWith20(string str){ string replaceby = \"%20\"; int n = 0; // loop till all space are replaced while ((n = str.find(\" \", n)) != string::npos ) { str.replace(n, 1, replaceby); n += replaceby.length(); } return str;} // driver function to check above methodsint main(){ string fnum = \"23.342\"; cout << \"Floating part is : \" << returnFloatingPart(fnum) << endl; string num = \"3452\"; if (containsOnlyDigit(num)) cout << \"string contains only digit\" << endl; string urlex = \"google com in\"; cout << replaceBlankWith20(urlex) << endl; return 0; }",
"e": 30370,
"s": 29030,
"text": null
},
{
"code": null,
"e": 30379,
"s": 30370,
"text": "Output :"
},
{
"code": null,
"e": 30447,
"s": 30379,
"text": "Floating part is : 342\nstring contains only digit\ngoogle%20com%20in"
},
{
"code": null,
"e": 30465,
"s": 30447,
"text": "Related Articles:"
},
{
"code": null,
"e": 30505,
"s": 30465,
"text": "How to quickly reverse a string in C++?"
},
{
"code": null,
"e": 30551,
"s": 30505,
"text": "C++ String Class and its Applications | Set 2"
},
{
"code": null,
"e": 30575,
"s": 30551,
"text": "Array of Strings in C++"
},
{
"code": null,
"e": 30625,
"s": 30575,
"text": "Converting string to number and vice-versa in C++"
},
{
"code": null,
"e": 30797,
"s": 30625,
"text": "This article is contributed by Utkarsh Trivedi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 30814,
"s": 30797,
"text": "BabisSarantoglou"
},
{
"code": null,
"e": 30828,
"s": 30814,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 30839,
"s": 30828,
"text": "nidhi_biet"
},
{
"code": null,
"e": 30853,
"s": 30839,
"text": "sumitgumber28"
},
{
"code": null,
"e": 30865,
"s": 30853,
"text": "CPP-Library"
},
{
"code": null,
"e": 30876,
"s": 30865,
"text": "cpp-string"
},
{
"code": null,
"e": 30880,
"s": 30876,
"text": "STL"
},
{
"code": null,
"e": 30891,
"s": 30880,
"text": "C Language"
},
{
"code": null,
"e": 30895,
"s": 30891,
"text": "C++"
},
{
"code": null,
"e": 30914,
"s": 30895,
"text": "School Programming"
},
{
"code": null,
"e": 30922,
"s": 30914,
"text": "Strings"
},
{
"code": null,
"e": 30930,
"s": 30922,
"text": "Strings"
},
{
"code": null,
"e": 30934,
"s": 30930,
"text": "STL"
},
{
"code": null,
"e": 30938,
"s": 30934,
"text": "CPP"
},
{
"code": null,
"e": 31036,
"s": 30938,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31045,
"s": 31036,
"text": "Comments"
},
{
"code": null,
"e": 31058,
"s": 31045,
"text": "Old Comments"
},
{
"code": null,
"e": 31093,
"s": 31058,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 31121,
"s": 31093,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 31153,
"s": 31121,
"text": "Command line arguments in C/C++"
},
{
"code": null,
"e": 31193,
"s": 31153,
"text": "Core Dump (Segmentation fault) in C/C++"
},
{
"code": null,
"e": 31239,
"s": 31193,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 31257,
"s": 31239,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 31303,
"s": 31257,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 31346,
"s": 31303,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 31374,
"s": 31346,
"text": "Socket Programming in C/C++"
}
]
|
How to make colorbar orientation horizontal in Python using Matplotlib? | To make colorbar orientation horizontal in Python, we can use orientation="horizontal" in the argument.
Set the figure size and adjust the padding between and around the subplots.
Create random x, y and z data points using numpy.
Create a figure and a set of subplots.
Use scatter() method to plot x, y and z data points.
Create a colorbar for a ScalarMappable instance, with horizontal orientation.
To display the figure, use show() method.
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
x, y, z = np.random.rand(3, 50)
f, ax = plt.subplots()
points = ax.scatter(x, y, c=z, s=50, cmap="plasma")
f.colorbar(points, orientation="horizontal")
plt.show() | [
{
"code": null,
"e": 1166,
"s": 1062,
"text": "To make colorbar orientation horizontal in Python, we can use orientation=\"horizontal\" in the argument."
},
{
"code": null,
"e": 1242,
"s": 1166,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1292,
"s": 1242,
"text": "Create random x, y and z data points using numpy."
},
{
"code": null,
"e": 1331,
"s": 1292,
"text": "Create a figure and a set of subplots."
},
{
"code": null,
"e": 1384,
"s": 1331,
"text": "Use scatter() method to plot x, y and z data points."
},
{
"code": null,
"e": 1462,
"s": 1384,
"text": "Create a colorbar for a ScalarMappable instance, with horizontal orientation."
},
{
"code": null,
"e": 1504,
"s": 1462,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1809,
"s": 1504,
"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nx, y, z = np.random.rand(3, 50)\nf, ax = plt.subplots()\n\npoints = ax.scatter(x, y, c=z, s=50, cmap=\"plasma\")\nf.colorbar(points, orientation=\"horizontal\")\n\nplt.show()"
}
]
|
How to fire an event on file select using jQuery ? - GeeksforGeeks | 17 Sep, 2019
Given an HTML document and the task to fire an event when a file is selected using jQuery. The JQuery change() method is used to fire an event when file is selected.
Using change() method: It is used to change the value of the input fields. This method works with “input, textarea and select” elements.
Syntax:
$(selector).change(function)
Example 1: The change() method is used to fire an event when file is selected.
<!DOCTYPE html><html> <head> <title> How to fire event on file select in jQuery? </title> <script src="https://code.jquery.com/jquery-1.12.4.min.js"> </script></head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <h3> How to fire event on file select in jQuery? </h3> <p>Click on button to select the file</p> <input type="file" id="Geeks" value="Click"> <script> $(document).ready(function() { $('input[type="file"]').change(function() { alert("A file has been selected."); }); }); </script></body> </html>
Output:
Example 2: The change() method is used to fire an event when file is selected.
<!DOCTYPE html><html> <head> <title> How to fire event on file select in jQuery? </title> <script src="https://code.jquery.com/jquery-1.12.4.min.js"> </script></head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <h3>How to fire event on file select in jQuery?</h3> <p>Click on button to select the file</p> <input type="file" id="Geeks" value="Click"> <h4></h4> <script> $(document).ready(function(){ $('input[type="file"]').change(function(){ $("h4").text("File is added!"); }); }); </script></body> </html>
Output:
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Form validation using jQuery
How to Dynamically Add/Remove Table Rows using jQuery ?
How to Show and Hide div elements using radio buttons?
Scroll to the top of the page using JavaScript/jQuery
jQuery | children() with Examples
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 26044,
"s": 26016,
"text": "\n17 Sep, 2019"
},
{
"code": null,
"e": 26210,
"s": 26044,
"text": "Given an HTML document and the task to fire an event when a file is selected using jQuery. The JQuery change() method is used to fire an event when file is selected."
},
{
"code": null,
"e": 26347,
"s": 26210,
"text": "Using change() method: It is used to change the value of the input fields. This method works with “input, textarea and select” elements."
},
{
"code": null,
"e": 26355,
"s": 26347,
"text": "Syntax:"
},
{
"code": null,
"e": 26384,
"s": 26355,
"text": "$(selector).change(function)"
},
{
"code": null,
"e": 26463,
"s": 26384,
"text": "Example 1: The change() method is used to fire an event when file is selected."
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to fire event on file select in jQuery? </title> <script src=\"https://code.jquery.com/jquery-1.12.4.min.js\"> </script></head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <h3> How to fire event on file select in jQuery? </h3> <p>Click on button to select the file</p> <input type=\"file\" id=\"Geeks\" value=\"Click\"> <script> $(document).ready(function() { $('input[type=\"file\"]').change(function() { alert(\"A file has been selected.\"); }); }); </script></body> </html>",
"e": 27174,
"s": 26463,
"text": null
},
{
"code": null,
"e": 27182,
"s": 27174,
"text": "Output:"
},
{
"code": null,
"e": 27261,
"s": 27182,
"text": "Example 2: The change() method is used to fire an event when file is selected."
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to fire event on file select in jQuery? </title> <script src=\"https://code.jquery.com/jquery-1.12.4.min.js\"> </script></head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <h3>How to fire event on file select in jQuery?</h3> <p>Click on button to select the file</p> <input type=\"file\" id=\"Geeks\" value=\"Click\"> <h4></h4> <script> $(document).ready(function(){ $('input[type=\"file\"]').change(function(){ $(\"h4\").text(\"File is added!\"); }); }); </script></body> </html>",
"e": 27966,
"s": 27261,
"text": null
},
{
"code": null,
"e": 27974,
"s": 27966,
"text": "Output:"
},
{
"code": null,
"e": 27981,
"s": 27974,
"text": "JQuery"
},
{
"code": null,
"e": 27998,
"s": 27981,
"text": "Web Technologies"
},
{
"code": null,
"e": 28096,
"s": 27998,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28125,
"s": 28096,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 28181,
"s": 28125,
"text": "How to Dynamically Add/Remove Table Rows using jQuery ?"
},
{
"code": null,
"e": 28236,
"s": 28181,
"text": "How to Show and Hide div elements using radio buttons?"
},
{
"code": null,
"e": 28290,
"s": 28236,
"text": "Scroll to the top of the page using JavaScript/jQuery"
},
{
"code": null,
"e": 28324,
"s": 28290,
"text": "jQuery | children() with Examples"
},
{
"code": null,
"e": 28364,
"s": 28324,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28397,
"s": 28364,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28442,
"s": 28397,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28485,
"s": 28442,
"text": "How to fetch data from an API in ReactJS ?"
}
]
|
How to add a border around a NumPy array? - GeeksforGeeks | 01 Oct, 2020
Sometimes we need to add a border around a NumPy matrix. Numpy provides a function known as ‘numpy.pad()’ to construct the border. The below examples show how to construct a border of ‘0’ around the identity matrix.
Syntax :
numpy.pad(array, pad_width, mode='constant', **kwargs)
Example 1: Construct a border of 0s around 2D identity matrix
Python3
# importing Numpy packageimport numpy as np # Creating a 2X2 Numpy matrixarray = np.ones((2, 2)) print("Original array")print(array) print("\n0 on the border and 1 inside the array") # constructing border of 0 around 2D identity matrix# using np.pad()array = np.pad(array, pad_width=1, mode='constant', constant_values=0) print(array)
Output:
In the above examples, we construct a border of 0s around the 2-D NumPy matrix.
Example 2: Construct a border of 0s around 3D identity matrix
Python3
# importing Numpy packageimport numpy as np # Creating a 3X3 Numpy matrixarray = np.ones((3, 3)) print("Original array")print(array) print("\n0 on the border and 1 inside the array") # constructing border of 0 around 3D identity matrix# using np.pad()array = np.pad(array, pad_width=1, mode='constant', constant_values=0) print(array)
Output:
In the above examples, we construct a border of 0s around the 3-D NumPy matrix.
Example 3: Construct a border of 0s around 4D identity matrix
Python3
# importing Numpy packageimport numpy as np # Creating a 4X4 Numpy matrixarray = np.ones((4, 4)) print("Original array")print(array) print("\n0 on the border and 1 inside the array") # constructing border of 0 around 4D identity matrix# using np.pad()array = np.pad(array, pad_width=1, mode='constant', constant_values=0) print(array)
Output:
In the above examples, we construct a border of 0s around the 4-D NumPy matrix.
Python numpy-arrayManipulation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Python | Get unique values from a list
Python | Pandas dataframe.groupby()
Defaultdict in Python | [
{
"code": null,
"e": 25555,
"s": 25527,
"text": "\n01 Oct, 2020"
},
{
"code": null,
"e": 25771,
"s": 25555,
"text": "Sometimes we need to add a border around a NumPy matrix. Numpy provides a function known as ‘numpy.pad()’ to construct the border. The below examples show how to construct a border of ‘0’ around the identity matrix."
},
{
"code": null,
"e": 25780,
"s": 25771,
"text": "Syntax :"
},
{
"code": null,
"e": 25838,
"s": 25780,
"text": "numpy.pad(array, pad_width, mode='constant', **kwargs) \n"
},
{
"code": null,
"e": 25900,
"s": 25838,
"text": "Example 1: Construct a border of 0s around 2D identity matrix"
},
{
"code": null,
"e": 25908,
"s": 25900,
"text": "Python3"
},
{
"code": "# importing Numpy packageimport numpy as np # Creating a 2X2 Numpy matrixarray = np.ones((2, 2)) print(\"Original array\")print(array) print(\"\\n0 on the border and 1 inside the array\") # constructing border of 0 around 2D identity matrix# using np.pad()array = np.pad(array, pad_width=1, mode='constant', constant_values=0) print(array)",
"e": 26262,
"s": 25908,
"text": null
},
{
"code": null,
"e": 26270,
"s": 26262,
"text": "Output:"
},
{
"code": null,
"e": 26350,
"s": 26270,
"text": "In the above examples, we construct a border of 0s around the 2-D NumPy matrix."
},
{
"code": null,
"e": 26412,
"s": 26350,
"text": "Example 2: Construct a border of 0s around 3D identity matrix"
},
{
"code": null,
"e": 26420,
"s": 26412,
"text": "Python3"
},
{
"code": "# importing Numpy packageimport numpy as np # Creating a 3X3 Numpy matrixarray = np.ones((3, 3)) print(\"Original array\")print(array) print(\"\\n0 on the border and 1 inside the array\") # constructing border of 0 around 3D identity matrix# using np.pad()array = np.pad(array, pad_width=1, mode='constant', constant_values=0) print(array)",
"e": 26774,
"s": 26420,
"text": null
},
{
"code": null,
"e": 26782,
"s": 26774,
"text": "Output:"
},
{
"code": null,
"e": 26862,
"s": 26782,
"text": "In the above examples, we construct a border of 0s around the 3-D NumPy matrix."
},
{
"code": null,
"e": 26924,
"s": 26862,
"text": "Example 3: Construct a border of 0s around 4D identity matrix"
},
{
"code": null,
"e": 26932,
"s": 26924,
"text": "Python3"
},
{
"code": "# importing Numpy packageimport numpy as np # Creating a 4X4 Numpy matrixarray = np.ones((4, 4)) print(\"Original array\")print(array) print(\"\\n0 on the border and 1 inside the array\") # constructing border of 0 around 4D identity matrix# using np.pad()array = np.pad(array, pad_width=1, mode='constant', constant_values=0) print(array)",
"e": 27286,
"s": 26932,
"text": null
},
{
"code": null,
"e": 27294,
"s": 27286,
"text": "Output:"
},
{
"code": null,
"e": 27374,
"s": 27294,
"text": "In the above examples, we construct a border of 0s around the 4-D NumPy matrix."
},
{
"code": null,
"e": 27405,
"s": 27374,
"text": "Python numpy-arrayManipulation"
},
{
"code": null,
"e": 27418,
"s": 27405,
"text": "Python-numpy"
},
{
"code": null,
"e": 27425,
"s": 27418,
"text": "Python"
},
{
"code": null,
"e": 27523,
"s": 27425,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27555,
"s": 27523,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27597,
"s": 27555,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27639,
"s": 27597,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27695,
"s": 27639,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27722,
"s": 27695,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27753,
"s": 27722,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27782,
"s": 27753,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 27821,
"s": 27782,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27857,
"s": 27821,
"text": "Python | Pandas dataframe.groupby()"
}
]
|
How to implement an Interface using an Enum in Java | 21 Jun, 2020
Enumerations serve the purpose of representing a group of named constants in a programming language. For example, the 4 suits in a deck of playing cards may be 4 enumerators named Club, Diamond, Heart, and Spade, belonging to an enumerated type named Suit. We have already discussed the basics of enum, how its declared in the previous article. In this article, we will understand how an enum implements an interface.
We primarily use enums when a method parameter can only take the value out of a small set of possible values means the input values are fixed and it takes from that fixed set of values. Java enum type is a special kind of java class which can contain constants and methods like normal java classes where the values are the only possible instances of this class. This enum extends the abstract class java.lang.Enum. Consider a situation when we have to implement some business logic which is tightly coupled with a discriminatory property of a given object or class at that time we implement an interface with enum. Think about a case where we need to merge the values of two enums into one group and treat them similarly, there Enum implements the interface.
Since an enum is implicitly extending the abstract class java.lang.Enum, it can not extend any other class or enum and also any class can not extend enum. So it’s clear that enum can not extend or can not be extended. But when there is a need to achieve multiple inheritance enum can implement any interface and in java, it is possible that an enum can implement an interface. Therefore, in order to achieve extensibility, the following steps are followed:
Create an interface.After creating an interface, implement that interface by Enum.
Create an interface.
After creating an interface, implement that interface by Enum.
The following is the code which demonstrates the implementation of an interface in an enum:
// Java program to demonstrate// how an enum implements an// interface // Defining an interfaceinterface week { // Defining an abstract method public int day();} // Initializing an enum which// implements the above interfaceenum Day implements week { // Initializing the possible // days Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday; public int day() { return ordinal() + 1; }} // Main Classpublic class Daycount { public static void main(String args[]) { System.out.println("It is day number " + Day.Wednesday.day() + " of a week."); }}
It is day number 3 of a week.
Java-Enumeration
java-interfaces
How To
Java
Write From Home
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java Tutorial
How to filter object array based on attributes?
How to Align Text in HTML?
How to Install FFmpeg on Windows?
How to Set Git Username and Password in GitBash?
Arrays.sort() in Java with examples
Reverse a string in Java
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Jun, 2020"
},
{
"code": null,
"e": 446,
"s": 28,
"text": "Enumerations serve the purpose of representing a group of named constants in a programming language. For example, the 4 suits in a deck of playing cards may be 4 enumerators named Club, Diamond, Heart, and Spade, belonging to an enumerated type named Suit. We have already discussed the basics of enum, how its declared in the previous article. In this article, we will understand how an enum implements an interface."
},
{
"code": null,
"e": 1205,
"s": 446,
"text": "We primarily use enums when a method parameter can only take the value out of a small set of possible values means the input values are fixed and it takes from that fixed set of values. Java enum type is a special kind of java class which can contain constants and methods like normal java classes where the values are the only possible instances of this class. This enum extends the abstract class java.lang.Enum. Consider a situation when we have to implement some business logic which is tightly coupled with a discriminatory property of a given object or class at that time we implement an interface with enum. Think about a case where we need to merge the values of two enums into one group and treat them similarly, there Enum implements the interface."
},
{
"code": null,
"e": 1662,
"s": 1205,
"text": "Since an enum is implicitly extending the abstract class java.lang.Enum, it can not extend any other class or enum and also any class can not extend enum. So it’s clear that enum can not extend or can not be extended. But when there is a need to achieve multiple inheritance enum can implement any interface and in java, it is possible that an enum can implement an interface. Therefore, in order to achieve extensibility, the following steps are followed:"
},
{
"code": null,
"e": 1745,
"s": 1662,
"text": "Create an interface.After creating an interface, implement that interface by Enum."
},
{
"code": null,
"e": 1766,
"s": 1745,
"text": "Create an interface."
},
{
"code": null,
"e": 1829,
"s": 1766,
"text": "After creating an interface, implement that interface by Enum."
},
{
"code": null,
"e": 1921,
"s": 1829,
"text": "The following is the code which demonstrates the implementation of an interface in an enum:"
},
{
"code": "// Java program to demonstrate// how an enum implements an// interface // Defining an interfaceinterface week { // Defining an abstract method public int day();} // Initializing an enum which// implements the above interfaceenum Day implements week { // Initializing the possible // days Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday; public int day() { return ordinal() + 1; }} // Main Classpublic class Daycount { public static void main(String args[]) { System.out.println(\"It is day number \" + Day.Wednesday.day() + \" of a week.\"); }}",
"e": 2603,
"s": 1921,
"text": null
},
{
"code": null,
"e": 2634,
"s": 2603,
"text": "It is day number 3 of a week.\n"
},
{
"code": null,
"e": 2651,
"s": 2634,
"text": "Java-Enumeration"
},
{
"code": null,
"e": 2667,
"s": 2651,
"text": "java-interfaces"
},
{
"code": null,
"e": 2674,
"s": 2667,
"text": "How To"
},
{
"code": null,
"e": 2679,
"s": 2674,
"text": "Java"
},
{
"code": null,
"e": 2695,
"s": 2679,
"text": "Write From Home"
},
{
"code": null,
"e": 2700,
"s": 2695,
"text": "Java"
},
{
"code": null,
"e": 2798,
"s": 2700,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2812,
"s": 2798,
"text": "Java Tutorial"
},
{
"code": null,
"e": 2860,
"s": 2812,
"text": "How to filter object array based on attributes?"
},
{
"code": null,
"e": 2887,
"s": 2860,
"text": "How to Align Text in HTML?"
},
{
"code": null,
"e": 2921,
"s": 2887,
"text": "How to Install FFmpeg on Windows?"
},
{
"code": null,
"e": 2970,
"s": 2921,
"text": "How to Set Git Username and Password in GitBash?"
},
{
"code": null,
"e": 3006,
"s": 2970,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 3031,
"s": 3006,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 3082,
"s": 3031,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 3113,
"s": 3082,
"text": "How to iterate any Map in Java"
}
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.