title stringlengths 3 221 | text stringlengths 17 477k | parsed listlengths 0 3.17k |
|---|---|---|
BeautifulSoup – Scraping List from HTML | 19 Oct, 2021
Prerequisite:
Requests
BeautifulSoup
Python can be employed to scrap information from a web page. It can also be used to retrieve data provided within a specific tag, this article how list elements can be scraped from HTML.
Module Needed:
bs4: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. This module does not come built-in with Python. To install this type the below command in the terminal.
pip install bs4
requests: Requests allows you to send HTTP/1.1 requests extremely easily. This module also does not come built-in with Python. To install this type the below command in the terminal.
pip install requests
Approach:
Import module
Get HTML Code using requests module
Find all list tag using find_all() method.
Iterate through all list tag and get text using text property
Example 1: Scraping List from HTML Code
Python3
# Import Required Modulesfrom bs4 import BeautifulSoupimport requests # HTML Codehtml_content = """<ul> <li>Coffee</li> <li>Tea</li> <li>Milk</li></ul>""" # Parse the html contentsoup = BeautifulSoup(html_content, "lxml") # Find all li tagdatas = soup.find_all("li") # Iterate through all li tagsfor data in datas: # Get text from each tag print(data.text) print(f"Total {len(datas)} li tag found")
Output:
Coffee
Tea
Milk
Total 3 li tag found
Example 2: Scraping List from Web URL
Python3
# Import Required Modulesfrom bs4 import BeautifulSoupimport requests # HTML Codehtml_content = """<ul> <li>Coffee</li> <li>Tea</li> <li>Milk</li></ul>""" # Parse the html contentsoup = BeautifulSoup(html_content, "lxml") # Find all li tagdatas = soup.find_all("li") # Iterate through all li tagsfor data in datas: # Get text from each tag print(data.text) print(f"Total {len(datas)} li tag found")
Output:
adnanirshad158
Picked
Python BeautifulSoup
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Oct, 2021"
},
{
"code": null,
"e": 43,
"s": 28,
"text": "Prerequisite: "
},
{
"code": null,
"e": 52,
"s": 43,
"text": "Requests"
},
{
"code": null,
"e": 66,
"s": 52,
"text": "BeautifulSoup"
}... |
Vector of sets in C++ | 03 Aug, 2021
Prerequisite: Vectors in C++ STL
Vectors are known as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container automatically.
Sets are a type of associative containers in which each element has to be unique because the value of the element identifies it. The value of the element cannot be modified once it is added to the set, though it is possible to remove and add the modified value of that element.
Vector of sets can be used to design complex and efficient data structures, in this article we are going to check one such instance where Vector of sets could be very useful.
Syntax:
vector<set<datatype>> v ;
Insertion in Vector of Sets
Elements can be inserted into a vector using the push_back() function of C++ STL. First insert elements into a set using insert(). Then insert that set into the vector using push_back().
Below example demonstrates the insertion operation in a vector of sets:
C++
// C++ program to demonstrate the// insertion into a vector of sets#include <bits/stdc++.h>using namespace std; // Defining the number of sets// in the vector and number of// elements in each set#define ROW 4#define COL 5 // Driver Codeint main(){ // Initialize vector of sets vector<set<int> > v; // Elements to insert // in column int num = 10; // Inserting elements // into vector for (int i = 0; i < ROW; i++) { // Stores the column elements set<int> s; for (int j = 0; j < COL; j++) { s.insert(num); num += 5; } // Push the set in the vector v.push_back(s); } // Display the vector of sets for (int i = 0; i < v.size(); i++) { for (auto x : v[i]) cout << x << " "; cout << endl; } return 0;}
10 15 20 25 30
35 40 45 50 55
60 65 70 75 80
85 90 95 100 105
Removal or Deletion in a Vector of Sets
Sets can be removed from the end of a vector of sets using the pop_back() function of C++ STL.Below example demonstrates the removal of sets from the end of a vector of sets:C++C++// C++ program to demonstrate// the removal of sets from// the end of vector of sets#include <bits/stdc++.h>using namespace std; // Defining the number of sets// in the vector and number of// elements in each set#define ROW 4#define COL 5 // Driver Codeint main(){ // Initialize the // vector of sets vector<set<int> > v; // Elements to insert // in column int num = 10; // Inserting elements // into vector for (int i = 0; i < ROW; i++) { // Vector to store // column elements set<int> s; for (int j = 0; j < COL; j++) { s.insert(num); num += 5; } // Push the set // into the vector v.push_back(s); } // Display the vector of sets // before removal of sets cout << "Before Removal:" << endl; for (int i = 0; i < v.size(); i++) { for (auto x : v[i]) cout << x << " "; cout << endl; } // Remove sets from last // index of the vector v.pop_back(); v.pop_back(); // Display the vector of sets // after removal of sets cout << endl << "After Removal:" << endl; for (int i = 0; i < v.size(); i++) { for (auto x : v[i]) cout << x << " "; cout << endl; } return 0;}Output:Before Removal:
10 15 20 25 30
35 40 45 50 55
60 65 70 75 80
85 90 95 100 105
After Removal:
10 15 20 25 30
35 40 45 50 55
The value of the element cannot be modified once it is added to the set, though it is possible to remove the value of that element. erase() function is used to remove a particular element from a particular set of a vector of sets.Below example demonstrates the removal of a given set element from a particular set of a vector of sets:C++C++// C++ program to demonstrate// the removal of sets from// the end of vector of sets#include <bits/stdc++.h>using namespace std; // Defining the number of sets// in the vector and number of// elements in each set#define ROW 4#define COL 5 // Driver Codeint main(){ // Initialize vector of sets vector<set<int> > v; // Elements to insert // in column int num = 10; // Inserting elements // into vector for (int i = 0; i < ROW; i++) { // Vector to store // column elements set<int> s; for (int j = 0; j < COL; j++) { s.insert(num); num += 5; } // Push the set // into the vector v.push_back(s); } // Display the vector of sets // before removal of sets cout << "Before Removal:" << endl; for (int i = 0; i < v.size(); i++) { for (auto x : v[i]) cout << x << " "; cout << endl; } // Erase 70 from 3rd set v[2].erase(70); // Erase 55 from 2nd set v[1].erase(55); // Display the vector of sets // after removal of sets cout << endl << "After Removal:" << endl; for (int i = 0; i < v.size(); i++) { for (auto x : v[i]) cout << x << " "; cout << endl; } return 0;}Output:Before Removal:
10 15 20 25 30
35 40 45 50 55
60 65 70 75 80
85 90 95 100 105
After Removal:
10 15 20 25 30
35 40 45 50
60 65 75 80
85 90 95 100 105
Sets can be removed from the end of a vector of sets using the pop_back() function of C++ STL.Below example demonstrates the removal of sets from the end of a vector of sets:C++C++// C++ program to demonstrate// the removal of sets from// the end of vector of sets#include <bits/stdc++.h>using namespace std; // Defining the number of sets// in the vector and number of// elements in each set#define ROW 4#define COL 5 // Driver Codeint main(){ // Initialize the // vector of sets vector<set<int> > v; // Elements to insert // in column int num = 10; // Inserting elements // into vector for (int i = 0; i < ROW; i++) { // Vector to store // column elements set<int> s; for (int j = 0; j < COL; j++) { s.insert(num); num += 5; } // Push the set // into the vector v.push_back(s); } // Display the vector of sets // before removal of sets cout << "Before Removal:" << endl; for (int i = 0; i < v.size(); i++) { for (auto x : v[i]) cout << x << " "; cout << endl; } // Remove sets from last // index of the vector v.pop_back(); v.pop_back(); // Display the vector of sets // after removal of sets cout << endl << "After Removal:" << endl; for (int i = 0; i < v.size(); i++) { for (auto x : v[i]) cout << x << " "; cout << endl; } return 0;}Output:Before Removal:
10 15 20 25 30
35 40 45 50 55
60 65 70 75 80
85 90 95 100 105
After Removal:
10 15 20 25 30
35 40 45 50 55
Sets can be removed from the end of a vector of sets using the pop_back() function of C++ STL.
Below example demonstrates the removal of sets from the end of a vector of sets:
C++
// C++ program to demonstrate// the removal of sets from// the end of vector of sets#include <bits/stdc++.h>using namespace std; // Defining the number of sets// in the vector and number of// elements in each set#define ROW 4#define COL 5 // Driver Codeint main(){ // Initialize the // vector of sets vector<set<int> > v; // Elements to insert // in column int num = 10; // Inserting elements // into vector for (int i = 0; i < ROW; i++) { // Vector to store // column elements set<int> s; for (int j = 0; j < COL; j++) { s.insert(num); num += 5; } // Push the set // into the vector v.push_back(s); } // Display the vector of sets // before removal of sets cout << "Before Removal:" << endl; for (int i = 0; i < v.size(); i++) { for (auto x : v[i]) cout << x << " "; cout << endl; } // Remove sets from last // index of the vector v.pop_back(); v.pop_back(); // Display the vector of sets // after removal of sets cout << endl << "After Removal:" << endl; for (int i = 0; i < v.size(); i++) { for (auto x : v[i]) cout << x << " "; cout << endl; } return 0;}
Before Removal:
10 15 20 25 30
35 40 45 50 55
60 65 70 75 80
85 90 95 100 105
After Removal:
10 15 20 25 30
35 40 45 50 55
The value of the element cannot be modified once it is added to the set, though it is possible to remove the value of that element. erase() function is used to remove a particular element from a particular set of a vector of sets.Below example demonstrates the removal of a given set element from a particular set of a vector of sets:C++C++// C++ program to demonstrate// the removal of sets from// the end of vector of sets#include <bits/stdc++.h>using namespace std; // Defining the number of sets// in the vector and number of// elements in each set#define ROW 4#define COL 5 // Driver Codeint main(){ // Initialize vector of sets vector<set<int> > v; // Elements to insert // in column int num = 10; // Inserting elements // into vector for (int i = 0; i < ROW; i++) { // Vector to store // column elements set<int> s; for (int j = 0; j < COL; j++) { s.insert(num); num += 5; } // Push the set // into the vector v.push_back(s); } // Display the vector of sets // before removal of sets cout << "Before Removal:" << endl; for (int i = 0; i < v.size(); i++) { for (auto x : v[i]) cout << x << " "; cout << endl; } // Erase 70 from 3rd set v[2].erase(70); // Erase 55 from 2nd set v[1].erase(55); // Display the vector of sets // after removal of sets cout << endl << "After Removal:" << endl; for (int i = 0; i < v.size(); i++) { for (auto x : v[i]) cout << x << " "; cout << endl; } return 0;}Output:Before Removal:
10 15 20 25 30
35 40 45 50 55
60 65 70 75 80
85 90 95 100 105
After Removal:
10 15 20 25 30
35 40 45 50
60 65 75 80
85 90 95 100 105
The value of the element cannot be modified once it is added to the set, though it is possible to remove the value of that element. erase() function is used to remove a particular element from a particular set of a vector of sets.
Below example demonstrates the removal of a given set element from a particular set of a vector of sets:
C++
// C++ program to demonstrate// the removal of sets from// the end of vector of sets#include <bits/stdc++.h>using namespace std; // Defining the number of sets// in the vector and number of// elements in each set#define ROW 4#define COL 5 // Driver Codeint main(){ // Initialize vector of sets vector<set<int> > v; // Elements to insert // in column int num = 10; // Inserting elements // into vector for (int i = 0; i < ROW; i++) { // Vector to store // column elements set<int> s; for (int j = 0; j < COL; j++) { s.insert(num); num += 5; } // Push the set // into the vector v.push_back(s); } // Display the vector of sets // before removal of sets cout << "Before Removal:" << endl; for (int i = 0; i < v.size(); i++) { for (auto x : v[i]) cout << x << " "; cout << endl; } // Erase 70 from 3rd set v[2].erase(70); // Erase 55 from 2nd set v[1].erase(55); // Display the vector of sets // after removal of sets cout << endl << "After Removal:" << endl; for (int i = 0; i < v.size(); i++) { for (auto x : v[i]) cout << x << " "; cout << endl; } return 0;}
Before Removal:
10 15 20 25 30
35 40 45 50 55
60 65 70 75 80
85 90 95 100 105
After Removal:
10 15 20 25 30
35 40 45 50
60 65 75 80
85 90 95 100 105
The following example demonstrates the use of vector of sets:
Given a string S, the task is to separate the given string S into three different set of characters i.e., vowel, consonants, or a special character.
Below is the implementation of the above problem:
C++
// C++ program to implement vector of sets#include <bits/stdc++.h>using namespace std; // Function to print set// of different charactersvoid separateChar(string s){ // Vector of set vector<set<char> > v(3); // Insert data in vector of set for (int i = 0; i < s.length(); i++) { if (s[i] >= 'a' && s[i] <= 'z') { // Insert vowels if (s[i] == 'a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'o' || s[i] == 'u') v[0].insert(s[i]); // Insert consonants else v[1].insert(s[i]); } // Insert special characters else v[2].insert(s[i]); } // Iterate over all the sets for (int i = 0; i < 3; i++) { cout << "Elements of set " << i + 1 << " :"; // Print elements of each set for (auto it : v[i]) { cout << it << " "; } cout << endl; }} // Driver Codeint main(){ string s = "geeks@for&geeks@"; // Function Call separateChar(s);}
Elements of set 1 :e o
Elements of set 2 :f g k r s
Elements of set 3 :& @
sagar0719kumar
cpp-set
cpp-vector
STL
C++ Programs
Data Structures
Data Structures
STL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Passing a function as a parameter in C++
Const keyword in C++
Program to implement Singly Linked List in C++ using class
cout in C++
Different ways to print elements of vector
DSA Sheet by Love Babbar
SDE SHEET - A Complete Guide for SDE Preparation
Top 50 Array Coding Problems for Interviews
Introduction to Data Structures
Doubly Linked List | Set 1 (Introduction and Insertion) | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n03 Aug, 2021"
},
{
"code": null,
"e": 86,
"s": 53,
"text": "Prerequisite: Vectors in C++ STL"
},
{
"code": null,
"e": 293,
"s": 86,
"text": "Vectors are known as dynamic arrays with the ability to resize themselves ... |
How to Calculate Moving Averages in Python? | 28 Nov, 2021
In this article, we are going to see how to calculate the moving Average in Python. Moving average refers to a series of averages of fixed size subsets of the total set of observations. It is also known as rolling average, running average, rolling means or running average.
Consider the set of n observations and k be the size of the window for determining the average at any time t. Then moving average list is calculated by initially taking the average of the first k observations present in the current window and storing it in the list. Now, the window is expanded according to the condition of the moving average to be determined and again average of the elements present in the window is calculated and stored in the list. This process is continued until the window has reached the end of the set.
For example: Given a list of five integers arr=[1, 2, 3, 7, 9] and we need to calculate moving averages of the list with window size specified as 3. We will first calculate average of first 3 elements and that will be stored as first moving average. Then window will be shifted one position to the right and again average of elements present in the window will be calculated and stored in the list. Similarly, the process will repeat till the window reaches the last element of the array. Following is the illustration of the above approach:
Below is the implementation:
Python3
# Program to calculate moving averagearr = [1, 2, 3, 7, 9]window_size = 3 i = 0# Initialize an empty list to store moving averagesmoving_averages = [] # Loop through the array to consider# every window of size 3while i < len(arr) - window_size + 1: # Store elements from i to i+window_size # in list to get the current window window = arr[i : i + window_size] # Calculate the average of current window window_average = round(sum(window) / window_size, 2) # Store the average of current # window in moving average list moving_averages.append(window_average) # Shift window to right by one position i += 1 print(moving_averages)
Output:
[2.0, 4.0, 6.33]
SMA is calculated by taking the unweighted mean of k (size of the window) observations at a time that is present in the current window. It is used for analyzing trends.
Formulae:
where,
SMAj = Simple Moving Average of jth window
k = size of the window
ai = ith element of the set of observations
Numpy module of Python provides an easy way to calculate the simple moving average of the array of observations. It provides a method called numpy.sum() which returns the sum of elements of the given array. A moving average can be calculated by finding the sum of elements present in the window and dividing it with window size.
Python3
# Program to calculate moving average using numpy import numpy as np arr = [1, 2, 3, 7, 9]window_size = 3 i = 0# Initialize an empty list to store moving averagesmoving_averages = [] # Loop through the array t o#consider every window of size 3while i < len(arr) - window_size + 1: # Calculate the average of current window window_average = round(np.sum(arr[ i:i+window_size]) / window_size, 2) # Store the average of current # window in moving average list moving_averages.append(window_average) # Shift window to right by one position i += 1 print(moving_averages)
Output:
[2.0, 4.0, 6.33]
Pandas module of Python provides an easy way to calculate the simple moving average of the series of observations. It provides a method called pandas.Series.rolling(window_size) which returns a rolling window of specified size. The mean of the window can be calculated by using pandas.Series.mean() function on the object of window obtained above. pandas.Series.rolling(window_size) will return some null series since it need at least k (size of window) elements to be rolling.
Python
# Python program to calculate# simple moving averages using pandasimport pandas as pd arr = [1, 2, 3, 7, 9]window_size = 3 # Convert array of integers to pandas seriesnumbers_series = pd.Series(arr) # Get the window of series# of observations of specified window sizewindows = numbers_series.rolling(window_size) # Create a series of moving# averages of each windowmoving_averages = windows.mean() # Convert pandas series back to listmoving_averages_list = moving_averages.tolist() # Remove null entries from the listfinal_list = moving_averages_list[window_size - 1:] print(final_list)
Output:
[2.0, 4.0, 6.33]
CMA is calculated by taking the unweighted mean of all the observations up to the time of calculation. It is used for time series analysis.
Formulae:
where:
CMAt = Cumulative Moving Average at time t
kt = number of observations upto time t
ai = ith element of the set of observations
Numpy module of Python provides an easy way to calculate the cumulative moving average of the array of observations. It provides a method called numpy.cumsum() which returns the array of the cumulative sum of elements of the given array. A moving average can be calculated by dividing the cumulative sum of elements by window size.
Python
# Program to calculate cumulative moving average# using numpy import numpy as np arr = [1, 2, 3, 7, 9] i = 1# Initialize an empty list to store cumulative moving# averagesmoving_averages = [] # Store cumulative sums of array in cum_sum arraycum_sum = np.cumsum(arr); # Loop through the array elementswhile i <= len(arr): # Calculate the cumulative average by dividing # cumulative sum by number of elements till # that position window_average = round(cum_sum[i-1] / i, 2) # Store the cumulative average of # current window in moving average list moving_averages.append(window_average) # Shift window to right by one position i += 1 print(moving_averages)
Output:
[1.0, 1.5, 2.0, 3.25, 4.4]
Pandas module of Python provides an easy way to calculate the cumulative moving average of the series of observations. It provides a method called pandas.Series.expanding() which returns a window spanning over all the observations up to time t. Mean of the window can be calculated by using pandas.Series.mean() function on the object of window obtained above.
Python
# Python program to calculate# cumulative moving averages using pandasimport pandas as pd arr = [1, 2, 3, 7, 9]window_size = 3 # Convert array of integers to pandas seriesnumbers_series = pd.Series(arr) # Get the window of series of# observations till the current timewindows = numbers_series.expanding() # Create a series of moving averages of each windowmoving_averages = windows.mean() # Convert pandas series back to listmoving_averages_list = moving_averages.tolist() print(moving_averages_list)
Output:
[1.0, 1.5, 2.0, 3.25, 4.4]
EMA is calculated by taking the weighted mean of the observations at a time. The weight of the observation exponentially decreases with time. It is used for analyzing recent changes.
Formulae:
where:
EMAt = Exponential Moving Average at time t
α = degree of decrease in weight of observation with time
at = observation at time t
Python
# Program to calculate exponential# moving average using formula import numpy as np arr = [1, 2, 3, 7, 9]x=0.5 # smoothening factor i = 1# Initialize an empty list to# store exponential moving averagesmoving_averages = [] # Insert first exponential average in the listmoving_averages.append(arr[0]) # Loop through the array elementswhile i < len(arr): # Calculate the exponential # average by using the formula window_average = round((x*arr[i])+ (1-x)*moving_averages[-1], 2) # Store the cumulative average # of current window in moving average list moving_averages.append(window_average) # Shift window to right by one position i += 1 print(moving_averages)
Output:
[1, 1.5, 2.25, 4.62, 6.81]
Pandas module of Python provides an easy way to calculate the exponential moving average of the series of observations. It provides a method called pandas.Series.ewm.mean() calculates the exponential moving average of given observations. pandas.Series.ewm() takes a parameter called smoothening factor i.e. degree with which weight of observation decrease with time. The value of a smoothening factor is always between 0 and 1.
Python
# Python program to# calculate exponential moving averagesimport pandas as pd arr = [1, 2, 3, 7, 9] # Convert array of integers to pandas seriesnumbers_series = pd.Series(arr) # Get the moving averages of series# of observations till the current timemoving_averages = round(numbers_series.ewm( alpha=0.5, adjust=False).mean(), 2) # Convert pandas series back to listmoving_averages_list = moving_averages.tolist() print(moving_averages_list)
Output:
[1.0, 1.5, 2.25, 4.62, 6.81]
Time-Series Analysis: It is used to smooth out short-term variation and highlight long-term observations such as trends and cycles.Financial Analysis: It is used in financial analysis of stock markets like calculation of stock prices, returns, and analyzing trends of the market.Environmental Engineering: It is used in analyzing environmental conditions by considering various factors such as the concentration of pollutants, etc.Computer Performance Analysis: It is used in analyzing computer performance by calculating metrics such as average CPU utilization, average process queue length, etc.
Time-Series Analysis: It is used to smooth out short-term variation and highlight long-term observations such as trends and cycles.
Financial Analysis: It is used in financial analysis of stock markets like calculation of stock prices, returns, and analyzing trends of the market.
Environmental Engineering: It is used in analyzing environmental conditions by considering various factors such as the concentration of pollutants, etc.
Computer Performance Analysis: It is used in analyzing computer performance by calculating metrics such as average CPU utilization, average process queue length, etc.
Picked
Python-numpy
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Nov, 2021"
},
{
"code": null,
"e": 302,
"s": 28,
"text": "In this article, we are going to see how to calculate the moving Average in Python. Moving average refers to a series of averages of fixed size subsets of the total set of obs... |
XAML - DatePicker | A DatePicker represents a control that allows a user to pick a date value. The user picks the date by using ComboBox selection for month, day, and year values. The hierarchical inheritance of DatePicker class is as follows −
CalendarIdentifier
Gets or sets the calendar system to use.
CalendarIdentifierProperty
Gets the identifier for the CalendarIdentifier dependency property.
Date
Gets or sets the date currently set in the date picker.
DateProperty
Gets the identifier for the Date dependency property.
DayFormat
Gets or sets the display format for the day value.
DayFormatProperty
Gets the identifier for the DayFormat dependency property.
DayVisible
Gets or sets a value that indicates whether the day selector is shown.
DayVisibleProperty
Gets the identifier for the DayVisible dependency property.
Header
Gets or sets the content for the control's header.
HeaderProperty
Identifies the Header dependency property.
HeaderTemplate
Gets or sets the DataTemplate used to display the content of the control's header.
HeaderTemplateProperty
Identifies the HeaderTemplate dependency property.
MaxYear
Gets or sets the maximum Gregorian year available for picking.
MaxYearProperty
Gets the identifier for the MaxYear dependency property.
MinYear
Gets or sets the minimum Gregorian year available for picking.
MinYearProperty
Gets the identifier for the MinYear dependency property.
MonthFormat
Gets or sets the display format for the month value.
MonthFormatProperty
Gets the identifier for the MonthFormat dependency property.
MonthVisible
Gets or sets a value that indicates whether the month selector is shown.
MonthVisibleProperty
Gets the identifier for the MonthVisible dependency property.
Orientation
Gets or sets a value that indicates whether the day, month, and year selectors are stacked horizontally or vertically.
OrientationProperty
Gets the identifier for the Orientation dependency property.
YearFormat
Gets or sets the display format for the year value.
YearFormatProperty
Gets the identifier for the YearFormat dependency property.
YearVisible
Gets or sets a value that indicates whether the year selector is shown.
YearVisibleProperty
Gets the identifier for the YearVisible dependency property.
DateChanged
Occurs when the date value is changed.
DragEnter
Occurs when the input system reports an underlying drag event with this element as the target. (Inherited from UIElement)
DragLeave
Occurs when the input system reports an underlying drag event with this element as the origin. (Inherited from UIElement)
DragOver
Occurs when the input system reports an underlying drag event with this element as the potential drop target. (Inherited from UIElement)
DragStarting
Occurs when a drag operation is initiated. (Inherited from UIElement)
GotFocus
Occurs when a UIElement receives focus. (Inherited from UIElement)
Holding
Occurs when an otherwise unhandled Hold interaction occurs over the hit test area of this element. (Inherited from UIElement)
IsEnabledChanged
Occurs when the IsEnabled property changes. (Inherited from Control)
KeyDown
Occurs when a keyboard key is pressed while the UIElement has focus. (Inherited from UIElement)
KeyUp
Occurs when a keyboard key is released while the UIElement has focus. (Inherited from UIElement)
LostFocus
Occurs when a UIElement loses focus. (Inherited from UIElement)
ClearValue
Clears the local value of a dependency property. (Inherited from DependencyObject)
FindName
Retrieves an object that has the specified identifier name. (Inherited from FrameworkElement)
OnApplyTemplate
Invoked whenever application code or internal processes (such as a rebuilding layout pass) call ApplyTemplate. In simplest terms, this means the method is called just before a UI element displays in your app. Override this method to influence the default post-template logic of a class. (Inherited from FrameworkElement)
OnDragEnter
Called before the DragEnter event occurs. (Inherited from Control)
OnDragLeave
Called before the DragLeave event occurs. (Inherited from Control)
OnDragOver
Called before the DragOver event occurs. (Inherited from Control)
OnDrop
Called before the Drop event occurs. (Inherited from Control)
OnGotFocus
Called before the GotFocus event occurs. (Inherited from Control)
OnKeyDown
Called before the KeyDown event occurs. (Inherited from Control)
OnKeyUp
Called before the KeyUp event occurs. (Inherited from Control)
OnLostFocus
Called before the LostFocus event occurs. (Inherited from Control)
SetBinding
Attaches a binding to a FrameworkElement, using the provided binding object. (Inherited from FrameworkElement)
The following example shows how to create a DatePicker control. When you click on any date from the DatePicker control, the program will update the title with that date.
Here is the XAML code to create a DatePicker with some properties and a click event.
<Window x:Class = "XAMLDatePicker.MainWindow"
xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"
Title = "MainWindow" Height = "350" Width = "604">
<Grid>
<DatePicker HorizontalAlignment = "Center"
Margin = "10,10,0,0" VerticalAlignment = "Top"
SelectedDateChanged = "DatePicker_SelectedDateChanged"/>
</Grid>
</Window>
Given below is the C# implementation for DatePicker_SelectedDateChanged event.
using System;
using System.Windows;
System.Windows.Controls;
namespace XAMLDatePicker {
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window {
public MainWindow() {
InitializeComponent();
}
private void DatePicker_SelectedDateChanged(object sender, SelectionChangedEventArgs e) {
var picker = sender as DatePicker;
DateTime? date = picker.SelectedDate;
if (date == null) {
this.Title = "No date";
} else {
this.Title = date.Value.ToShortDateString();
}
}
}
}
When you compile and execute the above code, it will display the following output −
We recommend you to execute the above example code and experiment with some other properties and events. | [
{
"code": null,
"e": 2282,
"s": 2057,
"text": "A DatePicker represents a control that allows a user to pick a date value. The user picks the date by using ComboBox selection for month, day, and year values. The hierarchical inheritance of DatePicker class is as follows −"
},
{
"code": null,
... |
How to Select Specific Columns in R dataframe? | 28 Nov, 2021
In this article, we will discuss how to select specific columns from dataframe in the R programming language.
In this approach to select a specific column, the user needs to write the name of the column name in the square bracket with the name of the given data frame as per the requirement to get those specific columns needed by the user.
Syntax:
data_frame
Example:
R
# Creating DataFramegfg < - data.frame(a=c(5, 1, 1, 5, 6, 7, 5, 4, 7, 9), b=c(1, 8, 6, 8, 6, 7, 4, 1, 7, 3), c=c(7, 1, 8, 9, 4, 1, 5, 6, 3, 7), d=c(4, 6, 8, 4, 6, 4, 8, 9, 8, 7), e=c(3, 1, 6, 4, 8, 9, 7, 8, 9, 4)) # Selecting specific Columns Using Base# R by column namegfg[c('b', 'd', 'e')]
Output:
In this approach to select the specific columns, the user needs to use the square brackets with the data frame given, and. With it, the user also needs to use the index of columns inside of the square bracket where the indexing starts with 1, and as per the requirements of the user has to give the required column index to inside the brackets
Syntax:
data_frame
Example:
R
# Creating DataFramegfg < - data.frame(a=c(5, 1, 1, 5, 6, 7, 5, 4, 7, 9), b=c(1, 8, 6, 8, 6, 7, 4, 1, 7, 3), c=c(7, 1, 8, 9, 4, 1, 5, 6, 3, 7), d=c(4, 6, 8, 4, 6, 4, 8, 9, 8, 7), e=c(3, 1, 6, 4, 8, 9, 7, 8, 9, 4)) # Selecting specific Columns Using Base R # by column indexgfg[c(2, 4, 5)]
Output:
In this method of selecting specific columns by subsetting data, the user needs to do the specification of a character vector containing the names of the columns to extract, the user has to enter the vector of the characters which corresponds to the column name in the square bracket with the data frame
Syntax:
data_frame[,c(column_name_1,column_name_2,...)]
Example:
R
# Creating DataFramegfg < - data.frame(a=c(5, 1, 1, 5, 6, 7, 5, 4, 7, 9), b=c(1, 8, 6, 8, 6, 7, 4, 1, 7, 3), c=c(7, 1, 8, 9, 4, 1, 5, 6, 3, 7), d=c(4, 6, 8, 4, 6, 4, 8, 9, 8, 7), e=c(3, 1, 6, 4, 8, 9, 7, 8, 9, 4)) # Selecting specific columns by subsetting # data by column namegfg[, c('b', 'd', 'e')]
Output:
In this method of selecting specific columns by subsetting data, the user needs to do the specification of an integer vector containing the index of the columns to extract, the user has to enter the vector of the indexes which corresponds to the column index in the square bracket with the data frame
Syntax:
data_frame[,c(column_index_1,column_index_2,...)]
Example:
R
# Creating DataFramegfg < - data.frame(a=c(5, 1, 1, 5, 6, 7, 5, 4, 7, 9), b=c(1, 8, 6, 8, 6, 7, 4, 1, 7, 3), c=c(7, 1, 8, 9, 4, 1, 5, 6, 3, 7), d=c(4, 6, 8, 4, 6, 4, 8, 9, 8, 7), e=c(3, 1, 6, 4, 8, 9, 7, 8, 9, 4)) # Selecting specific columns by subsetting data# by column index:gfg[, c(2, 4, 5)]
Output:
Subset function: This function will be returning the subsets of data frames that meet conditions.
Syntax:
subset(x, subset, select, drop = FALSE, ...)
Parameters:
x: object to be subsetted.
subset: logical expression indicating elements or rows to keep: missing values are taken as false.
select: expression, indicating columns to select from a data frame.
drop: passed on to [ indexing operator.
...: further arguments to be passed to or from other methods.
Example:
R
# Creating DataFramegfg < - data.frame(a=c(5, 1, 1, 5, 6, 7, 5, 4, 7, 9), b=c(1, 8, 6, 8, 6, 7, 4, 1, 7, 3), c=c(7, 1, 8, 9, 4, 1, 5, 6, 3, 7), d=c(4, 6, 8, 4, 6, 4, 8, 9, 8, 7), e=c(3, 1, 6, 4, 8, 9, 7, 8, 9, 4)) # Selecting specific columns by Subsetting # Data with select Argument of subset Functionsubset(gfg, select=c('b', 'd', 'e'))
Output:
In this approach to select the specific columns of the given data frame, the user needs first install and import the dplyr package in the working R console of the user and then call the select function and pass the name of the required columns as the argument of this function
Syntax:
data_frame %>% select(column_name_1,column_name_2,...)
Example:
R
# Importing dplyr librarylibrary("dplyr") # Creating DataFramegfg < - data.frame(a=c(5, 1, 1, 5, 6, 7, 5, 4, 7, 9), b=c(1, 8, 6, 8, 6, 7, 4, 1, 7, 3), c=c(7, 1, 8, 9, 4, 1, 5, 6, 3, 7), d=c(4, 6, 8, 4, 6, 4, 8, 9, 8, 7), e=c(3, 1, 6, 4, 8, 9, 7, 8, 9, 4)) # Selecting specific columns using dplyr # package by column namegfg % > % select(b, d, e)
Output:
In this approach to select the specific columns of the given data frame, the user needs first install and import the dplyr package in the working R console of the user and then call the select function and pass the index of the required columns as the argument of this function
Syntax:
data_frame %>% select(column_index_1,column_index_2,...)
Example:
R
# Importing dplyr librarylibrary("dplyr") # Creating DataFramegfg < - data.frame(a=c(5, 1, 1, 5, 6, 7, 5, 4, 7, 9), b=c(1, 8, 6, 8, 6, 7, 4, 1, 7, 3), c=c(7, 1, 8, 9, 4, 1, 5, 6, 3, 7), d=c(4, 6, 8, 4, 6, 4, 8, 9, 8, 7), e=c(3, 1, 6, 4, 8, 9, 7, 8, 9, 4)) # Selecting specific columns using dplyr # package by column indexgfg % > % select(2, 4, 5)
Output:
Picked
R DataFrame-Programs
R-DataFrame
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
Merge DataFrames by Column Names in R
How to Sort a DataFrame in R ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Nov, 2021"
},
{
"code": null,
"e": 138,
"s": 28,
"text": "In this article, we will discuss how to select specific columns from dataframe in the R programming language."
},
{
"code": null,
"e": 369,
"s": 138,
"text... |
C Program for Rat in a Maze - Backtracking-2? | Rat in a maze is also one popular problem that utilizes backtracking. I
A maze is a 2D matrix in which some cells are blocked. One of the cells is the source cell, from where we have to start. And another one of them is the destination, where we have to reach. We have to find a path from the source to the destination without moving into any of the blocked cell. A picture of an unsolved maze is shown below.
And this is its solution.
To solve this puzzle, we first start with the source cell and move in a direction where the path is not blocked. If taken path makes us reach to the destination then the puzzle is solved. Else, we come back and change our direction of the path taken. We are going to implement the same logic in our code also.
Input:
maze[][] = {
{0,1,0,1,1},
{0,0,0,0,0},
{1,0,1,0,1},
{0,0,1,0,0},
{1,0,0,1,0}}
Output:
1 0 0 0 0
1 1 1 1 0
0 0 0 1 0
0 0 0 1 1
0 0 0 0 1
Firstly, we will make a matrix to represent the maze, and the elements of the matrix will be either 0 or 1. 1 will represent the blocked cell and 0 will represent the cells in which we can move. The matrix for the maze shown above is:
0 1 0 1 1
0 0 0 0 0
1 0 1 0 1
0 0 1 0 0
1 0 0 1 0
Now, we will make one more matrix of the same dimension to store the solution. Its elements will also be either 0 or 1. 1 will represent the cells in our path and rest of the cells will be 0. The matrix representing the solution is:
1 0 0 0 0
1 1 1 1 0
0 0 0 1 0
0 0 0 1 1
0 0 0 0 1
Thus, we now have our matrices. Next, we will find a path from the source cell to the destination cell and the steps we will take are:
Check for the current cell, if it is the destination cell, then the puzzle is solved.
Check for the current cell, if it is the destination cell, then the puzzle is solved.
If not, then we will try to move downward and see if we can move in the downward cell or not (to move in a cell it must be vacant and not already present in the path).
If not, then we will try to move downward and see if we can move in the downward cell or not (to move in a cell it must be vacant and not already present in the path).
If we can move there, then we will continue with the path taken to the next downward cell.
If we can move there, then we will continue with the path taken to the next downward cell.
If not, we will try to move to the rightward cell. And if it is blocked or taken, we will move upward.
If not, we will try to move to the rightward cell. And if it is blocked or taken, we will move upward.
Similarly, if we can't move up as well, we will simply move to the left cell.
Similarly, if we can't move up as well, we will simply move to the left cell.
If none of the four moves (down, right, up, or left) are possible, we will simply move back and change our current path (backtracking).
If none of the four moves (down, right, up, or left) are possible, we will simply move back and change our current path (backtracking).
Thus, the summary is that we try to move to the other cell (down, right, up, and left) from the current cell and if no movement is possible, then just come back and change the direction of the path to another cell.
printsolution → This function is just printing the solution matrix.
solvemaze → This is the actual function where we are implementing the backtracking algorithm. Firstly, we are checking of our cell is the destination cell or not if (r==SIZE-1) and (c==SIZE-1). If it is the destination cell then our puzzle is already solved. If not, then we are checking if it a valid cell to move or not. A valid cell must be in the matrix i.e., indices must between 0 to SIZE-1 r>=0 && c>=0 && r<SIZE; must not be blocked maze[r][c] == 0and must not be taken in the path solution[r][c] == 0. If it is a valid move then we are free to take it and move to the next cell. Firstly, we will try the downward cell if(solveMaze(r+1, c)). If it doesn't give us the solution then we will move to the rightward cell, and similarly to the upward and the leftward cells. If all of the cells fail to give us the solution, we will leave the cell solution[r][c] = 0 and go to some other cell.
#include <iostream>
using namespace std;
#define SIZE 5
//the maze problem
int maze[SIZE][SIZE] = {
{0,1,0,1,1},
{0,0,0,0,0},
{1,0,1,0,1},
{0,0,1,0,0},
{1,0,0,1,0}
};
//matrix to store the solution
int solution[SIZE][SIZE];
//function to print the solution matrix
void printsolution() {
int i,j;
for(i=0;i<SIZE;i++) {
for(j=0;j<SIZE;j++) {
printf("%d\t",solution[i][j]);
}
printf("\n\n");
}
}
//function to solve the maze
//using backtracking
int solvemaze(int r, int c) {
//if destination is reached, maze is solved
//destination is the last cell(maze[SIZE-1][SIZE-1])
if((r==SIZE-1) && (c==SIZE-1) {
solution[r][c] = 1;
return 1;
}
//checking if we can visit in this cell or not
//the indices of the cell must be in (0,SIZE-1)
//and solution[r][c] == 0 is making sure that the cell is not already visited
//maze[r][c] == 0 is making sure that the cell is not blocked
if(r>=0 && c>=0 && r<SIZE && c<SIZE && solution[r][c] == 0 && maze[r][c] == 0){
//if safe to visit then visit the cell
solution[r][c] = 1;
//going down
if(solvemaze(r+1, c))
return 1;
//going right
if(solvemaze(r, c+1))
return 1;
//going up
if(solvemaze(r-1, c))
return 1;
//going left
if(solvemaze(r, c-1))
return 1;
//backtracking
solution[r][c] = 0;
return 0;
}
return 0;
}
int main() {
//making all elements of the solution matrix 0
int i,j;
for(i=0; i<SIZE; i++) {
for(j=0; j<SIZE; j++) {
solution[i][j] = 0;
}
}
if (solvemaze(0,0))
printsolution();
else
printf("No solution\n");
return 0;
} | [
{
"code": null,
"e": 1134,
"s": 1062,
"text": "Rat in a maze is also one popular problem that utilizes backtracking. I"
},
{
"code": null,
"e": 1472,
"s": 1134,
"text": "A maze is a 2D matrix in which some cells are blocked. One of the cells is the source cell, from where we have... |
Use of min() and max() in Python | In this article, we will be learning about min and max functions included in the Python Standard Library. It accepts infinite no of parameters according to the usage
max( arg1,arg2,arg3,...........)
Return Value − Maximum of all the arguments
Errors & Exceptions: Here error is raised only in the scenario where the arguments are not of the same type. Error is encountered while comparing them.
Let’s see what all ways we can implement the max() function first.
Live Demo
# Getting maximum element from a set of arguments passed
print("Maximum value among the arguments passed is:"+str(max(2,3,4,5,7,2,1,6)))
# the above statement also executes for characters as arguments
print("Maximum value among the arguments passed is:"+str(max('m','z','a','b','e')))
# it can also a accept arguments mapped in the form of a list
l=[22,45,1,7,3,2,9]
print("Maximum element of the list is:"+str(max(l)))
# it can also a accept arguments mapped in the form of a tuple
l=(22,45,1,7,71,91,3,2,9)
print("Maximum element of the tuple is:"+str(max(l)))
Maximum value among the arguments passed is:7
Maximum value among the arguments passed is:z
Maximum element of the list is:45
Maximum element of the tuple is:91
Here it is clearly observed that by the use of max function we can directly get the maximum values among the arguments without any comparison operations.
Similarly, we can implement the min() function here
Live Demo
# Getting maximum element from a set of arguments passed
print("Minimum value among the arguments passed is:"+str(min(2,3,4,5,7,2,1,6)))
# the above statement also executes for characters as arguments
print("Minimum value among the arguments passed is:"+str(min('m','z','a','b','e')))
# it can also a accept arguments mapped in the form of a list
l=[22,45,1,7,3,2,9]
print("Minimum element of the list is:"+str(min(l)))
# it can also a accept arguments mapped in the form of a tuple
l=(22,45,1,7,71,91,3,2,9)
print("Minimum element of the tuple is:"+str(min(l)))
Minimum value among the arguments passed is:1
Minimum value among the arguments passed is:a
Minimum element of the list is:1
Minimum element of the tuple is:1
By using built-in functions like max() & min() we can directly obtain the
corresponding maximum and minimum values without the actual implementation of
the logic to make the comparison happen
In this article, we learnt the implementation of max and min function included in the Standard Python Library. | [
{
"code": null,
"e": 1228,
"s": 1062,
"text": "In this article, we will be learning about min and max functions included in the Python Standard Library. It accepts infinite no of parameters according to the usage"
},
{
"code": null,
"e": 1261,
"s": 1228,
"text": "max( arg1,arg2,a... |
Data Structures | Queue | Question 11 - GeeksforGeeks | 06 Sep, 2019
Suppose a circular queue of capacity (n – 1) elements is implemented with an array of n elements. Assume that the insertion and deletion operation are carried out using REAR and FRONT as array index variables, respectively. Initially, REAR = FRONT = 0. The conditions to detect queue full and queue empty are(A) Full: (REAR+1) mod n == FRONT, empty: REAR == FRONT(B) Full: (REAR+1) mod n == FRONT, empty: (FRONT+1) mod n == REAR(C) Full: REAR == FRONT, empty: (REAR+1) mod n == FRONT(D) Full: (FRONT+1) mod n == REAR, empty: REAR == FRONTAnswer: (A)Explanation:
Suppose we start filling the queue.
Let the maxQueueSize ( Capacity of the Queue) is 4.
So the size of the array which is used to implement
this circular queue is 5, which is n.
In the beginning when the queue is empty, FRONT and REAR
point to 0 index in the array.
REAR represents insertion at the REAR index.
FRONT represents deletion from the FRONT index.
enqueue("a"); REAR = (REAR+1)%5; ( FRONT = 0, REAR = 1)
enqueue("b"); REAR = (REAR+1)%5; ( FRONT = 0, REAR = 2)
enqueue("c"); REAR = (REAR+1)%5; ( FRONT = 0, REAR = 3)
enqueue("d"); REAR = (REAR+1)%5; ( FRONT = 0, REAR = 4)
Now the queue size is 4 which is equal to the maxQueueSize.
Hence overflow condition is reached.
Now, we can check for the conditions.
When Queue Full :
( REAR+1)%n = (4+1)%5 = 0
FRONT is also 0.
Hence ( REAR + 1 ) %n is equal to FRONT.
When Queue Empty :
REAR was equal to FRONT when empty ( because in the starting
before filling the queue FRONT = REAR = 0 )
Hence Option A is correct.
Quiz of this Question
Akanksha_Rai
Data Structures
Data Structures-Queue
Data Structures
Data Structures
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Count of triplets in an Array (i, j, k) such that i < j < k and a[k] < a[i] < a[j]
Advantages and Disadvantages of Linked List
C program to implement Adjacency Matrix of a given Graph
Introduction to Data Structures | 10 most commonly used Data Structures
Difference between Singly linked list and Doubly linked list
FIFO vs LIFO approach in Programming
Data Structures | Stack | Question 6
Bit manipulation | Swap Endianness of a number
Advantages of vector over array in C++
Data Structures | Stack | Question 4 | [
{
"code": null,
"e": 24657,
"s": 24629,
"text": "\n06 Sep, 2019"
},
{
"code": null,
"e": 25219,
"s": 24657,
"text": "Suppose a circular queue of capacity (n – 1) elements is implemented with an array of n elements. Assume that the insertion and deletion operation are carried out ... |
My experience with uploading a dataset on HuggingFace’s dataset-hub | by Kartik Godawat | Towards Data Science | HuggingFace’s datasets library is a one-liner python library to download and preprocess datasets from HuggingFace dataset hub. The library, as of now, contains around 1,000 publicly-available datasets.
In this post, I’ll share my experience in uploading and mantaining a dataset on the dataset-hub. The following meme summarizes the intent behind using datasets library:
With the help and guidance from folks at HuggingFace, I was able to download the metadata of information available on the model-hub(where, similar to datasets, HuggingFace hosts 10,000+ publicly available models) into a csv file. I then began the process to upload it as a dataset on dataset-hub.
$pip install datasets
There are two ways of adding a public dataset:
Community-provided: Dataset is hosted on dataset hub. It’s unverified and identified under a namespace or organization, just like a GitHub repo.
Canonical: Dataset is added directly to the datasets repo by opening a PR(Pull Request) to the repo. Usually, data isn’t hosted and one has to go through PR merge process.
Since I wanted to host the data, along with the pre-processing script(referred to as “dataset loading script” by the library), I chose to upload the dataset as a community-provided dataset.
There are two primary requirements for converting an existing dataset of csv, json, xml or any other format into a dataset:
Dataset loading script
Dataset metadata
There’s good documentation available on creating such a script. I, however preferred copy-pasting by using the scripts of pre-existing datasets similar to mine, which are presnt in the datasets library. eg: If my dataset is of csv type, I’ll start with a similar csv type script and modify it according to my needs.
The script primarily needs three components to be defined:
Information about column and data types (referred as Features)
URLs to download data from ( or local files ) and specifying train/test/validation splits
Yield 1 row of data, utilizing split and features
1. _info: The headers of the csv field need to be defined with their datatype. I ended up using string , int32 and large_string. Description of supported datatypes is available in features.
def _info(self): return datasets.DatasetInfo( description=_DESCRIPTION, features=datasets.Features( { "modelId": datasets.Value("string"), "lastModified": datasets.Value("string"), "tags": datasets.features.Sequence(datasets.Value("string")), "pipeline_tag": datasets.Value("string"), "files": datasets.features.Sequence(datasets.Value("string")), "publishedBy": datasets.Value("string"), "downloads_last_month": datasets.Value("int32"), "library": datasets.Value("string"), "modelCard": datasets.Value("large_string"), } ), homepage=_HOMEPAGE, license=_LICENSE, citation=_CITATION, )
The columns “tags” and “files” are arrays, as they can be multiple which are supported by library by dataset.features.Sequence.
2. URLs / local files:
Next step is to then define a URL, which in my case is a local file. Since the data is only exploratory and doesn’t have any target labels(not specifically meant for training anything), there wasn’t any need of test split. Hence, only train dataset split will do.
_URL = "huggingface-modelhub.csv"...def _split_generators(self, dl_manager): """Returns SplitGenerators.""" data_file = dl_manager.download_and_extract(_URL) return [ datasets.SplitGenerator( name=datasets.Split.TRAIN, gen_kwargs={ "filepath": data_file, },),]
3. Yield a row:
The next step is to yield a single row of data. At runtime, appropriate generator (defined above) will pick the datasource from URL or local file and use it to generate a row. Here, since the data format was csv , we can use python’s inbuilt csv module and it’s function csv.reader to read the data from the file.
def _generate_examples(self, filepath): """Yields examples.""" with open(filepath, encoding="utf-8") as f: reader = csv.reader(f) for id_, row in enumerate(reader): if id_ == 0: continue yield id_, { "modelId": row[0], "lastModified": row[1], "tags": ast.literal_eval(row[2]), "pipeline_tag": row[3], "files": ast.literal_eval(row[4]), "publishedBy": row[5], "downloads_last_month": float(row[6]) if row[6] else 0, "library": row[7], "modelCard": row[8] }
ast.literal_eval is a handy function to parse the array present in a string into an actual array(list).
The script could be tested like this:
>>> from datasets import load_dataset>>> dataset = load_dataset('PATH/TO/MY/SCRIPT.py')>>> dataset["train"] # To access train generator>>> dataset["train"][0] #Access elements in dataset
With the script in place, we move on to adding the dataset metadata and getting the dataset ready for publishing.
The documentation explains in detail on how to prepare dataset for sharing. To add the metadata, there is a helper command available through datasets-cli , which gets installed when we install datasetslibrary.
datasets-cli test datasets/<your-dataset-folder> --save_infos --all_configs
Running the above command generates a file dataset_infos.json , which contains the metadata like dataset size, checksum etc.
Huggingface uses git and git-lfs behind the scenes to manage the dataset as a respository. To start, we need to create a new repository.
Once, the repository is ready, the standard git practices apply. i.e. from your project directory run:
$ git init .$ git remote add origin https://huggingface.co/datasets/<user>/<repo>$ git pull origin main
Now, we’ve synced our local machine with the repository. Next step is to add the following files and commit:
dataset files (csv): The data itself
dataset loading script: Loader for the data
dataset metadata: Metadata like size, citations etc
But there’s a catch! Conventional git systems aren’t suitable for handling large files. That is managed through git-lfs(Large File Storage). We don’t need to go deeper into how it works, we can simply run the following commands in order to be able to push large files to the repo:
$ git lfs install$ git lfs track huggingface-modelhub.csv$ git add dataset_infos.json huggingface-modelhub.csv huggingface-modelhub.py$ git commit -m "Commit message"$ git push origin main
The documentation covers lfs in detail as well. Since this is just a git repo, any other files like README could be committed as well. Dataset-hub UI also provides a quick way to update the README (referred to as datasetCard)
And that’s it. The dataset should be uploaded to dataset-hub. To access it, run:
>>> dataset = load_dataset("<user>/<repo>")
Since the repo of dataset is controllable using git, I believe it might be a good practice to first commit to a dev branch, test it completely and then perform the merge to main . That will help a lot in “accidentally” ruining an already existing and a stable, working dataset. This is very much analogous to standard git based software-release philosophy.
Another advantage is that dataset version also doesn’t mandatorily need to be serial( 1, 1.1, 1.2 etc). Different branches could hold different versions of the dataset.
>>> dataset = load_dataset("<user>/<repo>",>>> script_version="dev") # tag name, branch name, or commit hash
HuggingFace forum is very actively mantained and the team+community are very helpful and supportive. I personally found it to be more active and quick-responsive than stackoverflow. One could also open issues directly on github as well, but I prefer forums as they’re a bit informal.
No question is a dumb question! Never be afraid to ask.
That’s all folks!
I hope you enjoyed the post and found the datasets library to be useful.The dataset I uploaded with the loading script could be viewed here and used as a reference for csv formats.
Please share your views in comments. I’m also up for a discussion on twitter.
Have a great day. :) | [
{
"code": null,
"e": 374,
"s": 172,
"text": "HuggingFace’s datasets library is a one-liner python library to download and preprocess datasets from HuggingFace dataset hub. The library, as of now, contains around 1,000 publicly-available datasets."
},
{
"code": null,
"e": 543,
"s": 37... |
How to pop the first element from a C# List? | To pop the first element in the list, use the RemoveAt() method. It eliminates the element from the position you want to remove the element.
Set the list
List<string> myList = new List<string>() {
"Operating System",
"Computer Networks",
"Compiler Design"
};
Now pop the first element using RemoveAt(0)
myList.RemoveAt(0);
Let us see the complete example.
Live Demo
using System;
using System.Collections.Generic;
using System.Linq;
class Program {
static void Main() {
List<string> myList = new List<string>() {
"Operating System",
"Computer Networks",
"Compiler Design"
};
Console.Write("Initial list...");
foreach (string list in myList) {
Console.WriteLine(list);
}
Console.Write("Removing first element from the list...");
myList.RemoveAt(0);
foreach (string list in myList) {
Console.WriteLine(list);
}
}
}
Initial list...
Operating System
Computer Networks
Compiler Design
Removing first element from the list...
Computer Networks
Compiler Design | [
{
"code": null,
"e": 1203,
"s": 1062,
"text": "To pop the first element in the list, use the RemoveAt() method. It eliminates the element from the position you want to remove the element."
},
{
"code": null,
"e": 1216,
"s": 1203,
"text": "Set the list"
},
{
"code": null,
... |
Train Your Mind to Think Recursively in 5 Steps | by Sara A. Metwalli | Towards Data Science | Along the way on your programming journey, there are a few milestones that you need to conquer to advance ahead. For example, getting comfortable with classes, understanding pointers, master the art of functionalizing your code, and so on. One of the trickest programming concepts to learn for newcomers and master for those who have been programming for a while is recursion.
When I first started to code — almost a decade ago — I struggled a bit in wrapping my head around recursion. While some people can naturally think recursively, others — myself included — can’t.
But,
Thinking recursively is something you can train your brain to do and master, even if you’re not born with this ability.
Back in 2012, I came across a pretty cool book called “Think Like a Programmer.” This book taught me to develop a thinking process that helped me tackle various programming problems throughout the years. It gave me the foundation of the correct thinking process a programmer needs to develop to excel in their career.
Over the years, I expanded on those techniques proposed in the book to get comfortable with various programming concepts.
In this article, I will walk you through the different steps I used to solve any recursive problem. Although I will use Python to demonstrate the steps, these steps can be applied to any programming language. Their logic is not language-specific.
Let’s — let's, let's, let’s — get to it!
To demonstrate the process, let’s take a simple problem. Assume we need to sum up the digits of any given number. For example, the sum of 123 is 6, for 57190 is 22, and so on.
So, I need to write a code that solves this problem for me using recursion. Before you say it, I know there are other ways to solve this problem — that arguably are better and easier to recursion. But, for the sake of this article, let’s consider the recursive solution.
This step is relatively simple for most people. We have a number and want to sum its digits using loops. Basically, we need to know how to count how many digits in the number and then sum them up one by one.
One way to do that is to cast the variable containing the number to str to make it easier to iterate over.
num = 123 #The variable containing the number we want to sum its digitsnum = str(num) #Casting the number to a strs = 0 #Initialize a varible to accumulate the sum#Loop over the digits and add them upfor i in range(len(num)): s += int(num[i])
Solving the problem using loops will help us understand the answer and figure out all the non-recursive aspects of it. Now that we have the answer, we can dissect it and extract the information we need to move on.
At this point, we need to ask ourselves a question, if I were to write this in a function form, what will the function parameters be?
The answer to this question depends on the programming language you are using. For Python, we can say that we only need one parameter, which is the variable num.
def sumOfDigitsIter(num): num = str(num) s = 0 for i in range(len(num)): s += int(num[i]) return s
Once we get the function parameters, we are going to give them a deeper look. In our case, we only have one parameter that is num.
What we need to do now is find the minimal problem instance based on its parameters. To recall, our purpose was to sum the digits of a given number. The easiest instance of this problem is if the number only has one digit.
For example, if num = 3, then the answer will be equal to the variable itself since there are no more digits to add.
Let’s look again at the function we just wrote:
def sumOfDigitsIter(num): num = str(num) s = 0 for i in range(len(num)): s += int(num[i]) return s
Following this function's logic, if the parameter num is only one digit, the loop will still be executed. To avoid that, we can add a conditional statement that only executes if the number of digits in the input number is one.
def SumOfDigitsIter(num): num = str(num) if len(num) == 1: return num else: s = 0 for i in range(len(num)): s += int(num[i]) return s
This is the step where recursion happens. Up until now, we didn’t care much about recursion; we were solving the problem logically. That’s the best approach to start with recursion, think about it logically, and then convert into a recursive solution.
Now, let’s consider the else section of our function.
else: s = 0 for i in range(len(num)): s += int(num[i]) return s
You can think of recursion as unrolling a problem instance and then rolling it again. We can look at this problem from another angle, we can say that the sum of 123 is 1 + the sum of 23, and the sum of 23 is 2 + sum 3 — which is 3.
So, rolling back this becomes the sume of 123 = 1 +2 +3 =6.
Let’s convert that into code. We already have the last part written, which handles one-digit numbers. What we need to do is break the rest of the num variables into one-digit numbers.
That’s recursion.
def SumOfDigits2(num): num = str(num) if len(num) == 1: return num else: return num[0] + sumOfDigits(num[1:])
So, every time, I call the same function but with a smaller input. Once I reach the last digit, I will end up with something like 1 + 2 + 3, which will eventually add up to 6.
And, voila, I got myself a recursive function.
Let’s consider another example, say we want to get the sum of the absolute differences between two lists of integers of the same length. For example if we have [15,-4,56,10,-23] and [14,-9,56,14,-23], that answer will be 10.
Step 1: Solve with loops
assert len(arr1) == len(arr2) diffSum = 0 for i in range(len(arr1)): diffSum += abs(arr1[i]-arr2[i])
Step 2: Extract parameters
parameter list = [arr1, arr2].
Step 3: Deduct minimal instance
The minimal instance of this problem is when the two lists are empty; in this case, there’s no difference, so that the answer will be 0.
Step 4: Solve minimal instance.
if len(arr1) == 0: return 0
Now you might say, why didn’t you make sure that len(arr2) == 0 as well? The assert statement already ensured that both lists have the same length, which means if I want to check if they are empty, I only need to check the length of one of them.
Step 5: Recurse
Like the digits sum example, if I want to sum the absolute difference between two lists, I can get the difference between the first two elements, and then the second and then the third, and so on, until I run out of elements.
def recDiff(arr1,arr2): assert len(arr1) == len(arr2) if len(arr1) == 0: return 0 else: return abs(arr1[0]-arr2[0]) + recDiff(arr1[1:],arr2[1:])
Recursion is considered one of the advanced techniques that a programmer needs to go through along their journey to becoming a “good programmer.” However, it can be quite tricky to wrap one’s head around initially, and many find it difficult to master.
Following simple, concise five steps, you can tackle any recursion problem with ease:
Solve the problem using loops first.From that, extract the possible inputs if you would turn this into a function.Deduct the simplest version of the problem.Write a function that solves the simplest instance of that problem.Use that function to write a new recursive function.
Solve the problem using loops first.
From that, extract the possible inputs if you would turn this into a function.
Deduct the simplest version of the problem.
Write a function that solves the simplest instance of that problem.
Use that function to write a new recursive function.
Although I proposed 5 steps, you will not need to go through all 5 steps explicitly as you get better with precision. With time and practice, you will be able to perform some of these steps in your mind without explicitly writing them down.
I will leave you with this, recursive is one of the challenging programming concepts to master. So, just stick with it, be patient, and practice a lot; that’s the only way you can truly get the hang of it. | [
{
"code": null,
"e": 549,
"s": 172,
"text": "Along the way on your programming journey, there are a few milestones that you need to conquer to advance ahead. For example, getting comfortable with classes, understanding pointers, master the art of functionalizing your code, and so on. One of the tric... |
loc vs iloc in Pandas and Python | Towards Data Science | Indexing and slicing pandas DataFrames and Python may sometimes be tricky. The two most commonly used properties when it comes to slicing are iloc and loc.
In today’s article we are going to discuss the difference between these two properties. We’ll also go through a couple of examples to make sure you understand when to use one over the other.
First, let’s create a pandas DataFrame that we’ll use as an example to demonstrate a few concepts.
import pandas as pddf = pd.DataFrame( index=[4, 6, 2, 1], columns=['a', 'b', 'c'], data=[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]],)print(df)# a b c# 4 1 2 3# 6 4 5 6# 2 7 8 9# 1 10 11 12
loc[] property is used to slice a pandas DataFrame or Series and access row(s) and column(s) by label. This means that the input label(s) will correspond to the indices of rows that should be returned.
Therefore, if we pass an integer to loc[] it will be interpreted as the label of the index and not as the positional index. In the example shown below, loc will return the row with index label equal to 1.
>>> df.loc[1]a 10b 11c 12Name: 1, dtype: int64
loc also accepts an array of labels:
>>> df.loc[[6, 2]] a b c6 4 5 62 7 8 9
Similarly, we can also use a slice object to retrieve specific range of labels. In the example below, notice how the slicing is computed; 4:2 does not correspond to indices but instead, to labels. In other words, it tells pandas to return all the rows in between the indices 4 and 2.
>>> df.loc[4:2] a b c4 1 2 36 4 5 62 7 8 9
On the other hand, iloc property offers integer-location based indexing where the position is used to retrieve the requested rows.
Therefore, whenever we pass an integer to iloc you should expect to retrieve the row with the corresponding positional index. In the example below, iloc[1] will return the row in position 1 (i.e. the second row):
>>> df.iloc[1]a 4b 5c 6Name: 6, dtype: int64# Recall the difference between loc[1]>>> df.loc[1]a 10b 11c 12Name: 1, dtype: int64
Again, you can even pass an array of positional indices to retrieve a subset of the original DataFrame. For example,
>>> df.iloc[[0, 2]] a b c4 1 2 32 7 8 9
Or even a slice object of integers:
>>> df.iloc[1:3] a b c6 4 5 62 7 8 9
iloc can also accept a callable function that accepts a single argument of type pd.Series or pd.DataFrame and returns an output which is valid for indexing.
For instance, in order to retrieve only the rows with odd index a simple lambda function should do the trick:
>>> df.iloc[lambda x: x.index % 2 != 0] a b c1 10 11 12
Finally, you can also use iloc to index both axes. For example, in order to fetch the first two records and discard the last column you should call
>>> df.iloc[:2, :2] a b4 1 26 4 5
In this article we discussed how to properly index slice pandas DataFrames (or Series) using two of the most commonly properties namely loc and iloc.
It’s very important to understand the differences between these two properties and be able to use them effectively in order to create the desired output for your specific use-case. loc is used to index a pandas DataFrame or Series using labels. On the other hand, iloc can be used to retrieve records based on their positional index. | [
{
"code": null,
"e": 327,
"s": 171,
"text": "Indexing and slicing pandas DataFrames and Python may sometimes be tricky. The two most commonly used properties when it comes to slicing are iloc and loc."
},
{
"code": null,
"e": 518,
"s": 327,
"text": "In today’s article we are goin... |
What is difference between self and __init__ methods in python Class?
| The word 'self' is used to represent the instance of a class. By using the "self" keyword we access the attributes and methods of the class in python.
"__init__" is a reseved method in python classes. It is called as a constructor in object oriented terminology. This method is called when an object is created from a class and it allows the class to initialize the attributes of the class.
Find out the cost of a rectangular field with breadth(b=120), length(l=160). It costs x (2000) rupees per 1 square unit
class Rectangle:
def __init__(self, length, breadth, unit_cost=0):
self.length = length
self.breadth = breadth
self.unit_cost = unit_cost
def get_area(self):
return self.length * self.breadth
def calculate_cost(self):
area = self.get_area()
return area * self.unit_cost
# breadth = 120 units, length = 160 units, 1 sq unit cost = Rs 2000
r = Rectangle(160, 120, 2000)
print("Area of Rectangle: %s sq units" % (r.get_area()))
This gives the output
Area of Rectangle: 19200 sq units
Cost of rectangular field: Rs.38400000 | [
{
"code": null,
"e": 1213,
"s": 1062,
"text": "The word 'self' is used to represent the instance of a class. By using the \"self\" keyword we access the attributes and methods of the class in python."
},
{
"code": null,
"e": 1453,
"s": 1213,
"text": "\"__init__\" is a reseved met... |
C++ Program to Find the Length of a String | A string is a one dimensional character array that is terminated by a null character. The length of a string is the number of characters in the string before the null character.
For example.
char str[] = “The sky is blue”;
Number of characters in the above string = 15
A program to find the length of a string is given as follows.
Live Demo
#include<iostream>
using namespace std;
int main() {
char str[] = "Apple";
int count = 0;
while (str[count] != '\0')
count++;
cout<<"The string is "<<str<<endl;
cout <<"The length of the string is "<<count<<endl;
return 0;
}
The string is Apple
The length of the string is 5
In the above program, the count variable is incremented in a while loop until the null character is reached in the string. Finally the count variable holds the length of the string. This is given as follows.
while (str[count] != '\0')
count++;
After the length of the string is obtained, it is displayed on screen. This is demonstrated by the following code snippet.
cout<<"The string is "<<str<<endl;
cout<<"The length of the string is "<<count<<endl;
The length of the string can also be found by using the strlen() function. This is demonstrated in the following program.
Live Demo
#include<iostream>
#include<string.h>
using namespace std;
int main() {
char str[] = "Grapes are green";
int count = 0;
cout<<"The string is "<<str<<endl;
cout <<"The length of the string is "<<strlen(str);
return 0;
}
The string is Grapes are green
The length of the string is 16 | [
{
"code": null,
"e": 1240,
"s": 1062,
"text": "A string is a one dimensional character array that is terminated by a null character. The length of a string is the number of characters in the string before the null character."
},
{
"code": null,
"e": 1253,
"s": 1240,
"text": "For ... |
Visualizing statistical plots with Seaborn | by Pranav Prathvikumar | Towards Data Science | This is the second article on visualization. You can read the first article where I talk about the basics of visualization using matplotlib here.
To recap, visualization allows us to see how the data is distributed, detect outliers and allows us to convey information more effectively. Which is why it is important for data scientists/analysts to know how to visualize and what are the options available to them. In this article I will be covering the usage of seaborn to visualize statistical plots.
To do this we will be making use of some of the datasets present within seaborn itself. This avoids us the trouble of having to download and import datasets. You can see the entire list of available datasets in this link.
We will start off by importing in the required libraries.
import matplotlib.pyplot as pltimport numpy as npimport seaborn as sns
Next lets load the ‘iris’ dataset and have a look at it.
iris = sns.load_dataset('iris')iris.head()
The Iris dataset contains the details of the flowers of three different species. As this dataset contains mainly numerical columns, we will be using this to explore visualizations that is suitable for numeric data.
So the first thing we can do is check the distribution of any one of the columns.
sns.set(style = 'darkgrid')sns.distplot(iris['sepal_length'])
The first line allows you to set the style of graph and the second line build a distribution plot. This ‘distplot’ command builds both a histogram and a KDE plot in the same graph.
But we have the option to customize the above graph or even separate them out.
sns.distplot(iris['sepal_length'], kde = False, bins = 30)
Here we have not only removed the KDE plot but were also able to add more bins into the plot to give a better idea of the distribution. This was achieved by the ‘kde’ and ‘bins’ parameters respectively.
And the KDE plot can be viewed separately with the help of the kdeplot command.
sns.kdeplot(iris['sepal_length'])
One way to make this plot better is to be able to show the presence of various data points to better understand the distribution of the data. Similar to histogram, but with small bins. This is done with the help of rug plots.
sns.kdeplot(iris['sepal_length'])sns.rugplot(iris['sepal_length'])
The above plot is known as rug plot and gives the distribution and density of the points.
Enough with visualizing only a single variable, what if you wanted to see how are two variables distributed with respect to each other.
Suppose we want to see the relation between the sepal and petal lengths of the flower. In this case we can use a jointplot to visualize it.
sns.jointplot(x = 'sepal_length', y = 'petal_length', data = iris)
The above plot not only gives the joint distribution, but also the individual distributions along the axis. From the above figure it seems that there is an almost linear relationship between the two, except at the lower end.
A cool feature in joinplot is the ability to fit a regression line for the data.
sns.jointplot(x = 'sepal_length', y = 'petal_length', data = iris, kind = 'reg')
By passing ‘reg’ to the kind parameter we are able to add a regression line and add kde plots to the histograms on the sides.
And now finally if we want to get a quick understanding of the entire data in one go then we can make use of the pairplot function.
sns.pairplot(iris)
The only parameter to be passed is the dataset name and it will automatically build the above plot for all the numerical columns present in the data. It plots every numerical column against every other numerical column and helps to get a quick overview of the data.
But the above plot still is missing a column, species, which happens to be a categorical column. Can we include information about the categorical column in this?
sns.pairplot(iris, hue = 'species', palette = 'magma')
The categorical data is represented in the form of the colour scheme in each one of the individual plots. The parameter ‘hue’ can be used to pass this information and ‘palette’ controls the colour scheme for the plots.
Now lets look at visualizing data that has more categorical columns in it. For this we will be using the ‘tips’ dataset. Let load it and have a look at it.
tips = sns.load_dataset('tips')tips.head()
The ‘tips’ dataset contains information regarding the tip paid by diners and their information such as bill amount, sex, time etc. Lets start off by looking at the distribution of the tip amounts and its relationship with the total bill amount.
sns.distplot(tips['tip'], kde = False, bins = 30)sns.jointplot(x = 'total_bill', y = 'tip', data = tips, kind = 'kde')
Now lets see if the tip given varies by day or not. This can be done with the help of a boxplot.
sns.boxplot(x = 'day',y = 'tip', data = tips, palette = 'coolwarm')
Perhaps we want to compare by the sex of the diners. Like in the pairplot, we can specify that by the ‘hue’ parameter as well
sns.boxplot(x = 'day',y = 'tip', data = tips, hue = 'sex', palette = 'coolwarm')
This creates two boxplots for each day on the basis of sex.
Another way of visualizing the above data in with the help of a violinplot.
sns.violinplot(x = 'day',y = 'tip', data = tips, palette = 'rainbow')
The violin plot can be thought of as a combination of the box and kde plots. The thick line in the center indicates the interquartile range with the kde of the tip on both sides.
Similar to the box plot, we can use ‘sex’ to create two violin plots side by side to compare. But we have a better option in this case.
sns.violinplot(x = 'day',y = 'tip', data = tips, hue = 'sex', split = True, palette = 'rainbow')
By indicating ‘split’ as true we are able to create two different kdes on each side of the central line. This allows us to see the differences side by side and not crowd out the plot.
Previously we saw that we were able to use pair plots to have a look at the whole data and include one categorical column. But in this case we have multiple categorical columns. These can be integrated into the plots using Facet Grid.
g = sns.FacetGrid(tips, col="time", row="smoker")
The above command created a 2 x 2 plots to account for the four possibilities across ‘time’ and ‘smoker’. That is one plot each for every combination of what time was the meal and whether the diner was a smoker or not.
To these plots we can add the numerical data and compare how they differ across the above two columns of ‘time’ and ‘smoker’.
g = sns.FacetGrid(tips, col="time", row="smoker")g = g.map(plt.hist, "tip")
I added the distribution for tip values to see how they differ across ‘time’ and ‘smoker’. Above each plot is a line indicating which ‘time’ and ‘smoker’ value it corresponds to.
Similarly we can also plot two numerical columns and see the relationship between the two and across ‘time’ and ‘smoker’.
g = sns.FacetGrid(tips, col="time", row="smoker",hue='sex')g = g.map(plt.scatter, "total_bill", "tip").add_legend()
The above plot shows the relationship between the tip and bill amounts and across ‘time’ and ‘smoker’. In addition, the colour scheme of each plot shows the sex as well. By using facet grids we can create plots involving multiple numerical and categorical columns.
Lastly I want to cover heatmaps and clustermaps.
In the below figure I am using a heatmap to show the correlation of all the numerical values against each other.
sns.heatmap(tips.corr(), cmap = 'coolwarm', annot = True)
The command ‘tips.corr’ gives the correlation between all the numerical variables. By indicating ‘annot’ as true we can have the correlation values on the figure as well.
For building the clustermap I first pivoted the tips dataset to get the value of tip amount across day and sex.
tip_pivot = tips.pivot_table(values='tip',index='day',columns='sex')
Using this I can create a clustermap on the value of tips and how close are the days to each other.
sns.clustermap(tip_pivot, cmap = 'coolwarm', standard_scale = 1)
As there are only two sexes, there is not much to see in terms of clustering there. But in the case of days we see that Saturday and Thursday are grouped together indicating the similarity in the tip amounts given on those days.
The above clustermap is pretty simple as there are not many categories on each axis. A clustermap can really shine when there are multiple categories allowing to discern similarities and patterns.
This covers some of the statistical plots and visualisations that can be built using Seaborn. Hope you found it useful.
You can connect with me on LinkedIn as well. | [
{
"code": null,
"e": 318,
"s": 172,
"text": "This is the second article on visualization. You can read the first article where I talk about the basics of visualization using matplotlib here."
},
{
"code": null,
"e": 673,
"s": 318,
"text": "To recap, visualization allows us to see... |
Bubble Sort for Linked List by Swapping nodes - GeeksforGeeks | 04 Mar, 2020
Given a singly linked list, sort it using bubble sort by swapping nodes.
Example:
Input: 10->30->20->5
Output: 5->10->20->30
Input: 20->4->3
Output: 3->4->20
Approach:
Get the Linked List to be sortedApply Bubble Sort to this linked list, in which, while comparing the two adjacent nodes, actual nodes are swapped instead of just swapping the data.Print the sorted list
Get the Linked List to be sorted
Apply Bubble Sort to this linked list, in which, while comparing the two adjacent nodes, actual nodes are swapped instead of just swapping the data.
Print the sorted list
Below is the implementation of the above approach:
C++
C
// C++ program to sort Linked List// using Bubble Sort// by swapping nodes #include <iostream>using namespace std; /* structure for a node */struct Node { int data; struct Node* next;} Node; /*Function to swap the nodes */struct Node* swap(struct Node* ptr1, struct Node* ptr2){ struct Node* tmp = ptr2->next; ptr2->next = ptr1; ptr1->next = tmp; return ptr2;} /* Function to sort the list */int bubbleSort(struct Node** head, int count){ struct Node** h; int i, j, swapped; for (i = 0; i <= count; i++) { h = head; swapped = 0; for (j = 0; j < count - i - 1; j++) { struct Node* p1 = *h; struct Node* p2 = p1->next; if (p1->data > p2->data) { /* update the link after swapping */ *h = swap(p1, p2); swapped = 1; } h = &(*h)->next; } /* break if the loop ended without any swap */ if (swapped == 0) break; }} /* Function to print the list */void printList(struct Node* n){ while (n != NULL) { cout << n->data << " -> "; n = n->next; } cout << endl;} /* Function to insert a struct Nodeat the beginning of a linked list */void insertAtTheBegin(struct Node** start_ref, int data){ struct Node* ptr1 = (struct Node*)malloc(sizeof(struct Node)); ptr1->data = data; ptr1->next = *start_ref; *start_ref = ptr1;} // Driver Codeint main(){ int arr[] = { 78, 20, 10, 32, 1, 5 }; int list_size, i; /* start with empty linked list */ struct Node* start = NULL; list_size = sizeof(arr) / sizeof(arr[0]); /* Create linked list from the array arr[] */ for (i = 0; i < list_size; i++) insertAtTheBegin(&start, arr[i]); /* print list before sorting */ cout <<"Linked list before sorting\n"; printList(start); /* sort the linked list */ bubbleSort(&start, list_size); /* print list after sorting */ cout <<"Linked list after sorting\n"; printList(start); return 0;} // This code is contributed by// shubhamsingh10
// C program to sort Linked List// using Bubble Sort// by swapping nodes #include <stdio.h>#include <stdlib.h> /* structure for a node */struct Node { int data; struct Node* next;} Node; /*Function to swap the nodes */struct Node* swap(struct Node* ptr1, struct Node* ptr2){ struct Node* tmp = ptr2->next; ptr2->next = ptr1; ptr1->next = tmp; return ptr2;} /* Function to sort the list */int bubbleSort(struct Node** head, int count){ struct Node** h; int i, j, swapped; for (i = 0; i <= count; i++) { h = head; swapped = 0; for (j = 0; j < count - i - 1; j++) { struct Node* p1 = *h; struct Node* p2 = p1->next; if (p1->data > p2->data) { /* update the link after swapping */ *h = swap(p1, p2); swapped = 1; } h = &(*h)->next; } /* break if the loop ended without any swap */ if (swapped == 0) break; }} /* Function to print the list */void printList(struct Node* n){ while (n != NULL) { printf("%d -> ", n->data); n = n->next; } printf("\n");} /* Function to insert a struct Node at the beginning of a linked list */void insertAtTheBegin(struct Node** start_ref, int data){ struct Node* ptr1 = (struct Node*)malloc(sizeof(struct Node)); ptr1->data = data; ptr1->next = *start_ref; *start_ref = ptr1;} // Driver Codeint main(){ int arr[] = { 78, 20, 10, 32, 1, 5 }; int list_size, i; /* start with empty linked list */ struct Node* start = NULL; list_size = sizeof(arr) / sizeof(arr[0]); /* Create linked list from the array arr[] */ for (i = 0; i < list_size; i++) insertAtTheBegin(&start, arr[i]); /* print list before sorting */ printf("Linked list before sorting\n"); printList(start); /* sort the linked list */ bubbleSort(&start, list_size); /* print list after sorting */ printf("Linked list after sorting\n"); printList(start); return 0;}
Linked list before sorting
5 -> 1 -> 32 -> 10 -> 20 -> 78 ->
Linked list after sorting
1 -> 5 -> 10 -> 20 -> 32 -> 78 ->
SHUBHAMSINGH10
Algorithms-BubbleSort
BubbleSort
Linked Lists
Linked-List-Sorting
Linked List
Sorting
Linked List
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Linked List vs Array
Delete a Linked List node at a given position
Queue - Linked List Implementation
Implement a stack using singly linked list
Implementing a Linked List in Java using Class | [
{
"code": null,
"e": 24363,
"s": 24335,
"text": "\n04 Mar, 2020"
},
{
"code": null,
"e": 24436,
"s": 24363,
"text": "Given a singly linked list, sort it using bubble sort by swapping nodes."
},
{
"code": null,
"e": 24445,
"s": 24436,
"text": "Example:"
},
... |
Rightmost different bit | Practice | GeeksforGeeks | Given two numbers M and N. The task is to find the position of the rightmost different bit in the binary representation of numbers.
Example 1:
Input: M = 11, N = 9
Output: 2
Explanation: Binary representation of the given
numbers are: 1011 and 1001,
2nd bit from right is different.
Example 2:
Input: M = 52, N = 4
Output: 5
Explanation: Binary representation of the given
numbers are: 110100 and 0100,
5th-bit from right is different.
User Task:
The task is to complete the function posOfRightMostDiffBit() which takes two arguments m and n and returns the position of first different bits in m and n. If both m and n are the same then return -1 in this case.
Expected Time Complexity: O(max(log m, log n)).
Expected Auxiliary Space: O(1).
Constraints:
0 <= M <= 109
0 <= N <= 109
0
vsk63704 days ago
easy to understand:
int posOfRightMostDiffBit(int m, int n) { if(m==n){ return -1; }
int result=m^n; int count=0; while((result&1) !=1){ count+=1; result=result>>1; } return (count+1); }
0
mrnecto1 week ago
class Solution
{
public:
//Function to find the first position with different bits.
int posOfRightMostDiffBit(int m, int n)
{
// Your code here
m = m^n;
int cnt = 1;
while(m > 0)
{
if(m & 0x01) return cnt;
cnt++;
m >>= 1;
}
return -1;
}
};
0
sachinupreti1901 week ago
// Here we go.
class Solution{ public: //Function to find the first position with different bits. int posOfRightMostDiffBit(int m, int n) { // Your code here string p,q; int i; bitset<32>a(m); bitset<32>b(n); if(a==b) return -1; else { p=a.to_string(); q=b.to_string(); reverse(p.begin(),p.end()); reverse(q.begin(),q.end()); for(i=0;i<p.size();i++) { if(p[i]==q[i]) continue; else break; } return i+1; } }};
+1
atulharsh274Premium1 week ago
// one line solution for this problem
return m==n?-1: log2( (-(m^n)) & (m^n)) + 1;
0
harshpandeyalfa22 weeks ago
C++
(0.01sec)
int posOfRightMostDiffBit(int m, int n) { int count=1; while( m || n) { if( (1&m) != (1&n)) return count; else if( (1&m) == (1&n)) count++; if(m) m=m>>1; if(n) n=n>>1; } return -1; }
+1
anuraggulati2412 weeks ago
simple LOG(N^M) SOLUTION...
int posOfRightMostDiffBit(int m, int n)
{
if(m != n) {
// Your code here
// first find xor of both m and n...
int Xor = m ^ n;
// now we see the first det bit in xor ...
int value = Xor & ~(Xor - 1);
// now finded the position of the set bit...
int position = log2(value) + 1;
// return that position...
return position;
}
else {
return -1;
}
}
0
asifsaba5812 weeks ago
class Solution
{
public:
//Function to find the first position with different bits.
int posOfRightMostDiffBit(int m, int n)
{
//for example 11 and 9;
int count=0;
int zor=m^n; // 1011^1001=0010; // 2
if(zor==0){return -1;} // false;
while(zor>0){ //2>0 // 1>0
if((zor&1)==0) 0010&0001=0000 // true 0001&0001=0001 false
{
count++; //1
zor=zor>>1; 0010>>1=0001 //again it will go for while loop.
}
else{
count++; //1
break;
}
}
return count; //1+1=2
}
};
0
anirbandam103 weeks ago
int posOfRightMostDiffBit(int m, int n) { if (m == n) return -1; return log2((m^n) & ~((m^n)-1)) + 1; }
0
gauty verma3 weeks ago
private static int posOfRightMostDiffBit(int m, int n) { // TODO Auto-generated method stub int res = 1; if(m==n) { return -1; } int xor = m^n; int val = 1; while(true) { if((xor & val) != 0) { return res; } val = val<<1; res++; }}
0
rahuldebnath294 weeks ago
int posOfRightMostDiffBit(int m, int n) { // Your code here int x=m^n; for ( int i = 0; i < 32; i++){ if(x&(1<<i)) return i+1; } return -1; }
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": 370,
"s": 238,
"text": "Given two numbers M and N. The task is to find the position of the rightmost different bit in the binary representation of numbers."
},
{
"code": null,
"e": 382,
"s": 370,
"text": "Example 1: "
},
{
"code": null,
"e": 524,
... |
Why java8 introduces default method in an interface? | An interface in Java is similar to class but, it contains only abstract methods and fields which are final and static.
It is a specification of method prototypes. Whenever you need to guide the programmer or, make a contract specifying how the methods and fields of a type should be you can define an interface.
interface MyInterface{
public void display();
public void setName(String name);
public void setAge(int age);
}
If you need your class to follow a certain specification you need to implement the required interface and provide body for all the abstract methods in that interface.
For example, if you want to create a thread, one way to do so is to implement the runnable interface and provide body to the abstract method run().
public class RunnableDemo implements Runnable {
private Thread t;
private String threadName;
RunnableDemo(String name) {
threadName = name;
}
public void run() {
System.out.println("implementation of the runnable method");
}
public void start () {
t = new Thread (this, threadName);
t.start ();
}
public static void main(String args[]) {
RunnableDemo r = new RunnableDemo("Thread_1");
r.start();
}
}
Creating Thread_1
implementation of the runnable method
If you do not provide the implementation of all the abstract methods of an interface (you, implement) a compile time error is generated.
public class RunnableDemo implements Runnable {
private Thread t;
private String threadName;
RunnableDemo( String name) {
threadName = name;
System.out.println("Creating " + threadName );
}
/*public void run() {
System.out.println("implementation of the runnable method");
}*/
public static void main(String args[]) {
RunnableDemo r = new RunnableDemo( "Thread-1");
}
}
RunnableDemo.java:1: error: RunnableDemo is not abstract and does not override abstract method run() in Runnable
public class RunnableDemo implements Runnable {
^
1 error
What if new methods are added in the interfaces?
Suppose we are using certain interface and implemented all the abstract methods in that interface and new methods were added later.
Then, all the classes using this interface will not work unless you implement the newly added methods in each of them.
To resolve this issue from Java8 default methods are introduced.
A default method is also known as defender method or virtual extension method. You can define a default method using the default keyword as −
default void display() {
System.out.println("This is a default method");
}
Once write a default implementation to a particular method in an interface. there is no need to implement it in the classes that already using (implementing) this interface.
Following Java Example demonstrates the usage of the default method in Java.
interface sampleInterface{
public void demo();
default void display() {
System.out.println("This is a default method");
}
}
public class DefaultMethodExample implements sampleInterface{
public void demo() {
System.out.println("This is the implementation of the demo method");
}
public static void main(String args[]) {
DefaultMethodExample obj = new DefaultMethodExample();
obj.demo();
obj.display();
}
}
This is the implementation of the demo method
This is a default method
Note − All the methods of an interface are public therefore there is no need to use public before it explicitly. | [
{
"code": null,
"e": 1306,
"s": 1187,
"text": "An interface in Java is similar to class but, it contains only abstract methods and fields which are final and static."
},
{
"code": null,
"e": 1499,
"s": 1306,
"text": "It is a specification of method prototypes. Whenever you need t... |
Set iterator() method in Java with Examples | 31 Dec, 2018
The java.util.Set.iterator() method is used to return an iterator of the same elements as the set. The elements are returned in random order from what present in the set.
Syntax:
Iterator iterate_value = Set.iterator();
Parameters: The function does not take any parameter.
Return Value: The method iterates over the elements of the set and returns the values(iterators).
Below program illustrate the java.util.Set.iterator() method:
// Java code to illustrate iterator() import java.util.*; public class SetDemo { public static void main(String args[]) { // Creating an empty Set Set<String> set = new HashSet<String>(); // Use add() method to add elements into the Set set.add("Welcome"); set.add("To"); set.add("Geeks"); set.add("4"); set.add("Geeks"); // Displaying the Set System.out.println("Set: " + set); // Creating an iterator Iterator value = set.iterator(); // Displaying the values after iterating through the iterator System.out.println("The iterator values are: "); while (value.hasNext()) { System.out.println(value.next()); } }}
Set: [4, Geeks, Welcome, To]
The iterator values are:
4
Geeks
Welcome
To
Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Set.html#iterator()
Java-Collections
Java-Functions
java-set
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
ArrayList in Java
Stream In Java
Collections in Java
Multidimensional Arrays in Java
Singleton Class in Java
Stack Class in Java
Introduction to Java
Constructors in Java
Multithreading in Java | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n31 Dec, 2018"
},
{
"code": null,
"e": 199,
"s": 28,
"text": "The java.util.Set.iterator() method is used to return an iterator of the same elements as the set. The elements are returned in random order from what present in the set."
}... |
HTML | DOM button Object | 03 Mar, 2022
The button object in HTML is used to represent a <button> element. The getElementById() method is used to get the button object.Property Values:
autofocus: It sets or returns whether a button should automatically get focus when the page loads or not.
defaultValue: It sets or returns the default value of the button.
disabled: It sets or returns whether the button is disabled or not.
form: It returns a reference to the form that contains the button.
formAction: It sets or returns the value of the formation attribute of the button.
formEnctype: It sets or returns the value of the formEnctype attribute of the button.
formMethod: It sets or returns the value of the formMethod attribute of the button.
formNoValidate: It sets or returns whether the button, allows the form-data to be validated or not.
formTarget: It sets or returns the value of the formTarget attribute of the button.
name: It sets or returns the value of the name attribute of the submit button.
type: It returns the form element type of the button.
value: It sets or returns the value of the value attribute of the button
Creating button object: The button object can be created using JavaScript. The document.createElement() method is used to create <button> element. After creating a button object use appendChild() method to append the particular element (such as div) to display it.Example 1:
html
<!DOCTYPE html><html> <head> <title> DOM Button Object </title> <!-- script to create new button --> <script> function Geeks() { var myDiv = document.getElementById("GFG"); // creating button element var button = document.createElement('BUTTON'); // creating text to be //displayed on button var text = document.createTextNode("Button"); // appending text to button button.appendChild(text); // appending button to div myDiv.appendChild(button); ; } </script> </head> <body style = "text-align: center;"> <h1 style = "color:green;"> GeeksforGeeks </h1> <h2> DOM Button Property </h2> <p>Click the button to create a button.</p> <button onclick = "Geeks()"> Press me! </button> <br><br> <div id = "GFG"></div> </body></html>
Output: Before click on the button:
After click on the button:
Accessing button object: Access the button object by using the getElementById() method. Put the id of button element in the getElementById() to access it.Example 2:
html
<!DOCTYPE html><html> <head> <title> DOM Button Object </title> <script> function geek() { // Accessing the button element // by using id attribute var doc = document.getElementById("btn"); // Changing the text content doc.textContent = "Click me!"; } </script> </head> <body style = "text-align: center;"> <h1 style = "color:green;"> GeeksforGeeks </h1> <h2> DOM Button Property </h2> <p> Click the button to change the text inside it. </p> <button type = "button" id = "btn" onclick = "geek()"> Try it </button> </body></html>
Output: Before click on the button:
After click on the button:
Supported Browsers:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
ysachin2314
hritikbhatnagar2182
HTML-DOM
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
REST API (Introduction)
Hide or show elements in HTML using display property
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n03 Mar, 2022"
},
{
"code": null,
"e": 198,
"s": 53,
"text": "The button object in HTML is used to represent a <button> element. The getElementById() method is used to get the button object.Property Values:"
},
{
"code": null,
... |
Python OpenCV – destroyAllWindows() Function | 29 Jun, 2022
Python Opencv destroyAllWindows() function allows users to destroy or close all windows at any time after exiting the script. If you have multiple windows open at the same time and you want to close then you would use this function. It doesn’t take any parameters and doesn’t return anything. It is similar to destroyWindow() function but this function only destroys a specific window unlike destroyAllWindows().
In the Python script given below, we have created two windows named ‘P’ and ‘Q’ respectively that displayed an image of “gfg_logo.png” using the cv2.imshow() function that is supposed to display window ‘P’ first on the screen but before calling the waitKey() function to delay the closing of windows, we will destroy only the window named ‘P’ with destroyWindow(‘P’) function by passing the window name ‘P’ as its argument. We will see that the window ‘Q’ is only displayed on the screen which will close only when the user closes it.
Python
# importing cv2 moduleimport cv2 # read the imageimg = cv2.imread("gfg_logo.png") # showing the imagescv2.imshow('P', img)cv2.imshow('Q', img) # Destroying the window named P before# calling the waitKey() functioncv2.destroyWindow('P') # using the wait key function to delay the# closing of windows till any key is pressedcv2.waitKey(0)
Output:
In this case, instead of calling destroyWindow() to delete or close a particular window, we will use destroyAllWindows() to destroy all windows on the screen here we have called this function before waitKey(0), so the images will not at all displayed on the screen. DestroyAllWindows() is just a good coding practice.
Python
# importing cv2 moduleimport cv2 # read the imageimg = cv2.imread("gfg_logo.png") # showing the imagescv2.imshow('P', img)cv2.imshow('Q', img) # Destroying All the windowscv2.destroyAllWindows() # using the wait key function to delay# the closing of windows till any key is pressedcv2.waitKey(0)
Output:
sheetal18june
Picked
Python-OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
Introduction To PYTHON
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Jun, 2022"
},
{
"code": null,
"e": 441,
"s": 28,
"text": "Python Opencv destroyAllWindows() function allows users to destroy or close all windows at any time after exiting the script. If you have multiple windows open at the same tim... |
Regression Algorithms - Linear Regression | Linear regression may be defined as the statistical model that analyzes the linear relationship between a dependent variable with given set of independent variables. Linear relationship between variables means that when the value of one or more independent variables will change (increase or decrease), the value of dependent variable will also change accordingly (increase or decrease).
Mathematically the relationship can be represented with the help of following equation −
Y = mX + b
Here, Y is the dependent variable we are trying to predict
X is the dependent variable we are using to make predictions.
m is the slop of the regression line which represents the effect X has on Y
b is a constant, known as the Y-intercept. If X = 0,Y would be equal to b.
Furthermore, the linear relationship can be positive or negative in nature as explained below −
A linear relationship will be called positive if both independent and dependent variable increases. It can be understood with the help of following graph −
A linear relationship will be called positive if independent increases and dependent variable decreases. It can be understood with the help of following graph −
Linear regression is of the following two types −
Simple Linear Regression
Multiple Linear Regression
It is the most basic version of linear regression which predicts a response using a single feature. The assumption in SLR is that the two variables are linearly related.
We can implement SLR in Python in two ways, one is to provide your own dataset and other is to use dataset from scikit-learn python library.
Example 1 − In the following Python implementation example, we are using our own dataset.
First, we will start with importing necessary packages as follows −
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
Next, define a function which will calculate the important values for SLR −
def coef_estimation(x, y):
The following script line will give number of observations n −
n = np.size(x)
The mean of x and y vector can be calculated as follows −
m_x, m_y = np.mean(x), np.mean(y)
We can find cross-deviation and deviation about x as follows −
SS_xy = np.sum(y*x) - n*m_y*m_x
SS_xx = np.sum(x*x) - n*m_x*m_x
Next, regression coefficients i.e. b can be calculated as follows −
b_1 = SS_xy / SS_xx
b_0 = m_y - b_1*m_x
return(b_0, b_1)
Next, we need to define a function which will plot the regression line as well as will predict the response vector −
def plot_regression_line(x, y, b):
The following script line will plot the actual points as scatter plot −
plt.scatter(x, y, color = "m", marker = "o", s = 30)
The following script line will predict response vector −
y_pred = b[0] + b[1]*x
The following script lines will plot the regression line and will put the labels on them −
plt.plot(x, y_pred, color = "g")
plt.xlabel('x')
plt.ylabel('y')
plt.show()
At last, we need to define main() function for providing dataset and calling the function we defined above −
def main():
x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
y = np.array([100, 300, 350, 500, 750, 800, 850, 900, 1050, 1250])
b = coef_estimation(x, y)
print("Estimated coefficients:\nb_0 = {} \nb_1 = {}".format(b[0], b[1]))
plot_regression_line(x, y, b)
if __name__ == "__main__":
main()
Estimated coefficients:
b_0 = 154.5454545454545
b_1 = 117.87878787878788
Example 2 − In the following Python implementation example, we are using diabetes dataset from scikit-learn.
First, we will start with importing necessary packages as follows −
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets, linear_model
from sklearn.metrics import mean_squared_error, r2_score
Next, we will load the diabetes dataset and create its object −
diabetes = datasets.load_diabetes()
As we are implementing SLR, we will be using only one feature as follows −
X = diabetes.data[:, np.newaxis, 2]
Next, we need to split the data into training and testing sets as follows −
X_train = X[:-30]
X_test = X[-30:]
Next, we need to split the target into training and testing sets as follows −
y_train = diabetes.target[:-30]
y_test = diabetes.target[-30:]
Now, to train the model we need to create linear regression object as follows −
regr = linear_model.LinearRegression()
Next, train the model using the training sets as follows −
regr.fit(X_train, y_train)
Next, make predictions using the testing set as follows −
y_pred = regr.predict(X_test)
Next, we will be printing some coefficient like MSE, Variance score etc. as follows −
print('Coefficients: \n', regr.coef_)
print("Mean squared error: %.2f" % mean_squared_error(y_test, y_pred))
print('Variance score: %.2f' % r2_score(y_test, y_pred))
Now, plot the outputs as follows −
plt.scatter(X_test, y_test, color='blue')
plt.plot(X_test, y_pred, color='red', linewidth=3)
plt.xticks(())
plt.yticks(())
plt.show()
Coefficients:
[941.43097333]
Mean squared error: 3035.06
Variance score: 0.41
It is the extension of simple linear regression that predicts a response using two or more features. Mathematically we can explain it as follows −
Consider a dataset having n observations, p features i.e. independent variables and y as one response i.e. dependent variable the regression line for p features can be calculated as follows −
Here, h(xi) is the predicted response value and b0,b1,b2...,bp are the regression coefficients.
Multiple Linear Regression models always includes the errors in the data known as residual error which changes the calculation as follows −
We can also write the above equation as follows −
in this example, we will be using Boston housing dataset from scikit learn −
First, we will start with importing necessary packages as follows −
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets, linear_model, metrics
Next, load the dataset as follows −
boston = datasets.load_boston(return_X_y=False)
The following script lines will define feature matrix, X and response vector, Y −
X = boston.data
y = boston.target
Next, split the dataset into training and testing sets as follows −
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.7, random_state=1)
Now, create linear regression object and train the model as follows −
reg = linear_model.LinearRegression()
reg.fit(X_train, y_train)
print('Coefficients: \n', reg.coef_)
print('Variance score: {}'.format(reg.score(X_test, y_test)))
plt.style.use('fivethirtyeight')
plt.scatter(reg.predict(X_train), reg.predict(X_train) - y_train,
color = "green", s = 10, label = 'Train data')
plt.scatter(reg.predict(X_test), reg.predict(X_test) - y_test,
color = "blue", s = 10, label = 'Test data')
plt.hlines(y = 0, xmin = 0, xmax = 50, linewidth = 2)
plt.legend(loc = 'upper right')
plt.title("Residual errors")
plt.show()
Coefficients:
[
-1.16358797e-01 6.44549228e-02 1.65416147e-01 1.45101654e+00
-1.77862563e+01 2.80392779e+00 4.61905315e-02 -1.13518865e+00
3.31725870e-01 -1.01196059e-02 -9.94812678e-01 9.18522056e-03
-7.92395217e-01
]
Variance score: 0.709454060230326
The following are some assumptions about dataset that is made by Linear Regression model −
Multi-collinearity − Linear regression model assumes that there is very little or no multi-collinearity in the data. Basically, multi-collinearity occurs when the independent variables or features have dependency in them.
Auto-correlation − Another assumption Linear regression model assumes is that there is very little or no auto-correlation in the data. Basically, auto-correlation occurs when there is dependency between residual errors.
Relationship between variables − Linear regression model assumes that the relationship between response and feature variables must be linear. | [
{
"code": null,
"e": 2826,
"s": 2438,
"text": "Linear regression may be defined as the statistical model that analyzes the linear relationship between a dependent variable with given set of independent variables. Linear relationship between variables means that when the value of one or more independ... |
Python | Catching and Creating Exceptions | 12 Jun, 2019
Catching all exceptions is sometimes used as a crutch by programmers who can’t remember all of the possible exceptions that might occur in complicated operations. As such, it is also a very good way to write undebuggable code.Because of this, if one catches all exceptions, it is absolutely critical to log or reports the actual reason for the exception somewhere (e.g., log file, error message printed to screen, etc.).
Problem – Code that catches all the exceptions
try: ...except Exception as e: ... # Important log('Reason:', e)
This will catch all exceptions save SystemExit, KeyboardInterrupt, and GeneratorExit.
Code #2 : Considering the example.
def parse_int(s): try: n = int(v) except Exception: print("Couldn't parse")
Code #3 : Using the above function
print (parse_int('n / a'), "\n") print (parse_int('42'))
Output :
Couldn't parse
Couldn't parse
At this point, the question arises how it doesn’t work. Now if the function had been written as:
Code #4 :
def parse_int(s): try: n = int(v) except Exception as e: print("Couldn't parse") print('Reason:', e)
In this case, the following output will be received, which indicates that a programming mistake has been made.
parse_int('42')
Output :
Couldn't parse
Reason: global name 'v' is not defined
Problem – To wrap lower-level exceptions with custom ones that have more meaning in the context of the application (one is working on).
To create new exceptions just define them as classes that inherit from Exception (or one of the other existing exception types if it makes more sense).
Code #5 : Defining some custom exceptions
class NetworkError(Exception): passclass HostnameError(NetworkError): passclass TimeoutError(NetworkError): passclass ProtocolError(NetworkError): pass
Code #6 : Using these exceptions in the normal way.
try: msg = s.recv()except TimeoutError as e: ...except ProtocolError as e: ...
Custom exception classes should almost always inherit from the built-in Exception class, or inherit from some locally defined base exception that itself inherits from Exception.
BaseException is reserved for system-exiting exceptions, such as KeyboardInterrupt or SystemExit, and other exceptions that should signal the application to exit. Therefore, catching these exceptions is not the intended use case.
Python-exceptions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n12 Jun, 2019"
},
{
"code": null,
"e": 473,
"s": 52,
"text": "Catching all exceptions is sometimes used as a crutch by programmers who can’t remember all of the possible exceptions that might occur in complicated operations. As such, it... |
Python __import__() function | As we write python programs we need various other modules to leverage their functions, classes etc. in our current program. We can import those modules at the runtime using the import function. Though you can also import named modules at the beginning of the code, you may need the module temporarily for only few lines of code or you want to make the copy of an object from the module and modify and use it.
The syntax of the __import__() function is −
__import__(name, globals=None, locals=None, fromlist=(), level=0)
Where
name - the name of the module you want to import
globals and locals - determines how to interpret name
fromlist - objects or submodules that should be imported by name
level - specifies whether to use absolute or relative imports
In the below example we import the DateTime module and dcreate custom objects with values as needed in the program.
Live Demo
dttime = __import__('datetime', globals(), locals(), [], 0)
print(dttime.datetime.now())
# Make a copy of dttime
x = dttime.datetime.now()
# Get your custom results
print(x.strftime("%d-%B"))
Running the above code gives us the following result −
2021-01-12 07:38:54.903330
12-January
The use of __import__ is discouraged and you can import the entire module at the beginning of the code for greater efficiency. | [
{
"code": null,
"e": 1596,
"s": 1187,
"text": "As we write python programs we need various other modules to leverage their functions, classes etc. in our current program. We can import those modules at the runtime using the import function. Though you can also import named modules at the beginning o... |
Kotlin Type Conversion | 03 Jan, 2022
Type conversion (also called as Type casting) refers to changing the entity of one data type variable into another data type. As we know Java supports implicit type conversion from smaller to larger data types. An integer value can be assigned to the long data type. For example:
Java
public class TypecastingExample { public static void main(String args[]) { byte p = 12; System.out.println("byte value : "+p); // Implicit Typecasting long q = p; // integer value can be assigned // to long data type } }
But, Kotlin does not support implicit type conversion. An integer value can not be assigned to the long data type.
var myNumber = 100
var myLongNumber: Long = myNumber // Compiler error
// Type mismatch: inferred type is Int but Long was expected
In Kotlin, the helper function can be used to explicitly convert one data type to another data type.
Example:
var myNumber = 100
var myLongNumber: Long = myNumber.toLong() // compiles successfully
The following helper function can be used to convert one data type into another:
toByte()
toShort()
toInt()
toLong()
toFLoat()
toDouble()
toChar()
Note: There is No helper function available to convert into boolean type.
Conversion from larger to smaller data type
var myLongNumber = 10L
var myNumber2: Int = myLongNumber1.toInt()
Kotlin Program to convert the one data type into another:
Kotlin
fun main(args: Array<String>){ println("259 to byte: " + (259.toByte())) println("50000 to short: " + (50000.toShort())) println("21474847499 to Int: " + (21474847499.toInt())) println("10L to Int: " + (10L.toInt())) println("22.54 to Int: " + (22.54.toInt())) println("22 to float: " + (22.toFloat())) println("65 to char: " + (65.toChar())) println("A to Int: " + ('A'.toInt()))}
Output:
259 to byte: 3
50000 to short: -15536
21474847499 to Int: 11019
10L to Int: 10
22.54 to Int: 22
22 to float: 22.0
65 to char: A
A to Int: 65
iampradeephr
Kotlin
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?
How to Communicate Between Fragments in Android?
Retrofit with Kotlin Coroutine in Android
Kotlin constructor
Kotlin Higher-Order Functions
Suspend Function In Kotlin Coroutines
MVP (Model View Presenter) Architecture Pattern in Android with Example
Spinner in Kotlin
Android Menus
How to Get Current Location in Android? | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n03 Jan, 2022"
},
{
"code": null,
"e": 333,
"s": 52,
"text": "Type conversion (also called as Type casting) refers to changing the entity of one data type variable into another data type. As we know Java supports implicit type conversio... |
Find uncommon characters of the two strings | Set 2 | 25 Nov, 2021
Given two strings, str1 and str2, the task is to find and print the uncommon characters of the two given strings in sorted order without using extra space. Here, an uncommon character means that either the character is present in one string or it is present in the other string but not in both. The strings contain only lowercase characters and can contain duplicates.
Examples:
Input: str1 = “characters”, str2 = “alphabets” Output: b c l p r
Input: str1 = “geeksforgeeks”, str2 = “geeksquiz” Output: f i o q r u z
Approach: An approach that uses hashing has been discussed here. This problem can also be solved using bit operations. The approach uses 2 variables that store the bit-wise OR of the left shift of 1 with each character’s ASCII code – 97 i.e. 0 for ‘a’, 1 for ‘b’, and so on. For both the strings, we get an integer after performing these bit-wise operations. Now the XOR of these two integers will give the binary bit as 1 at only those positions that denote uncommon characters. Print the character values for those positions.
Below is the implementation of the above approach:
C++
Java
C#
Python3
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to print the uncommon// characters in the given string// in sorted ordervoid printUncommon(string str1, string str2){ int a1 = 0, a2 = 0; for (int i = 0; i < str1.length(); i++) { // Converting character to ASCII code int ch = int(str1[i]) - 'a'; // Bit operation a1 = a1 | (1 << ch); } for (int i = 0; i < str2.length(); i++) { // Converting character to ASCII code int ch = int(str2[i]) - 'a'; // Bit operation a2 = a2 | (1 << ch); } // XOR operation leaves only uncommon // characters in the ans variable int ans = a1 ^ a2; int i = 0; while (i < 26) { if (ans % 2 == 1) { cout << char('a' + i); } ans = ans / 2; i++; }} // Driver codeint main(){ string str1 = "geeksforgeeks"; string str2 = "geeksquiz"; printUncommon(str1, str2); return 0;}
// Java implementation of the approachclass GFG{ // Function to print the uncommon // characters in the given string // in sorted order static void printUncommon(String str1, String str2) { int a1 = 0, a2 = 0; for (int i = 0; i < str1.length(); i++) { // Converting character to ASCII code int ch = (str1.charAt(i)) - 'a'; // Bit operation a1 = a1 | (1 << ch); } for (int i = 0; i < str2.length(); i++) { // Converting character to ASCII code int ch = (str2.charAt(i)) - 'a'; // Bit operation a2 = a2 | (1 << ch); } // XOR operation leaves only uncommon // characters in the ans variable int ans = a1 ^ a2; int i = 0; while (i < 26) { if (ans % 2 == 1) { System.out.print((char) ('a' + i)); } ans = ans / 2; i++; } } // Driver code public static void main(String[] args) { String str1 = "geeksforgeeks"; String str2 = "geeksquiz"; printUncommon(str1, str2); }} // This code contributed by Rajput-Ji
// C# implementation of the approachusing System; class GFG{ // Function to print the uncommon// characters in the given string// in sorted orderstatic void printUncommon(string str1, string str2){ int a1 = 0, a2 = 0; for (int i = 0; i < str1.Length; i++) { // Converting character to ASCII code int ch = (str1[i] - 'a'); // Bit operation a1 = a1 | (1 << ch); } for (int i = 0; i < str2.Length; i++) { // Converting character to ASCII code int ch = (str2[i] - 'a'); // Bit operation a2 = a2 | (1 << ch); } // XOR operation leaves only uncommon // characters in the ans variable int ans = a1 ^ a2; int j = 0; while (j < 26) { if (ans % 2 == 1) { Console.Write((char)('a' + j)); } ans = ans / 2; j++; }} // Driver codepublic static void Main(){ string str1 = "geeksforgeeks"; string str2 = "geeksquiz"; printUncommon(str1, str2); }} // This code is contributed by SoM15242
# Python3 implementation of the approach # Function to print the uncommon# characters in the given string# in sorted orderdef printUncommon(str1, str2) : a1 = 0; a2 = 0; for i in range(len(str1)) : # Converting character to ASCII code ch = ord(str1[i]) - ord('a'); # Bit operation a1 = a1 | (1 << ch); for i in range(len(str2)) : # Converting character to ASCII code ch = ord(str2[i]) - ord('a'); # Bit operation a2 = a2 | (1 << ch); # XOR operation leaves only uncommon # characters in the ans variable ans = a1 ^ a2; i = 0; while (i < 26) : if (ans % 2 == 1) : print(chr(ord('a') + i),end=""); ans = ans // 2; i += 1; # Driver codeif __name__ == "__main__" : str1 = "geeksforgeeks"; str2 = "geeksquiz"; printUncommon(str1, str2); # This code is contributed by AnkitRai01
<script> // Javascript implementation of the approach // Function to print the uncommon// characters in the given string// in sorted orderfunction printUncommon(str1, str2){ var a1 = 0, a2 = 0; for (var i = 0; i < str1.length; i++) { // Converting character to ASCII code var ch = (str1[i].charCodeAt(0)) - 'a'.charCodeAt(0); // Bit operation a1 = a1 | (1 << ch); } for (var i = 0; i < str2.length; i++) { // Converting character to ASCII code var ch = (str2[i].charCodeAt(0)) - 'a'.charCodeAt(0); // Bit operation a2 = a2 | (1 << ch); } // XOR operation leaves only uncommon // characters in the ans variable var ans = a1 ^ a2; var i = 0; while (i < 26) { if (ans % 2 == 1) { document.write( String.fromCharCode('a'.charCodeAt(0) + i)); } ans = parseInt(ans / 2); i++; }} // Driver codevar str1 = "geeksforgeeks";var str2 = "geeksquiz";printUncommon(str1, str2); </script>
fioqruz
Time Complexity: O(|str1| + |str2| + 26)Auxiliary Space: O(1)
Rajput-Ji
SoumikMondal
ankthon
famously
subhammahato348
Bit Magic
Hash
Strings
Hash
Strings
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n25 Nov, 2021"
},
{
"code": null,
"e": 423,
"s": 54,
"text": "Given two strings, str1 and str2, the task is to find and print the uncommon characters of the two given strings in sorted order without using extra space. Here, an uncommon ... |
How to add column from another DataFrame in Pandas ? | 30 May, 2021
In this article, we will discuss how to add a column from another DataFrame in Pandas.
Method 1: Using join()
Using this approach, the column to be added to the second dataframe is first extracted from the first using its name. Here the extracted column has been assigned to a variable.
Syntax: dataframe1[“name_of_the_column”]
After extraction, the column needs to be simply added to the second dataframe using join() function.
Syntax: Dataframe2.join(“variable_name”)
This function needs to be called with reference to the dataframe in which the column has to be added and the variable name which stores the extracted column name has to be passed to it as the argument. As a result, the column will be added to the end of the second dataframe with the same name as it was in the previous dataframe.
Example:
Python3
import pandas as pd df1 = pd.DataFrame({"Col1": [1, 2, 3], "Col2": ["A", "B", "C"], "Col3": ["geeks", "for", "geeks"]}) print("First dataframe:")display(df1) df2 = pd.DataFrame({"C1": [4, 5, 6], "C2": ["D", "E", "F"]}) print("Second dataframe:")display(df2) extracted_col = df1["Col3"]print("column to added from first dataframe to second:")display(extracted_col) df2 = df2.join(extracted_col)print("Second dataframe after adding column from first dataframe:")display(df2)
Output:
Method 2: Using insert()
The approach is the same as above- the column to be added is first extracted and assigned to a variable and then added to another dataframe. The difference here is that this approach gives freedom to place the column anywhere and with a different column name if need be.
Syntax: insert(location, “new_name”, “extarcted_column” )
Here, the index where the column is desired to inserted is passed in place of location. new_name can be replaced by the name the column is supposed to be renamed with and extracted_column is the column from the first dataframe.
Example:
Python3
import pandas as pd df1 = pd.DataFrame({"Col1": [1, 2, 3], "Col2": ["A", "B", "C"], "Col3": ["geeks", "for", "geeks"]})print("First dataframe:")display(df1) df2 = pd.DataFrame({"C1": [4, 5, 6], "C2": ["D", "E", "F"]})print("Second dataframe:")display(df2) extracted_col = df1["Col3"]print("column to added from first dataframe to second:")display(extracted_col) df2.insert(1, "C3", extracted_col)print("Second dataframe after adding column from first dataframe:")display(df2)
Output:
Picked
Python pandas-dataFrame
Python Pandas-exercise
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 May, 2021"
},
{
"code": null,
"e": 115,
"s": 28,
"text": "In this article, we will discuss how to add a column from another DataFrame in Pandas."
},
{
"code": null,
"e": 139,
"s": 115,
"text": "Method 1: Using joi... |
GATE CS 1999 - GeeksforGeeks | 11 Aug, 2021
The number of binary relations on a set with n elements is:
A. Thread 1. Interrupt
B. Virtual address space 2. Memory
C. File system 3. CPU
D. Signal 4. Disk
Thread is handled by CPU.Virtual address space (it is a set of virtual memory addresses that a process can use) is associated with memory management.File System is used for disk management.Interrupt is a type of signal.
Thread is handled by CPU.
Virtual address space (it is a set of virtual memory addresses that a process can use) is associated with memory management.
File System is used for disk management.
Interrupt is a type of signal.
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ...
Software Testing - Web Based Testing
What are the different ways of Data Representation?
Bash Script - Command Substitution
SDE SHEET - A Complete Guide for SDE Preparation
7 Highest Paying Programming Languages For Freelancers in 2022
DSA Sheet by Love Babbar
How to Create a Shell Script in linux
How To Convert Numpy Array To Tensor?
7 Best React Project Ideas For Beginners in 2022 | [
{
"code": null,
"e": 29577,
"s": 29549,
"text": "\n11 Aug, 2021"
},
{
"code": null,
"e": 29637,
"s": 29577,
"text": "The number of binary relations on a set with n elements is:"
},
{
"code": null,
"e": 29799,
"s": 29637,
"text": "A. Thread ... |
How to Calculate the Mean by Group in R DataFrame ? | 01 Apr, 2021
In this article, we are going to see how to calculate the mean by the group in DataFrame in R Programming Language.
It can be done with two approaches:
Using aggregate function
Using dplyr Package
Dataset creation: First, we create a dataset so that later we can apply the above two approaches and find the Mean by group.
R
# GFG dataset name and creationGFG <- data.frame( Category = c ("A","B","C","B","C","A","C","A","B"), Frequency= c(9,5,0,2,7,8,1,3,7) ) # Prints the datasetprint(GFG)
So, as you can see the above code is for creating a dataset named “GFG”.
It also has 2 columns named Category and Frequency. So, when you run the above code in an R compiler, a table is shown as output as given below
And after applying that two approaches we need to get output as:
Before we discuss those approaches let us first know how we got the output values:
In Table 1, We have two columns named Category and Frequency.
In Category, we have some repeating variables of A, B and C.
A group values (9,8,3), B group values (5,2,7) and C group values (0,7,1) taken from the Frequency column.
So, to find Mean we have a formula
MEAN = Sum of terms / Number of terms
Hence, Mean by Group of each group (A,B,C) would be
Sum:
A=9+8+3=20
B=5+2+7=14
C=0+7+1=08
Number of terms:
A is repeated 3 times
B is repeated 3 times
C is repeated 3 times
Mean by group (A, B, C):
A(mean) = Sum/Number of terms = 20/3 = 6.67
B(mean) = Sum/Number of terms = 14/3 = 4.67
C(mean) = Sum/Number of terms = 8/3 = 2.67
Method 1: Using aggregate function
Aggregate function: Splits the data into subsets, computes summary statistics for each, and returns the result in a convenient form.
Syntax: aggregate(x = dataset_Name , by = group_list, FUN = any_function)
# Basic R syntax of aggregate function
Now, let’s sum our data using an aggregate function:
R
GFG <- data.frame( Category = c ("A","B","C","B","C","A","C","A","B"), Frequency= c(9,5,0,2,7,8,1,3,7)) # Specify data columnaggregate(x= GFG$Frequency, # Specify group indicator by = list(GFG$Category), # Specify function (i.e. mean) FUN = mean)
Output:
In the above aggregate function, it takes on three parameters
First is dataset name in our case it is “GFG”.
Second is the column name which values we need to make different groups in our case it is Category column, and it is separated into three groups (A, B, C).
In the third parameter, we need to mention which function(i.e mean, sum, etc) we need to perform on a group formed (A, B, C)
Method 2: Using dplyr Package
dplyr is a package which provides a set of tools for efficiently manipulating datasets in R
Methods in dplyr package:
mutate() adds new variables that are functions of existing variables
select() picks variables based on their names.
filter() picks cases based on their values.
summarise() reduces multiple values down to a single summary.
arrange() changes the ordering of the rows.
Install this library:
install.packages("dplyr")
Load this library:
library("dplyr")
Code:
R
# load dplyr librarylibrary("dplyr") GFG <- data.frame( Category = c ("A","B","C","B","C","A","C","A","B"), Frequency= c(9,5,0,2,7,8,1,3,7)) # Specify data frameGFG%>% # Specify group indicator, column, functiongroup_by(Category) %>% summarise_at(vars(Frequency), list(name = mean))
Output:
In the above code, we first take our dataset named “GFG”. With group_by() method we form groups in our case (A, B, C). summarise_at() it has two parameters first is a column on which it applies the operation given as the second parameter of it.
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.
Filter data by multiple conditions in R using Dplyr
How to Replace specific values in column in R DataFrame ?
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Loops in R (for, while, repeat)
How to Replace specific values in column in R DataFrame ?
How to Split Column Into Multiple Columns in R DataFrame?
How to change Row Names of DataFrame in R ?
How to filter R DataFrame by values in a column?
Remove rows with NA in one column of R DataFrame | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Apr, 2021"
},
{
"code": null,
"e": 144,
"s": 28,
"text": "In this article, we are going to see how to calculate the mean by the group in DataFrame in R Programming Language."
},
{
"code": null,
"e": 180,
"s": 144,
... |
C library function - atol() | The C library function long int atol(const char *str) converts the string argument str to a long integer (type long int).
Following is the declaration for atol() function.
long int atol(const char *str)
str − This is the string containing the representation of an integral number.
str − This is the string containing the representation of an integral number.
This function returns the converted integral number as a long int. If no valid conversion could be performed, it returns zero.
The following example shows the usage of atol() function.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main () {
long val;
char str[20];
strcpy(str, "98993489");
val = atol(str);
printf("String value = %s, Long value = %ld\n", str, val);
strcpy(str, "tutorialspoint.com");
val = atol(str);
printf("String value = %s, Long value = %ld\n", str, val);
return(0);
}
Let us compile and run the above program, this will produce the following result −
String value = 98993489, Long value = 98993489
String value = tutorialspoint.com, Long value = 0
12 Lectures
2 hours
Nishant Malik
12 Lectures
2.5 hours
Nishant Malik
48 Lectures
6.5 hours
Asif Hussain
12 Lectures
2 hours
Richa Maheshwari
20 Lectures
3.5 hours
Vandana Annavaram
44 Lectures
1 hours
Amit Diwan
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2129,
"s": 2007,
"text": "The C library function long int atol(const char *str) converts the string argument str to a long integer (type long int)."
},
{
"code": null,
"e": 2179,
"s": 2129,
"text": "Following is the declaration for atol() function."
},
{
... |
HTML5 Canvas & z-index issue in Google Chrome | When we apply z index to a canvas whose position is fixed, it stop causes chrome to render all other elements which have position:fixed properly. This only happens if canvas is greater than 256X256 px in size.
Wrap both h1 and canvas with the fixed div and solves the issue −
<div id = 'fixcontainer'>
<h1>Test Title</h1>
<canvas id = "backgroundCanvas" width = "1000" height = "300"></canvas>
</div>
The following is the CSS −
h1{
position: fixed;
}
body{
height: 1500px;
}
canvas{
position: fixed; z-index: -10;
} | [
{
"code": null,
"e": 1272,
"s": 1062,
"text": "When we apply z index to a canvas whose position is fixed, it stop causes chrome to render all other elements which have position:fixed properly. This only happens if canvas is greater than 256X256 px in size."
},
{
"code": null,
"e": 1338,
... |
How to select checkboxes using selenium java webdriver? | We can select the checkbox with Selenium. In an html document, each checkbox has an attribute type set to a value as checkbox. In order to select a checkbox, we shall first identify a checkbox with any locator and then apply the click() method to it.
Code Implementation.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class CheckBoxSelect{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
String url ="https://www.tutorialspoint.com/selenium/selenium_automation_practice.htm";
driver.get(url);
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
// identify element
WebElement l=driver.findElement(By.xpath("//*[@value='Manual Tester']"));
// select checkbox with click()
l.click();
driver.quit();
}
} | [
{
"code": null,
"e": 1313,
"s": 1062,
"text": "We can select the checkbox with Selenium. In an html document, each checkbox has an attribute type set to a value as checkbox. In order to select a checkbox, we shall first identify a checkbox with any locator and then apply the click() method to it."
... |
Kotlin Operator Overloading - GeeksforGeeks | 02 Aug, 2019
Since Kotlin provides user-defined types, it also provides the additional functionality to overload the standard operators, so that working with user-defined types is easier. All of the unary, binary, relational operators can be overloaded. The operators are overloaded either through the member functions or through extension functions. These functions are preceded by the operator modifier. There are standard functions for every type of operator that can be overloaded according to the usage.
The following table shows the various functions that can be defined for unary operators. These functions modify the calling instance.
Here, x corresponds to the type for which the operator is defined. The overloaded functionality is defined within the respective functions.
Kotlin program to demonstrate the unary operator overloading –
class UnaryOverload(var str:String) { // overloading the function operator fun unaryMinus() { str = str.reversed() }}// main functionfun main(args : Array<String>) { val obj = UnaryOverload("HELLO") println("Initial string is ${obj.str}")y //calling the overloaded function unaryMinus() -obj println("String after applying unary operator ${obj.str}")}
Output:
Initial string is HELLO
String after applying unary operator OLLEH
The increment and decrement operator can be defined for a type through the following functions. These function returns a new instance with the outcome of the expression.
Either used in postfix or prefix notation these functions work well in both the cases, with the same expected output, as one would expect when using prefix or postfix notations.
Kotlin program to demonstrate the operator overloading –
class IncDecOverload(var str:String) { // overloading increment function operator fun inc(): IncDecOverload { val obj = IncDecOverload(this.str) obj.str = obj.str + 'a' return obj } // overloading decrement function operator fun dec(): IncDecOverload { val obj = IncDecOverload(this.str) obj.str = obj.str.substring(0,obj.str.length-1) return obj } override fun toString(): String { return str }}// main functionfun main(args: Array<String>) { var obj = IncDecOverload("Hello") println(obj++) println(obj--) println(++obj) println(--obj)}
Output:
Hello
Helloa
Helloa
Hello
The following table shows the binary operators and their equivalent functions to be defined. All these functions modify the calling instance.
Kotlin program to overload the plus function –
class Object(var objName: String) { // Overloading the function operator fun plus(b: Int) { objName = "Name is $objName and data is $b" } override fun toString(): String { return objName }}// main functionfun main() { val obj = Object("Chair") // Calling the overloaded function obj+9 println(obj)}
Output:
Name is Chair and data is 9
Note- The relational operators do not have any specific functions to be defined, to use relational operators on instances of a user-defined type, the type must implement the Comparable interface.
Kotlin supports a wide range of operators, hence defining each for a type is not a good programming practice. The following table shows some of the other useful operators that can be overloaded is Kotlin.
Kotlin
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Broadcast Receiver in Android With Example
Android RecyclerView in Kotlin
Content Providers in Android with Example
Retrofit with Kotlin Coroutine in Android
How to Add and Customize Back Button of Action Bar in Android?
How to Get Current Location in Android?
Kotlin Setters and Getters
How to Change the Color of Status Bar in an Android App?
Kotlin Android Tutorial
Kotlin when expression | [
{
"code": null,
"e": 25135,
"s": 25107,
"text": "\n02 Aug, 2019"
},
{
"code": null,
"e": 25631,
"s": 25135,
"text": "Since Kotlin provides user-defined types, it also provides the additional functionality to overload the standard operators, so that working with user-defined types... |
Python if else - GeeksforGeeks | 30 Sep, 2021
There comes situations in real life when we need to make some decisions and based on these decisions, we decide what should we do next. Similar situations arise in programming also where we need to make some decisions and based on these decisions we will execute the next block of code. Decision-making statements in programming languages decide the direction of the flow of program execution.
In Python, if else elif statement is used for decision making.
if statement is the most simple decision-making statement. It is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not.
Syntax:
if condition:
# Statements to execute if
# condition is true
Here, the condition after evaluation will be either true or false. if statement accepts boolean values – if the value is true then it will execute the block of statements below it otherwise not. We can use condition with bracket ‘(‘ ‘)’ also.
As we know, python uses indentation to identify a block. So the block under an if statement will be identified as shown in the below example:
if condition:
statement1
statement2
# Here if the condition is true, if block
# will consider only statement1 to be inside
# its block.
Python3
# python program to illustrate If statement i = 10 if (i > 15): print("10 is less than 15")print("I am Not in if")
Output:
I am Not in if
As the condition present in the if statement is false. So, the block below the if statement is not executed.
The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false it won’t. But what if we want to do something else if the condition is false. Here comes the else statement. We can use the else statement with if statement to execute a block of code when the condition is false.
Syntax:
if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false
Python3
# python program to illustrate If else statement#!/usr/bin/python i = 20if (i < 15): print("i is smaller than 15") print("i'm in if Block")else: print("i is greater than 15") print("i'm in else Block")print("i'm not in if and not in else Block")
Output:
i is greater than 15
i'm in else Block
i'm not in if and not in else Block
The block of code following the else statement is executed as the condition present in the if statement is false after calling the statement which is not in block(without spaces).
Python3
# Explicit functiondef digitSum(n): dsum = 0 for ele in str(n): dsum += int(ele) return dsum # Initializing listList = [367, 111, 562, 945, 6726, 873] # Using the function on odd elements of the listnewList = [digitSum(i) for i in List if i & 1] # Displaying new listprint(newList)
[16, 3, 18, 18]
A nested if is an if statement that is the target of another if statement. Nested if statements mean an if statement inside another if statement. Yes, Python allows us to nest if statements within if statements. i.e, we can place an if statement inside another if statement.
Syntax:
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here
Python3
# python program to illustrate nested If statement#!/usr/bin/pythoni = 10if (i == 10): # First if statement if (i < 15): print("i is smaller than 15") # Nested - if statement # Will only be executed if statement above # it is true if (i < 12): print("i is smaller than 12 too") else: print("i is greater than 15")
Output:
i is smaller than 15
i is smaller than 12 too
Here, a user can decide among multiple options. The if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.
Syntax:
if (condition):
statement
elif (condition):
statement
.
.
else:
statement
Python3
# Python program to illustrate if-elif-else ladder#!/usr/bin/python i = 20if (i == 10): print("i is 10")elif (i == 15): print("i is 15")elif (i == 20): print("i is 20")else: print("i is not present")
Output:
i is 20
Whenever there is only a single statement to be executed inside the if block then shorthand if can be used. The statement can be put on the same line as the if statement.
Syntax:
if condition: statement
Python3
# Python program to illustrate short hand ifi = 10if i < 15: print("i is less than 15")
Output:
i is less than 15
This can be used to write the if-else statements in a single line where there is only one statement to be executed in both if and else block.
Syntax:
statement_when_True if condition else statement_when_False
Python3
# Python program to illustrate short hand if-elsei = 10print(True) if i < 15 else print(False)
Output:
True
punamsingh628700
nikhilaggarwal3
python-basics
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace() | [
{
"code": null,
"e": 42675,
"s": 42647,
"text": "\n30 Sep, 2021"
},
{
"code": null,
"e": 43070,
"s": 42675,
"text": "There comes situations in real life when we need to make some decisions and based on these decisions, we decide what should we do next. Similar situations arise in... |
How to Connect Android App with Back4App? - GeeksforGeeks | 12 Mar, 2021
Back4App is another famous backend platform that provides backend services for different types of applications whether it may be web, android, or IOS devices. Back4App also provides us similar services to that of Firebase. We have seen using Firebase in Android App. In this article, we will take a look at adding Back4App in your Android App in Android Studio. We will be building a simple application in which we will be connecting our Android App with Back4App.
Back4App is one of the finest and the most popular alternatives for Parse among the developer’s community. It’s an easy way to build, host, and manage apps using the open-source Parse Server. Based on the highly efficient open-source backend framework, Parse Server, Back4App has several rich functionalities:
Featured Parse Server: Back4App uses Parse Server as a core product as it is the finest framework for backend development which can help developers save precious time building an app.
Boosted Server Performance: It supports a smart database index, queries optimizers, auto-scaling, automated backups, and redundant storage capacity.
Easy Deployment: Back4app is a ready-to-go platform. You can set up your app in less than 5 minutes.
Real-time database and analytics: It provides real-time data storage and synchronization. Real-time analytics is a key feature.
Within your budget: Predictable pricing, transparent and easy-to-budget.
Great technical support team: The engineering support of Back4App is always available to help its users.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Add dependency and JitPack Repository
Navigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section.
implementation “com.github.parse-community.Parse-SDK-Android:parse:1.26.0”
Add the JitPack repository to your build file. Add it to your root build.gradle at the end of repositories inside the allprojects{ } section.
allprojects {
repositories {
...
maven { url “https://jitpack.io” }
}
}
Now sync your project and we are ready to add Back4App to our app.
Step 3: Adding permissions to the internet in the AndroidManifest.xml file
Navigate to the app > AndroidManifest.xml and add the below code to it.
XML
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/><uses-permission android:name="android.permission.INTERNET"/>
Step 4: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!--text view for displaying the text which we are going to pass in back4app--> <TextView android:id="@+id/textView" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerInParent="true" android:gravity="center_horizontal" android:padding="3dp" android:text="Hello World!" android:textAlignment="center" android:textColor="@color/black" /> </RelativeLayout>
Step 5: Creating a new app in back4App
Create a new account in back4App or you can simply sign in using your Google Account. After creating your new account you will get to see the below screen. Click on the first option to create a new app. The screenshot is shown below.
After clicking on this option you have to enter the name of your application and click on Create option. You will get to see this option on the below screenshot.
After you have created a new application it will take some time to create a new application. Once your app has been created you have to go to the left nav drawer and then click on the App Settings option > Security & Keys option to get the key and client id for your app. The screenshot for this option is given below.
Step 6: Adding your App id and app client key in your strings.xml file
Navigate to the app > res > values > strings.xml file and add the below code to it. Add your original client id and app id in these strings.
XML
<resources> <string name="app_name">GFG Parse</string> <string name="back4app_server_url">https://parseapi.back4app.com/</string> <!-- Change the following strings as required --> <string name="back4app_app_id">Enter your app id here</string> <string name="back4app_client_key">Enter your client key here</string> </resources>
Step 7: Creating a new Java class for our Application
Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name it as App and add the below code to it. Comments are added in the code to get to know in more detail.
Java
import android.app.Application; import com.parse.Parse; public class App extends Application { @Override public void onCreate() { super.onCreate(); // initializing our Parse application with // our application id, client key and server url Parse.initialize(new Parse.Configuration.Builder(this) .applicationId(getString(R.string.back4app_app_id)) .clientKey(getString(R.string.back4app_client_key)) .server(getString(R.string.back4app_server_url)) // at last we are building our // parse with the above credentials .build()); }}
Step 8: Adding the name for our App class in our AndroidManifest.xml file
Navigate to the app > AndroidManifest.xml file and inside your application tag on the first line. Add the below line of code. Along with that, we have to add metadata to our application in your Manifest file. Below is the complete code for the AndroidManifest.xml file.
XML
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.gtappdevelopers.gfgparse"> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.INTERNET" /> <application android:name=".App" 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/Theme.GFGParse"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> <!--Meta data for your file for server url--> <meta-data android:name="com.parse.SERVER_URL" android:value="@string/back4app_server_url" /> <!--Meta data for your file for application id--> <meta-data android:name="com.parse.APPLICATION_ID" android:value="@string/back4app_app_id" /> <!--Meta data for your file for client key--> <meta-data android:name="com.parse.CLIENT_KEY" android:value="@string/back4app_client_key" /> </manifest>
Step 9: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.os.Bundle;import android.widget.TextView;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.parse.ParseObject; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // creating and initializing variable for our text view. TextView textView = findViewById(R.id.textView); // creating a variable for parse object and setting name as First Class. ParseObject firstObject = new ParseObject("FirstClass"); // on below line we are passing the message as key and value to our object. firstObject.put("message", "Hey ! Welcome to Geeks for Geeks. Parse is now connected"); // on below line we are calling a // method to save in background. firstObject.saveInBackground(e -> { // checking if the error is null or not. if (e != null) { // displaying error toast message on failure. Toast.makeText(this, "Fail to add data.." + e.getLocalizedMessage(), Toast.LENGTH_SHORT).show(); } else { // if the data is send successfully we are displaying that data in our text view on below line. // as we are passing our key as message so we are calling our data with the key. textView.setText(String.format("Data saved is : \n %s", firstObject.get("message"))); } }); }}
Now run your app and see the output of the app. Make sure you have added all the keys inside your strings.xml file. After running your app you can see the data has been added to the back4app server which is shown in the below screenshot.
Output:
Check out the project on the below link: https://github.com/ChaitanyaMunje/GFG-Back4App
Android
Java
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Resource Raw Folder in Android Studio
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
Retrofit with Kotlin Coroutine in Android
How to Post Data to API using Retrofit in Android?
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Object Oriented Programming (OOPs) Concept in Java
Arrays.sort() in Java with examples | [
{
"code": null,
"e": 26381,
"s": 26353,
"text": "\n12 Mar, 2021"
},
{
"code": null,
"e": 26847,
"s": 26381,
"text": "Back4App is another famous backend platform that provides backend services for different types of applications whether it may be web, android, or IOS devices. Back... |
HTML5 | date attribute in <input> Tag - GeeksforGeeks | 03 Dec, 2018
The date attribute in input tag creates a calendar to choose the date, which includes day, month and year.
Syntax:
<input type = "date">
Example 1: Use date attribute in input tag
<!DOCTYPE html><html> <head> <title>Date Attribute</title> </head> <body> <form action="/"> Date of Birth: <input type = "date"> </form> </body></html>
Output:
Example 2: Initializing the default date value in input tag. The date format is value = “yyyy-mm-dd” in input tag
<html> <head> <title>Date Attribute</title> </head> <body> <form action="/"> Date of Birth: <input type="date" value="2018-10-19"> </form> </body></html>
Output:
Example 3: DOM for date attribute
<!DOCTYPE html><html> <head> <title>Date Attribute</title> </head> <body> Date of Birth: <input type="date" id="dob"> <button onclick="dateDisplay()">Submit</button> <p id="demo"></p> <script> function dateDisplay() { var x = document.getElementById("dob").value; document.getElementById("demo").innerHTML = x; } </script> </body></html>
Output:
Output in the phone:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
HTML-Attributes
Technical Scripter 2018
CSS
HTML
JavaScript
Technical Scripter
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to create footer to stay at the bottom of a Web page?
How to apply style to parent if it has child with CSS?
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property | [
{
"code": null,
"e": 24622,
"s": 24594,
"text": "\n03 Dec, 2018"
},
{
"code": null,
"e": 24729,
"s": 24622,
"text": "The date attribute in input tag creates a calendar to choose the date, which includes day, month and year."
},
{
"code": null,
"e": 24737,
"s": 247... |
Programming For Beginners: 10 Best HTML Coding Practices You Must Know - GeeksforGeeks | 01 Dec, 2021
HTML...One of the easiest things to learn is programming. Most of the newbies and even kids step into programming picking up HTML. They learn, they build some web pages but a lot of developers even experienced one make some silly mistake while writing the code for frontend. Making these silly mistakes not only annoys other developers (when they need to make some changes) but also hurts your main site and drives the end-user away. We are going to mention some common and best practices which you should follow to write a clean and clear HTML code.
Following some common practices makes debugging easier and saves a lot of time. It also helps in search engine optimization as well.
HTML has nature that it will still render your markup correctly even if you forget to mention some elements such as <html>, <head>, <body> and <!DOCTYPE html>. You will see the correct result in your browser as you want but that doesn’t mean you will find the same result in every browser. To avoid this issue it’s a good habit to follow a proper document structure with the correct doctype. Doctype is the first thing to mention in an HTML document. You can choose the right doctype from the link https://www.w3.org/wiki/Doctypes_and_markup_styles
Example:
HTML
<!DOCTYPE html><html> <head> <title>Hello World</title> </head> <body> <h1>Welcome Programmers</h1> <p>This website is GeeksforGeeks.</p> </body></html>
To avoid validation and compatibility issue don’t forget to close all the tags in your code. Today most of the text editors come up with features that close the HTML tags automatically still, it’s a good practice(and definitely for final check) to make sure that you don’t miss any parent or nested tag that is not closed. In HTML5 it’s optional to close HTML tags but according to W3C specification, you should close all the HTML tags to avoid any validation error in the future.
Make a habit to use lowercase for all the tags, attributes, and values in HTML code. It is an industry-standard practice and it also makes your code much more readable. Capitalizing the tags won’t affect the result in your browser but it’s a good practice to write elements in lowercase. Writing your code in lowercase is easy and it also looks cleaner.
Example:
HTML
<!-- Bad code--><SECTION> <p>This is a paragraph.</p> </SECTION> <!-- Good code--><section> <p>This is a paragraph.</p> </section>
When you add an image in your HTML code don’t forget to add alt attribute for validation and accessibility reasons. Also, make sure that you choose the right description for the alt attribute. Search engines rank your page lower as a result when you don’t mention alt attributes with an image. It’s also good to mention the height and width of the image. It reduces flickering because the browser can reserve space for the image before loading.
Example:
HTML
<!-- Bad Code--><img src="html5.gif"> <!-- Good Code--><img src="html5.gif"><img src="html5.gif" alt="HTML5" style="width:100px;height:100px">
A lot of newbies make this mistake that they add inline-style in HTML tags. It makes your code complicated and difficult to maintain. Make a habit to keep your styles separate from HTML mark-up. Using inline styles can create so many problems. It makes your code cluttered, unreadable, and hard to update or maintain. Separating HTML with CSS also helps other developers to make changes in code very easily.
Example:
HTML
<!-- Bad Code --><p style="color: #393; font-size: 24px;">Thank you!</p> <!-- Good Code --><p class="alert-success">Thank you!</p>
HTML title really matters a lot when it comes to search engine optimization or ranking of your page. Always try to make your title as meaningful as possible. The title of your HTML page appears in the google search engine result page and the indexing of your site relies on it. A meta description tells the user what the page is all about, so make it descriptive that clearly specifies the purpose of your website or page. Avoid using repeated words and phrases. When a user types some keyword in the search engine bar that keyword is picked up by the search engine spiders and then it is used to find the relevant page for users based on the matching keyword used in meta tags.
Example:
HTML
<meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/><meta name="description" content="A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions."/><link rel="shortcut icon" href="https://www.geeksforgeeks.org/favicon.ico" type="image/x-icon"/><link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"/><meta name="theme-color" content="#0f9d58" /> <meta property="og:image" content="https://www.geeksforgeeks.org/wp-content/uploads/gfg_200X200.png"/><meta property="og:image:type" content="image/png" /><meta property="og:image:width" content="200" /><meta property="og:image:height" content="200" /><script src="https://apis.google.com/js/platform.js"></script><script src="//cdnjs.cloudflare.com/ajax/libs/require.js/2.1.14/require.min.js"></script> <title>GeeksforGeeks | A computer science portal for geeks</title>
Heading tags also play a crucial role in making your website search engine-friendly. HTML has 6 different types of heading tags that should be used carefully. Learn to use <h1> to <h6> elements to denote your HTML’s content hierarchy also make sure that you use only one h1 per page. In W3C specs it is mentioned that your page content should be described by a single tag so you can add your most important text within h1 such as article title or blog post.
Example:
HTML
<h1>Topmost heading</h1><h2>Sub-heading underneath the topmost heading.</h2><h3>Sub-heading underneath the h2 heading.</h3>
A lot of beginners make a common mistake using the wrong HTML elements. They need to learn with time which element should be used where. We recommend you learn about all the HTML elements and use them correctly for a meaningful content structure. For example instead of using <br> between two paragraphs you can use CSS margin and/or padding properties. Learn when to use <em> and when to use <i> (both looks the same), learn when to use <b> and when to use <strong> (both looks the same). It comes with practice and when you keep your eyes on good code written by other developers. Another good example is given below.
HTML
<!-- Bad Code --><span class="heading"><strong>Hello Geeks</span></strong><br><br>This is Computer Science portal for geeks.<br><br> <!-- Good Code --><h1>Hello Geeks</h1> <p>This is Computer Science portal for geeks.</p>
it is important to give proper space or indentation in your HTML code to make it more readable and manageable. Avoid writing everything in one line. It makes your code cluttered and flat. When you use the nested element give proper indentation so that users can identify the beginning and end of the tag. A code that follows proper formatting is easy to change and looks nice to other developers. It’s a good coding practice that reduces development time as well.
HTML
<!-- Bad Code --><aside><h3>GeeksforGeeks</h3><h5>A computer science portal for geeks</h5><ul><li>Computer Science</li><li>Gate</li></ul></aside> <!-- Good Code --><aside> <h3>GeeksforGeeks</h3> <h5>A computer science portal for geeks</h5> <ul> <li>Computer Science</li> <li>Gate</li> </ul></aside>
Last but not least make a habit to validate your HTML code frequently. Validating your code is a great piece of work and helps in finding difficult issues. You can download the W3C markup validation or Firefox developers toolbar to validate your site by URL. Validators are very helpful in detecting errors and resolving them.
bunnyram19
punamsingh628700
GBlog
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
GET and POST requests using Python
Types of Software Testing
Working with csv files in Python
How to Start Learning DSA?
How to insert spaces/tabs in text using HTML/CSS?
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
How to set input type date in dd-mm-yyyy format using HTML ? | [
{
"code": null,
"e": 25795,
"s": 25767,
"text": "\n01 Dec, 2021"
},
{
"code": null,
"e": 26348,
"s": 25795,
"text": "HTML...One of the easiest things to learn is programming. Most of the newbies and even kids step into programming picking up HTML. They learn, they build some web ... |
Write a program to reverse digits of a number - GeeksforGeeks | 06 May, 2022
Write a program to reverse the digits of an integer.
Examples :
Input : num = 12345
Output: 54321
Input : num = 876
Output: 678
Flowchart:
ITERATIVE WAY
Algorithm:
Input: num
(1) Initialize rev_num = 0
(2) Loop while num > 0
(a) Multiply rev_num by 10 and add remainder of num
divide by 10 to rev_num
rev_num = rev_num*10 + num%10;
(b) Divide num by 10
(3) Return rev_num
Example:
num = 4562 rev_num = 0rev_num = rev_num *10 + num%10 = 2 num = num/10 = 456rev_num = rev_num *10 + num%10 = 20 + 6 = 26 num = num/10 = 45rev_num = rev_num *10 + num%10 = 260 + 5 = 265 num = num/10 = 4rev_num = rev_num *10 + num%10 = 2650 + 4 = 2654 num = num/10 = 0
Program:
C++
C
Java
Python
C#
PHP
Javascript
#include <bits/stdc++.h> using namespace std;/* Iterative function to reverse digits of num*/int reverseDigits(int num){ int rev_num = 0; while (num > 0) { rev_num = rev_num * 10 + num % 10; num = num / 10; } return rev_num;} /*Driver program to test reverseDigits*/int main(){ int num = 4562; cout << "Reverse of no. is " << reverseDigits(num); getchar(); return 0;} // This code is contributed// by Akanksha Rai(Abby_akku)
#include <stdio.h> /* Iterative function to reverse digits of num*/int reverseDigits(int num){ int rev_num = 0; while (num > 0) { rev_num = rev_num * 10 + num % 10; num = num / 10; } return rev_num;} /*Driver program to test reverseDigits*/int main(){ int num = 4562; printf("Reverse of no. is %d", reverseDigits(num)); getchar(); return 0;}
// Java program to reverse a number class GFG { /* Iterative function to reverse digits of num*/ static int reverseDigits(int num) { int rev_num = 0; while (num > 0) { rev_num = rev_num * 10 + num % 10; num = num / 10; } return rev_num; } // Driver code public static void main(String[] args) { int num = 4562; System.out.println("Reverse of no. is " + reverseDigits(num)); }} // This code is contributed by Anant Agarwal.
# Python program to reverse a number n = 4562rev = 0 while(n > 0): a = n % 10 rev = rev * 10 + a n = n // 10 print(rev) # This code is contributed by Shariq Raza
// C# program to reverse a numberusing System; class GFG { // Iterative function to // reverse digits of num static int reverseDigits(int num) { int rev_num = 0; while (num > 0) { rev_num = rev_num * 10 + num % 10; num = num / 10; } return rev_num; } // Driver code public static void Main() { int num = 4562; Console.Write("Reverse of no. is " + reverseDigits(num)); }} // This code is contributed by Sam007
<?php// Iterative function to // reverse digits of numfunction reverseDigits($num){ $rev_num = 0; while($num > 1) { $rev_num = $rev_num * 10 + $num % 10; $num = (int)$num / 10; } return $rev_num;} // Driver Code$num = 4562;echo "Reverse of no. is ", reverseDigits($num); // This code is contributed by aj_36?>
<script> let num = 4562; // Function to reverse digits of num function reverseDigits(num) { let rev_num = 0; while(num > 0) { rev_num = rev_num * 10 + num % 10; num = Math.floor(num / 10); } return rev_num; } // function call document.write(reverseDigits(num)); // This code is contributed by Surbhi tyagi </script>
Reverse of no. is 2654
Time Complexity: O(log(n)), where n is the input number.
Auxiliary Space: O(1)
RECURSIVE WAY :
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to reverse digits of a number#include <bits/stdc++.h>using namespace std;/* Recursive function to reverse digits of num*/int reverseDigits(int num){ static int rev_num = 0; static int base_pos = 1; if (num > 0) { reverseDigits(num / 10); rev_num += (num % 10) * base_pos; base_pos *= 10; } return rev_num;} // Driver Codeint main(){ int num = 4562; cout << "Reverse of no. is " << reverseDigits(num); return 0;} // This code is contributed// by Akanksha Rai(Abby_akku)
// C program to reverse digits of a number#include <stdio.h>; /* Recursive function to reverse digits of num*/int reversDigits(int num){ static int rev_num = 0; static int base_pos = 1; if (num > 0) { reversDigits(num / 10); rev_num += (num % 10) * base_pos; base_pos *= 10; } return rev_num;} /*Driver program to test reverse Digits*/int main(){ int num = 4562; printf("Reverse of no. is %d", reversDigits(num)); getchar(); return 0;}
// Java program to reverse digits of a number // Recursive function to// reverse digits of numclass GFG { static int rev_num = 0; static int base_pos = 1; static int reversDigits(int num) { if (num > 0) { reversDigits(num / 10); rev_num += (num % 10) * base_pos; base_pos *= 10; } return rev_num; } // Driver Code public static void main(String[] args) { int num = 4562; System.out.println(reversDigits(num)); }} // This code is contributed by mits
# Python 3 program to reverse digits# of a numberrev_num = 0base_pos = 1 # Recursive function to reverse# digits of num def reversDigits(num): global rev_num global base_pos if(num > 0): reversDigits((int)(num / 10)) rev_num += (num % 10) * base_pos base_pos *= 10 return rev_num # Driver Codenum = 4562print("Reverse of no. is ", reversDigits(num)) # This code is contributed by Rajput-Ji
// C# program to reverse digits of a number // Recursive function to// reverse digits of numusing System;class GFG { static int rev_num = 0; static int base_pos = 1; static int reversDigits(int num) { if (num > 0) { reversDigits(num / 10); rev_num += (num % 10) * base_pos; base_pos *= 10; } return rev_num; } // Driver Code public static void Main() { int num = 4562; Console.WriteLine(reversDigits(num)); }} // This code is contributed// by inder_verma
<?php// PHP program to reverse digits of a number$rev_num = 0; $base_pos = 1; /* Recursive function to reverse digits of num*/function reversDigits($num) { global $rev_num; global $base_pos; if($num > 0) { reversDigits((int)($num / 10)); $rev_num += ($num % 10) * $base_pos; $base_pos *= 10; } return $rev_num; } // Driver Code$num = 4562; echo "Reverse of no. is ", reversDigits($num); // This code is contributed by ajit?>
<script> // Javascript program to reverse digits of a number /* Recursive function to reverse digits of num*/var rev_num = 0;var base_pos = 1;function reversDigits(num){ if(num > 0) { reversDigits(Math.floor(num/10)); rev_num += (num%10)*base_pos; base_pos *= 10; } return rev_num;} // Driver Code let num = 4562; document.write("Reverse of no. is " + reversDigits(num)); // This code is contributed // by Mayank Tyagi </script>
Reverse of no. is 2654
Time Complexity: O(log(n))
Auxiliary Space: O(log(n)), where n is the input number.
Using String in java
We will convert the number to a string using StringBuffer after this, we will reverse that string using the reverse() method
corner case
Input: 32100
So for the above input if we try to solve this by reversing the string, then the output will be 00123.
So to deal with this situation we again need to convert the string to integer so that our output will be 123
C++
Java
Python3
C#
Javascript
// C++ program to reverse a number#include <bits/stdc++.h>using namespace std; int reverseDigits(int num){ // converting number to string string strin = to_string(num); // reversing the string reverse(strin.begin(), strin.end()); // converting string to integer num = stoi(strin); // returning integer return num;}int main(){ int num = 4562; cout << "Reverse of no. is " << reverseDigits(num); return 0;} // This Code is contributed by ShubhamSingh10
// Java program to reverse a number public class GFG { static int reversDigits(int num) { // converting number to string StringBuffer string = new StringBuffer(String.valueOf(num)); // reversing the string string.reverse(); // converting string to integer num = Integer.parseInt(String.valueOf(string)); // returning integer return num; } public static void main(String[] args) { int num = 4562; System.out.println("Reverse of no. is " + reversDigits(num)); }}
# Python 3 program to reverse a number def reversDigits(num): # converting number to string string = str(num) # reversing the string string = list(string) string.reverse() string = ''.join(string) # converting string to integer num = int(string) # returning integer return num # Driver codeif __name__ == "__main__": num = 4562 print("Reverse of no. is ", reversDigits(num)) # This code is contributed by ukasp.
// C# program to reverse a numberusing System; public class GFG{ public static string ReverseString(string s) { char[] array = s.ToCharArray(); Array.Reverse(array); return new string(array); } static int reversDigits(int num) { // converting number to string string strin = num.ToString(); // reversing the string strin = ReverseString(strin); // converting string to integer num = int.Parse(strin); // returning integer return num; } // Driver code static public void Main () { int num = 4562; Console.Write("Reverse of no. is " + reversDigits(num)); }} // This Code is contributed by ShubhamSingh10
<script> // Javascript program to reverse a number function reversDigits(num) { // converting number to string let str = num.toString().split("").reverse().join(""); // converting string to integer num = parseInt(str); // returning integer return str; } // Driver Code let num = 4562; document.write("Reverse of no. is " + reversDigits(num)); </script>
Reverse of no. is 2654
Time Complexity: O(log10n) where n is the input number
Auxiliary Space: O(1)
Reverse digits of an integer with overflow handled
Note that the above program doesn’t consider leading zeroes. For example, for 100 programs will print 1. If you want to print 001 then see this comment from Maheshwar.
Try extensions of above functions that should also work for floating-point numbers.
jit_t
Mithun Kumar
inderDuMCA
Akanksha_Rai
Rajput-Ji
RishabhPrabhu
MadhusudhanGupta
manish kumar 77
surbhityagi15
mayanktyagi1709
le0
ukasp
susmitakundugoaldanga
SHUBHAMSINGH10
souravmahato348
subhammahato348
arorakashish0911
rkbhola5
prophet1999
simranarora5sos
MakeMyTrip
MAQ Software
Modular Arithmetic
number-digits
Mathematical
Recursion
MakeMyTrip
MAQ Software
Mathematical
Recursion
Modular Arithmetic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Prime Numbers
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": 26983,
"s": 26955,
"text": "\n06 May, 2022"
},
{
"code": null,
"e": 27036,
"s": 26983,
"text": "Write a program to reverse the digits of an integer."
},
{
"code": null,
"e": 27049,
"s": 27036,
"text": "Examples : "
},
{
"code": nu... |
Maximum Manhattan distance between a distinct pair from N coordinates - GeeksforGeeks | 27 Apr, 2022
Given an array arr[] consisting of N integer coordinates, the task is to find the maximum Manhattan Distance between any two distinct pairs of coordinates.
The Manhattan Distance between two points (X1, Y1) and (X2, Y2) is given by |X1 – X2| + |Y1 – Y2|.
Examples:
Input: arr[] = {(1, 2), (2, 3), (3, 4)}Output: 4Explanation:The maximum Manhattan distance is found between (1, 2) and (3, 4) i.e., |3 – 1| + |4- 2 | = 4.
Input: arr[] = {(-1, 2), (-4, 6), (3, -4), (-2, -4)}Output: 17Explanation:The maximum Manhattan distance is found between (-4, 6) and (3, -4) i.e., |-4 – 3| + |6 – (-4)| = 17.
Naive Approach: The simplest approach is to iterate over the array, and for each coordinate, calculate its Manhattan distance from all remaining points. Keep updating the maximum distance obtained after each calculation. Finally, print the maximum distance obtained.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to calculate the maximum// Manhattan distancevoid MaxDist(vector<pair<int, int> >& A, int N){ // Stores the maximum distance int maximum = INT_MIN; for (int i = 0; i < N; i++) { int sum = 0; for (int j = i + 1; j < N; j++) { // Find Manhattan distance // using the formula // |x1 - x2| + |y1 - y2| sum = abs(A[i].first - A[j].first) + abs(A[i].second - A[j].second); // Updating the maximum maximum = max(maximum, sum); } } cout << maximum;} // Driver Codeint main(){ int N = 3; // Given Co-ordinates vector<pair<int, int> > A = { { 1, 2 }, { 2, 3 }, { 3, 4 } }; // Function Call MaxDist(A, N); return 0;}
// Java program for the above approachimport java.io.*;import java.util.*; class GFG { // Pair class public static class Pair { int x; int y; Pair(int x, int y) { this.x = x; this.y = y; } } // Function to calculate the maximum // Manhattan distance static void MaxDist(ArrayList<Pair> A, int N) { // Stores the maximum distance int maximum = Integer.MIN_VALUE; for (int i = 0; i < N; i++) { int sum = 0; for (int j = i + 1; j < N; j++) { // Find Manhattan distance // using the formula // |x1 - x2| + |y1 - y2| sum = Math.abs(A.get(i).x - A.get(j).x) + Math.abs(A.get(i).y - A.get(j).y); // Updating the maximum maximum = Math.max(maximum, sum); } } System.out.println(maximum); } // Driver Code public static void main(String[] args) { int n = 3; ArrayList<Pair> al = new ArrayList<>(); // Given Co-ordinates Pair p1 = new Pair(1, 2); al.add(p1); Pair p2 = new Pair(2, 3); al.add(p2); Pair p3 = new Pair(3, 4); al.add(p3); // Function call MaxDist(al, n); }} // This code is contributed by bikram2001jha
# Python3 program for the above approachimport sys # Function to calculate the maximum# Manhattan distance def MaxDist(A, N): # Stores the maximum distance maximum = - sys.maxsize for i in range(N): sum = 0 for j in range(i + 1, N): # Find Manhattan distance # using the formula # |x1 - x2| + |y1 - y2| Sum = (abs(A[i][0] - A[j][0]) + abs(A[i][1] - A[j][1])) # Updating the maximum maximum = max(maximum, Sum) print(maximum) # Driver codeN = 3 # Given co-ordinatesA = [[1, 2], [2, 3], [3, 4]] # Function callMaxDist(A, N) # This code is contributed by divyeshrabadiya07
// C# program for the above approachusing System;using System.Collections.Generic; class GFG { // Pair class public class Pair { public int x; public int y; public Pair(int x, int y) { this.x = x; this.y = y; } } // Function to calculate the maximum // Manhattan distance static void MaxDist(List<Pair> A, int N) { // Stores the maximum distance int maximum = int.MinValue; for (int i = 0; i < N; i++) { int sum = 0; for (int j = i + 1; j < N; j++) { // Find Manhattan distance // using the formula // |x1 - x2| + |y1 - y2| sum = Math.Abs(A[i].x - A[j].x) + Math.Abs(A[i].y - A[j].y); // Updating the maximum maximum = Math.Max(maximum, sum); } } Console.WriteLine(maximum); } // Driver Code public static void Main(String[] args) { int n = 3; List<Pair> al = new List<Pair>(); // Given Co-ordinates Pair p1 = new Pair(1, 2); al.Add(p1); Pair p2 = new Pair(2, 3); al.Add(p2); Pair p3 = new Pair(3, 4); al.Add(p3); // Function call MaxDist(al, n); }} // This code is contributed by Amit Katiyar
<script> // JavaScript program for the above approach // Function to calculate the maximum// Manhattan distancefunction MaxDist(A, N){ // Stores the maximum distance let maximum = Number.MIN_VALUE for(let i = 0; i < N; i++) { let Sum = 0 for(let j = i + 1; j < N; j++) { // Find Manhattan distance // using the formula // |x1 - x2| + |y1 - y2| Sum = (Math.abs(A[i][0] - A[j][0]) + Math.abs(A[i][1] - A[j][1])) // Updating the maximum maximum = Math.max(maximum, Sum) } } document.write(maximum)} // Driver codelet N = 3 // Given co-ordinateslet A = [[1, 2], [2, 3], [3, 4]] // Function callMaxDist(A, N) // This code is contributed by shinjanpatra </script>
4
Time Complexity: O(N2), where N is the size of the given array.Auxiliary Space: O(1)
Efficient Approach: The idea is to use store sums and differences between X and Y coordinates and find the answer by sorting those differences. Below are the observations to the above problem statement:
Manhattan Distance between any two points (Xi, Yi) and (Xj, Yj) can be written as follows:
|Xi – Xj| + |Yi – Yj| = max(Xi – Xj -Yi + Yj, -Xi + Xj + Yi – Yj, -Xi + Xj – Yi + Yj, Xi – Xj + Yi – Yj).
The above expression can be rearranged as:
|Xi – Xj| + |Yi – Yj| = max((Xi – Yi) – (Xj – Yj), (-Xi + Yi) – (-Xj + Yj), (-Xi – Yi) – (-Xj – Yj), (Xi + Yi) – (Xj + Yj))
It can be observed from the above expression, that the answer can be found by storing the sum and differences of the coordinates.
Follow the below steps to solve the problem:
Initialize two arrays sum[] and diff[].Store the sum of X and Y coordinates i.e., Xi + Yi in sum[] and their difference i.e., Xi – Yi in diff[].Sort the sum[] and diff[] in ascending order.The maximum of the values (sum[N-1] – sum[0]) and (diff[N-1] – diff[0]) is the required result.
Initialize two arrays sum[] and diff[].
Store the sum of X and Y coordinates i.e., Xi + Yi in sum[] and their difference i.e., Xi – Yi in diff[].
Sort the sum[] and diff[] in ascending order.
The maximum of the values (sum[N-1] – sum[0]) and (diff[N-1] – diff[0]) is the required result.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to calculate the maximum// Manhattan distancevoid MaxDist(vector<pair<int, int> >& A, int N){ // Vectors to store maximum and // minimum of all the four forms vector<int> V(N), V1(N); for (int i = 0; i < N; i++) { V[i] = A[i].first + A[i].second; V1[i] = A[i].first - A[i].second; } // Sorting both the vectors sort(V.begin(), V.end()); sort(V1.begin(), V1.end()); int maximum = max(V.back() - V.front(), V1.back() - V1.front()); cout << maximum << endl;} // Driver Codeint main(){ int N = 3; // Given Co-ordinates vector<pair<int, int> > A = { { 1, 2 }, { 2, 3 }, { 3, 4 } }; // Function Call MaxDist(A, N); return 0;}
// Java program for the above approachimport java.io.*;import java.util.*; class GFG { // Pair class public static class Pair { int x; int y; Pair(int x, int y) { this.x = x; this.y = y; } } // Function to calculate the maximum // Manhattan distance static void MaxDist(ArrayList<Pair> A, int N) { // ArrayLists to store maximum and // minimum of all the four forms ArrayList<Integer> V = new ArrayList<>(); ArrayList<Integer> V1 = new ArrayList<>(); for (int i = 0; i < N; i++) { V.add(A.get(i).x + A.get(i).y); V1.add(A.get(i).x - A.get(i).y); } // Sorting both the ArrayLists Collections.sort(V); Collections.sort(V1); int maximum = Math.max((V.get(V.size() - 1) - V.get(0)), (V1.get(V1.size() - 1) - V1.get(0))); System.out.println(maximum); } // Driver Code public static void main(String[] args) { int n = 3; ArrayList<Pair> al = new ArrayList<>(); // Given Co-ordinates Pair p1 = new Pair(1, 2); al.add(p1); Pair p2 = new Pair(2, 3); al.add(p2); Pair p3 = new Pair(3, 4); al.add(p3); // Function call MaxDist(al, n); }} // This code is contributed by bikram2001jha
# Python3 program for the above approach # Function to calculate the maximum# Manhattan distance def MaxDist(A, N): # List to store maximum and # minimum of all the four forms V = [0 for i in range(N)] V1 = [0 for i in range(N)] for i in range(N): V[i] = A[i][0] + A[i][1] V1[i] = A[i][0] - A[i][1] # Sorting both the vectors V.sort() V1.sort() maximum = max(V[-1] - V[0], V1[-1] - V1[0]) print(maximum) # Driver codeif __name__ == "__main__": N = 3 # Given Co-ordinates A = [[1, 2], [2, 3], [3, 4]] # Function call MaxDist(A, N) # This code is contributed by rutvik_56
// C# program for the above approachusing System;using System.Collections.Generic; class GFG { // Pair class class Pair { public int x; public int y; public Pair(int x, int y) { this.x = x; this.y = y; } } // Function to calculate the maximum // Manhattan distance static void MaxDist(List<Pair> A, int N) { // Lists to store maximum and // minimum of all the four forms List<int> V = new List<int>(); List<int> V1 = new List<int>(); for (int i = 0; i < N; i++) { V.Add(A[i].x + A[i].y); V1.Add(A[i].x - A[i].y); } // Sorting both the Lists V.Sort(); V1.Sort(); int maximum = Math.Max((V[V.Count - 1] - V[0]), (V1[V1.Count - 1] - V1[0])); Console.WriteLine(maximum); } // Driver Code public static void Main(String[] args) { int n = 3; List<Pair> al = new List<Pair>(); // Given Co-ordinates Pair p1 = new Pair(1, 2); al.Add(p1); Pair p2 = new Pair(2, 3); al.Add(p2); Pair p3 = new Pair(3, 4); al.Add(p3); // Function call MaxDist(al, n); }} // This code is contributed by Amit Katiyar
<script> // JavaScript program for the above approach // Function to calculate the maximum// Manhattan distancefunction MaxDist(A, N){ // List to store maximum and // minimum of all the four forms let V = new Array(N).fill(0) let V1 = new Array(N).fill(0) for(let i = 0; i < N; i++){ V[i] = A[i][0] + A[i][1] V1[i] = A[i][0] - A[i][1] } // Sorting both the vectors V.sort() V1.sort() let maximum = Math.max(V[V.length-1] - V[0], V1[V1.length-1] - V1[0]) document.write(maximum,"</br>")} // Driver codelet N = 3 // Given Co-ordinateslet A = [[1, 2], [2, 3], [3, 4]] // Function callMaxDist(A, N) // This code is contributed by shinjanpatra </script>
4
Time Complexity: O(N*log N)Auxiliary Space: O(N)
Improving the Efficient Approach: Instead of storing the sums and differences in an auxiliary array, then sorting the arrays to determine the minimum and maximums, it is possible to keep a running total of the extreme sums and differences.
C++
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to calculate the maximum// Manhattan distancevoid MaxDist(vector<pair<int, int> >& A, int N){ // Variables to track running extrema int minsum, maxsum, mindiff, maxdiff; minsum = maxsum = A[0].first + A[0].second; mindiff = maxdiff = A[0].first - A[0].second; for (int i = 1; i < N; i++) { int sum = A[i].first + A[i].second; int diff = A[i].first - A[i].second; if (sum < minsum) minsum = sum; else if (sum > maxsum) maxsum = sum; if (diff < mindiff) mindiff = diff; else if (diff > maxdiff) maxdiff = diff; } int maximum = max(maxsum - minsum, maxdiff - mindiff); cout << maximum << endl;} // Driver Codeint main(){ int N = 3; // Given Co-ordinates vector<pair<int, int> > A = { { 1, 2 }, { 2, 3 }, { 3, 4 } }; // Function Call MaxDist(A, N); return 0;}
<script> // JavaScript program for the above approach // Function to calculate the maximum// Manhattan distancefunction MaxDist(A, N){ // Variables to track running extrema let minsum, maxsum, mindiff, maxdiff; minsum = maxsum = A[0][0] + A[0][1]; mindiff = maxdiff = A[0][0] - A[0][1]; for (let i = 1; i < N; i++) { let sum = A[i][0] + A[i][1]; let diff = A[i][0] - A[i][1]; if (sum < minsum) minsum = sum; else if (sum > maxsum) maxsum = sum; if (diff < mindiff) mindiff = diff; else if (diff > maxdiff) maxdiff = diff; } let maximum = Math.max(maxsum - minsum, maxdiff - mindiff); document.write(maximum,"</br>");} // Driver Code let N = 3; // Given Co-ordinateslet A = [ [ 1, 2 ], [ 2, 3 ], [ 3, 4 ] ]; // Function CallMaxDist(A, N); // code is contributed by shinjanpatra </script>
4
Time Complexity: O(N)Auxiliary Space: O(1)
The ideas presented here are in two dimensions, but can be extended to further dimensions. Each additional dimension requires double the amount of computations on each point. For example, in 3-D space, the result is the maximum difference between the four extrema pairs computed from x+y+z, x+y-z, x-y+z, and x-y-z.
bikram2001jha
amit143katiyar
divyeshrabadiya07
rutvik_56
nandinij15
eblake
shinjanpatra
Arrays
Geometric
Mathematical
Sorting
Arrays
Mathematical
Sorting
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Linked List vs Array
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Closest Pair of Points using Divide and Conquer algorithm
How to check if a given point lies inside or outside a polygon?
Program for distance between two points on earth
How to check if two given line segments intersect?
Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping) | [
{
"code": null,
"e": 26887,
"s": 26859,
"text": "\n27 Apr, 2022"
},
{
"code": null,
"e": 27043,
"s": 26887,
"text": "Given an array arr[] consisting of N integer coordinates, the task is to find the maximum Manhattan Distance between any two distinct pairs of coordinates."
},
... |
Returning a function from a function - Python - GeeksforGeeks | 20 May, 2021
Functions in Python are first-class objects. First-class objects in a language are handled uniformly throughout. They may be stored in data structures, passed as arguments, or used in control structures.
Properties of first-class functions:
A function is an instance of the Object type.
You can store the function in a variable.
You can pass the function as a parameter to another function.
You can return the function from a function.
You can store them in data structures such as hash tables, lists, ...
Example 1: Functions without arguments
In this example, the first method is A() and the second method is B(). A() method returns the B() method that is kept as an object with name returned_function and will be used for calling the second method.
Python3
# define two methods # second method that will be returned# by first methoddef B(): print("Inside the method B.") # first method that return second methoddef A(): print("Inside the method A.") # return second method return B # form a object of first method# i.e; second methodreturned_function = A() # call second method by first methodreturned_function()
Output :
Inside the method A.
Inside the method B.
Example 2: Functions with arguments
In this example, the first method is A() and the second method is B(). Here A() method is called which returns the B() method i.e; executes both the functions.
Python3
# define two methods # second method that will be returned# by first methoddef B(st2): print("Good " + st2 + ".") # first method that return second methoddef A(st1, st2): print(st1 + " and ", end = "") # return second method return B(st2) # call first method that do two work:# 1. execute the body of first method, and# 2. execute the body of second method as# first method return the second methodA("Hello", "Morning")
Output :
Hello and Good Morning.
Example 3: Functions with lambda
In this example, the first method is A() and the second method is unnamed i.e; with lambda. A() method returns the lambda statement method that is kept as an object with the name returned_function and will be used for calling the second method.
Python3
# first method that return second methoddef A(u, v): w = u + v z = u - v # return second method without name return lambda: print(w * z) # form a object of first method# i.e; second methodreturned_function = A(5, 2) # check objectprint(returned_function) # call second method by first methodreturned_function()
Output :
<function A.<locals>.<lambda> at 0x7f65d8e17158>
21
gabaa406
Python function-programs
Python-Functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25561,
"s": 25533,
"text": "\n20 May, 2021"
},
{
"code": null,
"e": 25765,
"s": 25561,
"text": "Functions in Python are first-class objects. First-class objects in a language are handled uniformly throughout. They may be stored in data structures, passed as a... |
GFact 48 | Overloading main() in Java - GeeksforGeeks | 03 Sep, 2018
Consider the below Java program.
// A Java program with overloaded main()import java.io.*; public class Test { // Normal main() public static void main(String[] args) { System.out.println("Hi Geek (from main)"); Test.main("Geek"); } // Overloaded main methods public static void main(String arg1) { System.out.println("Hi, " + arg1); Test.main("Dear Geek","My Geek"); } public static void main(String arg1, String arg2) { System.out.println("Hi, " + arg1 + ", " + arg2); }}
Output:
Hi Geek (from main)
Hi, Geek
Hi, Dear Geek, My Geek
Important Points:The main method in Java is no extra-terrestrial method. Apart from the fact that main() is just like any other method & can be overloaded in a similar manner, JVM always looks for the method signature to launch the program.
The normal main method acts as an entry point for the JVM to start the execution of program.
We can overload the main method in Java. But the program doesn’t execute the overloaded main method when we run your program, we need to call the overloaded main method from the actual main method only.
Related Articles :Valid variants of main() in JavaOverload main in C++Can we Overload or Override static methods in java ?
This article is contributed by Himanshi Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Java-Overloading
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Reverse a string in Java
Arrays.sort() in Java with examples
Stream In Java
Interfaces in Java
How to iterate any Map in Java | [
{
"code": null,
"e": 25031,
"s": 25003,
"text": "\n03 Sep, 2018"
},
{
"code": null,
"e": 25064,
"s": 25031,
"text": "Consider the below Java program."
},
{
"code": "// A Java program with overloaded main()import java.io.*; public class Test { // Normal main() ... |
Balance a string after removing extra brackets - GeeksforGeeks | 25 May, 2021
Given a string of characters with opening and closing brackets. The task is to remove extra brackets from string and balance it.Examples:
Input: str = “gau)ra)v(ku(mar(rajput))” Output: gaurav(ku(mar(rajput)))Input: str = “1+5)+5+)6+(5+9)*9” Output: 1+5+5+6+(5+9)*9
Approach:
Start traversing from left to right.
Check if the element at current index is an opening bracket ‘(‘ then print that bracket and increment count.
Check if the element at current index is a closing bracket ‘)’ and if the count is not equal to zero then print it and decrement the count.
Check if there is any element other than brackets at the current index in the string then print it.
And in last if the count is not equal to zero then print ‘)’ equal to the number of the count to balance the string.
Below is the implementation of above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Print balanced and remove// extra brackets from stringvoid balancedString(string str){ int count = 0, i; int n = str.length(); // Maintain a count for opening brackets // Traversing string for (i = 0; i < n; i++) { // check if opening bracket if (str[i] == '(') { // print str[i] and increment count by 1 cout << str[i]; count++; } // check if closing bracket and count != 0 else if (str[i] == ')' && count != 0) { cout << str[i]; // decrement count by 1 count--; } // if str[i] not a closing brackets // print it else if (str[i] != ')') cout << str[i]; } // balanced brackets if opening brackets // are more then closing brackets if (count != 0) // print remaining closing brackets for (i = 0; i < count; i++) cout << ")";} // Driver codeint main(){ string str = "gau)ra)v(ku(mar(rajput))"; balancedString(str); return 0;}
// Java implementation of above approachclass GFG { // Print balanced and remove// extra brackets from stringpublic static void balancedString(String str){ int count = 0, i; int n = str.length(); // Maintain a count for opening brackets // Traversing string for (i = 0; i < n; i++) { // check if opening bracket if (str.charAt(i) == '(') { // print str.charAt(i) and increment count by 1 System.out.print(str.charAt(i)); count++; } // check if closing bracket and count != 0 else if (str.charAt(i) == ')' && count != 0) { System.out.print(str.charAt(i)); // decrement count by 1 count--; } // if str.charAt(i) not a closing brackets // print it else if (str.charAt(i) != ')') System.out.print(str.charAt(i)); } // balanced brackets if opening brackets // are more then closing brackets if (count != 0) // print remaining closing brackets for (i = 0; i < count; i++) System.out.print(")");} // Driver Methodpublic static void main(String args[]){ String str = "gau)ra)v(ku(mar(rajput))"; balancedString(str);}}
# Python implementation of above approach # Print balanced and remove# extra brackets from stringdef balancedString(str): count, i = 0, 0 n = len(str) # Maintain a count for opening # brackets Traversing string for i in range(n): # check if opening bracket if (str[i] == '('): # print str[i] and increment # count by 1 print(str[i], end = "") count += 1 # check if closing bracket and count != 0 elif (str[i] == ')' and count != 0): print(str[i], end = "") # decrement count by 1 count -= 1 # if str[i] not a closing brackets # print it elif (str[i] != ')'): print(str[i], end = "") # balanced brackets if opening brackets # are more then closing brackets if (count != 0): # print remaining closing brackets for i in range(count): print(")", end = "") # Driver codeif __name__ == '__main__': str = "gau)ra)v(ku(mar(rajput))" balancedString(str) # This code is contributed by 29AjayKumar
// C# implementation of above approachusing System; class GFG{ // Print balanced and remove// extra brackets from stringpublic static void balancedString(String str){ int count = 0, i; int n = str.Length; // Maintain a count for opening // brackets Traversing string for (i = 0; i < n; i++) { // check if opening bracket if (str[i] == '(') { // print str[i] and increment // count by 1 Console.Write(str[i]); count++; } // check if closing bracket // and count != 0 else if (str[i] == ')' && count != 0) { Console.Write(str[i]); // decrement count by 1 count--; } // if str[i] not a closing // brackets print it else if (str[i] != ')') Console.Write(str[i]); } // balanced brackets if opening // brackets are more then closing // brackets if (count != 0) // print remaining closing brackets for (i = 0; i < count; i++) Console.Write(")");} // Driver Codepublic static void Main(){ String str = "gau)ra)v(ku(mar(rajput))"; balancedString(str);}} // This code is contributed// by PrinciRaj1992
<?php// PHP implementation of above approach // Print balanced and remove// extra brackets from stringfunction balancedString($str){ $count = 0; $n = strlen($str); // Maintain a count for opening // brackets Traversing string for ($i = 0; $i < $n; $i++) { // check if opening bracket if ($str[$i] == '(') { // print str[i] and increment // count by 1 echo $str[$i]; $count++; } // check if closing bracket and count != 0 else if ($str[$i] == ')' && $count != 0) { echo $str[$i]; // decrement count by 1 $count--; } // if str[i] not a closing brackets // print it else if ($str[$i] != ')') echo $str[$i]; } // balanced brackets if opening brackets // are more then closing brackets if ($count != 0) // print remaining closing brackets for ($i = 0; $i < $count; $i++) echo ")";} // Driver code$str = "gau)ra)v(ku(mar(rajput))";balancedString($str); // This code is contributed// by Akanksha Rai?>
<script> // javascript implementation of above approach // Print balanced and remove// extra brackets from stringfunction balancedString( str){ var count = 0, i; var n = str.length; // Maintain a count for opening // brackets Traversing string for (i = 0; i < n; i++) { // check if opening bracket if (str[i] == '(') { // print str[i] and increment // count by 1 document.write(str[i]); count++; } // check if closing bracket // and count != 0 else if (str[i] == ')' && count != 0) { document.write(str[i]); // decrement count by 1 count--; } // if str[i] not a closing // brackets print it else if (str[i] != ')') document.write(str[i]); } // balanced brackets if opening // brackets are more then closing // brackets if (count != 0) // print remaining closing brackets for (i = 0; i < count; i++) document.write(")");} // Driver Code var str = "gau)ra)v(ku(mar(rajput))"; balancedString(str); // This code is contributed by bunnyram19.</script>
gaurav(ku(mar(rajput)))
ankit15697
princiraj1992
Akanksha_Rai
29AjayKumar
bunnyram19
Constructive Algorithms
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
Print all the duplicates in the input string
Vigenère Cipher
String class in Java | Set 1
Print all subsequences of a string
sprintf() in C
Convert character array to string in C++
How to Append a Character to a String in C
Program to count occurrence of a given character in a string
Naive algorithm for Pattern Searching | [
{
"code": null,
"e": 26097,
"s": 26069,
"text": "\n25 May, 2021"
},
{
"code": null,
"e": 26236,
"s": 26097,
"text": "Given a string of characters with opening and closing brackets. The task is to remove extra brackets from string and balance it.Examples: "
},
{
"code": nu... |
Minimum number of deletions to make a sorted sequence - GeeksforGeeks | 02 Jun, 2021
Given an array of n integers. The task is to remove or delete the minimum number of elements from the array so that when the remaining elements are placed in the same sequence order to form an increasing sorted sequence.Examples :
Input : {5, 6, 1, 7, 4}
Output : 2
Removing 1 and 4
leaves the remaining sequence order as
5 6 7 which is a sorted sequence.
Input : {30, 40, 2, 5, 1, 7, 45, 50, 8}
Output : 4
A simple solution is to remove all subsequences one by one and check if remaining set of elements are in sorted order or not. Time complexity of this solution is exponential.An efficient approach uses the concept of finding the length of the longest increasing subsequence of a given sequence.Algorithm:
-->arr be the given array.
-->n number of elements in arr.
-->len be the length of longest
increasing subsequence in arr.
-->// minimum number of deletions
min = n - len
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation to find// minimum number of deletions// to make a sorted sequence#include <bits/stdc++.h>using namespace std; /* lis() returns the length of the longest increasing subsequence in arr[] of size n */int lis( int arr[], int n ){ int result = 0; int lis[n]; /* Initialize LIS values for all indexes */ for (int i = 0; i < n; i++ ) lis[i] = 1; /* Compute optimized LIS values in bottom up manner */ for (int i = 1; i < n; i++ ) for (int j = 0; j < i; j++ ) if ( arr[i] > arr[j] && lis[i] < lis[j] + 1) lis[i] = lis[j] + 1; /* Pick resultimum of all LIS values */ for (int i = 0; i < n; i++ ) if (result < lis[i]) result = lis[i]; return result;} // function to calculate minimum// number of deletionsint minimumNumberOfDeletions(int arr[], int n){ // Find longest increasing // subsequence int len = lis(arr, n); // After removing elements // other than the lis, we // get sorted sequence. return (n - len);} // Driver Codeint main(){ int arr[] = {30, 40, 2, 5, 1, 7, 45, 50, 8}; int n = sizeof(arr) / sizeof(arr[0]); cout << "Minimum number of deletions = " << minimumNumberOfDeletions(arr, n); return 0;}
// Java implementation to find// minimum number of deletions// to make a sorted sequence class GFG{ /* lis() returns the length of the longest increasing subsequence in arr[] of size n */ static int lis( int arr[], int n ) { int result = 0; int[] lis = new int[n]; /* Initialize LIS values for all indexes */ for (int i = 0; i < n; i++ ) lis[i] = 1; /* Compute optimized LIS values in bottom up manner */ for (int i = 1; i < n; i++ ) for (int j = 0; j < i; j++ ) if ( arr[i] > arr[j] && lis[i] < lis[j] + 1) lis[i] = lis[j] + 1; /* Pick resultimum of all LIS values */ for (int i = 0; i < n; i++ ) if (result < lis[i]) result = lis[i]; return result; } // function to calculate minimum // number of deletions static int minimumNumberOfDeletions(int arr[], int n) { // Find longest // increasing subsequence int len = lis(arr, n); // After removing elements // other than the lis, we get // sorted sequence. return (n - len); } // Driver Code public static void main (String[] args) { int arr[] = {30, 40, 2, 5, 1, 7, 45, 50, 8}; int n = arr.length; System.out.println("Minimum number of" + " deletions = " + minimumNumberOfDeletions(arr, n)); }} /* This code is contributed by Harsh Agarwal */
# Python3 implementation to find# minimum number of deletions to# make a sorted sequence # lis() returns the length# of the longest increasing# subsequence in arr[] of size ndef lis(arr, n): result = 0 lis = [0 for i in range(n)] # Initialize LIS values # for all indexes for i in range(n): lis[i] = 1 # Compute optimized LIS values # in bottom up manner for i in range(1, n): for j in range(i): if ( arr[i] > arr[j] and lis[i] < lis[j] + 1): lis[i] = lis[j] + 1 # Pick resultimum # of all LIS values for i in range(n): if (result < lis[i]): result = lis[i] return result # Function to calculate minimum# number of deletionsdef minimumNumberOfDeletions(arr, n): # Find longest increasing # subsequence len = lis(arr, n) # After removing elements # other than the lis, we # get sorted sequence. return (n - len) # Driver Codearr = [30, 40, 2, 5, 1, 7, 45, 50, 8]n = len(arr)print("Minimum number of deletions = ", minimumNumberOfDeletions(arr, n)) # This code is contributed by Anant Agarwal.
// C# implementation to find// minimum number of deletions// to make a sorted sequenceusing System; class GfG{ /* lis() returns the length of the longest increasing subsequence in arr[] of size n */ static int lis( int []arr, int n ) { int result = 0; int[] lis = new int[n]; /* Initialize LIS values for all indexes */ for (int i = 0; i < n; i++ ) lis[i] = 1; /* Compute optimized LIS values in bottom up manner */ for (int i = 1; i < n; i++ ) for (int j = 0; j < i; j++ ) if ( arr[i] > arr[j] && lis[i] < lis[j] + 1) lis[i] = lis[j] + 1; /* Pick resultimum of all LIS values */ for (int i = 0; i < n; i++ ) if (result < lis[i]) result = lis[i]; return result; } // function to calculate minimum // number of deletions static int minimumNumberOfDeletions( int []arr, int n) { // Find longest increasing // subsequence int len = lis(arr, n); // After removing elements other // than the lis, we get sorted // sequence. return (n - len); } // Driver Code public static void Main (String[] args) { int []arr = {30, 40, 2, 5, 1, 7, 45, 50, 8}; int n = arr.Length; Console.Write("Minimum number of" + " deletions = " + minimumNumberOfDeletions(arr, n)); }} // This code is contributed by parashar.
<?php// PHP implementation to find// minimum number of deletions// to make a sorted sequence /* lis() returns the length of the longest increasing subsequence in arr[] of size n */function lis( $arr, $n ){ $result = 0; $lis[$n] = 0; /* Initialize LIS values for all indexes */ for ($i = 0; $i < $n; $i++ ) $lis[$i] = 1; /* Compute optimized LIS values in bottom up manner */ for ($i = 1; $i < $n; $i++ ) for ($j = 0; $j < $i; $j++ ) if ( $arr[$i] > $arr[$j] && $lis[$i] < $lis[$j] + 1) $lis[$i] = $lis[$j] + 1; /* Pick resultimum of all LIS values */ for ($i = 0; $i < $n; $i++ ) if ($result < $lis[$i]) $result = $lis[$i]; return $result;} // function to calculate minimum// number of deletionsfunction minimumNumberOfDeletions($arr, $n){ // Find longest increasing // subsequence $len = lis($arr, $n); // After removing elements // other than the lis, we // get sorted sequence. return ($n - $len);} // Driver Code$arr = array(30, 40, 2, 5, 1, 7, 45, 50, 8);$n = sizeof($arr) / sizeof($arr[0]);echo "Minimum number of deletions = " , minimumNumberOfDeletions($arr, $n); // This code is contributed by nitin mittal.?>
<script>// javascript implementation to find// minimum number of deletions// to make a sorted sequence/* lis() returns the lengthof the longest increasingsubsequence in arr[] of size n */function lis(arr,n){ let result = 0; let lis= new Array(n); /* Initialize LIS values for all indexes */ for (let i = 0; i < n; i++ ) lis[i] = 1; /* Compute optimized LIS values in bottom up manner */ for (let i = 1; i < n; i++ ) for (let j = 0; j < i; j++ ) if ( arr[i] > arr[j] && lis[i] < lis[j] + 1) lis[i] = lis[j] + 1; /* Pick resultimum of all LIS values */ for (let i = 0; i < n; i++ ) if (result < lis[i]) result = lis[i]; return result;} // function to calculate minimum// number of deletionsfunction minimumNumberOfDeletions(arr,n){ // Find longest increasing // subsequence let len = lis(arr,n); // After removing elements // other than the lis, we // get sorted sequence. return (n - len);} let arr = [30, 40, 2, 5, 1,7, 45, 50, 8]; let n = arr.length; document.write("Minimum number of deletions = " + minimumNumberOfDeletions(arr,n)); // This code is contributed by vaibhavrabadiya117.</script>
Output :
Minimum number of deletions = 4
Time Complexity : O(n2)Time Complexity can be decreased to O(nlogn) by finding the Longest Increasing Subsequence Size(N Log N)This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
parashar
nitin mittal
vaibhavrabadiya117
LIS
Dynamic Programming
Dynamic Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bellman–Ford Algorithm | DP-23
Floyd Warshall Algorithm | DP-16
Subset Sum Problem | DP-25
Coin Change | DP-7
Matrix Chain Multiplication | DP-8
Longest Palindromic Substring | Set 1
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Edit Distance | DP-5
Sieve of Eratosthenes
Overlapping Subproblems Property in Dynamic Programming | DP-1 | [
{
"code": null,
"e": 26673,
"s": 26645,
"text": "\n02 Jun, 2021"
},
{
"code": null,
"e": 26906,
"s": 26673,
"text": "Given an array of n integers. The task is to remove or delete the minimum number of elements from the array so that when the remaining elements are placed in the s... |
How to make grid items auto height using tailwind CSS ? - GeeksforGeeks | 14 Jun, 2021
You can easily make CSS grid items to auto height using grid-template-columns property in Tailwind CSS.
Tailwind uses grid-col and grid-row property which is an alternative to the grid-template-columns property in CSS. The grid-template-columns property in CSS is used to set the number of columns and size of the columns of the grid.
This class accepts more than one value in tailwind CSS all the properties are covered as in class form. The number of columns is set by the number of values given to this class.
Grid Template Columns:
grid-cols-1: Each row concedes only one column.
grid-cols-6: Each row concedes six columns.
grid-cols-12: Each row concedes twelve columns.
Syntax:
<element class="grid grid-cols-number"> Contents... </element>
Example 1:
HTML
<!DOCTYPE html><html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet" /></head> <body class="text-center"> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <div class="grid grid-cols-2"> <div class="bg-pink-500 m-3">GEEKSFORGEEKs</div> <div class="bg-green-500 m-3">Courses</div> <div class="px-1 bg-green-500 m-3"> <ol> <li>Data Structure</li> <li>Competitive Programming</li> </ol> </div> <div class="px-1 bg-pink-500 m-3"> Web Development </div> <div class="px-1 bg-pink-500 m-3"> Machine Learning </div> <div class="px-1 bg-green-500 m-3"> <ul> <li>ReactJs</li> <li>Angular</li> <li>Vue</li> </ul> </div> </div></body> </html>
Output:
Note: From the above output, you can observe that each row has a different height depending on max-height required by a grid of a particular row.
Example 2:
HTML
<!DOCTYPE html><html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet" /></head> <body class="text-center"> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <div class="grid grid-cols-3"> <div class="h-40 w-40 bg-green-400 m-3">1) ROW-1</div> <div class="h-50 w-40 bg-green-400 m-3">2) ROW-1</div> <div class="h-60 w-40 bg-green-400 m-3">3) ROW-1</div> <div class="h-80 w-40 bg-blue-400 m-3">1) ROW-2</div> <div class="h-40 w-40 bg-blue-400 m-3">1) ROW-2</div> <div class="h-20 w-40 bg-blue-400 m-3">1) ROW-2</div> <div class="h-40 w-40 bg-red-400 m-3">1) ROW-3</div> <div class="h-40 w-40 bg-pink-500 m-3">2) ROW-3</div> <div class="h-40 w-40 bg-pink-500 m-3">3) ROW-3</div> </div></body> </html>
Output:
Tailwind CSS
Tailwind CSS-Questions
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a web page using HTML and CSS
How to set space between the flexbox ?
Form validation using jQuery
Search Bar using HTML, CSS and JavaScript
How to style a checkbox using CSS?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 26621,
"s": 26593,
"text": "\n14 Jun, 2021"
},
{
"code": null,
"e": 26726,
"s": 26621,
"text": "You can easily make CSS grid items to auto height using grid-template-columns property in Tailwind CSS. "
},
{
"code": null,
"e": 26957,
"s": 26726... |
Find minimum number of currency notes and values that sum to given amount - GeeksforGeeks | 13 May, 2022
Given an amount, find the minimum number of notes of different denominations that sum upto the given amount. Starting from the highest denomination note, try to accommodate as many notes possible for given amount.We may assume that we have infinite supply of notes of values {2000, 500, 200, 100, 50, 20, 10, 5, 1} Examples:
Input : 800
Output : Currency Count
500 : 1
200 : 1
100 : 1
Input : 2456
Output : Currency Count
2000 : 1
200 : 2
50 : 1
5 : 1
1 : 1
This problem is a simple variation of coin change problem. Here Greedy approach works as given system is canonical (Please refer this and this for details)Below is the program implementation to find number of notes:
C++
Python3
Java
C#
PHP
Javascript
// C++ program to accept an amount// and count number of notes#include <bits/stdc++.h>using namespace std; // function to count and// print currency notesvoid countCurrency(int amount){ int notes[9] = { 2000, 500, 200, 100, 50, 20, 10, 5, 1 }; int noteCounter[9] = { 0 }; // count notes using Greedy approach for (int i = 0; i < 9; i++) { if (amount >= notes[i]) { noteCounter[i] = amount / notes[i]; amount = amount - noteCounter[i] * notes[i]; } } // Print notes cout << "Currency Count ->" << endl; for (int i = 0; i < 9; i++) { if (noteCounter[i] != 0) { cout << notes[i] << " : " << noteCounter[i] << endl; } }} // Driver functionint main(){ int amount = 868; countCurrency(amount); return 0;}
# Python3 program to accept an amount# and count number of notes # Function to count and print# currency notesdef countCurrency(amount): notes = [2000, 500, 200, 100, 50, 20, 10, 5, 1] noteCounter = [0, 0, 0, 0, 0, 0, 0, 0, 0] print ("Currency Count -> ") for i, j in zip(notes, noteCounter): if amount >= i: j = amount // i amount = amount - j * i print (i ," : ", j) # Driver codeamount = 868countCurrency(amount)
// Java program to accept an amount// and count number of notesimport java.util.*;import java.lang.*; public class GfG{ // function to count and // print currency notes public static void countCurrency(int amount) { int[] notes = new int[]{ 2000, 500, 200, 100, 50, 20, 10, 5, 1 }; int[] noteCounter = new int[9]; // count notes using Greedy approach for (int i = 0; i < 9; i++) { if (amount >= notes[i]) { noteCounter[i] = amount / notes[i]; amount = amount - noteCounter[i] * notes[i]; } } // Print notes System.out.println("Currency Count ->"); for (int i = 0; i < 9; i++) { if (noteCounter[i] != 0) { System.out.println(notes[i] + " : " + noteCounter[i]); } } } // driver function public static void main(String argc[]){ int amount = 868; countCurrency(amount); } /* This code is contributed by Sagar Shukla */}
// C# program to accept an amount// and count number of notesusing System; public class GfG{ // function to count and // print currency notes public static void countCurrency(int amount) { int[] notes = new int[]{ 2000, 500, 200, 100, 50, 20, 10, 5, 1 }; int[] noteCounter = new int[9]; // count notes using Greedy approach for (int i = 0; i < 9; i++) { if (amount >= notes[i]) { noteCounter[i] = amount / notes[i]; amount = amount - noteCounter[i] * notes[i]; } } // Print notes Console.WriteLine("Currency Count ->"); for (int i = 0; i < 9; i++) { if (noteCounter[i] != 0) { Console.WriteLine(notes[i] + " : " + noteCounter[i]); } } } // Driver function public static void Main(){ int amount = 868; countCurrency(amount); } } /* This code is contributed by vt_m */
<?php// PHP program to accept an amount// and count number of notes // function to count and// print currency notesfunction countCurrency($amount){ $notes = array(2000, 500, 200, 100, 50, 20, 10, 5, 1); $noteCounter = array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0); // count notes using // Greedy approach for ($i = 0; $i < 9; $i++) { if ($amount >= $notes[$i]) { $noteCounter[$i] = intval($amount / $notes[$i]); $amount = $amount - $noteCounter[$i] * $notes[$i]; } } // Print notes echo ("Currency Count ->"."\n"); for ($i = 0; $i < 9; $i++) { if ($noteCounter[$i] != 0) { echo ($notes[$i] . " : " . $noteCounter[$i] . "\n"); } }} // Driver Code$amount = 868;countCurrency($amount); // This code is contributed by// Manish Shaw(manishshaw1)?>
<script> // Javascript program to accept an amount// and count number of notes // function to count and // print currency notes function countCurrency(amount) { let notes = [ 2000, 500, 200, 100, 50, 20, 10, 5, 1 ]; let noteCounter = Array(9).fill(0); // count notes using Greedy approach for (let i = 0; i < 9; i++) { if (amount >= notes[i]) { noteCounter[i] = Math.floor(amount / notes[i]); amount = amount - noteCounter[i] * notes[i]; } } // Print notes document.write("Currency Count ->" + "<br/>"); for (let i = 0; i < 9; i++) { if (noteCounter[i] != 0) { document.write(notes[i] + " : " + noteCounter[i] + "<br/>"); } } } // driver code let amount = 868; countCurrency(amount); </script>
Output:
Currency Count ->
500 : 1
200 : 1
100 : 1
50 : 1
10 : 1
5 : 1
1 : 3
manishshaw1
avijitmondal1998
khushboogoyal499
simmytarika5
Greedy
Greedy
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)
Job Sequencing Problem
Difference between Prim's and Kruskal's algorithm for MST
Dijkstra’s Algorithm for Adjacency List Representation | Greedy Algo-8
Program for Least Recently Used (LRU) Page Replacement algorithm
Shortest Remaining Time First (Preemptive SJF) Scheduling Algorithm
Graph Coloring | Set 2 (Greedy Algorithm)
Program for Page Replacement Algorithms | Set 2 (FIFO)
Greedy approach vs Dynamic programming
3 Different ways to print Fibonacci series in Java | [
{
"code": null,
"e": 26160,
"s": 26132,
"text": "\n13 May, 2022"
},
{
"code": null,
"e": 26487,
"s": 26160,
"text": "Given an amount, find the minimum number of notes of different denominations that sum upto the given amount. Starting from the highest denomination note, try to ac... |
ML | Mean-Shift Clustering - GeeksforGeeks | 24 Feb, 2022
Meanshift is falling under the category of a clustering algorithm in contrast of Unsupervised learning that assigns the data points to the clusters iteratively by shifting points towards the mode (mode is the highest density of data points in the region, in the context of the Meanshift). As such, it is also known as the Mode-seeking algorithm. Mean-shift algorithm has applications in the field of image processing and computer vision.
Given a set of data points, the algorithm iteratively assigns each data point towards the closest cluster centroid and direction to the closest cluster centroid is determined by where most of the points nearby are at. So each iteration each data point will move closer to where the most points are at, which is or will lead to the cluster center. When the algorithm stops, each point is assigned to a cluster.
Unlike the popular K-Means cluster algorithm, mean-shift does not require specifying the number of clusters in advance. The number of clusters is determined by the algorithm with respect to the data.
Note: The downside to Mean Shift is that it is computationally expensive O(n2).
The first step when applying mean shift clustering algorithms is representing your data in a mathematical manner this means representing your data as points such as the set below.
Mean-shift builds upon the concept of kernel density estimation, in short KDE. Imagine that the above data was sampled from a probability distribution. KDE is a method to estimate the underlying distribution also called the probability density function for a set of data.
It works by placing a kernel on each point in the data set. A kernel is a fancy mathematical word for a weighting function generally used in convolution. There are many different types of kernels, but the most popular one is the Gaussian kernel. Adding up all of the individual kernels generates a probability surface example density function. Depending on the kernel bandwidth parameter used, the resultant density function will vary.
Below is the KDE surface for our points above using a Gaussian kernel with a kernel bandwidth of 2.
Surface plot:
Contour plot:
Below is the Python implementation :
import numpy as npimport pandas as pdfrom sklearn.cluster import MeanShiftfrom sklearn.datasets.samples_generator import make_blobsfrom matplotlib import pyplot as pltfrom mpl_toolkits.mplot3d import Axes3D # We will be using the make_blobs method# in order to generate our own data. clusters = [[2, 2, 2], [7, 7, 7], [5, 13, 13]] X, _ = make_blobs(n_samples = 150, centers = clusters, cluster_std = 0.60) # After training the model, We store the# coordinates for the cluster centersms = MeanShift()ms.fit(X)cluster_centers = ms.cluster_centers_ # Finally We plot the data points# and centroids in a 3D graph.fig = plt.figure() ax = fig.add_subplot(111, projection ='3d') ax.scatter(X[:, 0], X[:, 1], X[:, 2], marker ='o') ax.scatter(cluster_centers[:, 0], cluster_centers[:, 1], cluster_centers[:, 2], marker ='x', color ='red', s = 300, linewidth = 5, zorder = 10) plt.show()
Try Code here
Output:
To illustrate, suppose we are given a data set {ui} of points in d-dimensional space, sampled from some larger population, and that we have chosen a kernel K having bandwidth parameter h. Together, these data and kernel function returns the following kernel density estimator for the full population’s density function.
The kernel function here is required to satisfy the following two conditions:
-> The first requirement is needed to ensure that our estimate is normalized.-> The second is associated with the symmetry of our space.
Two popular kernel functions that satisfy these conditions are given by-
Below we plot an example in one dimension using the Gaussian kernel to estimate the density of some population along the x-axis. We can see that each sample point adds a small Gaussian to our estimate, centered about it and equations above may look a bit intimidating, but the graphic here should clarify that the concept is pretty straightforward.
Iterative Mode Search –
1. Initialize random seed and window W.
2. Calculate the center of gravity (mean) of W.
3. Shift the search window to the mean.
4. Repeat Step 2 until convergence.
General algorithm outline –
for p in copied_points: while not at_kde_peak: p = shift(p, original_points)
Shift function looks like this –
def shift(p, original_points): shift_x = float(0) shift_y = float(0) scale_factor = float(0) for p_temp in original_points: # numerator dist = euclidean_dist(p, p_temp) weight = kernel(dist, kernel_bandwidth) shift_x += p_temp[0] * weight shift_y += p_temp[1] * weight # denominator scale_factor += weight shift_x = shift_x / scale_factor shift_y = shift_y / scale_factor return [shift_x, shift_y]
Pros:
Finds variable number of modes
Robust to outliers
General, application-independent tool
Model-free, doesn’t assume any prior shape like spherical, elliptical, etc. on data clusters
Just a single parameter (window size h) where h has a physical meaning (unlike k-means)
Cons:
Output depends on window size
Window size (bandwidth) selecHon is not trivial
Computationally (relatively) expensive (approx 2s/image)
Doesn’t scale well with dimension of feature space.
mikegu0508
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Decision Tree
Activation functions in Neural Networks
Decision Tree Introduction with example
Introduction to Recurrent Neural Network
Support Vector Machine Algorithm
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": 25647,
"s": 25619,
"text": "\n24 Feb, 2022"
},
{
"code": null,
"e": 26085,
"s": 25647,
"text": "Meanshift is falling under the category of a clustering algorithm in contrast of Unsupervised learning that assigns the data points to the clusters iteratively by ... |
Django Authentication Project with Firebase - GeeksforGeeks | 05 Oct, 2021
Django is a Python-based web framework that allows you to quickly create efficient web applications.. When we are building any website, we will need a set of components: how to handle user authentication (signing up, signing in, signing out), a management panel for managing our website, how to upload files, etc. Django gives us ready-made components to use that easily.
If you are new to Django then you can refer to Django Introduction and Installation.
To check how to create a new project with django and firebase, check – How to create a new project in Django using Firebase Database?
Here we are going to learn How to create Login and Registration in Django using Firebase as Database . In Firebase Authentication ,we need to enable Sign-in-method
Step 1 : Go to Authentication -> Sign-in-method -> Email/Password.
Step 2 : Enable Email/Password and Click on Save .
Now, I hope that you have already created a project in Django. If not then Refer to How to Create a Basic Project using MVT in Django ?
Create URLs, to map the requests in urls.py
Python3
from django.contrib import adminfrom django.urls import pathfrom . import views urlpatterns = [ path('admin/', admin.site.urls), # Here we are assigning the path of our url path('', views.signIn), path('postsignIn/', views.postsignIn), path('signUp/', views.signUp, name="signup"), path('logout/', views.logout, name="log"), path('postsignUp/', views.postsignUp),]
Views.py
Here, We will be using our firebase credentials for authentication .
Python3
from django.shortcuts import renderimport pyrebase config={ apiKey: "Use Your Api Key Here", authDomain: "Use Your authDomain Here", databaseURL: "Use Your databaseURL Here", projectId: "Use Your projectId Here", storageBucket: "Use Your storageBucket Here", messagingSenderId: "Use Your messagingSenderId Here", appId: "Use Your appId Here"}# Initialising database,auth and firebase for further usefirebase=pyrebase.initialize_app(config)authe = firebase.auth()database=firebase.database() def signIn(request): return render(request,"Login.html")def home(request): return render(request,"Home.html") def postsignIn(request): email=request.POST.get('email') pasw=request.POST.get('pass') try: # if there is no error then signin the user with given email and password user=authe.sign_in_with_email_and_password(email,pasw) except: message="Invalid Credentials!!Please ChecK your Data" return render(request,"Login.html",{"message":message}) session_id=user['idToken'] request.session['uid']=str(session_id) return render(request,"Home.html",{"email":email}) def logout(request): try: del request.session['uid'] except: pass return render(request,"Login.html") def signUp(request): return render(request,"Registration.html") def postsignUp(request): email = request.POST.get('email') passs = request.POST.get('pass') name = request.POST.get('name') try: # creating a user with the given email and password user=authe.create_user_with_email_and_password(email,passs) uid = user['localId'] idtoken = request.session['uid'] print(uid) except: return render(request, "Registration.html") return render(request,"Login.html")
Login.html
HTML
{% if message %}<script> alert('{{ message }}');</script>{% endif %}<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Sign In</title> <style> body{ background-image: url(https://images.unsplash.com/photo-1493723843671-1d655e66ac1c?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1050&q=80); } input{ margin-top:20px; height: 30px; padding: 12px 20px; width: 150px; margin: 8px 0; border-radius: 5px; } input[type="submit"]{ background-color: rgba(7, 179, 185, 0.753); color: rgb(255, 255, 255); border: none; border-radius: 5px; } button{ background-color: rgba(7, 179, 185, 0.753); color: white; width: 150px; height: 30px; border: none; border-radius: 5px; } </style></head><body> <form action="/postsignIn/" method="post"> {% csrf_token %} <br/> <!-- Enter Your Email: --> <label for="Email">Email</label> <input type="email"id="Email" name="email"><br><br> <!-- Enter Your Password: --> <label for="Password">Password</label> <input type="password" id="Password" name="pass"><br><br> <input type="submit" value="SignIn"><br><br> <label> <input type="checkbox" checked="checked" name="remember"> Remember me </label> <button type="button" onclick="location.href='{% url 'signup' %} '">SignUp</button></form></body></html>
Registration.html
HTML
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Sign Up</title> <style> body{ background-image: url(https://images.unsplash.com/photo-1493723843671-1d655e66ac1c?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1050&q=80); } input{ margin-top:20px; height: 30px; width: 150px; border-radius: 5px; } input[type="submit"]{ background-color: rgba(7, 179, 185, 0.753); color: rgb(255, 255, 255); border: none; border-radius: 5px; } </style></head><body> <form action="/postsignUp/" method="post"> {% csrf_token %} <br/> <h1>Sign Up</h1> <p>Please fill in this form</p> <label for="username">Username</label> <input type="name" id="Username" name="name" placeholder="Your Name"><br><br> <!-- Email: --> <label for="Email" >Email</label> <input type="email" id="Email" name="email" placeholder="Your Email Id"><br><br> <!-- Password: --> <label for="Password">Password/label> <input type="password" id="Password" name="pass" placeholder="Password"><br><br> <!-- RepeatPassword: --> <label for="confirm_password">Confirm Password</label> <input type="password" id="confirm_password" name="pass-repeat" placeholder=" Repeat Password"><br><br> <label> <input type="checkbox" checked="checked" name="remember" style="margin-bottom:15px"> Remember me </label> <input type="submit" value="SignUp"><br><br> </form></body></html>
Home.html
HTML
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Welcome</title> <style> body{ background-image: url(https://images.unsplash.com/photo-1493723843671-1d655e66ac1c?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1050&q=80); } div{ position:absolute; right:10px; top:5px; } p{ font-size: 32px; } button{ background-color: rgba(7, 179, 185, 0.753); color: white; width: 70px; height: 40px; border: none; border-radius: 5px; } </style></head><body><br><br><div><button type="button" onclick="location.href='{% url 'log' %}' ">Logout</button></div></body></html>
Now move to your project directory and run our project using the given command :
python manage.py runserver
Login Page
Registration Page
Home Page
Here we are going to learn How to Reset Password in Django with Database as Firebase . Like most of the times it happens that you forget your password and you want to reset your password. So in this article we are going to learn how to do that in Django.
Urls.py
Python3
path('reset/', views.reset),path('postReset/', views.postReset),
Views.py
Here we are basically rendering to Reset.html page where the user will type his/her registered email id and will get a email to reset password. send_password_reset_email is predefined method of firebase to reset the password.
Python3
def reset(request): return render(request, "Reset.html") def postReset(request): email = request.POST.get('email') try: authe.send_password_reset_email(email) message = "A email to reset password is successfully sent" return render(request, "Reset.html", {"msg":message}) except: message = "Something went wrong, Please check the email you provided is registered or not" return render(request, "Reset.html", {"msg":message})
Login.html
HTML
{% if message %}<script> alert('{{ message }}');</script>{% endif %}<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Sign In</title> <style> body{ background-image: url(https://images.unsplash.com/photo-1493723843671-1d655e66ac1c?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1050&q=80); } input{ margin-top:20px; height: 30px; padding: 12px 20px; width: 150px; margin: 8px 0; border-radius: 5px; } input[type="submit"]{ background-color: rgba(7, 179, 185, 0.753); color: rgb(255, 255, 255); border: none; border-radius: 5px; } button{ background-color: rgba(7, 179, 185, 0.753); color: white; width: 150px; height: 30px; border: none; border-radius: 5px; } </style></head><body> <form action="/postsignIn/" method="post"> {% csrf_token %} <br/> <!-- Enter Your Email: --> <label for="Email">Email</label> <input type="email"id="Email" name="email"><br><br> <!-- Enter Your Password: --> <label for="Password">Password</label> <input type="password" id="Password" name="pass"><br><br> <input type="submit" value="SignIn"><br><br> <p style="color: black;padding: 10px 0;">Forgot Password? <a href="/reset/" style="color: black;">Click Here to Reset</a></p> <label> <input type="checkbox" checked="checked" name="remember"> Remember me </label> <button type="button" onclick="location.href='{% url 'signup' %} '">SignUp</button></form></body></html>
Reset.html
HTML
<!DOCTYPE html>{% load static %}{%if msg%} <script> window.alert('{{msg}}'); </script>{% endif%}<html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="{% static '/css/Reset.css/' %}"> <link rel="stylesheet" type="text/css" href="{% static '/css/footer.css/' %}"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> <script src='https://kit.fontawesome.com/a076d05399.js'></script></head><body> <div class="back"> <a href="/"><i class='fas fa-arrow-left' style='font-size:22px'> </i>Back</a> </div> <div class="container"> <div class="inner"> <h1>Reset Your Password</h1><br> <form action="/postReset/" method="POST"> {% csrf_token %} <input type="email" name="email" id="email" placeholder="Enter Your email" required><br><br> <input type="submit" value="Send Reset Link"> </form> </div> </div></body></html>
Now move to your project directory and run our project using the given command :
python manage.py runserver
Click On Click Here to Reset and then you will be redirected on another page.
Enter your Email and Click on Send Reset Link and then You will get a link on your email to change your password.
A alert box will come confirming that a mail is sent.
Now, You will receive a mail like this
.click on it to view the description of mail.
Here ,Click on the given link to change your password.
Here, Type a new password and click on Save.
Now , You can sign in with your new password.
sweetyty
Firebase
Python Django
Technical Scripter 2020
Python
Technical Scripter
Web Technologies
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
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": 26085,
"s": 26057,
"text": "\n05 Oct, 2021"
},
{
"code": null,
"e": 26459,
"s": 26085,
"text": "Django is a Python-based web framework that allows you to quickly create efficient web applications.. When we are building any website, we will need a set of compo... |
PostgreSQL - DROP SCHEMA - GeeksforGeeks | 28 Aug, 2020
PostgreSQL also supports the deletion of a schema and its objects using the DROP SCHEMA statement.
Syntax: DROP SCHEMA [IF EXISTS] schema_name [ CASCADE | RESTRICT ];
Let’s analyze the above syntax:
First, specify the name of the schema from which you want to remove after the DROP SCHEMA keywords.
Second, use the IF EXISTS option to conditionally to delete schema only if it exists.
Third, use CASCADE to delete schema and all of its objects, and in turn, all objects that depend on those objects. If you want to delete schema only when it is empty, you can use the RESTRICT option. By default, PostgreSQL uses RESTRICT.
To execute the DROP SCHEMA statement, you must be the owner of the schema that you want to drop or a superuser. PostgreSQL also allows you to drop multiple schemas at the same time by using a single DROP SCHEMA statement.Now let’s look into some examples.
Example 1:This example uses the DROP SCHEMA statement to remove the marketing schema present in our database:
DROP SCHEMA IF EXISTS marketing;
To verify so use the below statement:
SELECT * FROM pg_catalog.pg_namespace ORDER BY nspname;
Output:
Example 2:The following example uses the DROP SCHEMA statement to drop multiple schemas gfg and Raju using a single statement:
DROP SCHEMA IF EXISTS gfg, raju;
To verify so use the below statement:
SELECT * FROM pg_catalog.pg_namespace ORDER BY nspname;
Output:
postgreSQL-schema
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 - Function Returning A Table
PostgreSQL - Create Auto-increment Column using SERIAL
PostgreSQL - CREATE PROCEDURE
PostgreSQL - ARRAY_AGG() Function
PostgreSQL - DROP INDEX
PostgreSQL - Copy Table
PostgreSQL - Identity Column | [
{
"code": null,
"e": 29245,
"s": 29217,
"text": "\n28 Aug, 2020"
},
{
"code": null,
"e": 29344,
"s": 29245,
"text": "PostgreSQL also supports the deletion of a schema and its objects using the DROP SCHEMA statement."
},
{
"code": null,
"e": 29412,
"s": 29344,
... |
Python - Extract hashtags from text - GeeksforGeeks | 11 Aug, 2021
A hashtag is a keyword or phrase preceded by the hash symbol (#), written within a post or comment to highlight it and facilitate a search for it. Some examples are: #like, #gfg, #selfieWe are provided with a string containing hashtags, we have to extract these hashtags into a list and print them.
Examples :
Input : GeeksforGeeks is a wonderful #website for #ComputerScience
Output : website , ComputerScience
Input : This day is beautiful! #instagood #photooftheday #cute
Output : instagood, photooftheday, cute
Method 1:
Split the text into words using the split() method.
For every word check if the first character is a hash symbol(#) or not.
If yes then add the word to the list of hashtags without the hash symbol.
Print the list of hashtags.
Python3
# function to print all the hashtags in a textdef extract_hashtags(text): # initializing hashtag_list variable hashtag_list = [] # splitting the text into words for word in text.split(): # checking the first character of every word if word[0] == '#': # adding the word to the hashtag_list hashtag_list.append(word[1:]) # printing the hashtag_list print("The hashtags in \"" + text + "\" are :") for hashtag in hashtag_list: print(hashtag) if __name__=="__main__": text1 = "GeeksforGeeks is a wonderful # website for # ComputerScience" text2 = "This day is beautiful ! # instagood # photooftheday # cute" extract_hashtags(text1) extract_hashtags(text2)
Output :
The hashtags in "GeeksforGeeks is a wonderful #website for #ComputerScience" are :
website
ComputerScience
The hashtags in "This day is beautiful! #instagood #photooftheday #cute" are :
instagood
photooftheday
cute
Method 2 : Using regular expressions.
Python3
# import the regex moduleimport re # function to print all the hashtags in a textdef extract_hashtags(text): # the regular expression regex = "#(\w+)" # extracting the hashtags hashtag_list = re.findall(regex, text) # printing the hashtag_list print("The hashtags in \"" + text + "\" are :") for hashtag in hashtag_list: print(hashtag) if __name__=="__main__": text1 = "GeeksforGeeks is a wonderful # website for # ComputerScience" text2 = "This day is beautiful ! # instagood # photooftheday # cute" extract_hashtags(text1) extract_hashtags(text2)
Output :
The hashtags in "GeeksforGeeks is a wonderful #website for #ComputerScience" are :
website
ComputerScience
The hashtags in "This day is beautiful! #instagood #photooftheday #cute" are :
instagood
photooftheday
cute
sagartomar9927
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
How to print without newline in Python?
Python | Convert string dictionary to dictionary | [
{
"code": null,
"e": 25725,
"s": 25697,
"text": "\n11 Aug, 2021"
},
{
"code": null,
"e": 26025,
"s": 25725,
"text": "A hashtag is a keyword or phrase preceded by the hash symbol (#), written within a post or comment to highlight it and facilitate a search for it. Some examples ar... |
C++ Program to Implement Randomized Binary Search Tree | A Binary Search Tree is a sorted binary tree in which all the nodes have the following few properties −
The right sub-tree of a node has a key greater than to its parent node's key.
The left sub-tree of a node has a key less than or equal to its parent node's key.
Each node should not have more than two children.
Here is a C++ Program to Implement Randomized Binary Search Tree.
Begin
class BST to declare following functions:
search() = To search an item in BST.
initialize temp = root;
while(temp != NULL)
Increase depth
if(temp->info == data)
print Data and depth
else if(temp->info >data)
temp = temp->l;
else
temp = temp->r;
insert() = To insert items in the tree:
If tree is empty insert data as root.
If tree is not empty
data<root
Insert data as left child.
Else
Insert data as right child.
del() = To delete an item from tree.
casea() = Called from del() if l = r = null.
caseb() = Called from del() if l != null, r = null.
caseb() = Called from del() if l = null, r != null.
casec() = Called from del() if l != null, r != null.
inorder() to traverse the node as inorder as:
left – root – right.
preorder() to traverse the node as preorder as:
root – Left – right.
postorder() to traverse the node as preorder as:
left – right – root
End
# include <iostream>
# include <cstdlib>
using namespace std;
struct nod//node declaration {
int info;
struct nod *l;
struct nod *r;
}*r;
class BST {
public:
//declaration of functions
void search(nod *, int);
void find(int, nod **, nod **);
void insert(nod *, nod *);
void del(int);
void casea(nod *,nod *);
void caseb(nod *,nod *);
void casec(nod *,nod *);
void preorder(nod *);
void inorder(nod *);
void postorder(nod *);
void show(nod *, int);
BST() {
r = NULL;
}
};
void BST::find(int i, nod **par, nod **loc)//find the position of element {
nod *ptr, *ptrsave;
if (r == NULL) {
*loc = NULL;
*par = NULL;
return;
}
if (i == r->info) {
*loc = r;
*par = NULL;
return;
} if (i < r->info)
ptr = r->l;
else
ptr = r->r;
ptrsave = r;
while (ptr != NULL) {
if (i == ptr->info) {
*loc = ptr;
*par = ptrsave;
return;
}
ptrsave = ptr;
if (i < ptr->info)
ptr = ptr->l;
else
ptr = ptr->r;
}
*loc = NULL;
*par = ptrsave;
}
void BST::search(nod *root, int data) {
int depth = 0;
nod *temp = new nod;
temp = root;
while(temp != NULL) {
depth++;
if(temp->info == data) {
cout<<"\nData found at depth: "<<depth<<endl;
return;
} else if(temp->info >data)
temp = temp->l;
else
temp = temp->r;
}
cout<<"\n Data not found"<<endl;
return;
}
void BST::insert(nod *tree, nod *newnode) {
if (r == NULL) {
r = new nod;
r->info = newnode->info;
r->l = NULL;
r->r = NULL;
cout<<"Root Node is Added"<<endl;
return;
}
if (tree->info == newnode->info) {
cout<<"Element already in the tree"<<endl;
return;
}
if (tree->info >newnode->info) {
if (tree->l != NULL) {
insert(tree->l, newnode);
} else {
tree->l= newnode;
(tree->l)->l = NULL;
(tree->l)->r= NULL;
cout<<"Node Added to Left"<<endl;
return;
}
} else {
if (tree->r != NULL) {
insert(tree->r, newnode);
} else {
tree->r = newnode;
(tree->r)->l= NULL;
(tree->r)->r = NULL;
cout<<"Node Added to Right"<<endl;
return;
}
}
}
void BST::del(int i) {
nod *par, *loc;
if (r == NULL) {
cout<<"Tree empty"<<endl;
return;
}
find(i, &par, &loc);
if (loc == NULL) {
cout<<"Item not present in tree"<<endl;
return;
}
if(loc->l == NULL && loc->r == NULL) {
casea(par, loc);
cout<<"item deleted"<<endl;
}
if (loc->l!= NULL && loc->r == NULL) {
caseb(par, loc);
cout<<"item deleted"<<endl;
}
if (loc->l== NULL && loc->r != NULL) {
caseb(par, loc);
cout<<"item deleted"<<endl;
}
if (loc->l != NULL && loc->r != NULL) {
casec(par, loc);
cout<<"item deleted"<<endl;
}
free(loc);
}
void BST::casea(nod *par, nod *loc ) {
if (par == NULL) {
r = NULL;
} else {
if (loc == par->l)
par->l = NULL;
else
par->r = NULL;
}
}
void BST::caseb(nod *par, nod *loc) {
nod *child;
if (loc->l!= NULL)
child = loc->l;
else
child = loc->r;
if (par == NULL) {
r = child;
} else {
if (loc == par->l)
par->l = child;
else
par->r = child;
}
}
void BST::casec(nod *par, nod *loc) {
nod *ptr, *ptrsave, *suc, *parsuc;
ptrsave = loc;
ptr = loc->r;
while (ptr->l!= NULL) {
ptrsave = ptr;
ptr = ptr->l;
}
suc = ptr;
parsuc = ptrsave;
if (suc->l == NULL && suc->r == NULL)
casea(parsuc, suc);
else
caseb(parsuc, suc);
if (par == NULL) {
r = suc;
} else {
if (loc == par->l)
par->l = suc;
else
par->r= suc;
}
suc->l = loc->l;
suc->r= loc->r;
}
void BST::preorder(nod *ptr) {
if (r == NULL) {
cout<<"Tree is empty"<<endl;
return;
}
if (ptr != NULL) {
cout<<ptr->info<<" ";
preorder(ptr->l);
preorder(ptr->r);
}
}
void BST::inorder(nod *ptr) {
if (r == NULL) {
cout<<"Tree is empty"<<endl;
return;
}
if (ptr != NULL) {
inorder(ptr->l);
cout<<ptr->info<<" ";
inorder(ptr->r);
}
}
void BST::postorder(nod *ptr) {
if (r == NULL) {
cout<<"Tree is empty"<<endl;
return;
}
if (ptr != NULL) {
postorder(ptr->l);
postorder(ptr->r);
cout<<ptr->info<<" ";
}
}
void BST::show(nod *ptr, int level) {
int i;
if (ptr != NULL) {
show(ptr->r, level+1);
cout<<endl;
if (ptr == r)
cout<<"Root->: ";
else {
for (i = 0;i < level;i++)
cout<<" ";
}
cout<<ptr->info;
show(ptr->l, level+1);
}
}
int main() {
int c, n,item;
BST bst;
nod *t;
while (1) {
cout<<"1.Insert Element "<<endl;
cout<<"2.Delete Element "<<endl;
cout<<"3.Search Element"<<endl;
cout<<"4.Inorder Traversal"<<endl;
cout<<"5.Preorder Traversal"<<endl;
cout<<"6.Postorder Traversal"<<endl;
cout<<"7.Display the tree"<<endl;
cout<<"8.Quit"<<endl;
cout<<"Enter your choice : ";
cin>>c;
switch©//perform switch operation {
case 1:
t = new nod;
cout<<"Enter the number to be inserted : ";
cin>>t->info;
bst.insert(r, t);
break;
case 2:
if (r == NULL) {
cout<<"Tree is empty, nothing to delete"<<endl;
continue;
}
cout<<"Enter the number to be deleted : ";
cin>>n;
bst.del(n);
break;
case 3:
cout<<"Search:"<<endl;
cin>>item;
bst.search(r,item);
break;
case 4:
cout<<"Inorder Traversal of BST:"<<endl;
bst.inorder(r);
cout<<endl;
break;
case 5:
cout<<"Preorder Traversal of BST:"<<endl;
bst.preorder(r);
cout<<endl;
break;
case 6:
cout<<"Postorder Traversal of BST:"<<endl;
bst.postorder(r);
cout<<endl;
break;
case 7:
cout<<"Display BST:"<<endl;
bst.show(r,1);
cout<<endl;
break;
case 8:
exit(1);
default:
cout<<"Wrong choice"<<endl;
}
}
}
1.Insert Element
2.Delete Element
3.Search Element
4.Inorder Traversal
5.Preorder Traversal
6.Postorder Traversal
7.Display the tree
8.Quit
Enter your choice : 1
Enter the number to be inserted : 6
Root Node is Added
1.Insert Element
2.Delete Element
3.Search Element
4.Inorder Traversal
5.Preorder Traversal
6.Postorder Traversal
7.Display the tree
8.Quit
Enter your choice : 1
Enter the number to be inserted : 7
Node Added to Right
1.Insert Element
2.Delete Element
3.Search Element
4.Inorder Traversal
5.Preorder Traversal
6.Postorder Traversal
7.Display the tree
8.Quit
Enter your choice : 1
Enter the number to be inserted : 5
Node Added to Left
1.Insert Element
2.Delete Element
3.Search Element
4.Inorder Traversal
5.Preorder Traversal
6.Postorder Traversal
7.Display the tree
8.Quit
Enter your choice : 1
Enter the number to be inserted : 4
Node Added to Left
1.Insert Element
2.Delete Element
3.Search Element
4.Inorder Traversal
5.Preorder Traversal
6.Postorder Traversal
7.Display the tree
8.Quit
Enter your choice : 3
Search:
7
Data found at depth: 2
1.Insert Element
2.Delete Element
3.Search Element
4.Inorder Traversal
5.Preorder Traversal
6.Postorder Traversal
7.Display the tree
8.Quit
Enter your choice : 3
Search:
1
Data not found
1.Insert Element
2.Delete Element
3.Search Element
4.Inorder Traversal
5.Preorder Traversal
6.Postorder Traversal
7.Display the tree
8.Quit
Enter your choice : 4
Inorder Traversal of BST:
4 5 6 7
1.Insert Element
2.Delete Element
3.Search Element
4.Inorder Traversal
5.Preorder Traversal
6.Postorder Traversal
7.Display the tree
8.Quit
Enter your choice : 5
Preorder Traversal of BST:
6 5 4 7
1.Insert Element
2.Delete Element
3.Search Element
4.Inorder Traversal
5.Preorder Traversal
6.Postorder Traversal
7.Display the tree
8.Quit
Enter your choice : 6
Postorder Traversal of BST:
4 5 7 6
1.Insert Element
2.Delete Element
3.Search Element
4.Inorder Traversal
5.Preorder Traversal
6.Postorder Traversal
7.Display the tree
8.Quit
Enter your choice : 7
Display BST:
7
Root->: 6
5
4
1.Insert Element
2.Delete Element
3.Search Element
4.Inorder Traversal
5.Preorder Traversal
6.Postorder Traversal
7.Display the tree
8.Quit
Enter your choice : 2
Enter the number to be deleted : 1
Item not present in tree
1.Insert Element
2.Delete Element
3.Search Element
4.Inorder Traversal
5.Preorder Traversal
6.Postorder Traversal
7.Display the tree
8.Quit
Enter your choice : 5
Preorder Traversal of BST:
6 5 4 7
1.Insert Element
2.Delete Element
3.Search Element
4.Inorder Traversal
5.Preorder Traversal
6.Postorder Traversal
7.Display the tree
8.Quit
Enter your choice : 2
Enter the number to be deleted : 5
item deleted
1.Insert Element
2.Delete Element
3.Search Element
4.Inorder Traversal
5.Preorder Traversal
6.Postorder Traversal
7.Display the tree
8.Quit
Enter your choice : 7
Display BST:
7
Root->: 6
4
1.Insert Element
2.Delete Element
3.Search Element
4.Inorder Traversal
5.Preorder Traversal
6.Postorder Traversal
7.Display the tree
8.Quit
Enter your choice : 8 | [
{
"code": null,
"e": 1166,
"s": 1062,
"text": "A Binary Search Tree is a sorted binary tree in which all the nodes have the following few properties −"
},
{
"code": null,
"e": 1244,
"s": 1166,
"text": "The right sub-tree of a node has a key greater than to its parent node's key."... |
Binary Array Sorting | Practice | GeeksforGeeks | Given a binary array A[] of size N. The task is to arrange the array in increasing order.
Note: The binary array contains only 0 and 1.
Example 1:
Input:
N = 5
A[] = {1,0,1,1,0}
Output: 0 0 1 1 1
Example 2:
Input:
N = 10
A[] = {1,0,1,1,1,1,1,0,0,0}
Output: 0 0 0 0 1 1 1 1 1 1
Your Task:
Complete the function SortBinaryArray() which takes given array as input and returns the sorted array.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(1).
Challenge: Try doing it in one pass.
Constraints:
1 <= N <= 106
0 <= A[i] <= 1
0
vishalja77194 days ago
vector<int> SortBinaryArray(vector<int> binArray)
{
// Your code goes here
int zero=0,ones=0;
for(int i=0;i<binArray.size();i++)
{
if(binArray[i] == 0)
zero++;
if(binArray[i] == 1)
ones++;
}
int k=0;
for(int i=0;i<zero;i++)
{
binArray[k++]=0;
}
for(int i=0;i<ones;i++)
{
binArray[k++]=1;
}
return binArray;
}
+1
harshscode6 days ago
in O(N) and O(1)
int z=0,o=0; for(int i=0;i<b.size();i++) { if(b[i]==0) z++; if(b[i]==1) o++; } int k=0; for(int i=0;i<z;i++) b[k++]=0; for(int i=0;i<o;i++) b[k++]=1; return b;
0
mestryruturaj1 week ago
Java: O(N)
class Solution
{
static int[] SortBinaryArray(int arr[], int n)
{
int left = 0;
for (int i = 0; i < n; i++) {
if (arr[i] == 0) {
arr[i] = arr[left];
arr[left++] = 0;
}
}
return arr;
}
}
0
kssaini32011 week ago
C++
class Solution{ public: vector<int> SortBinaryArray(vector<int> binArray) { // Your code goes here sort(binArray.begin(),binArray.end()); return binArray; }};
+1
zerefkhan2 weeks ago
C++ solution
Total Time Taken:
0.98/2.36
vector<int> SortBinaryArray(vector<int> binArray)
{
int left = 0, right = (binArray.size())-1;
while(left < right){
if (binArray[left] == 0) left++;
else if (binArray[right] == 1) right--;
else {
// Swapping elements at the position left and right
int swap_int = binArray[left];
binArray[left] = binArray[right];
binArray[right] = swap_int;
left++;
right--;
}
}
return binArray;
}
+1
bipulharsh1232 weeks ago
vector<int> SortBinaryArray(vector<int> binArray) { // Your code goes here int oneInd = -1; for(int ind=0; ind<binArray.size(); ind++) if(binArray[ind]==1){ oneInd = ind; break; } if(oneInd==-1) return binArray; for(int ind=oneInd+1; ind<binArray.size(); ind++) if(binArray[ind]==0){ swap(binArray[ind], binArray[oneInd]); oneInd++; } return binArray; }
Space: O(1)
Time: O(n)
0
mayank180919992 weeks ago
vector<int> SortBinaryArray(vector<int> binArray)
{
// Your code goes here
vector<int>ans;
for(int i=0;i<binArray.size();i++){
if(binArray[i]==0){
ans.push_back(binArray[i]);
}
}
for(int i=0;i<binArray.size();i++){
if(binArray[i]!=0){
ans.push_back(binArray[i]);
}
}
return ans;
}
0
dsm2 weeks ago
These 2 questions are same. Just differ in use of array and vector.
Same solution required and same statement.
0
__cloude__2 weeks ago
vector<int>res; int z=0,o=0; for(auto i:binArray){ if(i==0)++z; else ++o; } for(int i=1;i<=z;++i){ res.push_back(0); } for(int i=1;i<=o;++i){ res.push_back(1); } return res;
+2
shreyashobha02013 weeks ago
//simple and clean cpp solution
vector<int> SortBinaryArray(vector<int> b) { int i = 0, j = 0; while(i < b.size()) { if(b[i] == 0) swap(b[i], b[j++]); i++; } return b; }
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": 380,
"s": 290,
"text": "Given a binary array A[] of size N. The task is to arrange the array in increasing order."
},
{
"code": null,
"e": 427,
"s": 380,
"text": "Note: The binary array contains only 0 and 1."
},
{
"code": null,
"e": 438,
"s"... |
Add and Remove Elements in Perl Hashes | Adding a new key/value pair in a Perl hash can be done with one line of code using a simple assignment operator. But to remove an element from the hash you need to use delete function as shown below in the example −
Live Demo
#!/usr/bin/perl
%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);
@keys = keys %data;
$size = @keys;
print "1 - Hash size: is $size\n";
# adding an element to the hash;
$data{'Ali'} = 55;
@keys = keys %data;
$size = @keys;
print "2 - Hash size: is $size\n";
# delete the same element from the hash;
delete $data{'Ali'};
@keys = keys %data;
$size = @keys;
print "3 - Hash size: is $size\n";
This will produce the following result −
1 - Hash size: is 3
2 - Hash size: is 4
3 - Hash size: is 3 | [
{
"code": null,
"e": 1278,
"s": 1062,
"text": "Adding a new key/value pair in a Perl hash can be done with one line of code using a simple assignment operator. But to remove an element from the hash you need to use delete function as shown below in the example −"
},
{
"code": null,
"e": ... |
Cucumber - Comments | Comment is basically a piece of code meant for documentation purpose and not for execution. Be it a step definition file or a feature file, to make it more readable and understandable. So, it is important to use/put comments at appropriate places in the file. This also helps while debugging the code. Cucumber feature files can have comments at any place. To put comments, we just need to start the statement with “#” sign.
Different programming languages have got different norms for defining the comments. Let’s see how Cucumber deals with it.
Step definition file − If you are using Java as a platform then mark your comments with “//”.
Step definition file − If you are using Java as a platform then mark your comments with “//”.
Feature File − In case of feature file, we just need to put # before beginning your comment.
Feature File − In case of feature file, we just need to put # before beginning your comment.
The highlighted text in the program refer to the comments in the code.
Feature: annotation
#This is how background can be used to eliminate duplicate steps
Background:
User navigates to Facebook
Given I am on Facebook login page
#Scenario with AND
Scenario:
When I enter username as "TOM"
And I enter password as "JERRY"
Then Login should fail
#Scenario with BUT
Scenario:
When I enter username as "TOM"
And I enter password as "JERRY"
Then Login should fail
But Relogin option should be available
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2387,
"s": 1962,
"text": "Comment is basically a piece of code meant for documentation purpose and not for execution. Be it a step definition file or a feature file, to make it more readable and understandable. So, it is important to use/put comments at appropriate places in the... |
C# All method | The All Method checks for all the values in a collection and returns a Boolean. Even if one of the element do not satisfy the set condition, the All() method returns False.
Let us see an example −
int[] arr = {10, 15, 20};
Now, using All() method, we will check whether each element in the above array is greater than 5 or not.
arr.AsQueryable().All(val => val > 5);
Live Demo
using System;
using System.Linq;
class Demo {
static void Main() {
int[] arr = {10, 15, 20};
// checking if all the array elements are greater than 5
bool res = arr.AsQueryable().All(val => val > 5);
Console.WriteLine(res);
}
}
True | [
{
"code": null,
"e": 1235,
"s": 1062,
"text": "The All Method checks for all the values in a collection and returns a Boolean. Even if one of the element do not satisfy the set condition, the All() method returns False."
},
{
"code": null,
"e": 1259,
"s": 1235,
"text": "Let us se... |
How to use a textarea (a multi-line text input field) in HTML? | To add a multi-line text input, use the HTML <textarea> tag. You can set the size of a text area using the cols and rows attributes. It is used within a form, to allow users to input text over multiple rows.
Here are the attributes of <textarea> tag −
You can try to run the following code to use a textarea in HTML −
<!DOCTYPE html>
<html>
<head>
<title>HTML textarea Tag</title>
</head>
<body>
<form action = "/cgi-bin/hello_get.cgi" method = "get">
What improvements you want in college?
<br>
<textarea rows = "4" cols = "40" name = "description">
Enter details here...
</textarea>
<br>
<input type = "submit" value = "submit" />
</form>
</body>
</html> | [
{
"code": null,
"e": 1270,
"s": 1062,
"text": "To add a multi-line text input, use the HTML <textarea> tag. You can set the size of a text area using the cols and rows attributes. It is used within a form, to allow users to input text over multiple rows."
},
{
"code": null,
"e": 1314,
... |
Apache NiFi - Logging | Apache NiFi uses logback library to handle its logging. There is a file logback.xml present in the conf directory of NiFi, which is used to configure the logging in NiFi. The logs are generated in logs folder of NiFi and the log files are as described below.
This is the main log file of nifi, which logs all the activities of apache NiFi application ranging from NAR files loading to the run time errors or bulletins encountered by NiFi components. Below is the default appender in logback.xml file for nifi-app.log file.
<appender name="APP_FILE"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${org.apache.nifi.bootstrap.config.log.dir}/nifi-app.log</file>
<rollingPolicy
class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>
${org.apache.nifi.bootstrap.config.log.dir}/
nifi-app_%d{yyyy-MM-dd_HH}.%i.log
</fileNamePattern>
<maxFileSize>100MB</maxFileSize>
<maxHistory>30</maxHistory>
</rollingPolicy>
<immediateFlush>true</immediateFlush>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>%date %level [%thread] %logger{40} %msg%n</pattern>
</encoder>
</appender>
The appender name is APP_FILE, and the class is RollingFileAppender, which means logger is using rollback policy. By default, the max file size is 100 MB and can be changed to the required size. The maximum retention for APP_FILE is 30 log files and can be changed as per the user requirement.
This log contains the user events like web security, web api config, user authorization, etc. Below is the appender for nifi-user.log in logback.xml file.
<appender name="USER_FILE"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${org.apache.nifi.bootstrap.config.log.dir}/nifi-user.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>
${org.apache.nifi.bootstrap.config.log.dir}/
nifi-user_%d.log
</fileNamePattern>
<maxHistory>30</maxHistory>
</rollingPolicy>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>%date %level [%thread] %logger{40} %msg%n</pattern>
</encoder>
</appender>
The appender name is USER_FILE. It follows the rollover policy. The maximum retention period for USER_FILE is 30 log files. Below is the default loggers for USER_FILE appender present in nifi-user.log.
<logger name="org.apache.nifi.web.security" level="INFO" additivity="false">
<appender-ref ref="USER_FILE"/>
</logger>
<logger name="org.apache.nifi.web.api.config" level="INFO" additivity="false">
<appender-ref ref="USER_FILE"/>
</logger>
<logger name="org.apache.nifi.authorization" level="INFO" additivity="false">
<appender-ref ref="USER_FILE"/>
</logger>
<logger name="org.apache.nifi.cluster.authorization" level="INFO" additivity="false">
<appender-ref ref="USER_FILE"/>
</logger>
<logger name="org.apache.nifi.web.filter.RequestLogger" level="INFO" additivity="false">
<appender-ref ref="USER_FILE"/>
</logger>
This log contains the bootstrap logs, apache NiFi’s standard output (all system.out written in the code mainly for debugging), and standard error (all system.err written in the code). Below is the default appender for the nifi-bootstrap.log in logback.log.
<appender name="BOOTSTRAP_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${org.apache.nifi.bootstrap.config.log.dir}/nifi-bootstrap.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>
${org.apache.nifi.bootstrap.config.log.dir}/nifi-bootstrap_%d.log
</fileNamePattern>
<maxHistory>5</maxHistory>
</rollingPolicy>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>%date %level [%thread] %logger{40} %msg%n</pattern>
</encoder>
</appender>
nifi-bootstrap.log file,s appender name is BOOTSTRAP_FILE, which also follows rollback policy. The maximum retention for BOOTSTRAP_FILE appender is 5 log files. Below is the default loggers for nifi-bootstrap.log file.
<logger name="org.apache.nifi.bootstrap" level="INFO" additivity="false">
<appender-ref ref="BOOTSTRAP_FILE" />
</logger>
<logger name="org.apache.nifi.bootstrap.Command" level="INFO" additivity="false">
<appender-ref ref="CONSOLE" />
<appender-ref ref="BOOTSTRAP_FILE" />
</logger>
<logger name="org.apache.nifi.StdOut" level="INFO" additivity="false">
<appender-ref ref="BOOTSTRAP_FILE" />
</logger>
<logger name="org.apache.nifi.StdErr" level="ERROR" additivity="false">
<appender-ref ref="BOOTSTRAP_FILE" />
</logger>
46 Lectures
3.5 hours
Arnab Chakraborty
23 Lectures
1.5 hours
Mukund Kumar Mishra
16 Lectures
1 hours
Nilay Mehta
52 Lectures
1.5 hours
Bigdata Engineer
14 Lectures
1 hours
Bigdata Engineer
23 Lectures
1 hours
Bigdata Engineer
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2577,
"s": 2318,
"text": "Apache NiFi uses logback library to handle its logging. There is a file logback.xml present in the conf directory of NiFi, which is used to configure the logging in NiFi. The logs are generated in logs folder of NiFi and the log files are as described b... |
Add minor gridlines to Matplotlib plot using Seaborn | To add minor gridlines to matplotlib plot using Seaborn, we can take the following steps −
Create a list of numbers to plot a histogram using Seaborn.
Create a list of numbers to plot a histogram using Seaborn.
Plot univariate or bivariate histograms to show distributions of datasets using histplot() method.
Plot univariate or bivariate histograms to show distributions of datasets using histplot() method.
To make minor grid lines, we can first use major grid lines and then minor grid lines.
To make minor grid lines, we can first use major grid lines and then minor grid lines.
To display the figure, use show() method.
To display the figure, use show() method.
import seaborn as sns
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
x = [5, 6, 7, 2, 3, 4, 1, 8, 2]
ax = sns.histplot(x, kde=True, color='red')
ax.grid(b=True, which='major', color='black', linewidth=0.075)
ax.grid(b=True, which='minor', color='black', linewidth=0.075)
plt.show() | [
{
"code": null,
"e": 1153,
"s": 1062,
"text": "To add minor gridlines to matplotlib plot using Seaborn, we can take the following steps −"
},
{
"code": null,
"e": 1213,
"s": 1153,
"text": "Create a list of numbers to plot a histogram using Seaborn."
},
{
"code": null,
... |
Numeric and Date-time data types in SQL Server - GeeksforGeeks | 15 Sep, 2020
MS SQL Server supports a wide range of data types. There are a few more important data types that are included in the article. In this article, we will cover numeric SQL server data types and different date-time data types. Let’s discuss one by one.
bit :A bit is the smallest unit of a computer system. A bit can be either 0 or 1. The bit datatype can take NULL values as well.Syntax –column_name bit; A bit can take up to 8 bytes of storage while 2 bits can take up to 16 bits and the cycle continues.int :A data type that can store integer values(positive and negative). The storage size is up to 8 bytes(-263 to 263-1). It is sub-categorized into tinyint, int, smallint, bigint. They can be used according to the number of bytes that can be stored.(i). bigint –A numeric integer datatype that has the maximum storage of 8 bytes.(-263 to 263-1). It can store positive and negative values as well. It can be used for storing huge numbers.Syntax –column_name bigint; (ii). int –A numeric integer datatype having a storage size of 4 bytes.Syntax –column_name int; (iii). smallint –A numeric integer type that stores 2 bytes of data.Syntax –column_name smallint; (iv). tinyint –A numeric datatype that stores 1 byte.Syntax –column_name tinyint; For example, a student roll number in a class table can be assigned as follows.rollnumber int; SQL server Numeric Data Types Table :Numeric Data TypeInteger size (In Bytes)bit Value(0, 1 or NULL)tinyint1 smallint2 int4 bigint8 decimal(p,s)5 to 17 numeric(p,s)5 to 17 smallmoney4 money8 float(n)4 or 8 real4 decimal :A data type that can store decimal values. This datatype can be used for storing percentage values.Syntax –column_name decimal(precision, scale) For example,percentage(4,3) Precision is a term used for describing the number of digits to be stored from left to right while the scale is a term used for storing the number of digits after the decimal point.Take the instance of e-commerce where the product delivery date and time are to be stored in the database. For such cases, there are few data types supported by MS SQL SERVER:date :It stores the date in the format of yyyy-mm-dd.Syntax –date time :It stores the time based on 24 hours clock.Syntax –time datetime2 :It stores the date and time as well in the format of yyyy-mm-dd hh:mm: ss.Syntax –datetime2 There are data types that can store money, unique identifiers, XML data, and much more. However, in the future versions of SQL Server, some data types will be removed for some reason. Make sure to use the data types that are available in the SQL Server. Different types of date-time data types table in the SQL server as follows:Data typeSize (In Bytes)datetime8 datetime26 to 8 smalldatetime4 date3 time3 to 5datetimeoffset8 to 10 timestampUnique no.
bit :A bit is the smallest unit of a computer system. A bit can be either 0 or 1. The bit datatype can take NULL values as well.Syntax –column_name bit; A bit can take up to 8 bytes of storage while 2 bits can take up to 16 bits and the cycle continues.
Syntax –
column_name bit;
A bit can take up to 8 bytes of storage while 2 bits can take up to 16 bits and the cycle continues.
int :A data type that can store integer values(positive and negative). The storage size is up to 8 bytes(-263 to 263-1). It is sub-categorized into tinyint, int, smallint, bigint. They can be used according to the number of bytes that can be stored.(i). bigint –A numeric integer datatype that has the maximum storage of 8 bytes.(-263 to 263-1). It can store positive and negative values as well. It can be used for storing huge numbers.Syntax –column_name bigint; (ii). int –A numeric integer datatype having a storage size of 4 bytes.Syntax –column_name int; (iii). smallint –A numeric integer type that stores 2 bytes of data.Syntax –column_name smallint; (iv). tinyint –A numeric datatype that stores 1 byte.Syntax –column_name tinyint; For example, a student roll number in a class table can be assigned as follows.rollnumber int; SQL server Numeric Data Types Table :Numeric Data TypeInteger size (In Bytes)bit Value(0, 1 or NULL)tinyint1 smallint2 int4 bigint8 decimal(p,s)5 to 17 numeric(p,s)5 to 17 smallmoney4 money8 float(n)4 or 8 real4
(i). bigint –A numeric integer datatype that has the maximum storage of 8 bytes.(-263 to 263-1). It can store positive and negative values as well. It can be used for storing huge numbers.Syntax –column_name bigint;
Syntax –
column_name bigint;
(ii). int –A numeric integer datatype having a storage size of 4 bytes.Syntax –column_name int;
Syntax –
column_name int;
(iii). smallint –A numeric integer type that stores 2 bytes of data.Syntax –column_name smallint;
Syntax –
column_name smallint;
(iv). tinyint –A numeric datatype that stores 1 byte.Syntax –column_name tinyint; For example, a student roll number in a class table can be assigned as follows.rollnumber int; SQL server Numeric Data Types Table :Numeric Data TypeInteger size (In Bytes)bit Value(0, 1 or NULL)tinyint1 smallint2 int4 bigint8 decimal(p,s)5 to 17 numeric(p,s)5 to 17 smallmoney4 money8 float(n)4 or 8 real4
Syntax –
column_name tinyint;
For example, a student roll number in a class table can be assigned as follows.
rollnumber int;
SQL server Numeric Data Types Table :
decimal :A data type that can store decimal values. This datatype can be used for storing percentage values.Syntax –column_name decimal(precision, scale) For example,percentage(4,3) Precision is a term used for describing the number of digits to be stored from left to right while the scale is a term used for storing the number of digits after the decimal point.Take the instance of e-commerce where the product delivery date and time are to be stored in the database. For such cases, there are few data types supported by MS SQL SERVER:
Syntax –
column_name decimal(precision, scale)
For example,
percentage(4,3)
Precision is a term used for describing the number of digits to be stored from left to right while the scale is a term used for storing the number of digits after the decimal point.
Take the instance of e-commerce where the product delivery date and time are to be stored in the database. For such cases, there are few data types supported by MS SQL SERVER:
date :It stores the date in the format of yyyy-mm-dd.Syntax –date
Syntax –
date
time :It stores the time based on 24 hours clock.Syntax –time
Syntax –
time
datetime2 :It stores the date and time as well in the format of yyyy-mm-dd hh:mm: ss.Syntax –datetime2 There are data types that can store money, unique identifiers, XML data, and much more. However, in the future versions of SQL Server, some data types will be removed for some reason. Make sure to use the data types that are available in the SQL Server. Different types of date-time data types table in the SQL server as follows:Data typeSize (In Bytes)datetime8 datetime26 to 8 smalldatetime4 date3 time3 to 5datetimeoffset8 to 10 timestampUnique no.
Syntax –
datetime2
There are data types that can store money, unique identifiers, XML data, and much more. However, in the future versions of SQL Server, some data types will be removed for some reason. Make sure to use the data types that are available in the SQL Server. Different types of date-time data types table in the SQL server as follows:
Data Types
SQL-Server
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?
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
How to Write a SQL Query For a Specific Date Range and Date Time?
SQL Query to Convert VARCHAR to INT
SQL Query to Delete Duplicate Rows
SQL indexes
SQL Query to Compare Two Dates | [
{
"code": null,
"e": 23877,
"s": 23849,
"text": "\n15 Sep, 2020"
},
{
"code": null,
"e": 24127,
"s": 23877,
"text": "MS SQL Server supports a wide range of data types. There are a few more important data types that are included in the article. In this article, we will cover numer... |
Hashtable isEmpty() Method in Java - GeeksforGeeks | 28 Jun, 2018
The java.util.Hashtable.isEmpty() method of Hashtable class is used to check for the emptiness of the table. The method returns True if no key-value pair or mapping is present in the table else False.
Syntax:
Hash_Table.isEmpty()
Parameters: The method does not take any parameters.
Return Value: The method returns boolean true if the table is empty or does not contain any mapping pairs else boolean false.
Below programs illustrates the working of java.util.Hashtable.isEmpty() method:Program 1:
// Java code to illustrate the isEmpty() methodimport java.util.*; public class Hash_Table_Demo { public static void main(String[] args) { // Creating an empty Hashtable Hashtable<String, Integer> hash_table = new Hashtable<String, Integer>(); // Inserting elements into the table hash_table.put("Geeks", 10); hash_table.put("4", 15); hash_table.put("Geeks", 20); hash_table.put("Welcomes", 25); hash_table.put("You", 30); // Displaying the Hashtable System.out.println("The table is: " + hash_table); // Checking for the emptiness of Table System.out.println("Is the table empty? " + hash_table.isEmpty()); }}
The table is: {You=30, Welcomes=25, 4=15, Geeks=20}
Is the table empty? false
Program 2:
// Java code to illustrate the isEmpty() methodimport java.util.*; public class Hash_Table_Demo { public static void main(String[] args) { // Creating an empty Hashtable Hashtable<String, Integer> hash_table = new Hashtable<String, Integer>(); // Displaying the Hashtable System.out.println("The table is: " + hash_table); // Checking for the emptiness of Table System.out.println("Is the table empty? " + hash_table.isEmpty()); }}
The table is: {}
Is the table empty? true
Note: The same operation can be performed with any type of variation and combination of different data types.
Java-HashTable
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
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
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
How to iterate any Map in Java
Interfaces in Java
Initialize an ArrayList in Java | [
{
"code": null,
"e": 23153,
"s": 23125,
"text": "\n28 Jun, 2018"
},
{
"code": null,
"e": 23354,
"s": 23153,
"text": "The java.util.Hashtable.isEmpty() method of Hashtable class is used to check for the emptiness of the table. The method returns True if no key-value pair or mappin... |
DateTime.Equals() Method in C# | The DateTime.Equals() method in C# is used check whether two DateTime objects or instances are equal or not. TRUE is returned if both are equal, else FALSE would be the return value.
Following is the syntax −
public static bool Equals (DateTime date1, DateTime date2);
Let us now see an example to implement the DateTime.Equals() method −
using System;
public class Demo {
public static void Main() {
DateTime d1 = new DateTime(2019, 09, 10, 5, 15, 25);
DateTime d2 = d1.AddMonths(25);
Console.WriteLine("Initial DateTime = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", d1);
Console.WriteLine("\nNew DateTime (After adding months) = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", d2);
bool res = DateTime.Equals(d1, d2);
if (res)
Console.WriteLine("\ndate1 = date2. ");
else
Console.WriteLine("\ndate1 is not equal to date2. ");
}
}
This will produce the following output −
Initial DateTime = 10 September 2019, 05:15:25
New DateTime (After adding months) = 10 October 2021, 05:15:25
date1 is not equal to date2.
Let us now see another example to implement the DateTime.Equals() method −
using System;
public class Demo {
public static void Main() {
DateTime d1 = new DateTime(2019, 11, 11, 7, 15, 30);
DateTime d2 = new DateTime(2019, 11, 11, 7, 15, 30);
Console.WriteLine("DateTime1 = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", d1);
Console.WriteLine("\nDateTime2 = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", d2);
bool res = DateTime.Equals(d1, d2);
if (res)
Console.WriteLine("\ndate1 = date2 ");
else
Console.WriteLine("\ndate1 is not equal to date2 ");
}
}
This will produce the following output −
DateTime1 = 10 September 2019, 05:15:25
DateTime2 = 10 September 2019, 05:15:25
date1 = date2 | [
{
"code": null,
"e": 1245,
"s": 1062,
"text": "The DateTime.Equals() method in C# is used check whether two DateTime objects or instances are equal or not. TRUE is returned if both are equal, else FALSE would be the return value."
},
{
"code": null,
"e": 1271,
"s": 1245,
"text": ... |
How to change the width of a Frame dynamically in Tkinter? | The frame widget in Tkinter works like a container where we can place widgets and all the other GUI components. To change the frame width dynamically, we can use the configure() method and define the width property in it.
In this example, we have created a button that is packed inside the main window and whenever we click the button, it will update the width of the frame.
# Import the required libraries
from tkinter import *
from tkinter import ttk
# Create an instance of tkinter frame or window
win=Tk()
# Set the size of the window
win.geometry("700x350")
def update_width():
frame.config(width=100)
# Create a frame
frame=Frame(win, bg="skyblue3", width=700, height=250)
frame.pack()
# Add a button in the main window
ttk.Button(win, text="Update", command=update_width).pack()
win.mainloop()
Run the above code to display a window that contains a frame widget and a button.
Click the "Update" button to update the width of the frame. | [
{
"code": null,
"e": 1284,
"s": 1062,
"text": "The frame widget in Tkinter works like a container where we can place widgets and all the other GUI components. To change the frame width dynamically, we can use the configure() method and define the width property in it."
},
{
"code": null,
... |
Explain how to remove Leading Zeroes from a String in Java | Whenever you read an integer value into a String, you can remove leading zeroes of it using StringBuffer class, using regular expressions or, by converting the given String to character array.
Following Java program reads an integer value from the user into a String and removes the leading zeroes from it by converting the given String into Character array.
import java.util.Scanner;
public class LeadingZeroes {
public static String removeLeadingZeroes(String num){
int i=0;
char charArray[] = num.toCharArray();
for( ; i<= charArray.length; i++){
if(charArray[i] != '0'){
break;
}
}
return (i == 0) ? num :num.substring(i);
}
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter an integer: ");
String num = sc.next();
String result = LeadingZeroes.removeLeadingZeroes(num);
System.out.println(result);
}
}
Enter an integer value as a String
00126718
126718
Following Java program reads an integer value from the user into a String and removes the leading zeroes from it using the StringBuffer class.
import java.util.Scanner;
public class LeadingZeroesSB {
public static String removeLeadingZeroes(String num){
int i=0;
StringBuffer buffer = new StringBuffer(num);
while(i<num.length() && num.charAt(i)=='0')
i++;
buffer.replace(0, i, "");
return buffer.toString();
}
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter an integer: ");
String num = sc.next();
String result = LeadingZeroesSB.removeLeadingZeroes(num);
System.out.println(result);
}
}
Enter an integer:
00012320002
12320002
Following Java program reads an integer value from the user into a String and removes the leading zeroes from it using the Regular expressions.
import java.util.Scanner;
public class LeadingZeroesRE {
public static String removeLeadingZeroes(String str){
String strPattern = "^0+(?!$)";
str = str.replaceAll(strPattern, "");
return str;
}
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter an integer: ");
String num = sc.next();
String result = TailingZeroesRE.removeLeadingZeroes(num);
System.out.println(result);
}
}
Enter an integer:
000012336000
12336000
Add the following dependency to your pom.xml file
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
Following Java program reads an integer value from the user into a String and removes the leading zeroes from it using the stripStart() method of the StringUtils class.
import java.util.Scanner;
import org.apache.commons.lang3.StringUtils;
public class LeadingZeroesCommons {
public static String removeLeadingZeroes(String str){
str = StringUtils.stripStart(str, "0");
return str;
}
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter an integer: ");
String num = sc.next();
String result = LeadingZeroesCommons.removeLeadingZeroes(num);
System.out.println(result);
}
}
Enter an integer:
000125004587
125004587 | [
{
"code": null,
"e": 1255,
"s": 1062,
"text": "Whenever you read an integer value into a String, you can remove leading zeroes of it using StringBuffer class, using regular expressions or, by converting the given String to character array."
},
{
"code": null,
"e": 1421,
"s": 1255,
... |
Batch Script - NET USE | Connects or disconnects your computer from a shared resource or displays information about your connections.
NET USE [devicename | *] [\\computername\sharename[\volume] [password | *]]
[/USER:[domainname\]username]
[/USER:[dotted domain name\]username]
[/USER:[username@dotted domain name]
[/SMARTCARD]
[/SAVECRED] [[/DELETE] | [/PERSISTENT:{YES | NO}]]
where
\\computername\sharename − This is the name of the share which needs to be connected to.
\\computername\sharename − This is the name of the share which needs to be connected to.
/USER − This needs to be specified to ensure that the right credentials are specified when connecting to the network share.
/USER − This needs to be specified to ensure that the right credentials are specified when connecting to the network share.
net use z: \\computer\test
The above command will connect to the share name \\computer\test and assign the Z: drive name to it.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2278,
"s": 2169,
"text": "Connects or disconnects your computer from a shared resource or displays information about your connections."
},
{
"code": null,
"e": 2528,
"s": 2278,
"text": "NET USE [devicename | *] [\\\\computername\\sharename[\\volume] [password... |
Difference Between this and this() in Java - GeeksforGeeks | 12 Mar, 2021
In Java, both this and this() are completely different from each other.
this keyword is used to refer to the current object, i.e. through which the method is called.
this() is used to call one constructor from the other of the same class.
The below table shows the point-to-point difference between both this keyword and this().
this keyword is used with the objects only.
this() is used with constructors only.
It refers to the current object.
It refers to the constructor of the same class whose parameters matches with the parameters passed to this(parameters).
Dot(.) operator is used to access the members. For example, this.variableName;
No Dot(.) operator is used. Only the matching parameters are passed.
It is used to differentiate between the local variable and the instance variable in the method.
It is used to refer to the constructor belonging to the same class.
See the code below, which describes the utilization of this keyword.
Java
import java.io.*; public class Student { private String name; private int age; // Note that in the Constructor below "this keyword" is // used to differentiate between the local variable and // the instance variable. public Student(String name, int age) { // Assigns the value of local name variable // to the name(instance variable). this.name = name; // Assigns the value of local Age variable // to the Age(instance variable). this.age = age; } public void show() { System.out.println("Name = " + this.name); System.out.println("Age = " + this.age); } public static void main(String[] args) { // Creating new instance of Student Class Student student = new Student("Geeks", 20); student.show(); }}
Name = Geeks
Age = 20
Now take a look at the code below which describes the use of this().
Java
import java.io.*; public class Student { private String name; private int age; // Constructor 1 with String as parameter. public Student(String name) { // This line of code calls the second constructor. this(20); System.out.println("Name of Student : " + name); } // Constructor 2 with int in parameter. public Student(int age) { System.out.println("Age of student = " + age); } // Constructor 3 with no parameters. public Student() { // This line calls the first constructor. this("Geeks"); } public static void main(String[] args) { // This calls the third constructor. Student student = new Student(); }}
Age of student = 20
Name of Student : Geeks
Please note that this() should always be the first executable statement in the constructor. Otherwise, the program will give compile time error.
Difference Between
Java
Java
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
Difference Between Method Overloading and Method Overriding in Java
Difference between Internal and External fragmentation
Difference between Prim's and Kruskal's algorithm for MST
Differences and Applications of List, Tuple, Set and Dictionary in Python
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Arrays.sort() in Java with examples
Reverse a string in Java | [
{
"code": null,
"e": 24884,
"s": 24856,
"text": "\n12 Mar, 2021"
},
{
"code": null,
"e": 24956,
"s": 24884,
"text": "In Java, both this and this() are completely different from each other."
},
{
"code": null,
"e": 25050,
"s": 24956,
"text": "this keyword is us... |
Android | Creating a RatingBar - GeeksforGeeks | 23 Feb, 2021
RatingBar is used to allow the users to rate some products. In the below code getRating() function is used to calculate the rating of the products. The getRating() function returns double type value.
Below steps are involved to create a RatingBar in Android:
Create a new android project.Add RatingBar in your activity_main.xml.Add Button to invoke action.Use TextView to display the ratings.
Create a new android project.
Add RatingBar in your activity_main.xml.
Add Button to invoke action.
Use TextView to display the ratings.
To use the rating bar in the app, we will use the in-built RatingBar widget, hence the first step is to import it into the project.
In the MainActivity, make the RatingBar object denoted by the variable ‘rt’ and find its corresponding view in the XML file. This is done by the findViewById() method. After the java object has successfully bind to its view, create the ‘stars’ layout, which the user will interact with, to set the rating.
To get the drawable stars, the method rt.getProcessDrawable() is used. Then to modify the colours of the stars, the method setColorFilter() is used and the argument Color.YELLOW is passed. Finally, the Call method is written to extract the value of the rating that the user has selected, by the method rt.getMethod().
Program to create MainActivity:
// Below is the code for MainActivity.javapackage com.example.hp.rating; // importing required librariesimport android.graphics.Color;import android.graphics.PorterDuff;import android.graphics.drawable.LayerDrawable;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.RatingBar;import android.widget.TextView; public class MainActivity extends AppCompatActivity {RatingBar rt; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //binding MainActivity.java with activity_main.xml file rt = (RatingBar) findViewById(R.id.ratingBar); //finding the specific RatingBar with its unique ID LayerDrawable stars=(LayerDrawable)rt.getProgressDrawable(); //Use for changing the color of RatingBar stars.getDrawable(2).setColorFilter(Color.YELLOW, PorterDuff.Mode.SRC_ATOP); } public void Call(View v) { // This function is called when button is clicked. // Display ratings, which is required to be converted into string first. TextView t = (TextView)findViewById(R.id.textView2); t.setText("You Rated :"+String.valueOf(rt.getRating())); }}
Note: For the layout, ConstraintLayout is good to use if you are a beginner because it can adjust the views as per the screens.This XML file defines the view of the application.
Program to create layout for MainActivity:
<?xml version="1.0" encoding="utf-8"?><android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:app="http://schemas.android.com/apk/res-auto" <!-- Cover the entire width of the screen --> android:layout_width="match_parent" <!-- Cover the entire height of the screen --> android:layout_height="match_parent" tools:context="com.example.hp.rating.MainActivity" android:background="@color/colorPrimary"> <RatingBar android:id="@+id/ratingBar" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="104dp" android:background="@color/colorPrimary" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" tools:layout_constraintLeft_creator="1" tools:layout_constraintRight_creator="1" tools:layout_constraintTop_creator="1" /> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Rate Me!!!" android:textColor="@android:color/background_dark" android:textSize="30sp" android:textStyle="bold|italic" tools:layout_editor_absoluteX="127dp" tools:layout_editor_absoluteY="28dp" /> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="148dp" android:textColorHint="@color/colorAccent" android:textSize="24sp" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toBottomOf="@+id/ratingBar" tools:layout_constraintRight_creator="1" tools:layout_constraintLeft_creator="1" /> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="50dp" android:layout_marginTop="50dp" android:background="@android:color/holo_red_dark" android:onClick="Call" android:text="Submit" android:textColor="@android:color/background_light" android:textStyle="bold|italic" app:layout_constraintBottom_toTopOf="@+id/textView2" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toBottomOf="@+id/ratingBar" tools:layout_constraintBottom_creator="1" tools:layout_constraintLeft_creator="1" tools:layout_constraintRight_creator="1" tools:layout_constraintTop_creator="1" /></android.support.constraint.ConstraintLayout>
Here we don’t need to change the manifest file, no permission is required for the ratingBar. By default, all the created new activities are mentioned in the manifest file.
Below is the code for AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.hp.rating" > <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>
Output:
Android-Bars
Android
Java
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
How to Post Data to API using Retrofit in Android?
Android Listview in Java with Example
Retrofit with Kotlin Coroutine in Android
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": 24725,
"s": 24697,
"text": "\n23 Feb, 2021"
},
{
"code": null,
"e": 24925,
"s": 24725,
"text": "RatingBar is used to allow the users to rate some products. In the below code getRating() function is used to calculate the rating of the products. The getRating()... |
Image Filters in Python. I am currently working on a computer... | by Manvir Sekhon | Towards Data Science | I am currently working on a computer vision project and I wanted to look into image pre-processing to help improve the machine learning models that I am planning to build. Image pre-processing involves applying image filters to an image. This article will compare a number of the most well known image filters.
Image filters can be used to reduce the amount of noise in an image and to enhance the edges in an image. There are two types of noise that can be present in an image: speckle noise and salt-and-pepper noise. Speck noise is the noise that occurs during image acquisition while salt-and-pepper noise (which refers to sparsely occurring white and black pixels) is caused by sudden disturbances in an image signal. Enhancing the edges of an image can help a model detect the features of an image.
An image pre-processing step can improve the accuracy of machine learning models. Pre-processed images can hep a basic model achieve high accuracy when compared to a more complex model trained on images that were not pre-processed. For Python, the Open-CV and PIL packages allow you to apply several digital filters. Applying a digital filter involves taking the convolution of an image with a kernel (a small matrix). A kernal is an n x n square matrix were n is an odd number. The kernel depends on the digital filter. Figure 1 shows the kernel that is used for a 3 x 3 mean filter. An image from the KDEF data set (which can be found here: http://kdef.se/) will be used for the digital filter examples.
The mean filter is used to blur an image in order to remove noise. It involves determining the mean of the pixel values within a n x n kernel. The pixel intensity of the center element is then replaced by the mean. This eliminates some of the noise in the image and smooths the edges of the image. The blur function from the Open-CV library can be used to apply a mean filter to an image.
When dealing with color images it is first necessary to convert from RGB to HSV since the dimensions of RGB are dependent on one another where as the three dimensions in HSV are independent of one another (this allows us to apply filters to each of the three dimensions separately.)
The following is a python implementation of a mean filter:
import numpy as npimport cv2from matplotlib import pyplot as pltfrom PIL import Image, ImageFilter%matplotlib inlineimage = cv2.imread('AM04NES.JPG') # reads the imageimage = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) # convert to HSVfigure_size = 9 # the dimension of the x and y axis of the kernal.new_image = cv2.blur(image,(figure_size, figure_size))plt.figure(figsize=(11,6))plt.subplot(121), plt.imshow(cv2.cvtColor(image, cv2.COLOR_HSV2RGB)),plt.title('Original')plt.xticks([]), plt.yticks([])plt.subplot(122), plt.imshow(cv2.cvtColor(new_image, cv2.COLOR_HSV2RGB)),plt.title('Mean filter')plt.xticks([]), plt.yticks([])plt.show()
Figure 2 shows that while some of the speckle noise has been reduced there are a number of artifacts that are now present in the image that were not there previously. We can check to see if any artifacts are created when a mean filter is applied to a gray scale image.
# The image will first be converted to grayscaleimage2 = cv2.cvtColor(image, cv2.COLOR_HSV2BGR)image2 = cv2.cvtColor(image2, cv2.COLOR_BGR2GRAY)figure_size = 9new_image = cv2.blur(image2,(figure_size, figure_size))plt.figure(figsize=(11,6))plt.subplot(121), plt.imshow(image2, cmap='gray'),plt.title('Original')plt.xticks([]), plt.yticks([])plt.subplot(122), plt.imshow(new_image, cmap='gray'),plt.title('Mean filter')plt.xticks([]), plt.yticks([])plt.show()
Figure 3 shows that mean filtering removes some of the noise and does not create artifacts for a grayscale image. However, some detail has been lost.
The Gaussian Filter is similar to the mean filter however it involves a weighted average of the surrounding pixels and has a parameter sigma. The kernel represents a discrete approximation of a Gaussian distribution. While the Gaussian filter blurs the edges of an image (like the mean filter) it does a better job of preserving edges than a similarly sized mean filter. The ‘GaussianBlur’ function from the Open-CV package can be used to implement a Gaussian filter. The function allows you to specify the shape of the kernel. You can also specify the the standard deviation for the x and y directions separately. If only one sigma value is specified then it is considered the sigma value for both the x and y directions.
new_image = cv2.GaussianBlur(image, (figure_size, figure_size),0)plt.figure(figsize=(11,6))plt.subplot(121), plt.imshow(cv2.cvtColor(image, cv2.COLOR_HSV2RGB)),plt.title('Original')plt.xticks([]), plt.yticks([])plt.subplot(122), plt.imshow(cv2.cvtColor(new_image, cv2.COLOR_HSV2RGB)),plt.title('Gaussian Filter')plt.xticks([]), plt.yticks([])plt.show()
Figure 4 shows that the Gaussian Filter does a better job of retaining the edges of the image when compared to the mean filter however it also produces artifacts on a color image. We can now check to see if the Gaussian filter produces artifacts on a grayscale image.
new_image_gauss = cv2.GaussianBlur(image2, (figure_size, figure_size),0)plt.figure(figsize=(11,6))plt.subplot(121), plt.imshow(image2, cmap='gray'),plt.title('Original')plt.xticks([]), plt.yticks([])plt.subplot(122), plt.imshow(new_image_gauss, cmap='gray'),plt.title('Gaussian Filter')plt.xticks([]), plt.yticks([])plt.show()
Figure 5 shows that a 9 x 9 Gaussian filter does not produce artifacts when applied to a grayscale image. The filter can retain more detail than a 9 x 9 mean filter and remove some noise.
The median filter calculates the median of the pixel intensities that surround the center pixel in a n x n kernel. The median then replaces the pixel intensity of the center pixel. The median filter does a better job of removing salt and pepper noise than the mean and Gaussian filters. The median filter preserves the edges of an image but it does not deal with speckle noise. The ‘medianBlur’ function from the Open-CV library can be used to implement a median filter.
new_image = cv2.medianBlur(image, figure_size)plt.figure(figsize=(11,6))plt.subplot(121), plt.imshow(cv2.cvtColor(image, cv2.COLOR_HSV2RGB)),plt.title('Original')plt.xticks([]), plt.yticks([])plt.subplot(122), plt.imshow(cv2.cvtColor(new_image, cv2.COLOR_HSV2RGB)),plt.title('Median Filter')plt.xticks([]), plt.yticks([])plt.show()
Figure 6 shows that the median filter is able to retain the edges of the image while removing salt-and-pepper noise. Unlike the mean and Gaussian filter, the median filter does not produce artifacts on a color image. The median filter will now be applied to a grayscale image.
new_image = cv2.medianBlur(image2, figure_size)plt.figure(figsize=(11,6))plt.subplot(121), plt.imshow(image2, cmap='gray'),plt.title('Original')plt.xticks([]), plt.yticks([])plt.subplot(122), plt.imshow(new_image, cmap='gray'),plt.title('Median Filter')plt.xticks([]), plt.yticks([])plt.show()
Figure 7 shows that a 9 x 9 median filter can remove some of the salt and pepper noise while retaining the edges of the image.
Here are a few more filters that can be used for image pre-processing:
The conservative filter is used to remove salt and pepper noise. Determines the minimum intensity and maximum intensity within a neighborhood of a pixel. If the intensity of the center pixel is greater than the maximum value it is replaced by the maximum value. If it is less than the minimum value than it is replaced by the minimum value. The conservative filter preserves edges but does not remove speckle noise.
The following code can be used to define a conservative filter:
# first a conservative filter for grayscale images will be defined.def conservative_smoothing_gray(data, filter_size):temp = [] indexer = filter_size // 2 new_image = data.copy() nrow, ncol = data.shape for i in range(nrow): for j in range(ncol): for k in range(i-indexer, i+indexer+1): for m in range(j-indexer, j+indexer+1): if (k > -1) and (k < nrow): if (m > -1) and (m < ncol): temp.append(data[k,m]) temp.remove(data[i,j]) max_value = max(temp) min_value = min(temp) if data[i,j] > max_value: new_image[i,j] = max_value elif data[i,j] < min_value: new_image[i,j] = min_value temp =[] return new_image.copy()
Now the conservative filter can be applied to a gray scale image:
new_image = conservative_smoothing_gray(image2,5)plt.figure(figsize=(11,6))plt.subplot(121), plt.imshow(image2, cmap='gray'),plt.title('Original')plt.xticks([]), plt.yticks([])plt.subplot(122), plt.imshow(new_image, cmap='gray'),plt.title('Conservative Smoothing')plt.xticks([]), plt.yticks([])plt.show()
Figure 9 shows that the conservative smoothing filter was able to remove some salt-and-pepper noise. It also suggests that the filter is not able to remove as much salt-and-pepper noise as a median filter (although it does preserve more detail.)
The Laplacian of an image highlights the areas of rapid changes in intensity and can thus be used for edge detection. If we let I(x,y) represent the intensities of an image then the Laplacian of the image is given by the following formula:
The discrete approximation of the Laplacian at a specific pixel can be determined by taking the weighted mean of the pixel intensities in a small neighborhood of the pixel. Figure 10 shows two kernels which represent two different ways of approximating the Laplacian.
Since the Laplacian filter detects the edges of an image it can be used along with a Gaussian filter in order to first remove speckle noise and then to highlight the edges of an image. This method is referred to as the Lapalcian of Gaussian filtering. The ‘Laplacian’ function from the Open-CV library can be used to find the Laplacian of an image.
new_image = cv2.Laplacian(image2,cv2.CV_64F)plt.figure(figsize=(11,6))plt.subplot(131), plt.imshow(image2, cmap='gray'),plt.title('Original')plt.xticks([]), plt.yticks([])plt.subplot(132), plt.imshow(new_image, cmap='gray'),plt.title('Laplacian')plt.xticks([]), plt.yticks([])plt.subplot(133), plt.imshow(image2 + new_image, cmap='gray'),plt.title('Resulting image')plt.xticks([]), plt.yticks([])plt.show()
Figure 11 shows that while adding the Laplacian of an image to the original image may enhance the edges, some of the noise is also enhanced.
When applying frequency filters to an image it is important to first convert the image to the frequency domain representation of the image. The Fourier transform (which decomposes a function into its sine and cosine components) can be applied to an image in order to obtain its frequency domain representation. The reason we are interested in an image’s frequency domain representation is that it is less expensive to apply frequency filters to an image in the frequency domain than it is to apply the filters in the spatial domain. This is due to the fact that each pixel in the frequency domain representation corresponds to a frequency rather than a location of the image.
Low pass filters and high pass filters are both frequency filters. The low pass filters preserves the lowest frequencies (that are below a threshold) which means it blurs the edges and removes speckle noise from the image in the spatial domain. The high pass filter preserves high frequencies which means it preserves edges. The ‘dft’ function determines the discrete Fourier transform of an image. For a N x N image the two dimensional discrete Fourier transform is given by:
where f is the image value in the spatial domain and F in its the frequency domain. The following is the formula for the inverse discrete Fourier transform (which converts an image from its frequency domain to the spatial domain):
Once a frequency filter is applied to an image, the inverse Fourier transform can be used to convert the image back to the spatial domain. Now the python implementation of the low pass filter will be given:
dft = cv2.dft(np.float32(image2),flags = cv2.DFT_COMPLEX_OUTPUT)# shift the zero-frequncy component to the center of the spectrumdft_shift = np.fft.fftshift(dft)# save image of the image in the fourier domain.magnitude_spectrum = 20*np.log(cv2.magnitude(dft_shift[:,:,0],dft_shift[:,:,1]))# plot both imagesplt.figure(figsize=(11,6))plt.subplot(121),plt.imshow(image2, cmap = 'gray')plt.title('Input Image'), plt.xticks([]), plt.yticks([])plt.subplot(122),plt.imshow(magnitude_spectrum, cmap = 'gray')plt.title('Magnitude Spectrum'), plt.xticks([]), plt.yticks([])plt.show()
rows, cols = image2.shapecrow,ccol = rows//2 , cols//2# create a mask first, center square is 1, remaining all zerosmask = np.zeros((rows,cols,2),np.uint8)mask[crow-30:crow+30, ccol-30:ccol+30] = 1# apply mask and inverse DFTfshift = dft_shift*maskf_ishift = np.fft.ifftshift(fshift)img_back = cv2.idft(f_ishift)img_back = cv2.magnitude(img_back[:,:,0],img_back[:,:,1])# plot both imagesplt.figure(figsize=(11,6))plt.subplot(121),plt.imshow(image2, cmap = 'gray')plt.title('Input Image'), plt.xticks([]), plt.yticks([])plt.subplot(122),plt.imshow(img_back, cmap = 'gray')plt.title('Low Pass Filter'), plt.xticks([]), plt.yticks([])plt.show()
Figure 13 shows that a decent amount of detail was lost however some of the speckle noise was removed.
The Crimmins complementary culling algorithm is used to remove speckle noise and smooth the edges. It also reduces the intensity of salt and pepper noise. The algorithm compares the intensity of a pixel in a image with the intensities of its 8 neighbors. The algorithm considers 4 sets of neighbors (N-S, E-W, NW-SE, NE-SW.) Let a,b,c be three consecutive pixels (for example from E-S). Then the algorithm is:
For each iteration:a) Dark pixel adjustment: For each of the four directions 1) Process whole image with: if a ≥ b+2 then b = b + 1 2) Process whole image with: if a > b and b ≤ c then b = b + 1 3) Process whole image with: if c > b and b ≤ a then b = b + 1 4) Process whole image with: if c ≥ b+2 then b = b + 1b) Light pixel adjustment: For each of the four directions 1) Process whole image with: if a ≤ b — 2 then b = b — 1 2) Process whole image with: if a < b and b ≥ c then b = b — 1 3) Process whole image with: if c < b and b ≥ a then b = b — 1 4) Process whole image with: if c ≤ b — 2 then b = b — 1
For each iteration:a) Dark pixel adjustment: For each of the four directions 1) Process whole image with: if a ≥ b+2 then b = b + 1 2) Process whole image with: if a > b and b ≤ c then b = b + 1 3) Process whole image with: if c > b and b ≤ a then b = b + 1 4) Process whole image with: if c ≥ b+2 then b = b + 1b) Light pixel adjustment: For each of the four directions 1) Process whole image with: if a ≤ b — 2 then b = b — 1 2) Process whole image with: if a < b and b ≥ c then b = b — 1 3) Process whole image with: if c < b and b ≥ a then b = b — 1 4) Process whole image with: if c ≤ b — 2 then b = b — 1
The Python implementation of the complementary culling algorithm can be found here: https://github.com/m4nv1r/medium_articles/blob/master/Image_Filters_in_Python.ipynb
Figure 14, shows the results of applying the Crimmins Speckle Removal filter to an image. Some of the speckle noise was removed however some of the edges were blurred.
The Unsharp filter can be used to enhance the edges of an image. The ImageFilter.Unsharpmask function from the PIL package applies an unsharp filter to an image (the image first needs to be converted to a PIL Image object.) The ImageFilter.Unsharpmask function has three parameters. The ‘radius’ parameter specifies how many neighboring pixels around edges get affected. The ‘percentage’ parameter specifies how much darker or lighter the edges become. The third parameter ‘threshold’ defines how far apart adjacent tonal values have to be before the filter does anything.
image = Image.fromarray(image.astype('uint8'))new_image = image.filter(ImageFilter.UnsharpMask(radius=2, percent=150))plt.subplot(121),plt.imshow(image, cmap = 'gray')plt.title('Input Image'), plt.xticks([]), plt.yticks([])plt.subplot(122),plt.imshow(new_image, cmap = 'gray')plt.title('Unsharp Filter'), plt.xticks([]), plt.yticks([])plt.show()
Figure 15 shows the results of an Unsharp filter. While the edges of the image were enhanced, some of the noise was also enhanced.
There is always a trade off between removing noise and preserving the edges of an image. In order to remove the speckle noise in an image a blurring filter needs to be applied which in turn blurs the edges of the image. If you want to retain the edges of an image the only noise that you can remove is the salt-and-pepper noise. A Jupyter notebook with all the code used for this article can be found here: https://github.com/m4nv1r/medium_articles/blob/master/Image_Filters_in_Python.ipynb | [
{
"code": null,
"e": 483,
"s": 172,
"text": "I am currently working on a computer vision project and I wanted to look into image pre-processing to help improve the machine learning models that I am planning to build. Image pre-processing involves applying image filters to an image. This article will... |
A Nontrivial Elevator Control System in a Train Station by Reinforcement Learning | by Shuyang Xiang | Towards Data Science | Today’s urban life is out of imagination without the presence of elevators and the elevator controller algorithm has been well studied by different techniques including reinforcement learning [1]. A glance over the references gave the impression that the majority of studies has focused on elevators installed in high-rise buildings while those in train stations are barely discussed. Elevators in train stations, however, deserve their own attention because of their obvious difference from systems in buildings.
An elevator-train-station system usually has the following properties:
The train platforms of different train lines are located in different floors. People having entered the station want to go to one specific floor to take the trains while those having arrived on train would either exit the station or change the train on another floor.In rush hours, there does not exist one direction that everyone goes to as happens in buildings. Some might want to exit the train station while others might want do a train change on another floor.People having arrived in the station on train wait in front of the elevator almost at the same time while those coming from outside of the station not necessarily fall into this case.Elevators are usually reserved for people with heavy luggage or baby strollers so that they might not have a huge capacity. Moreover, those with baby strollers might not have a second choice other than staying in the elevator waiting list until being transported.
The train platforms of different train lines are located in different floors. People having entered the station want to go to one specific floor to take the trains while those having arrived on train would either exit the station or change the train on another floor.
In rush hours, there does not exist one direction that everyone goes to as happens in buildings. Some might want to exit the train station while others might want do a train change on another floor.
People having arrived in the station on train wait in front of the elevator almost at the same time while those coming from outside of the station not necessarily fall into this case.
Elevators are usually reserved for people with heavy luggage or baby strollers so that they might not have a huge capacity. Moreover, those with baby strollers might not have a second choice other than staying in the elevator waiting list until being transported.
A good example is the Gare de Lyon in Paris, a station with 2 underground floors on which you find 2 different train lines’ platforms respectively.
From my personal experience, it usually takes quite a while to get to floor -2 from floor -1 for a train change with my baby stroller by elevator.
In the following, I am going to simulate an elevator- train-station environment that can be easily modified for your own purpose and reused and implement reinforcement learning to get the optimal policy for the elevator controller.
Consider an elevator in a train station with 3 floors such that floor 0 is the ground floor as entrance/exit and floor 1, 2, 3 are train platforms. People waiting for the elevator on floor 0 are coming from outside, willing to go upstairs to take trains while people on other floors are brought by scheduled trains, either exiting the station or going to another floor to for a change. We suppose that people can arrive at floor 0 from outside at any moment while people arrive at a positive floor on train at the same time.
For the sake of simplicity, we consider one single elevator in the first place. This simplification indeed does not remove much generality because it is always the case that only one elevator is available on a train platform.
The three positive floors are train platforms of different railway lines: line A on floor 1, line B on floor 2 and line C on floor 3. Every 10 minutes, line A arrives at the first minute, line B the second and line C the third. In addition, every time a train arrives, 5 people will join the waiting list of the elevator together. This makes sense because in general, only those with luggage or baby strollers want to take the elevator while others will take this time-consuming choice. For every person having arrived on train he will have {0.2, 0.2, 0.6} probability to go to the two other floors and the ground floor respectively. Meanwhile, we suppose that every 30 seconds, there is 0.9 probability that one person will join the waiting list on floor 0 during the first 3 minutes of every 10 minutes. For every person on the ground floor, he will have 1/3 probability to go to each of the three underground floors.
The max capacity of the elevator is 5 people. It looks like a small capacity but remember, they have their luggage as well! Moreover, the elevator need 10 seconds every time it stops and 2 seconds to travel from one floor to another.
To resume, we have:
One ground floor, three positive floors.Three groups of 5 scheduled people in the elevator waiting list and one group of non spontaneous people.An elevator with a capacity of 5 people.
One ground floor, three positive floors.
Three groups of 5 scheduled people in the elevator waiting list and one group of non spontaneous people.
An elevator with a capacity of 5 people.
The figure blow is a sketch of the system (forget about my bad drawing, I did not make any progress from kindergarten).
Before going on step further, I give at the beginning of this section some necessary elements for reinforcement learning.
Briefly, in RL, an agent interacts with the environment in discrete time or continuously. At time step, the agent applies an action according to the current state of the environment according to certain policy, leading to a new state and receiving a reward which measures the quality of the state transition. The goal of RL is to learn a policy, either deterministic or probabilistic to maximise the accumulative reward.
Let us go back to the elevator controller system.
The state of the environment is a R7 vector (floor_0_up, floor_1_up, ...,floor_3__down, occupancy, position) where floor_i^{up/down} is either 1 or 0, being 1 iif there is a demand of going up/down at the floor i outside of the elevator, occupancy an integer as the total number of passengers inside the elevator and position the current floor on which the elevator is. Note that we only allow going up at floor 0 and down at floor 3.
The reward of function is defined as -(occupancy+sum_i floor_i^{up/down}), that is, the total number of the demands insider and outside of the elevator. In other words, the only situation for which the reward is 0 is when no passengers are waiting in the system, neither inside nor outside of the elevator.
To build the RL environment, I used open AI Gym, a toolkit for developing and comparing reinforcement learning algorithms. How to build a custom Gym environment is not the purpose of this article and readers can find instructions for their own RL environment in want [2]. Below is the __init__ and reset function of the Elevator class.
import gymfrom gym import spacesclass Elevator(gym.Env): metadata = {'render.modes': ['human']} def __init__(self): #observation space # states0: floor_0_up # states1: floor_1_up # states2: floor_1_down # states3: floor_2_up # states4: floor_2_down # states5: floor_3_down # states6: occupancy # states7: position super(Elevator, self).__init__() self.done = 0 self.reward = 0 self.states = np.zeros(8) self.states[0]=1 self.last_time = 0 self.time = 0 self.max_occupancy = 5 self.action_space = spaces.Discrete(3) # 0 stop, 1 up, 2 down self.observation_space = spaces.MultiDiscrete([2,2,2,2,2,2,6,4]) def reset(self): self.states = np.zeros(8) #suppose that there are already 2 people # waiting on the first floor at the beginning of the session self.states[0]=1 self.last_time = 0 self.time = 0 self.floor_0_waiting = 2 self.floor_0_waiting_list = [1,2] self.floor_1_waiting = 0 self.floor_1_waiting_list = [] self.floor_2_waiting = 0 self.floor_2_waiting_list = [] self.floor_3_waiting = 0 self.floor_3_waiting_list = [] self.inside_list = [] self.done = 0 self.reward = 0 return self.states
The complete code in this article is available on Github for those who are interested in more details.
To train the system, I will use the DQN: deep Q-network. Note that the total cumulative reward of the RL system is also called a Q-value for a given initial state and an action. The desired policy should be the one that maximise the Q-value which are in general unknown and thus yields Q-learning as a “cheatsheet” for the agent [3]. The DQN aims to approximate the Q-value by a deep neural network. In my implementation, I built a DQN with 2 layers of size 64 with the help of stable-baselines, a set of improved implementations of reinforcement learning algorithms based on OpenAI Baseline. This implementation requires only 3 lines of code:
elevator= Elevator()elevator.reset()model = DQN('MlpPolicy', elevator, verbose=0)model.learn(total_timesteps=1e5)
Before training, I let the elevator do random actions and it takes more than 800 seconds to empty the waiting list from the beginning of the session. While after 1e5 training time steps, the elevator managed to empty the waiting list in 246 seconds on my local trial, that is, 4 minutes instead of more than 10 minutes (according my experience, I did wait for more than 10 minutes in a waiting line in a train station sometimes!). This stands out significant improvement of the elevator controller system.
Of course, I made many simplifications to the system, e.g. people on train join the waiting at the same time and no others will join when no train passes but the result of training is still exciting. Moreover, I suppose that there is only elevator in the system which might not be the case in some stations. As the next steps, it worth adding more elevators into the system and considering a multi agent RL system to do further optimisation.
[1] Xu Yuan Lucian Busoniu and Robert Babuska, Reinforcement Learning for Elevator Control, 2008. https://www.sciencedirect.com/science/article/pii/S1474667016392783
[2] Adam King, Create custom gym environments from scratch — A stock market example. https://towardsdatascience.com/creating-a-custom-openai-gym-environment-for-stock-trading-be532be3910e
[3] A Hands-On Introduction to Deep Q-Learning using OpenAI Gym in Python. https://www.analyticsvidhya.com/blog/2019/04/introduction-deep-q-learning-python/ | [
{
"code": null,
"e": 561,
"s": 47,
"text": "Today’s urban life is out of imagination without the presence of elevators and the elevator controller algorithm has been well studied by different techniques including reinforcement learning [1]. A glance over the references gave the impression that the m... |
How to use checktextview in android? | Before getting into the example, we should know what checktextview in android is. Check textview is expanded by textview and contains checkable interface. Using Checktextview we can find that, whether a user is clicked on textview or not.
This example demonstrate about How to use checktextview in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:app = "http://schemas.android.com/apk/res-auto"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
tools:context = ".MainActivity">
<CheckedTextView
android:id = "@+id/text"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:text = "Checked Text View"
android:textSize = "25sp"
app:layout_constraintBottom_toBottomOf = "parent"
app:layout_constraintLeft_toLeftOf = "parent"
app:layout_constraintRight_toRightOf = "parent"
app:layout_constraintTop_toTopOf = "parent" />
</android.support.constraint.ConstraintLayout>
In the above code, we have taken CheckedTextView, when user clicked on textview, it will show check image.
Step 3 − Add the following code to src/MainActivity.java
package com.example.andy.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.CheckedTextView;
public class MainActivity extends AppCompatActivity {
CheckedTextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = findViewById(R.id.text);
text.setCheckMarkDrawable(null);
text.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
text.setCheckMarkDrawable(R.drawable.ic_check_circle_pink_400_24dp);
}
});
}
}
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
In the above result shown initial screen. When user click on textview it will show the result as shown below –
Click here to download the project code | [
{
"code": null,
"e": 1301,
"s": 1062,
"text": "Before getting into the example, we should know what checktextview in android is. Check textview is expanded by textview and contains checkable interface. Using Checktextview we can find that, whether a user is clicked on textview or not."
},
{
... |
Set dashed line for border with CSS | To set the dashed line for the border, use the border-style property. You can try to run the following code to implement border-style property value dashed to set dashed border:
<html>
<head>
</head>
<body>
<p style = "border-width:3px; border-style:dashed;">
This is a dotted border.
</p>
</body>
</html> | [
{
"code": null,
"e": 1240,
"s": 1062,
"text": "To set the dashed line for the border, use the border-style property. You can try to run the following code to implement border-style property value dashed to set dashed border:"
},
{
"code": null,
"e": 1401,
"s": 1240,
"text": "<htm... |
NumPy - Environment | Standard Python distribution doesn't come bundled with NumPy module. A lightweight alternative is to install NumPy using popular Python package installer, pip.
pip install numpy
The best way to enable NumPy is to use an installable binary package specific to your operating system. These binaries contain full SciPy stack (inclusive of NumPy, SciPy, matplotlib, IPython, SymPy and nose packages along with core Python).
Anaconda (from https://www.continuum.io) is a free Python distribution for SciPy stack. It is also available for Linux and Mac.
Canopy (https://www.enthought.com/products/canopy/) is available as free as well as commercial distribution with full SciPy stack for Windows, Linux and Mac.
Python (x,y): It is a free Python distribution with SciPy stack and Spyder IDE for Windows OS. (Downloadable from https://www.python-xy.github.io/)
Package managers of respective Linux distributions are used to install one or more packages in SciPy stack.
sudo apt-get install python-numpy
python-scipy python-matplotlibipythonipythonnotebook python-pandas
python-sympy python-nose
sudo yum install numpyscipy python-matplotlibipython
python-pandas sympy python-nose atlas-devel
Core Python (2.6.x, 2.7.x and 3.2.x onwards) must be installed with distutils and zlib module should be enabled.
GNU gcc (4.2 and above) C compiler must be available.
To install NumPy, run the following command.
Python setup.py install
To test whether NumPy module is properly installed, try to import it from Python prompt.
import numpy
If it is not installed, the following error message will be displayed.
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
import numpy
ImportError: No module named 'numpy'
Alternatively, NumPy package is imported using the following syntax −
import numpy as np
63 Lectures
6 hours
Abhilash Nelson
19 Lectures
8 hours
DATAhill Solutions Srinivas Reddy
12 Lectures
3 hours
DATAhill Solutions Srinivas Reddy
10 Lectures
2.5 hours
Akbar Khan
20 Lectures
2 hours
Pruthviraja L
63 Lectures
6 hours
Anmol
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2403,
"s": 2243,
"text": "Standard Python distribution doesn't come bundled with NumPy module. A lightweight alternative is to install NumPy using popular Python package installer, pip."
},
{
"code": null,
"e": 2422,
"s": 2403,
"text": "pip install numpy\n"
... |
Sending an HTML e-mail using Python | When you send a text message using Python, then all the content are treated as simple text. Even if you include HTML tags in a text message, it is displayed as simple text and HTML tags will not be formatted according to HTML syntax. But Python provides option to send an HTML message as actual HTML message.
While sending an e-mail message, you can specify a Mime version, content type and character set to send an HTML e-mail.
Following is the example to send HTML content as an e-mail. Try it once −
#!/usr/bin/python
import smtplib
message = """From: From Person <from@fromdomain.com>
To: To Person <to@todomain.com>
MIME-Version: 1.0
Content-type: text/html
Subject: SMTP HTML e-mail test
This is an e-mail message to be sent in HTML format
<b>This is HTML message.</b>
<h1>This is headline.</h1>
"""
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receivers, message)
print "Successfully sent email"
except SMTPException:
print "Error: unable to send email" | [
{
"code": null,
"e": 1371,
"s": 1062,
"text": "When you send a text message using Python, then all the content are treated as simple text. Even if you include HTML tags in a text message, it is displayed as simple text and HTML tags will not be formatted according to HTML syntax. But Python provides... |
PHP File Open/Read/Close | In this chapter we will teach you how to open, read, and close a file
on the server.
A better method to open files is with the fopen() function. This function gives you more
options than the readfile() function.
We will use the text file, "webdictionary.txt", during the lessons:
The first parameter of fopen() contains the name of the file to be opened and the
second parameter specifies in which mode the file should be opened. The following example
also generates a message if the fopen() function is unable to open the specified file:
Tip: The fread() and the fclose() functions will be
explained below.
The file may be opened in one of the following modes:
The fread() function reads from an open file.
The first parameter of fread() contains the name of the file to read from and
the second parameter specifies the maximum number of bytes to read.
The following PHP code reads the "webdictionary.txt" file to the end:
The fclose() function is used to close an open file.
It's a good programming practice to close all files after you have finished with them.
You don't want an open file running around on your
server taking up resources!
The fclose() requires the name of the file (or a variable that holds the
filename) we want to close:
The fgets() function is used to read a single line from a file.
The example below outputs the first line of the "webdictionary.txt" file:
Note: After a call to the fgets() function, the file pointer has moved to the next line.
The feof() function checks if the "end-of-file" (EOF) has been reached.
The feof() function is useful for looping through data of unknown length.
The example below reads the "webdictionary.txt" file line by line, until end-of-file is reached:
The fgetc() function is used to read a single character from a file.
The example below reads the "webdictionary.txt" file character by
character, until end-of-file is reached:
Note: After a call to the fgetc() function, the file pointer moves to the next character.
For a complete reference of filesystem functions, go to our complete
PHP Filesystem Reference.
Open a file, and write the correct syntax to output one character at the time, until end-of-file.
$myfile = fopen("webdict.txt", "r");
while(!($myfile)) {
echo ($myfile);
}
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools. | [
{
"code": null,
"e": 86,
"s": 0,
"text": "In this chapter we will teach you how to open, read, and close a file \non the server."
},
{
"code": null,
"e": 214,
"s": 86,
"text": "A better method to open files is with the fopen() function. This function gives you more \noptions than... |
Python program to accept the strings which contains all vowels | Sometimes you want to accept input based on certain conditions. Here, we are going to see the same type of program. We will write a program that allows only words with vowels. We will show them whether the input is valid or not.
Let's see the approach step by step.
Define a list of vowels [A, E, I, O, U, a, e, i, o, u]
Define a list of vowels [A, E, I, O, U, a, e, i, o, u]
Initialize a word or sentence.
Initialize a word or sentence.
Iterate over the word or sentence.Check if it is present in the list or not.
Iterate over the word or sentence.
Check if it is present in the list or not.
Check if it is present in the list or not.
3.1.1. If not, break the loop and print Not accepted.
Else print accepted
Let's convert the text into Python code.
def check_vowels(string):
# vowels
vowels = ['A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u']
# iterating over the string
for char in string:
if char not in vowels:
print(f"{string}: Not accepted")
break
else:
print(f"{string}: Accepted")
if __name__ == '__main__':
# initializing strings
string_1 = "tutorialspoint"
string_2 = "AEiouaieeu"
# checking the strings
check_vowels(string_1)
check_vowels(string_2)
If you run the above code, you will get the following results.
tutorialspoint: Not accepted
AEiouaieeu: Accepted
You check different properties based on your requirements. If you have any doubts in the tutorial, mention them in the comment section. | [
{
"code": null,
"e": 1291,
"s": 1062,
"text": "Sometimes you want to accept input based on certain conditions. Here, we are going to see the same type of program. We will write a program that allows only words with vowels. We will show them whether the input is valid or not."
},
{
"code": nu... |
Android - Image Effects | Android allows you to manipulate images by adding different kinds of effects on the images. You can easily apply image processing techniques to add certain kinds of effects on images. The effects could be brightness,darkness, grayscale conversion e.t.c.
Android provides Bitmap class to handle images. This can be found under android.graphics.bitmap. There are many ways through which you can instantiate bitmap. We are creating a bitmap of image from the imageView.
private Bitmap bmp;
private ImageView img;
img = (ImageView)findViewById(R.id.imageView1);
BitmapDrawable abmp = (BitmapDrawable)img.getDrawable();
Now we will create bitmap by calling getBitmap() function of BitmapDrawable class. Its syntax is given below −
bmp = abmp.getBitmap();
An image is nothing but a two dimensional matrix. Same way you will handle a bitmap. An image consist of pixels. So you will get pixels from this bitmap and apply processing to it. Its syntax is as follows −
for(int i=0; i<bmp.getWidth(); i++){
for(int j=0; j<bmp.getHeight(); j++){
int p = bmp.getPixel(i, j);
}
}
The getWidth() and getHeight() functions returns the height and width of the matrix. The getPixel() method returns the pixel at the specified index. Once you got the pixel, you can easily manipulate it according to your needs.
Apart from these methods, there are other methods that helps us manipulate images more better.
copy(Bitmap.Config config, boolean isMutable)
This method copy this bitmap's pixels into the new bitmap
createBitmap(DisplayMetrics display, int width, int height, Bitmap.Config config)
Returns a mutable bitmap with the specified width and height
createBitmap(int width, int height, Bitmap.Config config)
Returns a mutable bitmap with the specified width and height
createBitmap(Bitmap src)
Returns an immutable bitmap from the source bitmap
extractAlpha()
Returns a new bitmap that captures the alpha values of the original
getConfig()
This mehtod eturn that config, otherwise return null
getDensity()
Returns the density for this bitmap
getRowBytes()
Return the number of bytes between rows in the bitmap's pixels
setPixel(int x, int y, int color)
Write the specified Color into the bitmap (assuming it is mutable) at the x,y coordinate
setDensity(int density)
This method specifies the density for this bitmap
The below example demonstrates some of the image effects on the bitmap. It crates a basic application that allows you to convert the picture into grayscale and much more.
To experiment with this example , you need to run this on an actual device.
Following is the content of the modified MainActivity.java.
package com.example.sairamkrishna.myapplication;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends ActionBarActivity {
Button b1, b2, b3;
ImageView im;
private Bitmap bmp;
private Bitmap operation;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button) findViewById(R.id.button);
b2 = (Button) findViewById(R.id.button2);
b3 = (Button) findViewById(R.id.button3);
im = (ImageView) findViewById(R.id.imageView);
BitmapDrawable abmp = (BitmapDrawable) im.getDrawable();
bmp = abmp.getBitmap();
}
public void gray(View view) {
operation = Bitmap.createBitmap(bmp.getWidth(),bmp.getHeight(), bmp.getConfig());
double red = 0.33;
double green = 0.59;
double blue = 0.11;
for (int i = 0; i < bmp.getWidth(); i++) {
for (int j = 0; j < bmp.getHeight(); j++) {
int p = bmp.getPixel(i, j);
int r = Color.red(p);
int g = Color.green(p);
int b = Color.blue(p);
r = (int) red * r;
g = (int) green * g;
b = (int) blue * b;
operation.setPixel(i, j, Color.argb(Color.alpha(p), r, g, b));
}
}
im.setImageBitmap(operation);
}
public void bright(View view){
operation= Bitmap.createBitmap(bmp.getWidth(), bmp.getHeight(),bmp.getConfig());
for(int i=0; i<bmp.getWidth(); i++){
for(int j=0; j<bmp.getHeight(); j++){
int p = bmp.getPixel(i, j);
int r = Color.red(p);
int g = Color.green(p);
int b = Color.blue(p);
int alpha = Color.alpha(p);
r = 100 + r;
g = 100 + g;
b = 100 + b;
alpha = 100 + alpha;
operation.setPixel(i, j, Color.argb(alpha, r, g, b));
}
}
im.setImageBitmap(operation);
}
public void dark(View view){
operation= Bitmap.createBitmap(bmp.getWidth(),bmp.getHeight(),bmp.getConfig());
for(int i=0; i<bmp.getWidth(); i++){
for(int j=0; j<bmp.getHeight(); j++){
int p = bmp.getPixel(i, j);
int r = Color.red(p);
int g = Color.green(p);
int b = Color.blue(p);
int alpha = Color.alpha(p);
r = r - 50;
g = g - 50;
b = b - 50;
alpha = alpha -50;
operation.setPixel(i, j, Color.argb(Color.alpha(p), r, g, b));
}
}
im.setImageBitmap(operation);
}
public void gama(View view) {
operation = Bitmap.createBitmap(bmp.getWidth(),bmp.getHeight(),bmp.getConfig());
for(int i=0; i<bmp.getWidth(); i++){
for(int j=0; j<bmp.getHeight(); j++){
int p = bmp.getPixel(i, j);
int r = Color.red(p);
int g = Color.green(p);
int b = Color.blue(p);
int alpha = Color.alpha(p);
r = r + 150;
g = 0;
b = 0;
alpha = 0;
operation.setPixel(i, j, Color.argb(Color.alpha(p), r, g, b));
}
}
im.setImageBitmap(operation);
}
public void green(View view){
operation = Bitmap.createBitmap(bmp.getWidth(),bmp.getHeight(), bmp.getConfig());
for(int i=0; <bmp.getWidth(); i++){
for(int j=0; j<bmp.getHeight(); j++){
int p = bmp.getPixel(i, j);
int r = Color.red(p);
int g = Color.green(p);
int b = Color.blue(p);
int alpha = Color.alpha(p);
r = 0;
g = g+150;
b = 0;
alpha = 0;
operation.setPixel(i, j, Color.argb(Color.alpha(p), r, g, b));
}
}
im.setImageBitmap(operation);
}
public void blue(View view){
operation = Bitmap.createBitmap(bmp.getWidth(),bmp.getHeight(), bmp.getConfig());
for(int i=0; i<bmp.getWidth(); i++){
for(int j=0; j<bmp.getHeight(); j++){
int p = bmp.getPixel(i, j);
int r = Color.red(p);
int g = Color.green(p);
int b = Color.blue(p);
int alpha = Color.alpha(p);
r = 0;
g = 0;
b = b+150;
alpha = 0;
operation.setPixel(i, j, Color.argb(Color.alpha(p), r, g, b));
}
}
im.setImageBitmap(operation);
}
}
Following is the modified content of the xml 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:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp"
android:text="Image Effects" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials Point"
android:id="@+id/textView2"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:textSize="35dp"
android:textColor="#ff16ff01" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:layout_below="@+id/textView2"
android:layout_centerHorizontal="true"
android:src="@drawable/abc"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Gray"
android:onClick="gray"
android:id="@+id/button"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="97dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="dark"
android:onClick="dark"
android:id="@+id/button2"
android:layout_alignBottom="@+id/button"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Bright"
android:onClick="bright"
android:id="@+id/button3"
android:layout_alignTop="@+id/button2"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Red"
android:onClick="gama"
android:id="@+id/button4"
android:layout_below="@+id/button3"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Green"
android:onClick="green"
android:id="@+id/button5"
android:layout_alignTop="@+id/button4"
android:layout_alignLeft="@+id/button3"
android:layout_alignStart="@+id/button3" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="blue"
android:onClick="blue"
android:id="@+id/button6"
android:layout_below="@+id/button2"
android:layout_toRightOf="@+id/textView"
android:layout_toEndOf="@+id/textView" />
</RelativeLayout>
Following is the content of AndroidManifest.xml file.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<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 our application we just modified. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project's activity files and click Run icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window −
Now if you will look at your device screen , you will see the an image of android along with three buttons.
Now just select the Gray button that will convert your image into grayscale and will update the UI. It is shown below −
Now tap on the bright button, that will add some value to each pixel of the image and thus makes an illusion of brightness. It is shown below −
Now tap on the dark button, that will subtract some value to each pixel of the image and thus makes an illusion of dark. It is shown below −
Now tap on the red button, that will subtract some value to each pixel of the image and thus makes an illusion of dark. It is shown below −
Now tap on the green button, that will subtract some value to each pixel of the image and thus makes an illusion of dark. It is shown below −
Now tap on the blue button, that will subtract some value to each pixel of the image and thus makes an illusion of dark. It is shown below −
46 Lectures
7.5 hours
Aditya Dua
32 Lectures
3.5 hours
Sharad Kumar
9 Lectures
1 hours
Abhilash Nelson
14 Lectures
1.5 hours
Abhilash Nelson
15 Lectures
1.5 hours
Abhilash Nelson
10 Lectures
1 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 3861,
"s": 3607,
"text": "Android allows you to manipulate images by adding different kinds of effects on the images. You can easily apply image processing techniques to add certain kinds of effects on images. The effects could be brightness,darkness, grayscale conversion e.t.c.... |
Replace one string with another string with Java Regular Expressions | To replace one string with another string using Java Regular Expressions, we need to use the replaceAll() method. The replaceAll() method returns a String replacing all the character sequence matching the regular expression and String after replacement.
Declaration − The java.lang.String.replaceAll() method is declared as follows −
public String replaceAll(String regex, String replaced)
Let us see a program to replace one string with another string using Java Regular Expressions −
Live Demo
public class Example {
public static void main( String args[] ) {
String str = new String("Good Harry Good");
System.out.println( "Initial String : "+ str);
// replacing "Good" with "Bad"
str = str.replaceAll( "Good" , "Bad" );
System.out.println( "The String after substitution : "+str );
}
}
Initial String : Good Harry Good
The String after substitution : Bad Harry Bad | [
{
"code": null,
"e": 1316,
"s": 1062,
"text": "To replace one string with another string using Java Regular Expressions, we need to use the replaceAll() method. The replaceAll() method returns a String replacing all the character sequence matching the regular expression and String after replacement.... |
Explaining Every Line of vim-sensible | by Rionaldi Chandraseta | Towards Data Science | There are 3 possible reasons why you clicked on this story. First, it pops up in your screen as a recommended story. You are not using Vim, but you are curious about Vim and Sensible Vim.
Alternatively, you have been obsessed with Vim for years and you thought “I already know all the lines inside it, but it’s an article about Vim so I will read it anyway.”
Finally, you are in the same stage of learning Vim as me and you have searched about an annotated version of Sensible but haven’t found one.
First, I will give a quick explanation about vimrc file. Vimrc file is a configuration file for Vim that enables you to customise Vim, install plugins, and so on. It is usually found in ~/.vimrc, but you can create it if it’s not there. For Windows, you can find more information about finding the vimrc file here.
vim.fandom.com
I was searching for a vimrc file that is filled with useful defaults to act as a base for my future vimrc. First, I want to share a recurring answer I found on multiple posts and discussions. Quoting from this post by Doug Black,
Don’t put any lines in your vimrc that you don’t understand.
I believe that is a really sound advice. A programmer wouldn’t put any extra or unnecessary lines inside their code, this should be the case too with vimrc files.
Along my search, I stumbled upon this Reddit post stating that Sensible is a good starting point for a vimrc file.
github.com
Compared to other alternatives I got, which was either quite similar with Sensible or over 300 lines, I decided to dive deeper into this as a starting point.
Here’s the full code for Sensible Vim.
Some of the hardest-to-understand lines are commented, but most of them don’t have any explanations at all. It’s understandable though, for those more familiar with Vim, it would not make sense to put comments on these lines.
Maybe it will look like this for them.
if speed > 80.0: # checks if speed is more than 80.0 speeding = True # set speeding flag to True n_violation += 1 # add 1 to variable n_violation
Anyway, I’m not a Vim expert, so I wanted the over-annotated version for me to better understand what these lines actually do.
Here’s what I found out, feel free to skip through some of the trivial explanations.
if exists(‘g:loaded_sensible’) || &compatible finishelse let g:loaded_sensible = ‘yes’endif
The very first bit is to set a vim variable of loaded_sensibleto ‘yes’, presumably for compatibility with other plugins that check if vim-sensible is used.
if has(‘autocmd’) filetype plugin indent onendif
The line will check if autocmd is enabled. Most Vim will come with it, but some distributions such as vim-small and vim-tiny will come without autocmd by default.
In this case, checking for autocmd is needed because the filetype detection system needs it to work properly.
filetype plugin indent on is a short form of these commands.
filetype onfiletype plugin onfiletype indent on
The first command turns on filetype detection for Vim to help set syntax highlighting and other options. The plugin part will load plugins for specific filetype if they exist. The last bit will load indent file for specific filetype if they exist too.
For example, if you want to activate certain plugins for only Python language, then you can create a file ~/.vim/ftplugin/python.vim. Put all the plugins and commands you want specifically for Python inside that file.
A good practice is to separate the indent configuration inside another file (~/.vim/indent/python.vim). However, I usually just put the indents inside the plugin file.
if has(‘syntax’) && !exists(‘g:syntax_on’) syntax enableendif
Similar with previous if command, this one checks if Vim is compiled with syntax and if the global variable syntax_on already exists. The goal is to avoid turning on syntax multiple times if it was already enabled.
set autoindent
autoindent option will use the current indentation when creating a new line in Insert mode, both through normal Return or o/O.
set backspace=indent,eol,start
If you have been using Vim for a while, you would notice that sometimes your Backspace key will not work properly in Insert mode. This would happen when you try to backspace over automatically inserted indents, line breaks, and start of insert.
Setting these backspace options will enable you to perform backspace normally over them in that particular order.
set complete-=i
The -= operator in Vim means it will remove the options if it’s already set. In this case, it will remove the i option from autocomplete.
The i option states that it will “scan current and included files”, which might pollute the autocomplete results if your current file includes a lot of other files. As such, it makes sense to disable this option.
set smarttab
smarttab will insert n blanks according to either shiftwidth, tabstop, or softtabstop if they are configured and will also delete a shiftwidth blanks at the start of the line instead of one blank by default.
set nrformats-=octal
nrformats is short for number formats, which helps define what kind of format will be considered as number for Vim. If you type 13 and then hover over it in Normal mode and press Ctrl+A, then it will increment it to 14. Or you can use Ctrl+X to decrement it to 12.
The octal option will cause 007 to be incremented to 010 due to using base 8. In normal usage, this is not the expected behaviour since not a lot of people are using base 8 in their daily work. By disabling it, 007 will be incremented to 008.
if !has(‘nvim’) && &ttimeoutlen == -1 set ttimeout set ttimeoutlen=100endif
The nvim variable is used to check if you are running NeoVim or normal Vim. ttimeoutlen sets the timeout for key codes, such as Escape, Ctrl, Shift, etc. By default, the value of ttimeoutlen is -1, which will be changed to 100, but this line sets it explicitly instead.
What’s the use of ttimeoutlen? Let’s say you set a mapping for Cmd+Shift+Up. The key code for that command is ^[[1;6A. On the other hand, the key code for Esc is ^[. If you set ttimeoutlen to 5000, every time you hit the Esc key, it will wait 5 seconds before registering the Esc command. This is due to Vim thinking there is a chance that you will press the rest of the key codes within the 5 seconds window.
There might be a case where it’s useful to set the ttimeoutlen longer, but personally I didn’t find them useful for my use case.
set incsearch
Incremental search or incsearch allows Vim to directly go to the next matching result as you type your search keywords. Without this setting, you need to press Enter to make Vim go to the search result.
“ Use <C-L> to clear the highlighting of :set hlsearch.if maparg(‘<C-L>’, ’n’) ==# ‘’ nnoremap <silent> <C-L> :nohlsearch<C-R>=has(‘diff’)?’<Bar>diffupdate’:’’<CR><CR><C-L>endif
Thankfully this code come with an explanation, because I will definitely spend quite a while before figuring out what it meant. If you have hlsearch enabled, then pressing Ctrl+L will clear the highlighting because it will not go away on its own.
set laststatus=2
Default value for laststatus is 1, which means Vim’s status bar will only show if there are 2 or more Vim windows open. By setting the value to 2, now the status bar will always be there even if you only open 1 Vim window.
set ruler
Show the line and column number of the cursor position. Sometimes it’s a bit redundant since most plugins for status bar have built-in ones.
set wildmenu
When invoking autocomplete in command-line, having wildmenu turned on will show the possible completion above the command-line. Easiest way to see the effect is to type :! in Normal mode and then press Tab to trigger the autocomplete.
if !&scrolloff set scrolloff=1endif
The scrolloff value ensures that you have at least n lines above and/or below your cursor at all time. This line checks if you have set the scrolloff value or not, and set it to 1 if you haven’t.
Default value for scrolloff is 5, so this setting actually reduces that to 1.Some people set the value to a very large number (999) to keep the cursor in the middle of the screen, but I find it a bit disorienting to have the screen refreshes and move by one line every time I created a new line. That said, I also set mine to 1.
if !&sidescrolloff set sidescrolloff=5endif
If scrolloff is for the lines above and below, sidescrolloff is for the number of characters on the left and right side of the cursor. The default value is 0. You can also set this to 999 to keep the cursor in the middle of the line.
set display+=lastline
If you open a file with a really long line and it doesn’t fit the screen, Vim will usually replace it with a bunch of “@”. By setting it to lastline, Vim will show as much characters as possible and then put “@@@” on the last columns.
The line uses += to avoid overriding the setting if you have set it to truncate, which will show the “@@@” in the first columns instead.
if &encoding ==# ‘latin1’ && has(‘gui_running’) set encoding=utf-8endif
The ==# operator means case-sensitive comparison, which is different than == since it depends on :set ignorecase. This line will change the encoding from latin1 to utf-8 if Vim has GUI running.
if &listchars ==# ‘eol:$’ set listchars=tab:>\ ,trail:-,extends:>,precedes:<,nbsp:+endif
listchars is used to specify how specific characters are displayed when using the command :list. The default is 'eol:$', so this line will not overwrite your setting if you have configured your own listchars.
Tabs will be replaced with > followed by a number of \ until the end of the tab. Trailing spaces will be replaced with -. Extend character > will be displayed in the last column and precede character < will be displayed in the first column if the current line does not fit on-screen. Finally, nbsp stands for non-breakable space character, which will be replaced with +.
if v:version > 703 || v:version == 703 && has(“patch541”) set formatoptions+=j “ Delete comment character when joining commented linesendif
Fortunately, this is also a commented line. Add the j option for formatoptions if Vim version is newer than 7.3 or version 7.3 with patch 541.
This line will delete comment character (e.g. “#”, “//”) when you are joining commented lines. The default value for formatoptions in Vim is tcq, but this is a bit misleading since it could change based on the opened file type.
if has(‘path_extra’) setglobal tags-=./tags tags-=./tags; tags^=./tags;endif
The setglobal command is a bit different from the usual set command. By using set, we set both the local and global value of an option, while the setglobal only set the global value.
Global value is the default value that is applied to all of Vim. Local value only applies to the current window or buffer.
tags command defines the file names for the tag command. What the line does is to remove ./tags and ./tags; from the current tags. The ^= command prepends the value ./tags; into the current tags.
For example, if the current value for tags is ./a, ./b and we execute setglobal tags ^= ./tags;, it will be changed into ./tags;, ./a, ./b. The ;means that Vim will stop looking for the tag file if it is already found in ./tags.
if &shell =~# ‘fish$’ && (v:version < 704 || v:version == 704 && !has(‘patch276’)) set shell=/usr/bin/env\ bashendif
=~# operator means match with regular expression, so in this case it checks if you are using fish shell. There are some known issues with Vim when it’s running on fish, mainly because fish is not fully POSIX compatible.
stackoverflow.com
This line will set your shell to bash if you are using older version of Vim (older than 7.4) or using version 7.4 without patch 276 to avoid errors in running some commands that could not be executed with fish shell.
set autoread
This will make Vim automatically read a file when it detects that the file has been changed outside of Vim. However, if the file is deleted, it will not be re-read to keep the content from before it was deleted.
if &history < 1000 set history=1000endif
Set the number of history that is kept to minimum 1000. By default, Vim will only remember 50 for each type of history. There are five types of history in Vim.
: commands
search strings
expressions
input lines (input() function)
debug mode commands
if &tabpagemax < 50 set tabpagemax=50endif
Set the maximum tab pages to be opened using the -p command line argument or the :tab all command to at least 50 from the default value 10.
if !empty(&viminfo) set viminfo^=!endif
Viminfo is a file that is written automatically by Vim as sort of a “cache” to remember information such as command line history, search string hitory, last search pattern, global variables, etc.
This line will prepend the ! value, which will save and restore global variables that start with uppercase letter and don’t have any lowercase letter in them.
Alternatively, if you want to run Vim in a kind of private mode, you can disable the viminfo functionality by using the command set viminfo=.
set sessionoptions-=options
Removing the options value from sessionoptions will disable saving of options, mappings, and global values when you use :mksession to make a session.
Tim Pope himself explains that he disable it because remembering global options will override changes made to the vimrc, which he doesn’t want.
github.com
set viewoptions-=options
Similar with the previous line, this line will disable the same things when using :mkview to make views.
I am not too familiar with views, but this page explains how not using this line could cause Vim to jump to a different working directory when loading a saved view.
vim.fandom.com
“ Allow color schemes to do bright colors without forcing bold.if &t_Co == 8 && $TERM !~# ‘^Eterm’ set t_Co=16endif
t_Co is the number of colours used by the terminal. This will increase the colours to 16 when the current number of colours is set to 8 and current terminal is not Eterm.
Most modern terminal doesn’t need this though, since usually it will be set to 256 by default. You can check this by typing :echo &t_Co.
“ Load matchit.vim, but only if the user hasn’t installed a newer version.if !exists(‘g:loaded_matchit’) && findfile(‘plugin/matchit.vim’, &rtp) ==# ‘’ runtime! macros/matchit.vimendif
matchit is a Vim feature that enables us to jump between opening and closing parentheses, HTML tags, and more. You can try this by pressing % in Normal mode on top of an opening bracket and it will move your cursor to the matching closing bracket.
This line will enable matchit if it is not yet enabled or the existing one is still the older version.
if empty(mapcheck(‘<C-U>’, ‘i’)) inoremap <C-U> <C-G>u<C-U>endifif empty(mapcheck(‘<C-W>’, ‘i’)) inoremap <C-W> <C-G>u<C-W>endif
The mapcheck command checks if you have set a custom mapping for specific key in certain mode. In this case, it checks if you have mapped Ctrl+U and Ctrl+W in Insert mode before creating a new mapping for them.
These two lines will prevent accidental deletion without the possibility of doing undo with both Ctrl+U and Ctrl+W. By doing Ctrl+G u before the actual Ctrl+U or Ctrl+W, we can recover our deleted text with the undo operation (u in Normal mode), which is not possible without these remaps.
vim.fandom.com
After understanding, or at least trying to understand, all of these lines, decided to not install Sensible as a plugin, but instead steal some of the useful lines.
One of my favourites is the set incsearch paired with set hlsearch to enable incremental search and highlight the search result incrementally too.
There are some I omitted, such as setting the shell to bash if using fish shell since I’m using zsh shell myself.
towardsdatascience.com
At first, I started my search for the best vimrc file to built on top of. Along the search, I found out that a lot of other people also searched the same thing. However, after searching more about Vim configuration and gaining basic understanding of it, I decided to build one from scratch since I use Vim not only for coding but also for writing.
If any of the explanation is wrong or not clear enough, please feel free to post a comment to give correction or ask for clarification on any lines.
One last tip, if you are ever unsure of what a line does, you can search Vim’s manual by typing :h 'commandname' to show the help for a specific command. It’s a good practice to know what the commands do and its effect in your vimrc file.
Learning Machine is a series of stories about things happening in the world of Machine Learning that I found interesting enough to share. Oh, and sometimes it will be about the fundamentals of Machine Learning too. Follow me to get regular updates on new stories. | [
{
"code": null,
"e": 360,
"s": 172,
"text": "There are 3 possible reasons why you clicked on this story. First, it pops up in your screen as a recommended story. You are not using Vim, but you are curious about Vim and Sensible Vim."
},
{
"code": null,
"e": 531,
"s": 360,
"text":... |
Android - Google Maps | Android allows us to integrate google maps in our application. You can show any location on the map , or can show different routes on the map e.t.c. You can also customize the map according to your choices.
Now you have to add the map fragment into xml layout file. Its syntax is given below −
<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
The next thing you need to do is to add some permissions along with the Google Map API key in the AndroidManifest.XML file. Its syntax is given below −
<!--Permissions-->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="com.google.android.providers.gsf.permission.
READ_GSERVICES" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!--Google MAP API key-->
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyDKymeBXNeiFWY5jRUejv6zItpmr2MVyQ0" />
You can easily customize google map from its default view , and change it according to your demand.
You can place a maker with some text over it displaying your location on the map. It can be done by via addMarker() method. Its syntax is given below −
final LatLng TutorialsPoint = new LatLng(21 , 57);
Marker TP = googleMap.addMarker(new MarkerOptions()
.position(TutorialsPoint).title("TutorialsPoint"));
You can also change the type of the MAP. There are four different types of map and each give a different view of the map. These types are Normal,Hybrid,Satellite and terrain. You can use them as below
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
You can also enable or disable the zoom gestures in the map by calling the setZoomControlsEnabled(boolean) method. Its syntax is given below −
googleMap.getUiSettings().setZoomGesturesEnabled(true);
Apart from these customization, there are other methods available in the GoogleMap class , that helps you more customize the map. They are listed below −
addCircle(CircleOptions options)
This method add a circle to the map
addPolygon(PolygonOptions options)
This method add a polygon to the map
addTileOverlay(TileOverlayOptions options)
This method add tile overlay to the map
animateCamera(CameraUpdate update)
This method Moves the map according to the update with an animation
clear()
This method removes everything from the map.
getMyLocation()
This method returns the currently displayed user location.
moveCamera(CameraUpdate update)
This method repositions the camera according to the instructions defined in the update
setTrafficEnabled(boolean enabled)
This method Toggles the traffic layer on or off.
snapshot(GoogleMap.SnapshotReadyCallback callback)
This method Takes a snapshot of the map
stopAnimation()
This method stops the camera animation if there is one in progress
Here is an example demonstrating the use of GoogleMap class. It creates a basic M application that allows you to navigate through the map.
To experiment with this example , you can run this on an actual device or in an emulator.
Create a project with google maps activity as shown below −
It will open the following screen and copy the console url for API Key as shown below −
Copy this and paste it to your browser. It will give the following screen −
Click on continue and click on Create API Key then it will show the following screen
Here is the content of activity_main.xml.
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.tutorialspoint7.myapplication.MapsActivity" />
Here is the content of MapActivity.java.
package com.example.tutorialspoint7.myapplication;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera.
* In this case, we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device.
* This method will only be triggered once the user has installed
Google Play services and returned to the app.
*/
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng TutorialsPoint = new LatLng(21, 57);
mMap.addMarker(new
MarkerOptions().position(TutorialsPoint).title("Tutorialspoint.com"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(TutorialsPoint));
}
}
Following is the content of AndroidManifest.xml file.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.tutorialspoint7.myapplication">
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but you must specify either coarse or fine
location permissions for the 'MyLocation' functionality.
-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<!--
The API key for Google Maps-based APIs is defined as a string resource.
(See the file "res/values/google_maps_api.xml").
Note that the API key is linked to the encryption key used to sign the APK.
You need a different API key for each encryption key, including the release key
that is used to sign the APK for publishing.
You can define the keys for the debug and
release targets in src/debug/ and src/release/.
-->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="AIzaSyAXhBdyKxUo_cb-EkSgWJQTdqR0QjLcqes" />
<activity
android:name=".MapsActivity"
android:label="@string/title_activity_maps">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Output should be like this −
46 Lectures
7.5 hours
Aditya Dua
32 Lectures
3.5 hours
Sharad Kumar
9 Lectures
1 hours
Abhilash Nelson
14 Lectures
1.5 hours
Abhilash Nelson
15 Lectures
1.5 hours
Abhilash Nelson
10 Lectures
1 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 3814,
"s": 3607,
"text": "Android allows us to integrate google maps in our application. You can show any location on the map , or can show different routes on the map e.t.c. You can also customize the map according to your choices."
},
{
"code": null,
"e": 3901,
... |
Google Charts - TreeMap Chart | TreeMap is a visual representation of a data tree, where each node may have zero or more children, and one parent (except for the root). Each node is displayed as a rectangle, can be sized and colored according to values that we assign. Sizes and colors are valued relative to all other nodes in the graph. Following is an example of a treemap chart. We've already seen the configuration used to draw this chart in Google Charts Configuration Syntax chapter. So, let's see the complete example.
We've used TreeMap class to show treemap diagram.
//TreeMap chart
var chart = new google.visualization.TreeMap(document.getElementById('container'));
googlecharts_treemap.htm
<html>
<head>
<title>Google Charts Tutorial</title>
<script type = "text/javascript" src = "https://www.gstatic.com/charts/loader.js">
</script>
<script type = "text/javascript" src = "https://www.google.com/jsapi">
</script>
<script type = "text/javascript">
google.charts.load('current', {packages: ['treemap']});
</script>
</head>
<body>
<div id = "container" style = "width: 550px; height: 400px; margin: 0 auto">
</div>
<script language = "JavaScript">
function drawChart() {
// Define the chart to be drawn.
var data = new google.visualization.DataTable();
var data = google.visualization.arrayToDataTable([
['Location', 'Parent', 'Market trade volume (size)', 'Market increase/decrease (color)'],
['Global', null, 0, 0],
['America', 'Global', 0, 0],
['Europe', 'Global', 0, 0],
['Asia', 'Global', 0, 0],
['Australia', 'Global', 0, 0],
['Africa', 'Global', 0, 0],
['USA', 'America', 52, 31],
['Mexico', 'America', 24, 12],
['Canada', 'America', 16, -23],
['France', 'Europe', 42, -11],
['Germany', 'Europe', 31, -2],
['Sweden', 'Europe', 22, -13],
['China', 'Asia', 36, 4],
['Japan', 'Asia', 20, -12],
['India', 'Asia', 40, 63],
['Egypt', 'Africa', 21, 0],
['Congo', 'Africa', 10, 12],
['Zaire', 'Africa', 8, 10]
]);
var options = {
minColor: '#f00',
midColor: '#ddd',
maxColor: '#0d0',
headerHeight: 15,
fontColor: 'black',
showScale: true
};
// Instantiate and draw the chart.
var chart = new google.visualization.TreeMap(document.getElementById('container'));
chart.draw(data, options);
}
google.charts.setOnLoadCallback(drawChart);
</script>
</body>
</html>
Verify the result.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2756,
"s": 2261,
"text": "TreeMap is a visual representation of a data tree, where each node may have zero or more children, and one parent (except for the root). Each node is displayed as a rectangle, can be sized and colored according to values that we assign. Sizes and colors... |
How to check whether a form or a control is valid or not in Angular 10 ? - GeeksforGeeks | 03 Jun, 2021
In this article, we are going to check whether a form is touched or not in Angular 10. The valid property is used to report that the control or the form is valid or not.
Syntax:
form.valid
Return Value:
boolean: the boolean value to check whether a form is valid or not.
NgModule: Module used by the valid property is:
FormsModule
Approach:
Create the Angular app to be used.
In app.component.html make a form using ngForm directive.
In app.component.ts get the information using the valid property.
Serve the angular app using ng serve to see the output.
Example:
Javascript
import { Component } from '@angular/core';import { FormGroup, FormControl, FormArray, Validators } from '@angular/forms' @Component({ selector: 'app-root', templateUrl: './app.component.html'}) export class AppComponent { form = new FormGroup({ name: new FormControl( ), rollno: new FormControl() }); get name(): any { return this.form.get('name'); } onSubmit(): void { console.log("Form is valid : ", this.form.valid); }}
app.component.html
<form [formGroup]="form" (ngSubmit)="onSubmit()"> <input formControlName="name" placeholder="Name"> <br> <button type='submit'>Submit</button> <br><br></form>
Output:
Reference: >https://angular.io/api/forms/AbstractControlDirective#valid
Angular10
AngularJS-Questions
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 10 Angular Libraries For Web Developers
How to make a Bootstrap Modal Popup in Angular 9/8 ?
Angular PrimeNG Dropdown Component
How to create module with Routing in Angular 9 ?
Angular 10 (blur) Event
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills | [
{
"code": null,
"e": 25183,
"s": 25155,
"text": "\n03 Jun, 2021"
},
{
"code": null,
"e": 25353,
"s": 25183,
"text": "In this article, we are going to check whether a form is touched or not in Angular 10. The valid property is used to report that the control or the form is valid o... |
sched_setscheduler() - Unix, Linux System Call | Unix - Home
Unix - Getting Started
Unix - File Management
Unix - Directories
Unix - File Permission
Unix - Environment
Unix - Basic Utilities
Unix - Pipes & Filters
Unix - Processes
Unix - Communication
Unix - The vi Editor
Unix - What is Shell?
Unix - Using Variables
Unix - Special Variables
Unix - Using Arrays
Unix - Basic Operators
Unix - Decision Making
Unix - Shell Loops
Unix - Loop Control
Unix - Shell Substitutions
Unix - Quoting Mechanisms
Unix - IO Redirections
Unix - Shell Functions
Unix - Manpage Help
Unix - Regular Expressions
Unix - File System Basics
Unix - User Administration
Unix - System Performance
Unix - System Logging
Unix - Signals and Traps
Unix - Useful Commands
Unix - Quick Guide
Unix - Builtin Functions
Unix - System Calls
Unix - Commands List
Unix Useful Resources
Computer Glossary
Who is Who
Copyright © 2014 by tutorialspoint
#include <sched.h>
int sched_setscheduler(pid_t pid, int policy,
const struct sched_param *param);
int sched_getscheduler(pid_t pid);
struct sched_param {
...
int sched_priority;
...
};
int sched_setscheduler(pid_t pid, int policy,
const struct sched_param *param);
int sched_getscheduler(pid_t pid);
struct sched_param {
...
int sched_priority;
...
};
sched_getscheduler() queries the scheduling policy currently applied to the process
identified by pid. If pid equals zero, the policy of the
calling process will be retrieved.
SCHED_OTHER is the default universal time-sharing scheduler
policy used by most processes.
SCHED_BATCH is intended for "batch" style execution of processes.
SCHED_FIFO and SCHED_RR are
intended for special time-critical applications that need precise
control over the way in which runnable processes are selected for
execution.
Processes scheduled with SCHED_OTHER or SCHED_BATCH
must be assigned the static priority 0.
Processes scheduled under SCHED_FIFO or
SCHED_RR can have a static priority in the range 1 to 99.
The system calls sched_get_priority_min() and
sched_get_priority_max() can be used to find out the valid
priority range for a scheduling policy in a portable way on all
POSIX.1-2001 conforming systems.
All scheduling is preemptive: If a process with a higher static
priority gets ready to run, the current process will be preempted and
returned into its wait list. The scheduling policy only determines the
ordering within the list of runnable processes with equal static
priority.
Since Linux 2.6.12, the
RLIMIT_RTPRIO resource limit defines a ceiling on an unprivileged process’s
priority for the
SCHED_RR and
SCHED_FIFO policies.
If an unprivileged process has a non-zero
RLIMIT_RTPRIO soft limit, then it can change its scheduling policy and priority,
subject to the restriction that the priority cannot be set to a
value higher than the
RLIMIT_RTPRIO soft limit.
If the
RLIMIT_RTPRIO soft limit is 0, then the only permitted change is to lower the priority.
Subject to the same rules,
another unprivileged process can also make these changes,
as long as the effective user ID of the process making the change
matches the real or effective user ID of the target process.
See
getrlimit(2)
for further information on
RLIMIT_RTPRIO. Privileged
(CAP_SYS_NICE) processes ignore this limit; as with older older kernels,
they can make arbitrary changes to scheduling policy and priority.
Memory locking is usually needed for real-time processes to avoid
paging delays, this can be done with
mlock() or
mlockall().
As a non-blocking end-less loop in a process scheduled under
SCHED_FIFO or SCHED_RR will block all processes with lower
priority forever, a software developer should always keep available on
the console a shell scheduled under a higher static priority than the
tested application. This will allow an emergency kill of tested
real-time applications that do not block or terminate as expected.
POSIX systems on which
sched_setscheduler() and
sched_getscheduler() are available define
_POSIX_PRIORITY_SCHEDULING in <unistd.h>.
Standard Linux is
not designed to support
hard real-time applications, that is, applications in which deadlines
(often much shorter than a second) must be guaranteed or the system
will fail catastrophically.
Like all general-purpose operating systems, Linux
is designed to maximize average case performance
instead of worst case performance.
Linux’s worst case performance for
interrupt handling is much poorer than its average case, its various
kernel locks (such as for SMP) produce long maximum wait times, and
many of its performance improvement techniques decrease average time by
increasing worst-case time.
For most situations, that’s what you want, but
if you truly are developing a hard real-time application,
consider using hard real-time extensions to Linux such as
RTLinux (http://www.rtlinux.org) or RTAI (http://www.rtai.org)
or use a different operating system
designed specifically for hard real-time applications.
getpriority (2)
getpriority (2)
mlock (2)
mlock (2)
mlockall (2)
mlockall (2)
munlock (2)
munlock (2)
munlockall (2)
munlockall (2)
nice (2)
nice (2)
sched_get_priority_max (2)
sched_get_priority_max (2)
sched_get_priority_min (2)
sched_get_priority_min (2)
sched_getaffinity (2)
sched_getaffinity (2)
sched_getparam (2)
sched_getparam (2)
sched_rr_get_interval (2)
sched_rr_get_interval (2)
sched_setaffinity (2)
sched_setaffinity (2)
sched_setparam (2)
sched_setparam (2)
sched_yield (2)
sched_yield (2)
setpriority (2)
setpriority (2)
Advertisements
129 Lectures
23 hours
Eduonix Learning Solutions
5 Lectures
4.5 hours
Frahaan Hussain
35 Lectures
2 hours
Pradeep D
41 Lectures
2.5 hours
Musab Zayadneh
46 Lectures
4 hours
GUHARAJANM
6 Lectures
4 hours
Uplatz
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 1466,
"s": 1454,
"text": "Unix - Home"
},
{
"code": null,
"e": 1489,
"s": 1466,
"text": "Unix - Getting Started"
},
{
"code": null,
"e": 1512,
"s": 1489,
"text": "Unix - File Management"
},
{
"code": null,
"e": 1531,
"s": 1... |
C# Linq FirstorDefault Method | Use the FirstorDefault() method to return the first element of a sequence or a default value if element isn’t there.
The following is our empty list −
List<double> val = new List<double> { };
Now, we cannot display the first element, since it is an empty collection. For that, use the FirstorDefault() method to display the default value.
val.AsQueryable().FirstOrDefault();
The following is the complete example.
Live Demo
using System;
using System.Collections.Generic;
using System.Linq;
class Demo {
static void Main() {
List<double> val = new List<double> { };
double d = val.AsQueryable().FirstOrDefault();
Console.WriteLine("Default Value = "+d);
if (d == 0.0D) {
d = 0.1D;
}
Console.WriteLine("Default Value changed = "+d);
}
}
Default Value = 0
Default Value changed = 0.1 | [
{
"code": null,
"e": 1179,
"s": 1062,
"text": "Use the FirstorDefault() method to return the first element of a sequence or a default value if element isn’t there."
},
{
"code": null,
"e": 1213,
"s": 1179,
"text": "The following is our empty list −"
},
{
"code": null,
... |
Vertical Concatenation in Matrix in Python | When it is required to concatenate a matrix vertically, the list comprehension can be used.
Below is a demonstration of the same −
Live Demo
from itertools import zip_longest
my_list = [["Hi", "Rob"], ["how", "are"], ["you"]]
print("The list is : ")
print(my_list)
my_result = ["".join(elem) for elem in zip_longest(*my_list, fillvalue ="")]
print("The list after concatenating the column is : ")
print(my_result)
The list is :
[['Hi', 'Rob'], ['how', 'are'], ['you']]
The list after concatenating the column is :
['Hihowyou', 'Robare']
The required packages are imported.
The required packages are imported.
A list of list is defined, and is displayed on the console.
A list of list is defined, and is displayed on the console.
The list comprehension is used to zip the elements, and join them by eliminating the empty spaces.
The list comprehension is used to zip the elements, and join them by eliminating the empty spaces.
This is assigned to a variable.
This is assigned to a variable.
This variable is displayed as output on the console.
This variable is displayed as output on the console. | [
{
"code": null,
"e": 1154,
"s": 1062,
"text": "When it is required to concatenate a matrix vertically, the list comprehension can be used."
},
{
"code": null,
"e": 1193,
"s": 1154,
"text": "Below is a demonstration of the same −"
},
{
"code": null,
"e": 1204,
"s":... |
Groovy - matches() | It outputs whether a String matches the given regular expression.
Boolean matches(String regex)
Regex − the expression for comparison.
This method returns true if, and only if, this string matches the given regular expression.
Following is an example of the usage of this method
class Example {
static void main(String[] args) {
String a = "Hello World";
println(a.matches("Hello"));
println(a.matches("Hello(.*)"));
}
}
When we run the above program, we will get the following result −
false
true
52 Lectures
8 hours
Krishna Sakinala
49 Lectures
2.5 hours
Packt Publishing
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2304,
"s": 2238,
"text": "It outputs whether a String matches the given regular expression."
},
{
"code": null,
"e": 2335,
"s": 2304,
"text": "Boolean matches(String regex)\n"
},
{
"code": null,
"e": 2374,
"s": 2335,
"text": "Regex − the e... |
Count of nodes in a Binary tree with immediate children as its factors - GeeksforGeeks | 15 Jun, 2021
Given a Binary Tree, the task is to print the count of nodes whose immediate children are its factors.
Examples:
Input:
1
/ \
15 20
/ \ / \
3 5 4 2
\ /
2 3
Output: 2
Explanation:
Children of 15 (3, 5)
are factors of 15
Children of 20 (4, 2)
are factors of 20
Input:
7
/ \
210 14
/ \ \
70 14 30
/ \ / \
2 5 10 15
/
23
Output:3
Explanation:
Children of 210 (70, 14)
are factors of 210
Children of 70 (2, 5)
are factors of 70
Children of 30 (10, 15)
are factors of 30
Approach: In order to solve this problem, we need to traverse the given Binary Tree in Level Order fashion and for every node with both children, check if both the children have values which are factors of the value of the current node. If true, then count such nodes and print it at the end.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for Counting nodes// whose immediate children// are its factors #include <bits/stdc++.h>using namespace std; // A Tree nodestruct Node { int key; struct Node *left, *right;}; // Utility function to create a new nodeNode* newNode(int key){ Node* temp = new Node; temp->key = key; temp->left = temp->right = NULL; return (temp);} // Function to check and print if// immediate children of a node// are its factors or notbool areChilrenFactors( struct Node* parent, struct Node* a, struct Node* b){ if (parent->key % a->key == 0 && parent->key % b->key == 0) return true; else return false;} // Function to get the// count of full Nodes in// a binary treeunsigned int getCount(struct Node* node){ // If tree is empty if (!node) return 0; queue<Node*> q; // Do level order traversal // starting from root int count = 0; // Store the number of nodes // with both children as factors q.push(node); while (!q.empty()) { struct Node* temp = q.front(); q.pop(); if (temp->left && temp->right) { if (areChilrenFactors( temp, temp->left, temp->right)) count++; } if (temp->left != NULL) q.push(temp->left); if (temp->right != NULL) q.push(temp->right); } return count;} // Function to find total no of nodes// In a given binary treeint findSize(struct Node* node){ // Base condition if (node == NULL) return 0; return 1 + findSize(node->left) + findSize(node->right);} // Driver Codeint main(){ /* 10 / \ 40 36 / \ 18 12 / \ / \ 2 6 3 4 / 7 */ // Create Binary Tree as shown Node* root = newNode(10); root->left = newNode(40); root->right = newNode(36); root->right->left = newNode(18); root->right->right = newNode(12); root->right->left->left = newNode(2); root->right->left->right = newNode(6); root->right->right->left = newNode(3); root->right->right->right = newNode(4); root->right->right->right->left = newNode(7); // Print all nodes having // children as their factors cout << getCount(root) << endl; return 0;}
// Java program for Counting nodes// whose immediate children// are its factors import java.util.*; class GFG{ // A Tree nodestatic class Node { int key; Node left, right;}; // Utility function to create a new nodestatic Node newNode(int key){ Node temp = new Node(); temp.key = key; temp.left = temp.right = null; return (temp);} // Function to check and print if// immediate children of a node// are its factors or notstatic boolean areChilrenFactors( Node parent, Node a, Node b){ if (parent.key % a.key == 0 && parent.key % b.key == 0) return true; else return false;} // Function to get the// count of full Nodes in// a binary treestatic int getCount(Node node){ // If tree is empty if (node==null) return 0; Queue<Node> q = new LinkedList<Node>(); // Do level order traversal // starting from root int count = 0; // Store the number of nodes // with both children as factors q.add(node); while (!q.isEmpty()) { Node temp = q.peek(); q.remove(); if (temp.left!=null && temp.right!=null) { if (areChilrenFactors( temp, temp.left, temp.right)) count++; } if (temp.left != null) q.add(temp.left); if (temp.right != null) q.add(temp.right); } return count;} // Function to find total no of nodes// In a given binary treestatic int findSize(Node node){ // Base condition if (node == null) return 0; return 1 + findSize(node.left) + findSize(node.right);} // Driver Codepublic static void main(String[] args){ /* 10 / \ 40 36 / \ 18 12 / \ / \ 2 6 3 4 / 7 */ // Create Binary Tree as shown Node root = newNode(10); root.left = newNode(40); root.right = newNode(36); root.right.left = newNode(18); root.right.right = newNode(12); root.right.left.left = newNode(2); root.right.left.right = newNode(6); root.right.right.left = newNode(3); root.right.right.right = newNode(4); root.right.right.right.left = newNode(7); // Print all nodes having // children as their factors System.out.print(getCount(root) +"\n"); }} // This code is contributed by sapnasingh4991
# Python3 program for counting nodes# whose immediate children# are its factorsfrom collections import deque as queue # A Binary Tree Nodeclass Node: def __init__(self, key): self.data = key self.left = None self.right = None # Function to check and print if# immediate children of a node# are its factors or notdef areChildrenFactors(parent, a, b): if (parent.data % a.data == 0 and parent.data % b.data == 0): return True else: return False # Function to get the# count of full Nodes in# a binary treedef getCount(node): # Base Case if (not node): return 0 q = queue() # Do level order traversal # starting from root count = 0 # Store the number of nodes # with both children as factors q.append(node) while (len(q) > 0): temp = q.popleft() #q.pop() if (temp.left and temp.right): if (areChildrenFactors(temp, temp.left, temp.right)): count += 1 if (temp.left != None): q.append(temp.left) if (temp.right != None): q.append(temp.right) return count # Function to find total# number of nodes# In a given binary treedef findSize(node): # Base condition if (node == None): return 0 return (1 + findSize(node.left) + findSize(node.right)) # Driver Codeif __name__ == '__main__': # /* 10 # / \ # 40 36 # / \ # 18 12 # / \ / \ # 2 6 3 4 # / # 7 # */ # Create Binary Tree root = Node(10) root.left = Node(40) root.right = Node(36) root.right.left = Node(18) root.right.right = Node(12) root.right.left.left = Node(2) root.right.left.right = Node(6) root.right.right.left = Node(3) root.right.right.right = Node(4) root.right.right.right.left = Node(7) # Print all nodes having # children as their factors print(getCount(root)) # This code is contributed by mohit kumar 29
// C# program for Counting nodes// whose immediate children// are its factorsusing System;using System.Collections.Generic; class GFG{ // A Tree nodeclass Node { public int key; public Node left, right;}; // Utility function to create a new nodestatic Node newNode(int key){ Node temp = new Node(); temp.key = key; temp.left = temp.right = null; return (temp);} // Function to check and print if// immediate children of a node// are its factors or notstatic bool areChilrenFactors( Node parent, Node a, Node b){ if (parent.key % a.key == 0 && parent.key % b.key == 0) return true; else return false;} // Function to get the// count of full Nodes in// a binary treestatic int getCount(Node node){ // If tree is empty if (node == null) return 0; List<Node> q = new List<Node>(); // Do level order traversal // starting from root int count = 0; // Store the number of nodes // with both children as factors q.Add(node); while (q.Count != 0) { Node temp = q[0]; q.RemoveAt(0); if (temp.left!=null && temp.right != null) { if (areChilrenFactors( temp, temp.left, temp.right)) count++; } if (temp.left != null) q.Add(temp.left); if (temp.right != null) q.Add(temp.right); } return count;} // Function to find total no of nodes// In a given binary treestatic int findSize(Node node){ // Base condition if (node == null) return 0; return 1 + findSize(node.left) + findSize(node.right);} // Driver Codepublic static void Main(String[] args){ /* 10 / \ 40 36 / \ 18 12 / \ / \ 2 6 3 4 / 7 */ // Create Binary Tree as shown Node root = newNode(10); root.left = newNode(40); root.right = newNode(36); root.right.left = newNode(18); root.right.right = newNode(12); root.right.left.left = newNode(2); root.right.left.right = newNode(6); root.right.right.left = newNode(3); root.right.right.right = newNode(4); root.right.right.right.left = newNode(7); // Print all nodes having // children as their factors Console.Write(getCount(root) +"\n"); }} // This code is contributed by sapnasingh4991
<script> // Javascript program for Counting nodes// whose immediate children are its factors // A Tree nodeclass Node{ // Utility function to create a new node constructor(key) { this.key = key; this.left = this.right = null; }} // Function to check and print if// immediate children of a node// are its factors or notfunction areChilrenFactors(parent, a, b){ if (parent.key % a.key == 0 && parent.key % b.key == 0) return true; else return false;} // Function to get the// count of full Nodes in// a binary treefunction getCount(node){ // If tree is empty if (node == null) return 0; let q = []; // Do level order traversal // starting from root let count = 0; // Store the number of nodes // with both children as factors q.push(node); while (q.length != 0) { let temp = q.shift(); if (temp.left != null && temp.right != null) { if (areChilrenFactors( temp, temp.left, temp.right)) count++; } if (temp.left != null) q.push(temp.left); if (temp.right != null) q.push(temp.right); } return count;} // Function to find total no of nodes// In a given binary treefunction findSize(node){ // Base condition if (node == null) return 0; return 1 + findSize(node.left) + findSize(node.right);} // Driver Code /* 10 / \ 40 36 / \ 18 12 / \ / \ 2 6 3 4 / 7 */ // Create Binary Tree as shownlet root = new Node(10); root.left = new Node(40);root.right = new Node(36); root.right.left = new Node(18);root.right.right = new Node(12); root.right.left.left = new Node(2);root.right.left.right = new Node(6);root.right.right.left = new Node(3);root.right.right.right = new Node(4);root.right.right.right.left = new Node(7); // Print all nodes having// children as their factorsdocument.write(getCount(root) + "<br>"); // This code is contributed by unknown2108 </script>
3
sapnasingh4991
mohit kumar 29
unknown2108
Binary Tree
factor
tree-level-order
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Binary Tree | Set 3 (Types of Binary Tree)
Binary Tree | Set 2 (Properties)
A program to check if a binary tree is BST or not
Decision Tree
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
Introduction to Tree Data Structure
Lowest Common Ancestor in a Binary Tree | Set 1
Expression Tree
BFS vs DFS for Binary Tree
Sorted Array to Balanced BST | [
{
"code": null,
"e": 25148,
"s": 25120,
"text": "\n15 Jun, 2021"
},
{
"code": null,
"e": 25252,
"s": 25148,
"text": "Given a Binary Tree, the task is to print the count of nodes whose immediate children are its factors. "
},
{
"code": null,
"e": 25264,
"s": 25252,... |
Java Examples - User defined Exception | How to create user defined Exception ?
This example shows how to create user defined exception by extending Exception Class.
class MyException extends Exception {
String s1;
MyException(String s2) {
s1 = s2;
}
@Override
public String toString() {
return ("Output String = "+s1);
}
}
public class NewClass {
public static void main(String args[]) {
try {
throw new MyException("Custom message");
} catch(MyException exp) {
System.out.println(exp);
}
}
}
The above code sample will produce the following result.
Output String = Custom message
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2107,
"s": 2068,
"text": "How to create user defined Exception ?"
},
{
"code": null,
"e": 2193,
"s": 2107,
"text": "This example shows how to create user defined exception by extending Exception Class."
},
{
"code": null,
"e": 2597,
"s": 2193,... |
Redis - Hashes | Redis Hashes are maps between the string fields and the string values. Hence, they are the perfect data type to represent objects.
In Redis, every hash can store up to more than 4 billion field-value pairs.
redis 127.0.0.1:6379> HMSET tutorialspoint name "redis tutorial"
description "redis basic commands for caching" likes 20 visitors 23000
OK
redis 127.0.0.1:6379> HGETALL tutorialspoint
1) "name"
2) "redis tutorial"
3) "description"
4) "redis basic commands for caching"
5) "likes"
6) "20"
7) "visitors"
8) "23000"
In the above example, we have set Redis tutorials detail (name, description, likes, visitors) in hash named ‘tutorialspoint’.
Following table lists some basic commands related to hash.
Deletes one or more hash fields.
Determines whether a hash field exists or not.
Gets the value of a hash field stored at the specified key.
Gets all the fields and values stored in a hash at the specified key
Increments the integer value of a hash field by the given number
Increments the float value of a hash field by the given amount
Gets all the fields in a hash
Gets the number of fields in a hash
Gets the values of all the given hash fields
Sets multiple hash fields to multiple values
Sets the string value of a hash field
Sets the value of a hash field, only if the field does not exist
Gets all the values in a hash
Incrementally iterates hash fields and associated values
22 Lectures
40 mins
Skillbakerystudios
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2176,
"s": 2045,
"text": "Redis Hashes are maps between the string fields and the string values. Hence, they are the perfect data type to represent objects."
},
{
"code": null,
"e": 2252,
"s": 2176,
"text": "In Redis, every hash can store up to more than 4 bi... |
Apache Configuration for PHP | Apache uses httpd.conf file for global settings, and the .htaccess file for per-directory access settings. Older versions of Apache split up httpd.conf into three files (access.conf, httpd.conf, and srm.conf), and some users still prefer this arrangement.
Apache server has a very powerful, but slightly complex, configuration system of its own. Learn more about it at the Apache Web site − www.apache.org
The following section describe settings in httpd.conf that affect PHP directly and cannot be set elsewhere. If you have standard installation then httpd.conf will be found at /etc/httpd/conf:
This value sets the default number of seconds before any HTTP request will time out. If you set PHP's max_execution_time to longer than this value, PHP will keep grinding away but the user may see a 404 error. In safe mode, this value will be ignored; you must use the timeout value in php.ini instead
DocumentRoot designates the root directory for all HTTP processes on that server. It looks something like this on Unix −
DocumentRoot ./usr/local/apache_1.3.6/htdocs.
You can choose any directory as document root.
The PHP MIME type needs to be set here for PHP files to be parsed. Remember that you can associate any file extension with PHP like .php3, .php5 or .htm.
AddType application/x-httpd-php .php
AddType application/x-httpd-phps .phps
AddType application/x-httpd-php3 .php3 .phtml
AddType application/x-httpd-php .html
You must uncomment this line for the Windows apxs module version of Apache with shared object support −
LoadModule php4_module modules/php4apache.dll
or on Unix flavors −
LoadModule php4_module modules/mod_php.so
You must uncomment this line for the static module version of Apache.
AddModule mod_php4.c
45 Lectures
9 hours
Malhar Lathkar
34 Lectures
4 hours
Syed Raza
84 Lectures
5.5 hours
Frahaan Hussain
17 Lectures
1 hours
Nivedita Jain
100 Lectures
34 hours
Azaz Patel
43 Lectures
5.5 hours
Vijay Kumar Parvatha Reddy
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 3013,
"s": 2757,
"text": "Apache uses httpd.conf file for global settings, and the .htaccess file for per-directory access settings. Older versions of Apache split up httpd.conf into three files (access.conf, httpd.conf, and srm.conf), and some users still prefer this arrangemen... |
AI with Python - Unsupervised Learning: Clustering | Unsupervised machine learning algorithms do not have any supervisor to provide any sort of guidance. That is why they are closely aligned with what some call true artificial intelligence.
In unsupervised learning, there would be no correct answer and no teacher for the guidance. Algorithms need to discover the interesting pattern in data for learning.
Basically, it is a type of unsupervised learning method and a common technique for statistical data analysis used in many fields. Clustering mainly is a task of dividing the set of observations into subsets, called clusters, in such a way that observations in the same cluster are similar in one sense and they are dissimilar to the observations in other clusters. In simple words, we can say that the main goal of clustering is to group the data on the basis of similarity and dissimilarity.
For example, the following diagram shows similar kind of data in different clusters −
Following are a few common algorithms for clustering the data −
K-means clustering algorithm is one of the well-known algorithms for clustering the data. We need to assume that the numbers of clusters are already known. This is also called flat clustering. It is an iterative clustering algorithm. The steps given below need to be followed for this algorithm −
Step 1 − We need to specify the desired number of K subgroups.
Step 2 − Fix the number of clusters and randomly assign each data point to a cluster. Or in other words we need to classify our data based on the number of clusters.
In this step, cluster centroids should be computed.
As this is an iterative algorithm, we need to update the locations of K centroids with every iteration until we find the global optima or in other words the centroids reach at their optimal locations.
The following code will help in implementing K-means clustering algorithm in Python. We are going to use the Scikit-learn module.
Let us import the necessary packages −
import matplotlib.pyplot as plt
import seaborn as sns; sns.set()
import numpy as np
from sklearn.cluster import KMeans
The following line of code will help in generating the two-dimensional dataset, containing four blobs, by using make_blob from the sklearn.dataset package.
from sklearn.datasets.samples_generator import make_blobs
X, y_true = make_blobs(n_samples = 500, centers = 4,
cluster_std = 0.40, random_state = 0)
We can visualize the dataset by using the following code −
plt.scatter(X[:, 0], X[:, 1], s = 50);
plt.show()
Here, we are initializing kmeans to be the KMeans algorithm, with the required parameter of how many clusters (n_clusters).
kmeans = KMeans(n_clusters = 4)
We need to train the K-means model with the input data.
kmeans.fit(X)
y_kmeans = kmeans.predict(X)
plt.scatter(X[:, 0], X[:, 1], c = y_kmeans, s = 50, cmap = 'viridis')
centers = kmeans.cluster_centers_
The code given below will help us plot and visualize the machine's findings based on our data, and the fitment according to the number of clusters that are to be found.
plt.scatter(centers[:, 0], centers[:, 1], c = 'black', s = 200, alpha = 0.5);
plt.show()
It is another popular and powerful clustering algorithm used in unsupervised learning. It does not make any assumptions hence it is a non-parametric algorithm. It is also called hierarchical clustering or mean shift cluster analysis. Followings would be the basic steps of this algorithm −
First of all, we need to start with the data points assigned to a cluster of their own.
First of all, we need to start with the data points assigned to a cluster of their own.
Now, it computes the centroids and update the location of new centroids.
Now, it computes the centroids and update the location of new centroids.
By repeating this process, we move closer the peak of cluster i.e. towards the region of higher density.
By repeating this process, we move closer the peak of cluster i.e. towards the region of higher density.
This algorithm stops at the stage where centroids do not move anymore.
This algorithm stops at the stage where centroids do not move anymore.
With the help of following code we are implementing Mean Shift clustering algorithm in Python. We are going to use Scikit-learn module.
Let us import the necessary packages −
import numpy as np
from sklearn.cluster import MeanShift
import matplotlib.pyplot as plt
from matplotlib import style
style.use("ggplot")
The following code will help in generating the two-dimensional dataset, containing four blobs, by using make_blob from the sklearn.dataset package.
from sklearn.datasets.samples_generator import make_blobs
We can visualize the dataset with the following code
centers = [[2,2],[4,5],[3,10]]
X, _ = make_blobs(n_samples = 500, centers = centers, cluster_std = 1)
plt.scatter(X[:,0],X[:,1])
plt.show()
Now, we need to train the Mean Shift cluster model with the input data.
ms = MeanShift()
ms.fit(X)
labels = ms.labels_
cluster_centers = ms.cluster_centers_
The following code will print the cluster centers and the expected number of cluster as per the input data −
print(cluster_centers)
n_clusters_ = len(np.unique(labels))
print("Estimated clusters:", n_clusters_)
[[ 3.23005036 3.84771893]
[ 3.02057451 9.88928991]]
Estimated clusters: 2
The code given below will help plot and visualize the machine's findings based on our data, and the fitment according to the number of clusters that are to be found.
colors = 10*['r.','g.','b.','c.','k.','y.','m.']
for i in range(len(X)):
plt.plot(X[i][0], X[i][1], colors[labels[i]], markersize = 10)
plt.scatter(cluster_centers[:,0],cluster_centers[:,1],
marker = "x",color = 'k', s = 150, linewidths = 5, zorder = 10)
plt.show()
The real world data is not naturally organized into number of distinctive clusters. Due to this reason, it is not easy to visualize and draw inferences. That is why we need to measure the clustering performance as well as its quality. It can be done with the help of silhouette analysis.
This method can be used to check the quality of clustering by measuring the distance between the clusters. Basically, it provides a way to assess the parameters like number of clusters by giving a silhouette score. This score is a metric that measures how close each point in one cluster is to the points in the neighboring clusters.
The score has a range of [-1, 1]. Following is the analysis of this score −
Score of +1 − Score near +1 indicates that the sample is far away from the neighboring cluster.
Score of +1 − Score near +1 indicates that the sample is far away from the neighboring cluster.
Score of 0 − Score 0 indicates that the sample is on or very close to the decision boundary between two neighboring clusters.
Score of 0 − Score 0 indicates that the sample is on or very close to the decision boundary between two neighboring clusters.
Score of -1 − Negative score indicates that the samples have been assigned to the wrong clusters.
Score of -1 − Negative score indicates that the samples have been assigned to the wrong clusters.
In this section, we will learn how to calculate the silhouette score.
Silhouette score can be calculated by using the following formula −
$$silhouette score = \frac{\left ( p-q \right )}{max\left ( p,q \right )}$$
Here, p is the mean distance to the points in the nearest cluster that the data point is not a part of. And, q is the mean intra-cluster distance to all the points in its own cluster.
For finding the optimal number of clusters, we need to run the clustering algorithm again by importing the metrics module from the sklearn package. In the following example, we will run the K-means clustering algorithm to find the optimal number of clusters −
Import the necessary packages as shown −
import matplotlib.pyplot as plt
import seaborn as sns; sns.set()
import numpy as np
from sklearn.cluster import KMeans
With the help of the following code, we will generate the two-dimensional dataset, containing four blobs, by using make_blob from the sklearn.dataset package.
from sklearn.datasets.samples_generator import make_blobs
X, y_true = make_blobs(n_samples = 500, centers = 4, cluster_std = 0.40, random_state = 0)
Initialize the variables as shown −
scores = []
values = np.arange(2, 10)
We need to iterate the K-means model through all the values and also need to train it with the input data.
for num_clusters in values:
kmeans = KMeans(init = 'k-means++', n_clusters = num_clusters, n_init = 10)
kmeans.fit(X)
Now, estimate the silhouette score for the current clustering model using the Euclidean distance metric −
score = metrics.silhouette_score(X, kmeans.labels_,
metric = 'euclidean', sample_size = len(X))
The following line of code will help in displaying the number of clusters as well as Silhouette score.
print("\nNumber of clusters =", num_clusters)
print("Silhouette score =", score)
scores.append(score)
You will receive the following output −
Number of clusters = 9
Silhouette score = 0.340391138371
num_clusters = np.argmax(scores) + values[0]
print('\nOptimal number of clusters =', num_clusters)
Now, the output for optimal number of clusters would be as follows −
Optimal number of clusters = 2
If we want to build recommender systems such as a movie recommender system then we need to understand the concept of finding the nearest neighbors. It is because the recommender system utilizes the concept of nearest neighbors.
The concept of finding nearest neighbors may be defined as the process of finding the closest point to the input point from the given dataset. The main use of this KNN)K-nearest neighbors) algorithm is to build classification systems that classify a data point on the proximity of the input data point to various classes.
The Python code given below helps in finding the K-nearest neighbors of a given data set −
Import the necessary packages as shown below. Here, we are using the NearestNeighbors module from the sklearn package
import numpy as np
import matplotlib.pyplot as plt
from sklearn.neighbors import NearestNeighbors
Let us now define the input data −
A = np.array([[3.1, 2.3], [2.3, 4.2], [3.9, 3.5], [3.7, 6.4], [4.8, 1.9],
[8.3, 3.1], [5.2, 7.5], [4.8, 4.7], [3.5, 5.1], [4.4, 2.9],])
Now, we need to define the nearest neighbors −
k = 3
We also need to give the test data from which the nearest neighbors is to be found −
test_data = [3.3, 2.9]
The following code can visualize and plot the input data defined by us −
plt.figure()
plt.title('Input data')
plt.scatter(A[:,0], A[:,1], marker = 'o', s = 100, color = 'black')
Now, we need to build the K Nearest Neighbor. The object also needs to be trained
knn_model = NearestNeighbors(n_neighbors = k, algorithm = 'auto').fit(X)
distances, indices = knn_model.kneighbors([test_data])
Now, we can print the K nearest neighbors as follows
print("\nK Nearest Neighbors:")
for rank, index in enumerate(indices[0][:k], start = 1):
print(str(rank) + " is", A[index])
We can visualize the nearest neighbors along with the test data point
plt.figure()
plt.title('Nearest neighbors')
plt.scatter(A[:, 0], X[:, 1], marker = 'o', s = 100, color = 'k')
plt.scatter(A[indices][0][:][:, 0], A[indices][0][:][:, 1],
marker = 'o', s = 250, color = 'k', facecolors = 'none')
plt.scatter(test_data[0], test_data[1],
marker = 'x', s = 100, color = 'k')
plt.show()
K Nearest Neighbors
1 is [ 3.1 2.3]
2 is [ 3.9 3.5]
3 is [ 4.4 2.9]
A K-Nearest Neighbors (KNN) classifier is a classification model that uses the nearest neighbors algorithm to classify a given data point. We have implemented the KNN algorithm in the last section, now we are going to build a KNN classifier using that algorithm.
The basic concept of K-nearest neighbor classification is to find a predefined number, i.e., the 'k' − of training samples closest in distance to a new sample, which has to be classified. New samples will get their label from the neighbors itself. The KNN classifiers have a fixed user defined constant for the number of neighbors which have to be determined. For the distance, standard Euclidean distance is the most common choice. The KNN Classifier works directly on the learned samples rather than creating the rules for learning. The KNN algorithm is among the simplest of all machine learning algorithms. It has been quite successful in a large number of classification and regression problems, for example, character recognition or image analysis.
Example
We are building a KNN classifier to recognize digits. For this, we will use the MNIST dataset. We will write this code in the Jupyter Notebook.
Import the necessary packages as shown below.
Here we are using the KNeighborsClassifier module from the sklearn.neighbors package −
from sklearn.datasets import *
import pandas as pd
%matplotlib inline
from sklearn.neighbors import KNeighborsClassifier
import matplotlib.pyplot as plt
import numpy as np
The following code will display the image of digit to verify what image we have to test −
def Image_display(i):
plt.imshow(digit['images'][i],cmap = 'Greys_r')
plt.show()
Now, we need to load the MNIST dataset. Actually there are total 1797 images but we are using the first 1600 images as training sample and the remaining 197 would be kept for testing purpose.
digit = load_digits()
digit_d = pd.DataFrame(digit['data'][0:1600])
Now, on displaying the images we can see the output as follows −
Image_display(0)
Image of 0 is displayed as follows −
Image of 9 is displayed as follows −
Now, we need to create the training and testing data set and supply testing data set to the KNN classifiers.
train_x = digit['data'][:1600]
train_y = digit['target'][:1600]
KNN = KNeighborsClassifier(20)
KNN.fit(train_x,train_y)
The following output will create the K nearest neighbor classifier constructor −
KNeighborsClassifier(algorithm = 'auto', leaf_size = 30, metric = 'minkowski',
metric_params = None, n_jobs = 1, n_neighbors = 20, p = 2,
weights = 'uniform')
We need to create the testing sample by providing any arbitrary number greater than 1600, which were the training samples.
test = np.array(digit['data'][1725])
test1 = test.reshape(1,-1)
Image_display(1725)
Image of 6 is displayed as follows −
Now we will predict the test data as follows −
KNN.predict(test1)
The above code will generate the following output −
array([6])
Now, consider the following −
digit['target_names']
The above code will generate the following output −
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
78 Lectures
7 hours
Arnab Chakraborty
87 Lectures
9.5 hours
DigiFisk (Programming Is Fun)
10 Lectures
1 hours
Nikoloz Sanakoevi
15 Lectures
54 mins
Mukund Kumar Mishra
11 Lectures
1 hours
Gilad James, PhD
20 Lectures
2 hours
Gilad James, PhD
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2393,
"s": 2205,
"text": "Unsupervised machine learning algorithms do not have any supervisor to provide any sort of guidance. That is why they are closely aligned with what some call true artificial intelligence."
},
{
"code": null,
"e": 2559,
"s": 2393,
"te... |
Concept of Time in database - GeeksforGeeks | 10 Apr, 2020
A database is used to model the state of some aspect of the real world outside in the form of relation. In general, database system store only one state that is the current state of the real world, and do not store data about previous and past states, except perhaps as audit trails. If the current state of the real world changes, the database gets modified and updated, and information about the past state gets lost.
However, in most of the real life applications, it is necessary to store and retrieve information about old states. For example, a student database must contain information about the previous performance history of that student for preparing the final result. An autonomous robotic system must store information about present and previous data of sensors from the environment for effective Action.
Example:
ID name dept name salary from to
10101 Srinivasan Comp. Sci. 61000 2007/1/1 2007/12/31
10101 Srinivasan Comp. Sci. 65000 2008/1/1 2008/12/31
12121 Wu Finance 82000 2005/1/1 2006/12/31
12121 Wu Finance 87000 2007/1/1 2007/12/31
12121 Wu Finance 90000 2008/1/1 2008/12/31
98345 Kim Elec. Eng. 80000 2005/1/1 2008/12/31
In the above example, to simplify the representation, every row has only one time interval associated with it; thus, a row is represented once for every disjoint time interval in which it is true. Intervals that are given here are a combination of attributes from and to; an actual implementation would have a structured type, which is known as Interval, that contains both fields.
There are few important terminologies used in the concept of time in database:
Temporal database :Databases that store information about states of the real world across time are known as temporal databases.Valid time :Valid time denotes the time period during which a fact is true with respect to the real world.Transaction time :Transaction time is the time period during which a fact is stored in the databases.Temporal relation :Temporal relation is one where each tuple has an associated time when it is true; the time may be either valid time or transaction time.Bi-temporal relation :Both valid time and transaction time can be stored, in which case the relation is said to be a Bi-temporal relation.
Temporal database :Databases that store information about states of the real world across time are known as temporal databases.
Valid time :Valid time denotes the time period during which a fact is true with respect to the real world.
Transaction time :Transaction time is the time period during which a fact is stored in the databases.
Temporal relation :Temporal relation is one where each tuple has an associated time when it is true; the time may be either valid time or transaction time.
Bi-temporal relation :Both valid time and transaction time can be stored, in which case the relation is said to be a Bi-temporal relation.
DBMS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Types of Functional dependencies in DBMS
Introduction of Relational Algebra in DBMS
KDD Process in Data Mining
Structure of Database Management System
Difference between File System and DBMS
What is Temporary Table in SQL?
Difference between Star Schema and Snowflake Schema
Insert Operation in B-Tree
Relational Model in DBMS
Nested Queries in SQL | [
{
"code": null,
"e": 24304,
"s": 24276,
"text": "\n10 Apr, 2020"
},
{
"code": null,
"e": 24724,
"s": 24304,
"text": "A database is used to model the state of some aspect of the real world outside in the form of relation. In general, database system store only one state that is th... |
Ionic - Javascript Forms | In this chapter, we will understand what JavaScript forms are and will learn what a JavaScript checkbox, radio buttons and toggle are.
Let us see how to use the Ionic JavaScript checkbox. Firstly, we need to create an ion-checkbox element in the HTML file. Inside this, we will assign an ng-model attribute that will be connected to the angular $scope. You will notice that we are using a dot when defining the value of a model even though it would work without it. This will allow us to keep the link between the child and the parent scopes at all times.
This is very important as it helps to avoid some issues that could happen in the future. After we create the element, we will bind its value using angular expressions.
<ion-checkbox ng-model = "checkboxModel.value1">Checkbox 1</ion-checkbox>
<ion-checkbox ng-model = "checkboxModel.value2">Checkbox 2</ion-checkbox>
<p>Checkbox 1 value is: <b>{{checkboxModel.value1}}</b></p>
<p>Checkbox 2 value is: <b>{{checkboxModel.value2}}</b></p>
Next, we need to assign values to our model inside the controller. The values we will use are false, since we want to start with unchecked checkboxes.
$scope.checkboxModel = {
value1 : false,
value2 : false
};
The above code will produce the following screen −
Now, when we tap the checkbox elements, it will automatically change their model value to “true” as shown in the following screenshot.
To start with, we should create three ion-radio elements in our HTML and assign the ng-model and the ng-value to it. After that, we will display the chosen value with angular expression. We will start by unchecking all the three radioelements, so the value will not be assigned to our screen.
<ion-radio ng-model = "radioModel.value" ng-value = "1">Radio 1</ion-radio>
<ion-radio ng-model = "radioModel.value" ng-value = "2">Radio 2</ion-radio>
<ion-radio ng-model = "radioModel.value" ng-value = "3">Radio 3</ion-radio>
<p>Radio value is: <b>{{radioModel.value}}</b></p>
The above code will produce the following screen −
When we tap on the second checkbox element, the value will change accordingly.
You will notice that toggle is similar to checkbox. We will follow the same steps as we did with our checkbox. In the HTML file, first we will create ion-toggle elements, then assign the ng-model value and then bind expression values of to our view.
<ion-toggle ng-model = "toggleModel.value1">Toggle 1</ion-toggle>
<ion-toggle ng-model = "toggleModel.value2">Toggle 2</ion-toggle>
<ion-toggle ng-model = "toggleModel.value3">Toggle 3</ion-toggle>
<p>Toggle value 1 is: <b>{{toggleModel.value1}}</b></p>
<p>Toggle value 2 is: <b>{{toggleModel.value2}}</b></p>
<p>Toggle value 3 is: <b>{{toggleModel.value3}}</b></p>
Next, we will assign values to $scope.toggleModel in our controller. Since, toggle uses Boolean values, we will assign true to the first element and false to the other two.
$scope.toggleModel = {
value1 : true,
value2 : false,
value3 : false
};
The above code will produce the following screen −
Now we will tap on second and third toggle to show you how the values change from false to true.
16 Lectures
2.5 hours
Frahaan Hussain
185 Lectures
46.5 hours
Nikhil Agarwal
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2598,
"s": 2463,
"text": "In this chapter, we will understand what JavaScript forms are and will learn what a JavaScript checkbox, radio buttons and toggle are."
},
{
"code": null,
"e": 3019,
"s": 2598,
"text": "Let us see how to use the Ionic JavaScript chec... |
Setup Vue.js Hello World In Visual Studio Code | by Ryan Gleason | Towards Data Science | Launch a simple Vue application after setting up a local development environment.
These are the tools you will install throughout the duration of this tutorial:
Visual Studio Code (VS Code): This certainly isn’t a requirement for creating Vue applications, but it is my recommended text editor. I believe it makes software development a lot more enjoyable and productive.
Git Bash: Git is a very popular tool used to manage source code, especially if you are working on a large development team. VS Code allows you to integrate a Git Bash terminal, and this makes pushing your code to Git repositories very convenient. Also, it lets you use most standard UNIX commands with the emulation of a Bash environment.
Node.js: the JavaScript runtime environment
npm: the Node package manager. This is used in conjunction with Node.js so that we can easily share packaged modules of code.
Download the stable build from Visual Studio Code.
This is a very easy download. Microsoft has done a good job of simplifying the installation process for this application.
Download Git Bash from https://git-scm.com/downloads for your specific operating system.
As you are clicking through the Git installer, I suggest using all of the default installation settings unless you really know what you are doing.
We are now going to add Git Bash as an integrated terminal inside of VSCode.
Open a new terminal in VS Code (Ctrl + Shift + `) or Terminal → New Terminal.
Open the command palette (Ctrl + Shift + P) or View → Command Palette.
Type “Terminal: Select Default Shell”.
You should see the options below:
Select Git Bash.
Select the + button in the terminal window.
You should see something like this.
Checkpoint: Type in the following command to ensure you have correctly installed Git.
git --version
Depending on what version you have installed, this should appear.
Go to this link to download: Node.js.
I selected the “Recommended For Most Users” option and then used all the default settings in the Node.js setup.
Checkpoint: Once it has finished installing, type into your command line:
node -v && npm -v
And it should look like this (your versions may be more recent than mine):
If you successfully installed Node and npm, skip to the next section.
If it doesn’t show up in your Git Bash, don’t fret! Restart your computer.
If that doesn’t work, type the same command into PowerShell or just your Windows command line and you should see it there.
To use Git Bash, you’re going to need to add it to your PATH. The PATH tells your operating system where to look for executable files in response to commands from a user. Below is how you do that on Windows:
Open “View Advanced System Settings”.
Click “Environment Variables”.
Under System Variables, select Path and then the Edit button.
Add this C:\Program Files\nodejs\.
If the above file path isn’t correct, you can easily find it by typing this command into your Windows command line:
where node
Select OK after retrieving the correct path to the Node directory and adding it to your Path system variable.
Restart your computer again.
Checkpoint: Now, try typing the following commands into Git Bash:
node -v && npm -v
Type the following command into the command line.
npm i -g @vue/cli
Once this is complete, we will create our project:
vue create hello-world
I chose the preset
Next, change directories into your new project, and start it up!
cd hello-world && npm run serve
Navigate to localhost:8080 and you should see something that looks like this:
And that’s it! We did it.
You’ve just installed the following tools to get you started creating Vue.js applications. | [
{
"code": null,
"e": 129,
"s": 47,
"text": "Launch a simple Vue application after setting up a local development environment."
},
{
"code": null,
"e": 208,
"s": 129,
"text": "These are the tools you will install throughout the duration of this tutorial:"
},
{
"code": null... |
Java - Types of Polymorphism and Advantages - 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 tutorial, we are going to understand the concept of polymorphism in Java and different types of it.
Polymorphism is a significant feature of Object Oriented Principles. The word polymorphism came from two Greek words ‘poly‘ and ‘morphs‘. Here poly means many and morphs means forms.
Polymorphism represents the ability of an object to assume different forms. Therefore, it enables programmers to create/write programs that are easier to understand and reuse.
Certainly, Polymorphism provides flexibility to the programmer to write programs that use a single method for different operations depending on the requirement.
In Java, we can define a single interface to represent multiple concrete classes. So by accepting the interface type, a method can behave differently for different inputs.
Java supports two types of polymorphism namely:
Compile-time polymorphism
Run-time polymorphism.
Compile-time polymorphism
Run-time polymorphism.
Compile-time polymorphism is the type of polymorphism occurs when the compiler compiles a program. Java supports compile-time polymorphism through method overloading. The other names of Compile-time polymorphism are static polymorphism or early binding.
Polymorphism occurs in method overloading because method overloading allows access to different methods through the same interface.
In method overloading, two or more methods in a class can use the same name as long as their parameter declarations are different.
When the compiler encounters a call to an overloaded method, it identifies the correct version of the overloaded method by comparing the type and the number of arguments.
Example:
public class OverloadingDemo {
public void meth(int value) {
System.out.println("int value : " + value);
}
public void meth(String name) {
System.out.println("String value : " + name);
}
public void meth(int value, String name) {
System.out.println("Name with value : " + value+" "+name);
}
public static void main(String[] args) {
OverloadingDemo demo = new OverloadingDemo();
demo.meth(10);
demo.meth("online tutorials point");
demo.meth(20, "Overloading Demo");
}
}
Output:
int value : 10
String value : online tutorials point
Name with value : 20 Overloading Demo
Run-time Polymorphism is the type of polymorphism that occurs dynamically when a program executes. Java supports run-time polymorphism by dynamically dispatching methods at run time through method overriding.
For this type of polymorphism, method invocations are resolved at run time by the JVM and not at the compile time.
Since the run-time polymorphism occurs dynamically, it is also called dynamic polymorphism or late binding.
interface Car {
void speed(int speed);
}
class Maruti implements Car {
public void speed(int speed) {
System.out.println("Maruti Speed is :" + speed);
}
}
class Tata implements Car {
public void speed(int speed) {
System.out.println("Tata Speed is :" + speed);
}
}
public class PolymorphismDemo {
public static void main(String[] args) {
Car car;
car = new Maruti();
car.speed(200);
car = new Tata();
car.speed(300);
}
}
Output:
Maruti Speed is :200
Tata Speed is :300
In the above example – Maruthi and Tata are two different classes, and both were two different implementations of the Car Interface. In other words, these two classes are types of Car.
Since because these two classes are the same type, we can refer these two objects to a single type called Car as above. Here, based on the type of the object being assigned with the reference, polymorphism is resolved at runtime.
Method overloading allows methods that perform similar or closely related functions to be accessed through a common name. For instance, a program performs operations on an array of numbers which can be int, float, or double type. Method overloading allows you to define three methods with the same name and different types of parameters to handle the array of operations.
Method overloading allows methods that perform similar or closely related functions to be accessed through a common name. For instance, a program performs operations on an array of numbers which can be int, float, or double type. Method overloading allows you to define three methods with the same name and different types of parameters to handle the array of operations.
Constructors allowing different ways to initialize objects of a class can implement method overloading. This enables you to define multiple constructors for handling different types of initializations.
Constructors allowing different ways to initialize objects of a class can implement method overloading. This enables you to define multiple constructors for handling different types of initializations.
Method overriding allows a subclass to use all the general definitions that a superclass provides and add specialized definitions through overridden methods.
Method overriding allows a subclass to use all the general definitions that a superclass provides and add specialized definitions through overridden methods.
Method overriding works together with inheritance to enable code-reuse of existing classes without the need for re-compilation.
Method overriding works together with inheritance to enable code-reuse of existing classes without the need for re-compilation.
Method overloading occurs at Compile-time whereas method overriding occurs at Run-time.
Method overloading occurs at Compile-time whereas method overriding occurs at Run-time.
Method overloading occurs when the type signatures of the two methods are different whereas method overriding occurs only when the type signatures of the two methods are the same.
Method overloading occurs when the type signatures of the two methods are different whereas method overriding occurs only when the type signatures of the two methods are the same.
In method overloading, the compiler calls the correct method by comparing the type signatures. However, in method overriding, the JVM determines the correct method based on the object that the invoking variable is referring to.
In method overloading, the compiler calls the correct method by comparing the type signatures. However, in method overriding, the JVM determines the correct method based on the object that the invoking variable is referring to.
Method overloading is possible on methods with private, static, and final access modifiers. On the other hand, method overriding is not possible on these access modifiers.
Method overloading is possible on methods with private, static, and final access modifiers. On the other hand, method overriding is not possible on these access modifiers.
Object Oriented Principles
Method Overriding and Overloading
Happy Learning 🙂
Overriding vs Overloading in Java
Oops Concepts In Java
Types Of Inheritance in Java
Advantages of Exception Handling
What is Java Constructor and Types of Constructors
Java Main Method – public static void main(String args[])
Advantages of Java Programming
Java variable types Example
Spring Bean Autowire ByType Example
Factory Method Pattern in Java
Top 40 Core Java Interview Questions and Answers
OOPS – Java Access Modifiers
Java Class Example Tutorials
Hello World Java Program Example
What are different Python Data Types
Overriding vs Overloading in Java
Oops Concepts In Java
Types Of Inheritance in Java
Advantages of Exception Handling
What is Java Constructor and Types of Constructors
Java Main Method – public static void main(String args[])
Advantages of Java Programming
Java variable types Example
Spring Bean Autowire ByType Example
Factory Method Pattern in Java
Top 40 Core Java Interview Questions and Answers
OOPS – Java Access Modifiers
Java Class Example Tutorials
Hello World Java Program Example
What are different Python Data Types
Sravanthi
November 3, 2017 at 2:38 pm - Reply
Good info but in Advantages can be made like hitting bulls eye.
simpe and short like code reuse,Better Performance, optimized way of achieving tasks etc.
priya
May 11, 2018 at 5:58 am - Reply
The basic reason behind polymorphism is that we can implement different behaviors of the same object depending upon the reference type passed to an object.
Sravanthi
November 3, 2017 at 2:38 pm - Reply
Good info but in Advantages can be made like hitting bulls eye.
simpe and short like code reuse,Better Performance, optimized way of achieving tasks etc.
Good info but in Advantages can be made like hitting bulls eye.
simpe and short like code reuse,Better Performance, optimized way of achieving tasks etc.
priya
May 11, 2018 at 5:58 am - Reply
The basic reason behind polymorphism is that we can implement different behaviors of the same object depending upon the reference type passed to an object.
The basic reason behind polymorphism is that we can implement different behaviors of the same object depending upon the reference type passed to an object. | [
{
"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,
... |
How to convert bool to int in MySQL?
| To convert bool to int in MySQL, you can use CAST(). Let us first create a table:
mysql> create table convertBoolToIntDemo
-> (
-> isYoung bool
-> );
Query OK, 0 rows affected (0.69 sec)
Following is the query to insert some records in the table using insert command:
mysql> insert into convertBoolToIntDemo values(true);
Query OK, 1 row affected (0.18 sec)
mysql> insert into convertBoolToIntDemo values(false);
Query OK, 1 row affected (0.09 sec)
mysql> insert into convertBoolToIntDemo values(true);
Query OK, 1 row affected (0.15 sec)
mysql> insert into convertBoolToIntDemo values(false);
Query OK, 1 row affected (0.18 sec)
Following is the query to display records from the table using select command:
mysql> select *from convertBoolToIntDemo;
This will produce the following output
+---------+
| isYoung |
+---------+
| 1 |
| 0 |
| 1 |
| 0 |
+---------+
4 rows in set (0.00 sec)
Following is the query to convert bool to int in MySQL:
mysql> select cast(isYoung=1 AS SIGNED INTEGER) from convertBoolToIntDemo;
This will produce the following output
+-----------------------------------+
| cast(isYoung=1 AS SIGNED INTEGER) |
+-----------------------------------+
| 1 |
| 0 |
| 1 |
| 0 |
+-----------------------------------+
4 rows in set (0.00 sec) | [
{
"code": null,
"e": 1144,
"s": 1062,
"text": "To convert bool to int in MySQL, you can use CAST(). Let us first create a table:"
},
{
"code": null,
"e": 1258,
"s": 1144,
"text": "mysql> create table convertBoolToIntDemo\n -> (\n -> isYoung bool\n -> );\nQuery OK, 0 rows af... |
File.AppendAllText(String, String, Encoding) Method in C# with Examples - GeeksforGeeks | 26 Feb, 2021
File.AppendAllText(String, String, Encoding) is an inbuilt File class method which is used to append the specified string to the given file using the specified encoding if that file exists else creates a new file and then appending is done.
Syntax:
public static void AppendAllText (string path, string contents, System.Text.Encoding encoding);
Parameter: This function accepts two parameters which are illustrated below:
path: This is the file where given contents are going to be appended.
contents: This is the specified contents which is to be appended to the file.
Encoding: This is the specified character encoding.
Exceptions:
ArgumentException: The path is a zero-length string, contains only white space, or contains one or more invalid characters as defined by InvalidPathChars.
ArgumentNullException: The path is null.
PathTooLongException: The given path, file name, or both exceed the system-defined maximum length.
DirectoryNotFoundException: The specified path is invalid (for example, the directory doesn’t exist or it is on an unmapped drive).
IOException: An I/O error occurred while opening the file.
UnauthorizedAccessException: The path specified a file that is read-only. OR this operation is not supported on the current platform. OR the path specified a directory. OR the caller does not have the required permission.
NotSupportedException: The path is in an invalid format.
SecurityException: The caller does not have the required permission.
Below are the programs to illustrate the File.AppendAllText(String, String, Encoding) method.Program 1: Before running the below code, a file is created with some contents shown below:
CSharp
// C# program to illustrate the usage// of File.AppendAllText() method // Using System, System.IO,// System.Text and System.Linq namespacesusing System;using System.IO;using System.Text;using System.Linq; class GFG { // Main() method public static void Main() { // Creating a file string myfile = @"file.txt"; // Adding extra texts string appendText = " is a CS portal." + Environment.NewLine; File.AppendAllText(myfile, appendText, Encoding.UTF8); // Opening the file to read from. string readText = File.ReadAllText(myfile); Console.WriteLine(readText); }}
Executing:
mcs -out:main.exe main.cs
mono main.exe
GeeksforGeeks is a CS portal.
After running the above code, above output is shown and the file contents become like shown below:
Program 2: Initially no file is created but the below code itself creates a new file and appends the specified contents.
CSharp
// C# program to illustrate the usage// of File.AppendAllText() method // Using System, System.IO,// System.Text and System.Linq namespacesusing System;using System.IO;using System.Text;using System.Linq; class GFG { // Main() method public static void Main() { // Creating a file string myfile = @"file.txt"; // Checking the existence of file if (!File.Exists(myfile)) { // Creating a file with below content string createText = "GFG" + Environment.NewLine; File.WriteAllText(myfile, createText); } // Adding extra texts string appendText = " is a CS portal." + Environment.NewLine; File.AppendAllText(myfile, appendText, Encoding.UTF8); // Opening the file to read from. string readText = File.ReadAllText(myfile); Console.WriteLine(readText); }}
Executing:
mcs -out:main.exe main.cs
mono main.exe
GFG
is a CS portal.
After running the above code, above output has been shown and a new file created which is shown below:
arorakashish0911
CSharp-File-Handling
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C# Dictionary with examples
C# | Method Overriding
C# | Class and Object
Introduction to .NET Framework
C# | Constructors
Difference between Ref and Out keywords in C#
C# | String.IndexOf( ) Method | Set - 1
C# | Abstract Classes
Extension Method in C#
C# | Delegates | [
{
"code": null,
"e": 24658,
"s": 24630,
"text": "\n26 Feb, 2021"
},
{
"code": null,
"e": 24900,
"s": 24658,
"text": "File.AppendAllText(String, String, Encoding) is an inbuilt File class method which is used to append the specified string to the given file using the specified enc... |
C# | ArrayList.InsertRange() Method - GeeksforGeeks | 06 Jun, 2019
ArrayList.InsertRange(Int32, ICollection) Method in C# is used to insert the elements from a collection into the ArrayList at a specified index. That is the inserted element belongs to a collection(i.e. queue etc).
Syntax:
public virtual void InsertRange (int index, ICollection element);
Parameters:
index: It is the index, where the new elements to be inserted.
element: It is the ICollection whose elements are going to be inserted into the ArrayList at a specified index.
Note: The collection cannot be null, but it can contain elements that are null.
Exceptions:
ArgumentNullException: If the element is null.
ArgumentOutOfRangeException: If the index is less than zero or index is greater than counter.
NotSupportedException: If the ArrayList is read-only or the ArrayList has a fixed size.
Example 1:
// C# program to demonstrate the // ArrayList.InsertRange(Int32, // ICollection) Methodusing System;using System.Collections; class GFG { // Main Method public static void Main() { // initializes a new ArrayList ArrayList ArrList = new ArrayList(); // adding values in the // ArrayList using "Add" ArrList.Add("A"); ArrList.Add("D"); ArrList.Add("E"); ArrList.Add("F"); // initializes a new Stack // as collection Stack s = new Stack(); // pushing values in the stack // values are pop as B, C s.Push("C"); s.Push("B"); // Displays the ArrayList and the Queue Console.WriteLine("The ArrayList initially has:"); Display(ArrList); Console.WriteLine("The collection initially has:"); Display(s); // Copies the elements of the stack // to the ArrayList at index 1. ArrList.InsertRange(1, s); // Displays the ArrayList. Console.WriteLine("After insert the collection in the ArrList:"); Display(ArrList); } // Display function public static void Display(IEnumerable ArrList) { foreach(Object a in ArrList) { Console.Write(" " + a); } Console.WriteLine(); }}
The ArrayList initially has:
A D E F
The collection initially has:
B C
After insert the collection in the ArrList:
A B C D E F
Example 2:+
// C# program to demonstrate the // ArrayList.InsertRange(Int32, // ICollection) Methodusing System;using System.Collections; class GFG { // Main Method public static void Main() { // initializes a new ArrayList ArrayList ArrList = new ArrayList(); // adding values in the ArrayList // using "Insert" method ArrList.Insert(0, "A"); ArrList.Insert(1, "D"); ArrList.Insert(2, "E"); ArrList.Insert(3, "G"); // Initializes a new Stack // as collection Stack s = new Stack(); // pushing values in the stack // values are pop as B, C s.Push("C"); s.Push("B"); // Displays the ArrayList and the Queue. Console.WriteLine("The ArrayList initially has:"); Display(ArrList); Console.WriteLine("The collection initially has:"); Display(s); // Copies the elements of the stack // to the ArrayList at index 1. ArrList.InsertRange(1, s); // Displays the ArrayList. Console.WriteLine("After insert the collection in the ArrList:"); Display(ArrList); // insert F by finding the index of G // using IndexOf() method ArrList.Insert(ArrList.IndexOf("G"), "F"); Console.WriteLine("After inserting F before G:"); Display(ArrList); } // Display function public static void Display(IEnumerable ArrList) { foreach(Object a in ArrList) { Console.Write(" " + a); } Console.WriteLine(); }}
The ArrayList initially has:
A D E G
The collection initially has:
B C
After insert the collection in the ArrList:
A B C D E G
After inserting F before G:
A B C D E F G
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.arraylist.insertrange?view=netframework-4.8
CSharp-Collections-ArrayList
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C# Dictionary with examples
C# | Method Overriding
C# | Class and Object
Difference between Ref and Out keywords in C#
C# | Constructors
Introduction to .NET Framework
Extension Method in C#
C# | String.IndexOf( ) Method | Set - 1
C# | Abstract Classes
C# | Delegates | [
{
"code": null,
"e": 25010,
"s": 24982,
"text": "\n06 Jun, 2019"
},
{
"code": null,
"e": 25225,
"s": 25010,
"text": "ArrayList.InsertRange(Int32, ICollection) Method in C# is used to insert the elements from a collection into the ArrayList at a specified index. That is the insert... |
How to play videos in Android TextureView? | This example demonstrates how do I play videos in Android TextureView.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="8dp"
tools:context=".MainActivity">
<TextureView
android:id="@+id/textureView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
Step 3 − Create an asset folder and copy-paste the video into the asset folder.
Step 4 − Add the following code to src/MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.content.res.AssetFileDescriptor;
import android.graphics.SurfaceTexture;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.view.Surface;
import android.view.TextureView;
import java.io.IOException;
public class MainActivity extends AppCompatActivity implements TextureView.SurfaceTextureListener, MediaPlayer.OnVideoSizeChangedListener {
TextureView textureView;
private MediaPlayer mediaPlayer;
AssetFileDescriptor fileDescriptor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textureView = findViewById(R.id.textureView);
textureView.setSurfaceTextureListener(this);
mediaPlayer = new MediaPlayer();
try {
fileDescriptor = getAssets().openFd("videoplayback.mp4");
}
catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int width, int height) {
Surface surface = new Surface(surfaceTexture);
try {
mediaPlayer.setSurface(surface);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
mediaPlayer.setDataSource(fileDescriptor);
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
mediaPlayer.start();
}
});
}
}
catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
}
@Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
return false;
}
@Override
public void onSurfaceTextureUpdated(SurfaceTexture surface) {
}
@Override
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
}
}
Step 5 − 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.sample">
<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 the 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": 1133,
"s": 1062,
"text": "This example demonstrates how do I play videos in Android TextureView."
},
{
"code": null,
"e": 1262,
"s": 1133,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to crea... |
CSS | Hue Background - GeeksforGeeks | 18 Jun, 2020
Hue background is a concept of a new design methodology that focuses on clean and aesthetic looking UI. It gives the website a clean and aesthetic look. It is perfect for professional websites such as some product landing page or some organization’s home page. It also has an advanced version in which the color keeps changing and we will be looking at the advanced part only as you can make the basic one if you know how to make the advanced background.
Approach:The approach is to give a gradient background and making some borders to give it a shiny reflection kind of look. For advanced concepts, we will use keyframes to change the background color.
HTML Code:In this part, we have created a section.
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>HUE background</title> </head> <body> <section><h1>GeeksforGeeks</h1></section> </body></html>
CSS Code:For CSS, follow the below given steps.
Step 1: Apply a basic gradient background using linear-gradient
Step 2: Now apply animation property with a identifier named as animate
Step 3: Now use keyframes to rotate hue at any angle of your choice using hue-rotate.This will make the color change at each frame.We have divide the frames in three parts but you can choose to divide it according to your need
Step 4: Now use beforeselector to create left side border emerging from top.
Step 5: Now use afterselector to create right side border emerging from top.
Tip:The keyframes step is completely optional if you want basic background. The borders which give a reflective effect can be of different types. We have chosen to use the borders which are emerging from the top. You can change their emerging direction and almost everything according to your need and creativity.
section { position: absolute; top: 0; left: 0; width: 100%; height: 100vh; background: linear-gradient(90deg, #07f79b, #01442a); animation: animate 20s linear infinite; } @keyframes animate { 0% { filter: hue-rotate(0deg); } 50% { filter: hue-rotate(360deg); } 100% { filter: hue-rotate(0deg); } } section::before { content: ""; position: absolute; top: 0; left: 0; border-top: 100vh solid transparent; border-left: 100vh solid #fff; opacity: 0.1; } section::after { content: ""; position: absolute; bottom: 0; right: 0; border-top: 100vh solid transparent; border-right: 100vh solid #fff; opacity: 0.1; } h1 { position: absolute; top: 50%; left: 40%; color: white; font: 40px; }
Complete Code:It is the combination of the above two sections of code.
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>HUE background</title> <style> section { position: absolute; top: 0; left: 0; width: 100%; height: 100vh; background: linear-gradient(90deg, #07f79b, #01442a); animation: animate 20s linear infinite; } @keyframes animate { 0% { filter: hue-rotate(0deg); } 50% { filter: hue-rotate(360deg); } 100% { filter: hue-rotate(0deg); } } section::before { content: ""; position: absolute; top: 0; left: 0; border-top: 100vh solid transparent; border-left: 100vh solid #fff; opacity: 0.1; } section::after { content: ""; position: absolute; bottom: 0; right: 0; border-top: 100vh solid transparent; border-right: 100vh solid #fff; opacity: 0.1; } h1 { position: absolute; top: 50%; left: 40%; color: white; font: 40px; } </style> </head> <body> <section><h1>GeeksforGeeks</h1></section> </body></html>
Output:
CSS-Advanced
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Design a web page using HTML and CSS
Form validation using jQuery
Search Bar using HTML, CSS and JavaScript
How to style a checkbox using CSS?
How to fetch data from localserver database and display on HTML table using PHP ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Angular Libraries For Web Developers
Convert a string to an integer in JavaScript | [
{
"code": null,
"e": 25296,
"s": 25268,
"text": "\n18 Jun, 2020"
},
{
"code": null,
"e": 25751,
"s": 25296,
"text": "Hue background is a concept of a new design methodology that focuses on clean and aesthetic looking UI. It gives the website a clean and aesthetic look. It is perf... |
Angular Google Charts - Stacked Bar Chart | Following is an example of a Stacked Bar Chart.
We have already seen the configurations used to draw a chart in Google Charts Configuration Syntax chapter. Now, let us see an example of a Stacked Bar Chart.
We've used isStacked option to show bar based chart as stacked.
options = {
isStacked:true,
}
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Population (in millions)';
type = 'BarChart';
data = [
["2012", 900, 390],
["2013", 1000, 400],
["2014", 1170, 440],
["2015", 1250, 480],
["2016", 1530, 540]
];
columnNames = ['Year', 'Asia','Europe'];
options = {
hAxis: {
title: 'Year'
},
vAxis:{
minValue:0
},
isStacked:true
};
width = 550;
height = 400;
}
Verify the result.
16 Lectures
1.5 hours
Anadi Sharma
28 Lectures
2.5 hours
Anadi Sharma
11 Lectures
7.5 hours
SHIVPRASAD KOIRALA
16 Lectures
2.5 hours
Frahaan Hussain
69 Lectures
5 hours
Senol Atac
53 Lectures
3.5 hours
Senol Atac
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 1844,
"s": 1796,
"text": "Following is an example of a Stacked Bar Chart."
},
{
"code": null,
"e": 2003,
"s": 1844,
"text": "We have already seen the configurations used to draw a chart in Google Charts Configuration Syntax chapter. Now, let us see an example... |
Working with Hugging Face Transformers and TF 2.0 | by Akash Desarda | Towards Data Science | I am assuming that you are aware of Transformers and its attention mechanism. The primary aim of this blog is to show how to use Hugging Face’s transformer library with TF 2.0, i.e. it will be more code-focused blog.
Hugging Face initially supported only PyTorch, but now TF 2.0 is also well supported. You can find a good number of quality tutorials for using the transformer library with PyTorch, but same is not true with TF 2.0 (primary motivation for this blog).
To use BERT or even AlBERT is quite easy and the standard process in TF 2.0 courtesy to tensorflow_hub, but the same is not the case with GPT2, RoBERTa, DistilBERT, etc. Here comes Hugging Face’s transformer library to rescue. They provide intuitive APIs to build a custom model from scratch or fine-tune a pre-trained model for a wide list of the transformer-based models.
It supports a wide range of NLP application like Text classification, Question-Answer system, Text summarization, Token classification, etc. Head over to their Docs for more detail.
This tutorial will be based on a Multi-Label Text classification of Kaggle’s Toxic Comment Classification Challenge.
Following is a general pipeline for any transformer model:
Tokenizer definition →Tokenization of Documents →Model Definition →Model Training →Inference
Let us now go over them one by one, I will also try to cover multiple possible use cases.
Every transformer based model has a unique tokenization technique, unique use of special tokens. The transformer library takes care of this for us. It supports tokenization for every model which is associated with it.
→Every transformer model has a similar token definition API
→Here I am using a tokenizer from a Pretrained model.
→Here,
add_special_tokens: Is used to add special character like <cls>, <sep>,<unk>, etc w.r.t Pretrained model in use. It should be always kept True
max_length: Max length of any sentence to tokenize, its a hyperparameter. (originally BERT has 512 max length)
pad_to_max_length: perform padding operation.
Next step is now to perform tokenization on documents. It can be performed either by encode() or encode_plus() method.
→Any transformer model generally needs three input:
input ids: word id associated with their vocabulary
attention mask: Which id must be paid attention to; 1=pay attention. In simple terms, it tells the model which are original words and which are padded words or special tokens
token type id: It's associated with model consuming multiply sentence like Question-Answer model. It tells model about the sequence of the sentences.
→Though it is not compulsory to provide all these three ids and only input ids will also do, but attention mask help model to focus on only valid words. So at least for classification task both this should be provided.
Now comes the most crucial part, the ‘Training’. The method which I am going to discuss is by no means ‘the only possible way’ to train. Though after a lot of experimenting I found this method to be most workable. I will discuss three possible ways to train the model:
Use Pretrained model directly as a classifierTransformer model to extract embedding and use it as input to another classifier.Fine-tuning a Pretrained transformer model on custom config and dataset.
Use Pretrained model directly as a classifier
Transformer model to extract embedding and use it as input to another classifier.
Fine-tuning a Pretrained transformer model on custom config and dataset.
2.3.1 Use Pretrained model directly as a classifier
This is the simplest but also with the least application. Hugging Face’s transformers library provide some models with sequence classification ability. These model have two heads, one is a pre-trained model architecture as the base & a classifier as the top head.
Tokenizer definition →Tokenization of Documents →Model Definition
→Note: Models which are SequenceClassification are only applicable here.
→Defining the proper config is crucial here. As you can see on line 6, I am defining the config. ‘num_labels’ is the number of classes to use when the model is a classification model. It also supports a variety of configs so go ahead & see their docs.
→ Some key things to note here are:
Here only weights of the pre-trained model can be updated, but updating them is not a good idea as it will defeat the purpose of transfer learning. So, actually there is nothing here to update. This is the reason I least prefer this.
It is also the least customizable.
A hack you can try is using num_labels with much higher no and finally adding a dense layer at the end which can be trained.
# Hackconfig = DistilBertConfig(num_labels=64)config.output_hidden_states = Falsetransformer_model=TFDistilBertForSequenceClassification.from_pretrained(distil_bert, config = config) input_ids = tf.keras.layers.Input(shape=(128,), name='input_token', dtype='int32')input_masks_ids = tf.keras.layers.Input(shape=(128,), name='masked_token', dtype='int32')X = transformer_model(input_ids, input_masks_ids)[0]X = tf.keras.layers.Dropout(0.2)(X)X = tf.keras.layers.Dense(6, activation='softmax')model = tf.keras.Model(inputs=[input_ids, input_masks_ids], outputs = X)for layer in model.layer[:2]: layer.trainable = False
2.3.2 Transformer model to extract embedding and use it as input to another classifier
This approach needs two level or two separate models. We use any transformer model to extract word embedding & then use this word embedding as input to any classifier (eg Logistic classifier, Random forest, Neural nets, etc).
I would suggest you read this article by Jay Alammar which discusses this approach with great detail and clarity.
As this blog is all about neural nets, let me give you an example of this approach with NN.
→Line #11 is key here. We are only interested in <cls> or classification token of the model which can be extracted using the slice operation. Now we have 2D data and build the network as one desired.
→This approach works generally better every time compared to 2.3.1 approach. But it also has some drawbacks, like:
It is not so suitable for production, as you must be using transformer model as a just feature extractor and so you have to now maintain two models, as your classifier head is different (like XGBoost or Catboast ).
While converting 3D data to 2D we may miss on valuable info.
The transformers library provide a great utility if you want to just extract word embedding.
import numpy as npfrom transformers import AutoTokenizer, pipeline, TFDistilBertModelmodel = TFDistilBertModel.from_pretrained('distilbert-base-uncased')tokenizer = AutoTokenizer.from_pretrained('distilbert-base-uncased')pipe = pipeline('feature-extraction', model=model, tokenizer=tokenizer)features = pipe('any text data or list of text data', pad_to_max_length=True)features = np.squeeze(features)features = features[:,0,:]
2.3.3 Fine-tuning a Pretrained transformer model
This is my favourite approach as here we are making use of the full potential of any transformer model. Here we’ll be using weights of pre-trained transformer model and then fine-tune on our data i.e transfer learning.
→Look at line #17 as 3D data is generated earlier embedding layer, we can use LSTM to extract great details.
→Next thing is to transform the 3D data into 2D so that we can use a FC layer. You can use any Pooling layer to perform this.
→ Also, note on line #18 & #19. We should always freeze the pre-trained weights of transformer model & never update them and update only remaining weights.
Some extras
→Every approach has two things in common:
config.output_hidden_states=False; as we are training & not interested in output state.X = transformer_model(...)[0]; this is inline in config.output_hidden_states as we want only the top head.
config.output_hidden_states=False; as we are training & not interested in output state.
X = transformer_model(...)[0]; this is inline in config.output_hidden_states as we want only the top head.
→config is a dictionary. So to see all available configuration, just simply print it.
→Choose base model carefully as TF 2.0 support is new, so there might be bugs.
As the model is based on tf.keras model API, we can use Keras’ same commonly used method of model.predict()
We can even use the transformer library’s pipeline utility (please refer to the example shown in 2.3.2). This utility is quite effective as it unifies tokenization and prediction under one common simple API.
Hugging Face has really made it quite easy to use any of their models now with tf.keras. It has open wide possibilities.
They have also made it quite easy to use their model in the cross library (from PyTorch to TF or vice versa).
I would suggest visiting their docs, as they have very intuitive & to-the-point docs.
You can contact me via LinkedIn | [
{
"code": null,
"e": 389,
"s": 172,
"text": "I am assuming that you are aware of Transformers and its attention mechanism. The primary aim of this blog is to show how to use Hugging Face’s transformer library with TF 2.0, i.e. it will be more code-focused blog."
},
{
"code": null,
"e": 6... |
Data Structures | Queue | Question 10 - GeeksforGeeks | 28 Jun, 2021
Consider the following operation along with Enqueue and Dequeue operations onqueues, where k is a global parameter.
MultiDequeue(Q){
m = k
while (Q is not empty and m > 0) {
Dequeue(Q)
m = m - 1
}
}
What is the worst case time complexity of a sequence of n MultiDequeue() operations on an initially empty queue? (GATE CS 2013)(A) (B) (C) (D)
(A) A(B) B(C) C(D) DAnswer: (A)Explanation: Since the queue is empty initially, the condition of while loop never becomes true. So the time complexity is .Quiz of this Question
Data Structures
Data Structures-Queue
Data Structures
Data Structures
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Advantages and Disadvantages of Linked List
C program to implement Adjacency Matrix of a given Graph
Difference between Singly linked list and Doubly linked list
Introduction to Data Structures | 10 most commonly used Data Structures
Data Structures | Stack | Question 6
FIFO vs LIFO approach in Programming
Bit manipulation | Swap Endianness of a number
Count of triplets in an Array (i, j, k) such that i < j < k and a[k] < a[i] < a[j]
Advantages of vector over array in C++
Data Structures | Stack | Question 4 | [
{
"code": null,
"e": 24659,
"s": 24631,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 24775,
"s": 24659,
"text": "Consider the following operation along with Enqueue and Dequeue operations onqueues, where k is a global parameter."
},
{
"code": null,
"e": 24880,
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.